vtc-service 0.12.0

Service for Verifiable Trust Communities
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
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
#![allow(clippy::result_large_err)]

//! The VTC member-facing **Trust Task document** dispatcher.
//!
//! This is the wire adapter the join ceremony grew up into: each holder- or
//! public-facing verb (`submit`/`request`, `manifest`, `status`)
//! is a [`trust_tasks_rs::TrustTask`] document, as are the member-initiated
//! `members/self-remove` and `members/vmc` (whose optional `requestId`
//! closes an approved join — the retired `accept` verb's semantics). The
//! success reply is a framework `#response` document (a [`VerdictResponse`]
//! for `submit`, a read body for `manifest`/`status`); every failure — invalid
//! VIC, expired, malformed, duplicate — is a framework `trust-task-error`
//! document, never a DIDComm problem-report and never a `deny` verdict
//! (`deny` is a *policy* refusal of a verified request; an error means the
//! request never reached the policy). See
//! `docs/05-design-notes/vtc-ceremony-protocol.md` §3.
//!
//! ## Transports
//!
//! Both REST and DIDComm render from the one [`dispatch_trust_task_core`]:
//! - **REST**: the request body is the document; the holder is authenticated
//!   by the document's `eddsa-jcs-2022` proof ([`verify_trust_task_proof`]).
//! - **DIDComm**: the message `type` is the Trust Task URL, the body is the
//!   document, and the authcrypt sender authenticates the holder.
//!
//! ## Auth is per-verb (unlike the VTA's uniform-`AuthClaims` dispatcher)
//!
//! The join family is mostly unauthenticated/holder-bound: `submit` and
//! `status` are bound to the holder DID (no ACL entry needed);
//! `manifest` is public. `present` belongs to the `credential-exchange` family
//! and is handled there.
//!
//! **Administrator verbs are routed here too**, since #1641 phase 2 — the
//! admin-facing member verbs were the first batch, `join-requests/decide` and
//! `community/profile/update` the second, `config/{export,import}` the third —
//! the first whose bearer routes were removed rather than kept — and
//! `endorsement-types/{register,delete}` the fourth and `backup/export` the
//! fifth. Their authority is not a bearer token (this endpoint reads none) but
//! the **verified signer's ACL entry**, read at execution time; see
//! [`admin_signer`]. Every later batch followed, and the last (#1641) moved
//! an administrator's own passkeys (`auth/passkey/{list,enroll,revoke}`,
//! [`admin_passkey_tasks`]) and the console's bearer → cookie bridge
//! (`vtc/auth/admin-session/0.1`, [`admin_session_tasks`]) and session
//! introspection (`auth/whoami/0.1`, [`whoami_tasks`], answered for the key a
//! sign-in bound to the session). No task whose specification declares
//! `proof` REQUIRED is served on a bearer route any more
//! (`docs/05-design-notes/vtc-trust-task-proof-enforcement.md` §6c).
//! `vtc/backup/import/0.1` is not served at all: the chunked `backup/*` family
//! ([`backup_tasks`]) supersedes it.
//!
//! The personhood pair (`members/personhood/{challenge,assert}`) is the
//! member-facing half of the family; its `revoke` verb is served here too,
//! with the rest of the member-facing verbs, by [`member_tasks`]. Both carry their own gate — challenge requires the caller to be a
//! member, assert requires the sender to *be* the subject — because "an
//! authenticated session", which is what the REST routes rest on, has no
//! equivalent on a transport that only proves who sent the bytes.

// `pub(crate)` only so sibling modules' tests can take the framework error
// version from `framework_error_type_uri()` rather than each naming it. The
// module's items are individually `pub(crate)` already; this widens the path,
// not the surface.
pub(crate) mod helpers;

// The accepted-document-id record (VTI-OPS-025…027). `pub(crate)` because
// VTI-OPS-027 makes it every binding's, not this spine's: the dispatcher below
// is its first caller, a bearer REST route is its second (#1641 phase 2).
pub(crate) mod accepted_ids;
// The per-type document size limit, checked before the parse.
mod credential_exchange;
// `pub` (not `pub(crate)`) only so `AppState::large_document_budget`'s type
// is nameable from the integration-test crates that build an `AppState`
// literal directly (`tests/emergency_bootstrap.rs`, `tests/passkey_state.rs`)
// — every other item the module exports stays `pub(crate)`.
pub mod size;
// `trust-task-discovery/0.3`: what this VTC serves and the acceptance window it
// applies (VTI-TRN-047).
mod discovery;

// The canonical `acl/{show,list,update,revoke}` tasks, and the operation-bound
// gate `acl/grant` shares with `acl/update`.
mod acl_tasks;
// The administrator action list: `vtc/admin/actions/*` and the
// `task-consent/decision` that completes a parked operation (VTI-APV-017).
pub(crate) mod action_tasks;
// The administrator console's live channel: `vtc/admin/events/subscribe`,
// whose success opens an event stream on the HTTPS door
// (`crate::admin_events`).
pub(crate) mod event_tasks;
// The administrator's operational verbs: the registry reconciler, the audit
// log, the runtime configuration, admin invites and sessions.
pub(crate) mod admin_tasks;
// The administrator's community verbs: roster, join queue, graph, directory,
// recognition, and invitation credentials.
pub(crate) mod community_tasks;
// The community's policy log and its self-hosted DID log.
pub(crate) mod policy_tasks;
// The administration surfaces that had only bearer REST: presentation to
// applicants, the schema registry, vetting reads, edge suspend/restore, a join
// request's vetting and credential query, and the host's rooms.
pub(crate) mod surface_tasks;
// `auth/signing-key/*`: the console's signing keys, as delegations.
pub(crate) mod signing_key_tasks;
// An administrator's own login passkeys: `auth/passkey/list/0.1`,
// `enroll/{start,finish}/0.2`, `revoke/{start,finish}/0.1` (#1641, which
// removed their `/v1/admin/passkeys/*` bearer routes).
pub(crate) mod admin_passkey_tasks;
// The console's bearer → cookie bridge, `vtc/auth/admin-session/0.1` (#1641,
// which removed `POST /v1/auth/admin-session`). HTTPS only: it sets cookies.
pub(crate) mod admin_session_tasks;
// `auth/whoami/0.1`, answered for the key bound to a session at sign-in (or a
// console key acting for its administrator), never for a cookie (#1641).
pub(crate) mod whoami_tasks;
// The website's content: chunked upload, deploy, ranged reads, the listing,
// delete, generation history and rollback.
#[cfg(feature = "website")]
pub(crate) mod website_tasks;

// Pre-session auth: `auth/{challenge,authenticate/{0.2,0.3},refresh/0.2}`.
mod auth_tasks;
// Wallet sign-in started by a trigger link: `auth/oob/*` (the key-grant
// flow). Pre-session, like `auth_tasks`; its state is `member_portal::oob`.
pub(crate) mod oob_tasks;
// First-admin onboarding: `vtc/install/claim/{start,finish}/0.2`,
// `vtc/admin/bootstrap/0.1`. Pre-session, like `auth_tasks`.
mod install_tasks;
// Cross-community recognition: `vtc/auth/recognise/{challenge/0.1,0.2}`.
// Pre-session, like `auth_tasks`.
mod recognise_tasks;

// The member-facing verbs that were HTTPS REST only: renewal, DID rotation,
// personhood revocation, the relationship graph's member verbs and the
// endorsement verbs. Each calls the operation its bearer route calls.
mod member_tasks;

// An applicant's OpenID4VP wallet sessions (#1988): opening one for a join
// criterion, and reading its outcome. The wallet's own two calls are HTTPS
// endpoints (`routes::oid4vp`).
mod wallet_session_tasks;

// The node-neutral `backup/*` family (#1641): a backup too large for one
// document moves as a chunked bundle. `pub(crate)` for `blob_dir`, which the
// retention sweeper needs.
pub(crate) mod backup_tasks;

// Members' step-up passkeys: `auth/passkey/enroll/invite/0.2` (`purpose:
// stepUp`), `enroll/redeem/{start,finish}/0.1` and `revoke/{start,finish}/0.2`.
// The operations are `crate::step_up_passkey`'s; this is their only door.
pub(crate) mod step_up_passkey_tasks;

// Step-up approvers: `auth/step-up/approver/{invite,redeem/start,redeem/finish,
// enroll,list,revoke}/0.1`. The operations are `crate::step_up_approver`'s;
// this is their only door.
pub(crate) mod step_up_approver_tasks;

// Custom administrative roles: `vtc/roles/{define,list,show,delete}/0.1`
// (`vtc-admin-roles.md` §6.2). The records are `crate::acl::roles`'s; this is
// their only door.
pub(crate) mod community_room_tasks;
// The member directory: `vtc/directory/{fields,card,entries}/*` (the
// `query/0.1` lookup stays in `community_tasks`, answered through the same
// projection). Its records are `crate::directory`'s.
pub(crate) mod directory_tasks;
pub(crate) mod role_tasks;
pub(crate) mod room_admin_tasks;
// The administrators' view of the OpenID4VP verifier identities (#1988).
pub(crate) mod oid4vp_tasks;
pub(crate) mod storage_tasks;
// Direct admission: adding a member without a join request, and making an
// existing ACL entry a membership — decided by the community's `admission`
// policy, which may park either for approval (`crate::ceremony::admission`).
pub(crate) mod admission_tasks;

// Capability modules: `governance/capability/{list,enable,disable}/0.1`
// (`design-docs/vtc-capability-modules.md`). The decisions and their registry
// projection are `crate::capability_modules`'s; this is their only door.
pub(crate) mod capability_module_tasks;

// The integration tests' soft WebAuthn authenticator, for the spine tests that
// drive a real passkey ceremony.
#[cfg(test)]
#[allow(dead_code)]
#[path = "../../tests/it/common/webauthn_harness.rs"]
mod soft_authenticator;

// The schema-conformance sweep (#1059): every bound, published `spec/vtc/*`
// URI must speak that URI's wire shape. Lives in `src` rather than `tests`
// because its census is derived from `DISPATCHED_URIS` below, which no
// integration test can see.
#[cfg(test)]
mod conformance;

// The declared-error-code census (#1600): every extended error code a bound,
// published `spec/vtc/*` task declares must be witnessed by a test that
// observes the service emitting it. Derived from the same census as
// `conformance`, and from `trust_tasks_rs::schema_index::error_codes_for`.
#[cfg(test)]
mod error_code_census;

use serde_json::Value;
use trust_tasks_rs::specs::vtc::members::personhood::{assert::v0_2 as pa, challenge::v0_1 as pc};
// The admin-facing member verbs (#1641 phase 2). Their wire types are
// generated from the published schemas, so there is no hand-written SDK
// constant to import and the Type URIs below are read off the payload types.
use trust_tasks_rs::specs::vtc::members::{
    admin_remove::v0_1 as member_admin_remove, credentials::v0_1 as member_credentials,
    purge::v0_1 as member_purge, update::v0_1 as member_update,
};
// The admin verbs #1641 phase 2 batch 2 moved: the join decision and the
// community profile edit. Same story — generated wire types, Type URIs read
// off the payload types.
use trust_tasks_rs::specs::vtc::community::profile::update::v0_1 as community_profile_update;
use trust_tasks_rs::specs::vtc::join_requests::decide::v0_1 as join_decide;
// Batch 3: the portable-configuration pair.
use trust_tasks_rs::specs::vtc::config::{
    export::v0_1 as config_export, import::v0_1 as config_import,
};
// Batch 4: the endorsement-type registry's two writes.
use trust_tasks_rs::specs::vtc::endorsement_types::{
    delete::v0_1 as endorsement_type_delete, register::v0_1 as endorsement_type_register,
};
// Batch 5: the backup export. Its `import` partner waits — see the design note.
use trust_tasks_rs::specs::vtc::backup::export::v0_1 as backup_export;
// The first verb that confers administrative authority on this door, and the
// answer to the operation-bound step-up it asks for (#1641; design note
// `vtc-operation-bound-step-up.md`).
use trust_tasks_rs::specs::acl::change_role::v0_1 as acl_change_role;
use trust_tasks_rs::specs::acl::grant::v0_1 as acl_grant;
// The rest of the canonical family: reading and amending an entry, and taking
// authority away — which until these were bound here existed only on bearer REST.
use trust_tasks_rs::specs::acl::{
    list::v0_1 as acl_list, revoke::v0_1 as acl_revoke, show::v0_1 as acl_show,
    update::v0_1 as acl_update,
};
use trust_tasks_rs::specs::auth::step_up::approve_response::v0_4 as step_up_approve_response;
// 0.5 requires the approver's proof on every response (no more unsigned
// webauthn answers); served alongside 0.4, never in place of it, because the
// console still answers an unsigned session-passkey gesture on 0.4 — see
// `handle_step_up_approve_response_v0_5`.
use trust_tasks_rs::specs::auth::step_up::approve_response::v0_5 as step_up_approve_response_v0_5;
// 0.6 adds `approverSigned` evidence — a step-up approver's statement — beside
// the passkey (design note `vtc-approver-step-up.md`).
use trust_tasks_rs::specs::auth::step_up::approve_response::v0_6 as step_up_approve_response_v0_6;
use trust_tasks_rs::{RejectReason, TrustTask};

use vta_sdk::protocols::trust_task_reject_reasons as reasons;
use vti_common::error::AppError;

use vta_sdk::protocols::join_requests::{
    self as jr, JoinRequestStatusBody, JoinRequestSubmitBody, VerdictResponse,
};
use vta_sdk::protocols::members::{self as mem, MemberVmcBody, MemberVmcReceiptBody};
use vta_sdk::protocols::vetting::{
    self as vetting_wire, revoke_statement::v0_1 as revoke_statement,
};

use crate::join::{JoinSubmitOutcome, JoinTransport};
use crate::server::AppState;

pub(crate) use helpers::TrustTaskOutcome;
// The one spelling of the framework error document's Type URI in this crate.
// Re-exported so the messaging layer labels a type-less reply with the same
// value the reject path emits, rather than a second literal.
pub(crate) use helpers::framework_error_type_uri;
use helpers::{
    app_error_to_reject, body_parse_error_response, extended_code, parse_payload, reject_with,
    reject_with_code, reject_with_code_because, success_response, task_error_to_reject,
    verdict_response, verify_received_approval_proof, verify_received_trust_task_proof,
    verify_trust_task_proof,
};

/// The transport-resolved caller identity threaded into the dispatcher.
///
/// `sender_did` is the transport-reported sender (DIDComm, TSP): a claim the
/// spine accepts only once the document's own proof binds it (step 3a of
/// [`dispatch_trust_task_core`]). It is `None` over REST,
/// where the holder is recovered from the document proof instead.
pub(crate) struct JoinAuthCtx {
    pub transport: JoinTransport,
    pub sender_did: Option<String>,
    /// The DID that signed this document's Data-Integrity proof, verified by
    /// the spine against the document **as received**.
    ///
    /// `None` when the task's specification does not require a proof, or when
    /// the context was built by a transport rather than by the spine.
    ///
    /// # Why the spine and not the handler
    ///
    /// A proof covers the document as it was sent. A handler that has been
    /// handed a typed payload can only re-derive those bytes if its payload type
    /// round-trips losslessly — and none promises to: parse a document into a
    /// type that does not know one of its fields and the field is gone, so the
    /// canonicalisation differs and a valid proof fails. Verifying here, once,
    /// against the bytes that arrived, is what makes typed handlers possible at
    /// all. Pinned by `vta-sdk/tests/typed_proof_verify.rs`.
    pub verified_signer: Option<String>,
}

impl JoinAuthCtx {
    /// The DIDComm context. The sender is only a claim until the spine binds
    /// it to the document proof.
    ///
    /// The envelope arm builds its context field by field, because an
    /// unauthenticated sender there is `None` rather than a refusal; this
    /// shorthand is for a caller that already holds a proven DID.
    #[allow(dead_code)]
    pub fn didcomm(sender_did: String) -> Self {
        Self {
            transport: JoinTransport::DIDComm,
            sender_did: Some(sender_did),
            verified_signer: None,
        }
    }

    /// The REST context: the holder is proven by the document proof.
    // Consumed by the REST transport adapter (the per-verb routes' rewire to
    // the document endpoint); kept here as the symmetric counterpart to
    // [`Self::didcomm`].
    #[allow(dead_code)]
    pub fn rest() -> Self {
        Self {
            transport: JoinTransport::Rest,
            sender_did: None,
            verified_signer: None,
        }
    }

    /// The same context with `verified_signer` filled in by the spine.
    fn with_verified_signer(&self, signer: Option<String>) -> Self {
        Self {
            transport: self.transport,
            sender_did: self.sender_did.clone(),
            verified_signer: signer,
        }
    }
}

/// The transport-neutral dispatch spine. Parses the document, holds it to the
/// specification it names, then routes by `type` to the matching verb handler.
///
/// In order: the acceptance window over `issuedAt` (VTI-OPS-024), expiry and
/// the recipient binding (VTI-OPS-023), the flag-driven rules the
/// specification itself declares — `proof`, `recipient` and `issuedAt`
/// REQUIRED, and audience binding (VTI-OPS-020, VTI-OPS-021), verification of
/// any `proof` present against the document's own `issuer`, and the
/// duplicate-execution record (VTI-OPS-025…027). Every one of them is reached
/// identically from REST, DIDComm and TSP, which is VTI-OPS-021's point.
///
/// Every one of those checks is unconditional. There is no configuration that
/// relaxes any of them — `docs/05-design-notes/vtc-trust-task-proof-enforcement.md`
/// has the whole argument, including the one transitional allowance #1641
/// shipped with and why it is gone.
pub(crate) async fn dispatch_trust_task_core(
    state: &AppState,
    ctx: &JoinAuthCtx,
    body: &[u8],
) -> TrustTaskOutcome {
    // Every answer is signed, refusals included — the early returns below as
    // well as the dispatched result (which `dispatch_trust_task_validated`
    // signs before recording it for redelivery).
    let address = large_document_budget_address(ctx);
    let outcome = dispatch_trust_task_validated(state, ctx, body, None, &address).await;
    sign_response(state, outcome).await
}

/// The address [`size::check_for_known_issuer`] charges a raised-limit
/// document's budget to, for a caller that has no address of its own to pass
/// (every non-HTTPS transport, and any direct test call). DIDComm and TSP
/// already authenticate `ctx.sender_did` at the transport layer, before the
/// document's own proof is read — the same "claim, not yet a verified issuer"
/// standing [`size`]'s module docs describe — so that VID is this budget's
/// address. A caller with no transport-authenticated sender (REST reached
/// other than through [`dispatch_trust_task_core_admitted`], which passes the
/// client IP explicitly) shares one placeholder address rather than being
/// charged against nothing.
fn large_document_budget_address(ctx: &JoinAuthCtx) -> String {
    ctx.sender_did
        .as_deref()
        .map(|vid| format!("vid:{vid}"))
        .unwrap_or_else(|| "ip:unknown".to_string())
}

/// A transport's say in whether a document whose proof has verified may go on
/// to execute: the HTTPS door's per-signer rate limit
/// ([`crate::routing::trust_task_admission`]).
///
/// It is asked once, after the proof has verified against the document's
/// `issuer` and before the duplicate-execution record is claimed, so a refusal
/// spends neither the document's `id` nor any work past verification.
pub(crate) trait VerifiedAdmission: Sync {
    /// `false` refuses the document. The spine then stops and answers an empty
    /// `429` outcome, which the transport replaces with its own refusal; the
    /// admission is expected to have recorded why.
    fn admit_verified(&self, signer: &str) -> bool;

    /// The transport has charged this document to a room budget sized for file
    /// transfer before anything in it was verified, and settles that charge
    /// itself — so the size check need not also charge an upload chunk to the
    /// large-document budget ([`size::check_for_known_issuer_with`]).
    fn room_precharged(&self) -> bool {
        false
    }
}

/// [`dispatch_trust_task_core`], with `admit` consulted once the proof has
/// verified (see [`VerifiedAdmission`]), and the raised-limit budget charged
/// against `client_ip` rather than the sender-VID fallback
/// [`large_document_budget_address`] uses — the real address a stranger
/// cannot choose over HTTPS, resolved by the caller from the connection peer
/// (or `X-Forwarded-For`, behind a configured trusted proxy).
pub(crate) async fn dispatch_trust_task_core_admitted(
    state: &AppState,
    ctx: &JoinAuthCtx,
    body: &[u8],
    admit: &dyn VerifiedAdmission,
    client_ip: std::net::IpAddr,
) -> TrustTaskOutcome {
    let address = format!("ip:{client_ip}");
    let outcome = dispatch_trust_task_validated(state, ctx, body, Some(admit), &address).await;
    sign_response(state, outcome).await
}

async fn dispatch_trust_task_validated(
    state: &AppState,
    ctx: &JoinAuthCtx,
    body: &[u8],
    admit: Option<&dyn VerifiedAdmission>,
    budget_address: &str,
) -> TrustTaskOutcome {
    // 0. The size the document's type accepts — decided before anything in it
    //    is parsed, on every transport (`size`). A document large enough to
    //    need its claimed (not yet verified) issuer's ACL entry for the
    //    raised limit is charged against `budget_address`'s large-document
    //    budget first — see `size`'s module docs for why an unverified claim
    //    alone would otherwise be a DoS amplifier. Settled below, once this
    //    document's own proof verification concludes (or does not run at
    //    all). An upload chunk a transport has already charged to its room
    //    budget is not charged again here (`size::check_for_known_issuer_with`).
    let large_doc_charge = match size::check_for_known_issuer_with(
        state,
        body,
        budget_address,
        crate::auth::session::now_epoch(),
        admit.is_some_and(|a| a.room_precharged()),
    )
    .await
    {
        Ok(charge) => charge,
        Err(refused) => return refused,
    };

    // 1. Parse the envelope.
    let doc: TrustTask<Value> = match serde_json::from_slice(body) {
        Ok(d) => d,
        Err(e) => return body_parse_error_response(&e.to_string()),
    };
    // The same bytes as JSON, kept verbatim: the proof at step 3 is verified
    // over what was received, never over a re-serialisation of `doc`, which
    // rewrites the timestamps a producer signed (VTI-45). It parsed as a Trust
    // Task, so it parses as JSON.
    let received: Value = match serde_json::from_slice(body) {
        Ok(v) => v,
        Err(e) => return body_parse_error_response(&e.to_string()),
    };

    // One instant for every temporal decision in this dispatch. The acceptance
    // window and the replay record's retention are the *same* bound (SPEC
    // §7.2, *Bounding the record*), so reading the clock twice could place
    // them on opposite sides of it.
    let now = chrono::Utc::now();

    // 2. Framework §7.2 item 13 — the timestamp bounds, and VTI-OPS-024's
    //    acceptance window. Checked first because it is decided from the
    //    document alone, before any resolution, verification or execution
    //    work, and because one of its rules changes how the other reads.
    if let Err(reason) = doc.validate_freshness(now, &freshness_policy()) {
        return reject_with(&doc, reason);
    }

    // 2b. Framework §7.2 items 4 + 5 — expiry + recipient enforcement. The
    //    recipient binding (document `recipient` must equal this VTC's DID) is
    //    the replay defence that the bespoke `audience` field used to provide.
    //    Skipped while the VTC has no DID configured (setup).
    let vtc_did = state.config.read().await.vtc_did.clone();
    if let Some(vtc_did) = vtc_did
        && let Err(reason) = doc.validate_basic(now, &vtc_did)
    {
        return reject_with(&doc, reason);
    }

    let type_uri = doc.type_uri.to_string();

    // 2c. SPEC §7.2's *flag-driven* checks — the ones the published
    //    specification declares rather than this consumer chooses:
    //
    //    * item 5b — `recipient` REQUIRED
    //    * item 7a — `proof` REQUIRED  → `proofRequired`
    //    * item 8  — audience binding (proof present, no in-band recipient, on
    //                a non-bearer specification)
    //    * §7.3 17 — `issuedAt` REQUIRED
    //
    // ## Why this is here now, and what it replaces
    //
    // Until #1641 this spine verified a proof whenever one was present and
    // otherwise took attribution from the transport — including for the nine
    // dispatched tasks whose own definitions declare `proof` REQUIRED. The
    // comment that stood here argued the transport had already proved the
    // sender, so demanding a proof would refuse every join over DIDComm and
    // TSP.
    //
    // That argument is refused by three documents at once, and none of them is
    // ambiguous:
    //
    // - **VTI-OPS-021 / VTI-OPS-093.** "A node MUST apply the same document
    //   requirements on every transport. A transport that authenticates its
    //   sender MUST NOT be treated as relieving a producer of addressing or
    //   signing the document it sends." A binding may not weaken the
    //   requirement on the strength of a transport property.
    // - **The DIDComm binding's own §5.** "A *Trust Task specification* that
    //   declares `proof` as REQUIRED overrides this binding-level allowance:
    //   the in-band `proof` is mandatory regardless of transport, because such
    //   specifications produce documents intended to be replayable past the
    //   original transport hop." The allowance the old rule leaned on is
    //   disclaimed by the very binding that grants it.
    // - **That binding's §6**, on where the guarantee stops: "At the message.
    //   The envelope is discarded on unwrap, and the guarantee does not travel
    //   with the document." Authcrypt tells this service who handed it the
    //   bytes. It leaves nothing behind that a third party — an auditor, a
    //   registry, the member themselves — could check afterwards.
    //
    // Read off `spec_policy_for`, never a list kept here: a list of URIs whose
    // requirement is published elsewhere is a list that drifts, and the
    // requirement moves when the specification does.
    //
    // The policy is enforced **as the registry states it**. #1641 shipped with
    // one transitional narrowing — `require_declared_proof = false` cleared
    // `is_proof_required` where the transport had authenticated the sender,
    // because `openvtc-core` sent five of these documents unsigned. openvtc#371
    // signs them, which was that switch's stated removal condition, so the
    // narrowing and the config key are gone. Nothing may reintroduce a
    // per-deployment relaxation here: VTI-OPS-093 forbids a binding weakening a
    // document requirement on a transport property, and a switch that lets an
    // operator do it is the same weakening with a longer path.
    //
    // `None` means this build knows no specification for the URI. The
    // dispatcher refuses an unrouted URI a few lines below
    // (`unsupported_type_or_version`), so there is no silently-unchecked task
    // here — only tasks whose definitions this build cannot read, which is the
    // `rooms/*`-shaped case the arms guard for themselves.
    if let Some(policy) = spec_policy_for(&type_uri)
        && let Err(reason) = policy.enforce(&doc)
    {
        tracing::info!(
            type_uri,
            ?reason,
            "document refused by its specification's own policy"
        );
        return reject_with(&doc, reason);
    }

    // 2d. The `auth/oob` family's signer must be an Ed25519 `did:key`, decided
    //     from the identifier before any proof is read (T21) — a rule its
    //     specifications state in prose, which `spec_policy_for` cannot carry.
    if let Some(refused) = oob_tasks::precheck(&doc, &type_uri) {
        return refused;
    }

    // 3. Framework §7.2 item 7, *first* clause — the proof, verified here
    //    against the document **as received**, because this is the last point
    //    at which those bytes exist: past dispatch a handler holds a payload
    //    that may have dropped a member it does not know, and canonicalising
    //    that yields different bytes and refuses a valid proof.
    //
    //    §4.7 binds the proof to the in-band `issuer`: the `verificationMethod`
    //    "MUST resolve to verification material controlled by the *party*
    //    identified by the document's `issuer` member". A valid proof by some
    //    *other* DID is not a proof by the issuer, and without this check the
    //    signature would establish only that somebody signed something —
    //    which is not what `verified_signer` is read as downstream.
    //
    //    A human approver's own decision (a step-up `approve-response`, a
    //    `task-consent/decision`) is an attestation, not an operational
    //    message: its proof must be made for `assertionMethod` by a key the
    //    approver lists under `assertionMethod`
    //    ([`verify_received_approval_proof`]).
    //
    //    "As received" literally: over `received`, the JSON the bytes parsed
    //    to, not over `doc` re-serialised (VTI-45).
    // An install claim under an existing DID is verified against that DID's
    // *live* document (`vtc/install/claim/finish/0.3` item 3), so its cached
    // copy is dropped and the DID resolved afresh first.
    if type_uri == install_tasks::CLAIM_FINISH_V0_3_TYPE
        && let Some(refused) = install_tasks::refresh_founder_did(state, &doc).await
    {
        return refused;
    }
    let ctx = if doc.proof.is_some() {
        let verified = if helpers::is_approval_type(&type_uri) {
            verify_received_approval_proof(state, &received, &type_uri).await
        } else {
            verify_received_trust_task_proof(state, &received).await
        };
        match verified {
            Ok(signer) => {
                if doc.issuer.as_deref() != Some(signer.as_str()) {
                    tracing::warn!(
                        type_uri,
                        issuer = ?doc.issuer,
                        %signer,
                        "proof verifies under a key the document's issuer does not control"
                    );
                    // Settle before returning: a proof that verifies under a
                    // different DID than the one this document claimed as
                    // `issuer` is exactly the "verified issuer turns out to be
                    // someone else" case `size`'s module docs describe, and
                    // penalises the budget address the same as an outright
                    // verification failure would.
                    size::settle_large_document_charge(
                        &state.large_document_budget,
                        large_doc_charge.as_ref(),
                        Some(signer.as_str()),
                    );
                    return reject_with(
                        &doc,
                        RejectReason::ProofInvalid {
                            reason: "the proof's verificationMethod does not belong to the \
                                     document's issuer (SPEC §4.7)"
                                .to_string(),
                        },
                    );
                }
                size::settle_large_document_charge(
                    &state.large_document_budget,
                    large_doc_charge.as_ref(),
                    Some(signer.as_str()),
                );
                // A delegated signing key is an operational credential, never
                // an approver's attestation (auth/signing-key/enroll item 7):
                // no approval is accepted under its proof, whatever its state.
                if helpers::is_approval_type(&type_uri) {
                    match crate::acl::console_key::get_delegation(&state.console_keys_ks, &signer)
                        .await
                    {
                        Ok(None) => {}
                        // approve-response 0.6 names this case: the proof
                        // must be the subject DID's own, and a console key
                        // signs as its own `did:key` — `subjectMismatch`.
                        // Same refusal, at the same point; only the code is
                        // the task's own.
                        Ok(Some(_)) if type_uri == STEP_UP_APPROVE_RESPONSE_V0_6_TYPE => {
                            return reject_with_code(
                                &doc,
                                helpers::extended_code(
                                    step_up_approve_response_v0_6::error_codes::SUBJECT_MISMATCH
                                        .code,
                                ),
                                "a delegated signing key is never accepted as the subject's own \
                                 proof; sign the approve-response with the subject DID's own key",
                                None,
                            );
                        }
                        Ok(Some(_)) => {
                            return reject_with(
                                &doc,
                                RejectReason::PermissionDenied {
                                    reason: "a delegated signing key is never accepted as an \
                                             approver's attestation; sign with the approver's \
                                             own key, or answer a passkey step-up unsigned"
                                        .to_string(),
                                },
                            );
                        }
                        Err(e) => return app_error_to_reject(&doc, &e),
                    }
                }
                &ctx.with_verified_signer(Some(signer))
            }
            // A proof that is present and does not verify is always fatal,
            // whatever the transport proved separately. Settled as an
            // unverified claim (`None`) before returning.
            Err(e) => {
                size::settle_large_document_charge(
                    &state.large_document_budget,
                    large_doc_charge.as_ref(),
                    None,
                );
                return app_error_to_reject(&doc, &e);
            }
        }
    } else {
        // No proof at all: whatever this document claimed as `issuer` was
        // never checked, so the charge settles exactly as an outright
        // verification failure would.
        size::settle_large_document_charge(
            &state.large_document_budget,
            large_doc_charge.as_ref(),
            None,
        );
        ctx
    };

    // 3a. Over DIDComm and TSP the transport-reported sender is a claim, not
    //     proof of who composed the document (VTI-OPS-021/093). Every document
    //     arriving that way must carry a proof (verified above against its
    //     `issuer`), and that issuer must be the sender: the proof VM's
    //     controller, the issuer and the sender are one DID. Handlers that read
    //     `sender_did` then read a DID the document proves, whatever the task's
    //     own proof requirement.
    if matches!(ctx.transport, JoinTransport::DIDComm | JoinTransport::Tsp) {
        let base = |d: &str| d.split('#').next().unwrap_or(d).to_string();
        match (ctx.verified_signer.as_deref(), ctx.sender_did.as_deref()) {
            (Some(signer), Some(sender)) if base(signer) == base(sender) => {}
            (None, _) => {
                tracing::warn!(type_uri, "messaging document carries no proof — refused");
                return reject_with(&doc, RejectReason::ProofRequired);
            }
            (Some(signer), sender) => {
                tracing::warn!(
                    type_uri,
                    %signer,
                    sender = ?sender,
                    "messaging document is signed by a DID other than its sender — refused"
                );
                return reject_with(
                    &doc,
                    RejectReason::IdentityMismatch(
                        trust_tasks_rs::ConsistencyError::IssuerMismatch {
                            in_band: signer.to_string(),
                            transport: sender.unwrap_or_default().to_string(),
                        },
                    ),
                );
            }
        }
    }

    // 3a'. The transport's admission of the verified signer — the HTTPS
    //      door's per-signer rate limit. After verification, so the bucket it
    //      charges is the one the proof establishes; before the claim below,
    //      so a refused document keeps its `id` for the retry.
    if let (Some(admit), Some(signer)) = (admit, ctx.verified_signer.as_deref())
        && !admit.admit_verified(signer)
    {
        return TrustTaskOutcome {
            status: axum::http::StatusCode::TOO_MANY_REQUESTS,
            body: Vec::new(),
        };
    }

    // 3b. SPEC §7.2 item 11 — the duplicate-execution record.
    //
    // Every transport that reaches this spine is at-least-once. The mediator
    // re-pushes a recipient's whole undelivered inbox when a socket enables
    // live delivery and when a duplicate socket displaces an existing session,
    // so a frame this VTC has already handled arrives again as a matter of
    // routine — not as an attack. Without a record, the second copy is executed
    // a second time.
    //
    // Expiry and the recipient binding (step 2) do not close this. Both are
    // properties of the document, and a redelivered copy satisfies them exactly
    // as the first did — which is the point: it *is* the first document.
    //
    // The record is digest-keyed, so a *different* document arriving under an
    // already-spent `id` is `idConflict` rather than being silently absorbed as
    // a retry, and it claims before dispatch, so two simultaneous deliveries
    // cannot both pass a check-then-act test.
    //
    // It lives in the store, not in this process, because **VTI-OPS-027**
    // requires the record to be shared across every binding this node exposes
    // — see [`accepted_ids`]. The dispatcher is its first caller; the bearer
    // REST routes #1641 phase 2 migrates are its second, and they must be able
    // to consult the same rows, or replay protection is defeated by presenting
    // the document at the other door.
    //
    // Placed after the proof check so an unauthenticated flood cannot spend
    // another sender's ids, matching where the webvh control plane puts its own
    // gate and for the same reason.
    let claim = match state
        .accepted_ids()
        .claim(&doc, retain_until(&doc, now), now)
        .await
    {
        Ok(accepted_ids::Acceptance::Fresh(claim)) => claim,
        Ok(accepted_ids::Acceptance::Duplicate {
            prior_response,
            in_flight,
        }) => {
            // §7.2 (*Disposition of a duplicate*): "In no case is a duplicate
            // reported as `taskFailed`; the task did not fail, it already
            // happened." A redelivery is the common case here, so answering it
            // with the original result is not a courtesy — it is what keeps a
            // caller whose reply was lost from retrying forever.
            return match prior_response {
                Some(v) => match serde_json::to_vec(&v) {
                    Ok(body) => TrustTaskOutcome {
                        status: axum::http::StatusCode::OK,
                        body,
                    },
                    Err(e) => reject_with(
                        &doc,
                        RejectReason::InternalError {
                            reason: format!("prior response is unserialisable: {e}"),
                        },
                    ),
                },
                // Still running: `202` is the only honest code. `200` claims a
                // result that does not exist yet and `409` a conflict that does
                // not exist — it is the same document.
                None if in_flight => TrustTaskOutcome {
                    status: axum::http::StatusCode::ACCEPTED,
                    body: Vec::new(),
                },
                None => TrustTaskOutcome {
                    status: axum::http::StatusCode::NO_CONTENT,
                    body: Vec::new(),
                },
            };
        }
        Ok(accepted_ids::Acceptance::Conflict) => {
            return reject_with(&doc, RejectReason::IdConflict);
        }
        // Fail closed. A consumer that cannot establish whether a document is a
        // duplicate has not satisfied item 11, so it must not execute — and
        // `unavailable` is retryable, which is the truthful signal.
        //
        // `Acceptance` is this crate's own enum rather than the library's
        // `#[non_exhaustive] ReplayVerdict`, so the arm that used to catch a
        // verdict this build did not know is gone: a new variant here is a
        // compile error at this match, which is the stronger form of the same
        // guard.
        Err(e) => return reject_with(&doc, e.reject_reason()),
    };

    // 4. Dispatch by type URI, then sign what comes back. The document as
    //    received travels with the dispatch, so an operation that has to wait
    //    for other administrators' approval is parked as exactly what its
    //    requester signed (`crate::admin_actions`).
    let submission = crate::admin_actions::Submission {
        received: std::sync::Arc::new(received),
        signer: ctx.verified_signer.clone(),
        transport: ctx.transport,
        waiver: Default::default(),
        immediate: Default::default(),
    };
    let outcome = crate::admin_actions::with_submission(
        submission,
        // Already boxed: `dispatch_typed` returns the chosen handler's future.
        dispatch_typed(state, ctx, doc, &type_uri),
    )
    .await;
    let outcome = sign_response(state, outcome).await;

    // Close out the claim taken at 3b.
    //
    // - **Succeeded** → record the response, so the redelivery this guard
    //   exists to absorb is answered with the result rather than with silence.
    // - **Failed** → release. A document refused downstream of the claim would
    //   otherwise burn its `id`, and a corrected resend under the same `id`
    //   would come back `idConflict` for as long as the record is retained.
    //
    // A response that carries a bearer secret (an invite's claim code) is
    // recorded as completed **without** its body, so the secret is not kept
    // for the acceptance window; a redelivery is then answered `204`.
    if outcome.status.is_success() {
        let recorded = if step_up_passkey_tasks::SECRET_RESPONSES.contains(&type_uri.as_str())
            || step_up_approver_tasks::SECRET_RESPONSES.contains(&type_uri.as_str())
            || admin_tasks::SECRET_RESPONSES.contains(&type_uri.as_str())
            || community_tasks::SECRET_RESPONSES.contains(&type_uri.as_str())
            || event_tasks::UNRECORDED_RESPONSES.contains(&type_uri.as_str())
        {
            None
        } else {
            serde_json::from_slice::<serde_json::Value>(&outcome.body).ok()
        };
        claim.completed(recorded.as_ref()).await;
    } else {
        claim.release().await;
    }

    outcome
}

/// The document requirements (SPEC §7.2 items 5b, 7a, 8; §7.3 item 17) of
/// `type_uri`: its published specification's, read off the registry.
pub(crate) fn spec_policy_for(type_uri: &str) -> Option<trust_tasks_rs::SpecPolicy> {
    trust_tasks_rs::schema_index::spec_policy_for(type_uri)
}

/// The acceptance window this VTC is willing to act inside — **VTI-OPS-024**,
/// SPEC §7.2 item 13, and the bound the accepted-id record's retention is
/// derived from.
///
/// # Acceptance and retention are one bound
///
/// This used to be a `retention_policy()` whose documentation said, in terms,
/// "**retention only** — this is not an acceptance policy and must not become
/// one", because many of this service's producers stamped no `issuedAt`. §7.2
/// (*Bounding the record*) makes that separation unavailable: a consumer
/// "**MUST NOT** accept for execution a document older than the window over
/// which it retains records", and one that "can establish neither an
/// `expiresAt` nor an age for a document has no window in which to place it,
/// and **MUST NOT** execute a *consequential Trust Task* on it". A record kept
/// for a window nothing is measured against is a record whose horizon is
/// capacity eviction, which makes the defence weakest exactly when the service
/// is busiest.
///
/// # Why ten minutes, and 60 seconds of skew
///
/// The library's `DEFAULT_MAX_AGE` is five minutes, "long enough to survive a
/// mediator queue, a retry with backoff, and a modest clock disagreement".
/// This service reaches members through a mediator that holds messages while a
/// recipient reconnects, so it takes double that — the same window
/// `vta-service` settled on, for the same reason, so a document that one
/// accepts is not stale at the other. The skew tolerance is the library's
/// `DEFAULT_SKEW`, 60 seconds, which is SPEC §4.2's own "typically ≤ 60s".
///
/// # Why `issuedAt` is required, and what that costs
///
/// Without it two shapes escape the window. A document carrying neither
/// timestamp is refused anyway — as `Stale { Unboundable }`, which renders as
/// the wire code `expired`, telling a producer to wait when what it must do is
/// reissue with the member it omitted. And a document carrying only
/// `expiresAt` is accepted for however long its *producer* chose, which would
/// let the producer decide how long this consumer must remember its `id`.
/// Requiring `issuedAt` makes the last instant an accepted document can return
/// provable — `issuedAt + max_age + skew` — which is what [`retain_until`]
/// caps on.
///
/// The cost is exact: the one shape that moves from accepted to refused is
/// **`expiresAt` present, `issuedAt` absent**. Every VTI producer stamps
/// `issuedAt` (`vta_sdk::trust_task_sign::build_unsigned`, and
/// `VtaClient::dispatch_trust_task` for every transport), and 52 of the 95
/// specifications this service binds declare the member REQUIRED in any case.
pub(super) fn freshness_policy() -> trust_tasks_rs::FreshnessPolicy {
    // The window this node also advertises in its `trust-task-discovery/0.3`
    // answer (VTI-TRN-047): one value, so the two cannot drift.
    vti_common::trust_task::acceptance::VTI_ACCEPTANCE_WINDOW
        .freshness_policy()
        .requiring_issued_at()
}

/// How long the duplicate-execution record for `doc` must be kept — the end of
/// this consumer's willingness to execute it, which SPEC §7.2 makes the same
/// instant as the end of the record's required retention.
///
/// `FreshnessPolicy::record_expiry` takes a producer-supplied `expiresAt`
/// **verbatim**, so a document stamped `expiresAt = now + 10 years` would pin
/// its `id` in the accepted-id record for ten years — an entry held long past
/// the last moment it could be needed, crowding out the records that are.
/// `requiring_issued_at` above makes the cap provable: a document with no
/// `issuedAt` never reaches here, and one that did reach here is refused once
/// `issuedAt + max_age + skew` has passed.
///
/// The cap only ever moves the instant **earlier than a producer asked for**,
/// never earlier than the acceptance window. Shortening retention below the
/// window is the direction §7.2 forbids: a replay arriving while the document
/// is still acceptable, with its record already dropped, executes twice.
fn retain_until(
    doc: &TrustTask<Value>,
    now: chrono::DateTime<chrono::Utc>,
) -> Option<chrono::DateTime<chrono::Utc>> {
    let policy = freshness_policy();
    let expiry = policy.record_expiry(doc, now)?;
    match (doc.issued_at, policy.max_age) {
        (Some(issued_at), Some(max_age)) => Some(expiry.min(issued_at + max_age + policy.skew)),
        // Unreachable while `require_issued_at` holds; if that ever changes,
        // over-retaining is the safe direction to fail in.
        _ => Some(expiry),
    }
}

/// Attach this community's Data-Integrity proof to a success response.
///
/// # Why here and not at each `success_response`
///
/// Signing is the same decision taken once per handler, and there are twenty-one
/// of them. Forgetting once is a task whose response is unattributable, and
/// nothing downstream would notice — which is exactly how every response came to
/// be unsigned in the first place. The spine is where the framework's inbound
/// checks already live; the outbound one belongs beside them.
///
/// # Why this was missing, and what it cost
///
/// SPEC §7.3 item 7: where a specification declares no separate requirement for
/// the *response*, the request's applies to it — "an omission can never weaken a
/// variant". 265 published specifications declare a single
/// `proofRequirement: REQUIRED`, so their responses require a proof, and this
/// service attached none to any of them.
///
/// Nothing went red because no consumer verifies one either. Producers not
/// signing and consumers not checking is a mutually consistent silence, and the
/// cost is that **no answer this service has ever given is evidence of
/// anything**: a member cannot show a third party what the host told them, and
/// cannot be contradicted when they misreport it.
///
/// # Scope
///
/// Every response document — success **and** `trust-task-error` — is signed
/// with `proofPurpose: authentication` (VTI-KEY-106): a client that refuses
/// unsigned replies must be able to attribute a refusal as well as a result.
/// A document that already carries a proof, or an empty body, is left alone.
///
/// A community with no signer configured (setup, before provisioning) returns
/// the document unsigned rather than failing: it has nothing to sign with, and
/// refusing to answer would make an unprovisioned VTC unusable rather than
/// merely unattributable.
pub(crate) async fn sign_response(state: &AppState, outcome: TrustTaskOutcome) -> TrustTaskOutcome {
    if outcome.body.is_empty() {
        return outcome;
    }
    let Some(signer) = state.credential_signer.clone() else {
        return outcome;
    };

    let mut doc: Value = match serde_json::from_slice(&outcome.body) {
        Ok(d) => d,
        Err(e) => {
            // The spine built this document a moment ago, so this cannot happen
            // without a bug above. Answer unsigned rather than turning a
            // successful operation into a failure over its envelope.
            tracing::error!(error = %e, "success response is not JSON; returning it unsigned");
            return outcome;
        }
    };
    if doc.get("proof").is_some() {
        return outcome;
    }
    if let Err(e) = signer.sign_operational_response(&mut doc).await {
        tracing::error!(error = %e, "could not sign the response; returning it unsigned");
        return outcome;
    }
    match serde_json::to_vec(&doc) {
        Ok(body) => TrustTaskOutcome {
            status: outcome.status,
            body,
        },
        Err(e) => {
            tracing::error!(error = %e, "could not serialise the signed response");
            outcome
        }
    }
}

/// Dispatch an approved action's stored document — the requester's own, parked
/// when it was submitted — through the handler it was sent to, and sign what
/// comes back (`crate::admin_actions`, VTI-APV-017).
///
/// Past the spine on purpose: freshness and the replay record held the
/// document once, when it arrived (VTI-OPS-024…027), and this service is
/// executing its own stored copy, not accepting the document again. Every
/// check the handler makes runs as it did on submission, against the community
/// as it is now.
async fn dispatch_parked(
    state: &AppState,
    ctx: JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let type_uri = doc.type_uri.to_string();
    let outcome = dispatch_typed(state, &ctx, doc, &type_uri).await;
    sign_response(state, outcome).await
}

/// [`dispatch_parked`] as `exec`'s execution, boxed behind a plain `fn` with a
/// named return type. The executor is reached from a decision, which is one
/// arm of [`dispatch_typed`]; an `async fn` cycle cannot prove its own future
/// `Send`, and a concrete `dyn` return type is what breaks it.
pub(crate) fn dispatch_parked_boxed<'a>(
    state: &'a AppState,
    ctx: JoinAuthCtx,
    doc: TrustTask<Value>,
    exec: crate::admin_actions::Executing,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = TrustTaskOutcome> + Send + 'a>> {
    Box::pin(crate::admin_actions::executing_scope(
        exec,
        dispatch_parked(state, ctx, doc),
    ))
}

/// The routing table, as a plain `fn` returning the chosen handler's future,
/// boxed — never an `async fn` that awaits it.
///
/// An `async fn` holding this `match` is one poll function with every arm's
/// handler future and its temporaries in a single stack frame, live under
/// whichever handler runs: unoptimised, that frame was ~1.1 MiB, and with
/// `vetting-pcs` a `git-ns/*` document overflowed a 2 MiB test thread on Linux
/// (it already had once, after VTI-13 grew the join path, which boxing three
/// arms put off). Here each arm is boxed where it is chosen and this frame is
/// gone before any handler is polled, so the stack a document is dispatched on
/// is the deepest handler's alone, not that plus the sum of all the others.
fn dispatch_typed<'a>(
    state: &'a AppState,
    ctx: &'a JoinAuthCtx,
    doc: TrustTask<Value>,
    type_uri: &'a str,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = TrustTaskOutcome> + Send + 'a>> {
    // Every `rooms/*` operation is authorized against the DID that **signed the
    // request**, so an unsigned one has nothing to authorize and is refused.
    //
    // That refusal is not new: each of these handlers used to call
    // `verify_trust_task_proof` itself and return this same rejection. The
    // verification moved to the spine; the requirement did not move anywhere.
    // Since #1641 the spine refuses a proof-less `rooms/*` document before this
    // arm is reached, because every one of them declares `proof` REQUIRED and
    // `spec_policy_for` is now enforced — so this guard is belt to that brace.
    // It stays: `verified_signer` is `Option`, and defaulting to an empty
    // presenter would authorize a room operation against nobody.
    let rooms_presenter = ctx.verified_signer.as_deref();

    match type_uri {
        jr::JOIN_REQUEST_SUBMIT_TYPE => {
            Box::pin(async move { handle_submit(state, ctx, doc).await })
        }
        jr::JOIN_REQUEST_MANIFEST_TYPE => {
            Box::pin(async move { handle_manifest(state, ctx, doc).await })
        }
        jr::JOIN_REQUEST_STATUS_TYPE => {
            Box::pin(async move { handle_status(state, ctx, doc).await })
        }
        jr::JOIN_REQUEST_WITHDRAW_TYPE => {
            Box::pin(async move { handle_withdraw(state, ctx, doc).await })
        }
        jr::JOIN_REQUEST_SUPPLEMENT_TYPE => {
            Box::pin(async move { handle_supplement(state, ctx, doc).await })
        }
        jr::JOIN_REQUEST_WALLET_SESSION_START_TYPE => {
            Box::pin(async move { wallet_session_tasks::handle_start(state, ctx, doc).await })
        }
        jr::JOIN_REQUEST_WALLET_SESSION_STATUS_TYPE => {
            Box::pin(async move { wallet_session_tasks::handle_status(state, ctx, doc).await })
        }
        jr::MEMBER_SELF_REMOVE_TYPE => {
            Box::pin(async move { handle_self_remove(state, ctx, doc).await })
        }
        mem::MEMBER_VMC_TYPE => Box::pin(async move { handle_member_vmc(state, ctx, doc).await }),
        vta_sdk::protocols::credential_exchange::REQUEST => {
            Box::pin(async move { credential_exchange::handle_request(state, ctx, doc).await })
        }
        vta_sdk::protocols::credential_exchange::PRESENT => {
            Box::pin(
                async move { Box::pin(credential_exchange::handle_present(state, ctx, doc)).await },
            )
        }
        vetting_wire::VETTING_REVOKE_STATEMENT_TYPE => {
            Box::pin(async move { handle_revoke_statement(state, ctx, doc).await })
        }
        vetting_wire::VETTING_VETTER_GRANT_TYPE => {
            Box::pin(async move { handle_vetter_grant(state, ctx, doc).await })
        }
        vetting_wire::VETTING_VETTER_PROFILE_TYPE => {
            Box::pin(async move { handle_vetter_profile(state, ctx, doc).await })
        }
        vetting_wire::VETTING_VETTER_LIST_TYPE => {
            Box::pin(async move { handle_vetter_list(state, ctx, doc).await })
        }
        vetting_wire::VETTING_VETTER_SHOW_TYPE => {
            Box::pin(async move { handle_vetter_show(state, ctx, doc).await })
        }
        vetting_wire::VETTING_VETTER_RESEND_TYPE => {
            Box::pin(async move { handle_vetter_resend(state, ctx, doc).await })
        }
        vetting_wire::VETTING_VETTER_RESEND_0_2_TYPE => {
            Box::pin(async move { handle_vetter_resend_v0_2(state, ctx, doc).await })
        }
        // Hidden vetting's community half (development branch `zkp-pcs`). Four exchanges: a
        // vetter enrolling, a vetter drawing its drip, a vetter asking to vet at an event, an
        // applicant asking for the challenge its proof must bind. Feature-gated, because a build
        // without the suite cannot serve them and answering "unsupported type" is the honest
        // response.
        #[cfg(feature = "vetting-pcs")]
        crate::vetting::pcs_tasks::PCS_ROOT_TYPE => {
            Box::pin(async move { handle_pcs_root(state, ctx, doc).await })
        }
        #[cfg(feature = "vetting-pcs")]
        crate::vetting::pcs_tasks::PCS_TOKENS_TYPE => {
            Box::pin(async move { handle_pcs_tokens(state, ctx, doc).await })
        }
        #[cfg(feature = "vetting-pcs")]
        crate::vetting::pcs_tasks::EVENT_MODE_TYPE => {
            Box::pin(async move { handle_event_mode(state, ctx, doc).await })
        }
        #[cfg(feature = "vetting-pcs")]
        crate::vetting::pcs_tasks::PCS_CHALLENGE_TYPE => {
            Box::pin(async move { handle_pcs_challenge(state, ctx, doc).await })
        }
        // The community's own act of turning hidden vetting on for a criterion. Admin REST with
        // no Trust Task of its own until now; was `POST /vetting/hidden`.
        #[cfg(feature = "vetting-pcs")]
        crate::vetting::pcs_tasks::HIDDEN_PUBLISH_TYPE => {
            Box::pin(async move { handle_hidden_publish(state, ctx, doc).await })
        }
        // Turning it off again, and reading what is stored before an edit.
        #[cfg(feature = "vetting-pcs")]
        crate::vetting::pcs_tasks::HIDDEN_WITHDRAW_TYPE => {
            Box::pin(async move { handle_hidden_withdraw(state, ctx, doc).await })
        }
        #[cfg(feature = "vetting-pcs")]
        crate::vetting::pcs_tasks::HIDDEN_SHOW_TYPE => {
            Box::pin(async move { handle_hidden_show(state, ctx, doc).await })
        }
        // The rooms family. Note what these still do not take: no `ctx`, and no auth
        // claims. A room operation is authorized by the authority chain the room itself
        // issued, never by this service's ACL, roster, or the caller's session —
        // invariant I5 of `docs/05-design-notes/data-rooms.md`, and what makes a room
        // portable.
        //
        // They do take the **verified signer**, which is not a weakening of that: it is
        // a cryptographic fact about the request, not an authority this service confers.
        // The handlers used to derive it themselves; they cannot once they hold a typed
        // payload, because re-deriving the signed bytes from a parsed payload is sound
        // only for a type that round-trips losslessly. See `JoinAuthCtx::
        // verified_signer`.
        // Every `rooms/*` task, in one arm, because the dispatcher *is* the
        // routing table: each registration names a payload type and the
        // framework derives the URI from it. There is no second list to keep in
        // step — which is what this replaces. Eleven hand-written arms had to
        // agree with `ROOMS_DISPATCHED_URIS` by hand, and had already failed to:
        // `rooms/records/curate` was dispatched and named in neither array, so
        // every version hint this service emitted was wrong about it.
        uri if crate::rooms::handlers::serves(uri) => Box::pin(async move {
            // A room operation is authorized against the DID that signed the
            // request, so an unsigned one has nothing to authorize. The spine
            // verified any proof that was present; absent, there is no signer.
            let Some(presenter) = rooms_presenter else {
                return reject_with(&doc, trust_tasks_rs::RejectReason::ProofRequired);
            };
            crate::rooms::handlers::dispatch(state, doc, presenter).await
        }),
        // Every `git-ns/*` task, in one arm, read off that family's own
        // dispatcher as the rooms arm is. Authority there is the signer's git
        // rights, resolved from the VTC's records at execution time — never
        // a bearer token, never a payload member. Every task in the family
        // requires the proof, which the spine has already enforced —
        // including `view` (every served version) and `account/link-status`,
        // whose handlers once fell back to the transport's authenticated
        // sender for a proof their spec allowed to be absent. The sender is
        // still passed through for `account/link-status`'s now-dead fallback
        // (see `git_ns::tasks::caller`); `view` no longer reads it.
        uri if backup_tasks::URIS.contains(&uri) => Box::pin(async move {
            match backup_tasks::dispatch(state, ctx, doc, uri).await {
                Some(outcome) => outcome,
                // `URIS` is exactly what `dispatch` routes.
                None => unreachable!("backup_tasks::URIS names {uri}, which it does not route"),
            }
        }),
        uri if admin_tasks::URIS.contains(&uri) => Box::pin(async move {
            match admin_tasks::dispatch(state, ctx, doc, uri).await {
                Some(outcome) => outcome,
                // `URIS` is exactly what `dispatch` routes.
                None => unreachable!("admin_tasks::URIS names {uri}, which it does not route"),
            }
        }),
        uri if oob_tasks::URIS.contains(&uri) => Box::pin(async move {
            match oob_tasks::dispatch(state, ctx, doc, uri).await {
                Some(outcome) => outcome,
                None => unreachable!("oob_tasks::URIS names {uri}, which it does not route"),
            }
        }),
        uri if auth_tasks::URIS.contains(&uri) => Box::pin(async move {
            match auth_tasks::dispatch(state, ctx, doc, uri).await {
                Some(outcome) => outcome,
                // `URIS` is exactly what `dispatch` routes.
                None => unreachable!("auth_tasks::URIS names {uri}, which it does not route"),
            }
        }),
        uri if install_tasks::URIS.contains(&uri) => Box::pin(async move {
            match install_tasks::dispatch(state, ctx, doc, uri).await {
                Some(outcome) => outcome,
                // `URIS` is exactly what `dispatch` routes.
                None => unreachable!("install_tasks::URIS names {uri}, which it does not route"),
            }
        }),
        uri if recognise_tasks::URIS.contains(&uri) => Box::pin(async move {
            match recognise_tasks::dispatch(state, ctx, doc, uri).await {
                Some(outcome) => outcome,
                // `URIS` is exactly what `dispatch` routes.
                None => {
                    unreachable!("recognise_tasks::URIS names {uri}, which it does not route")
                }
            }
        }),
        #[cfg(feature = "website")]
        uri if website_tasks::URIS.contains(&uri) => Box::pin(async move {
            match website_tasks::dispatch(state, ctx, doc, uri).await {
                Some(outcome) => outcome,
                // `URIS` is exactly what `dispatch` routes.
                None => unreachable!("website_tasks::URIS names {uri}, which it does not route"),
            }
        }),
        uri if admin_passkey_tasks::URIS.contains(&uri) => Box::pin(async move {
            match admin_passkey_tasks::dispatch(state, ctx, doc, uri).await {
                Some(outcome) => outcome,
                // `URIS` is exactly what `dispatch` routes.
                None => {
                    unreachable!("admin_passkey_tasks::URIS names {uri}, which it does not route")
                }
            }
        }),
        uri if whoami_tasks::URIS.contains(&uri) => Box::pin(async move {
            match whoami_tasks::dispatch(state, ctx, doc, uri).await {
                Some(outcome) => outcome,
                // `URIS` is exactly what `dispatch` routes.
                None => unreachable!("whoami_tasks::URIS names {uri}, which it does not route"),
            }
        }),
        uri if admin_session_tasks::URIS.contains(&uri) => Box::pin(async move {
            match admin_session_tasks::dispatch(state, ctx, doc, uri).await {
                Some(outcome) => outcome,
                // `URIS` is exactly what `dispatch` routes.
                None => {
                    unreachable!("admin_session_tasks::URIS names {uri}, which it does not route")
                }
            }
        }),
        uri if signing_key_tasks::URIS.contains(&uri) => Box::pin(async move {
            match signing_key_tasks::dispatch(state, ctx, doc, uri).await {
                Some(outcome) => outcome,
                // `URIS` is exactly what `dispatch` routes.
                None => {
                    unreachable!("signing_key_tasks::URIS names {uri}, which it does not route")
                }
            }
        }),
        uri if surface_tasks::URIS.contains(&uri) => Box::pin(async move {
            match surface_tasks::dispatch(state, ctx, doc, uri).await {
                Some(outcome) => outcome,
                // `URIS` is exactly what `dispatch` routes.
                None => unreachable!("surface_tasks::URIS names {uri}, which it does not route"),
            }
        }),
        uri if policy_tasks::URIS.contains(&uri) => Box::pin(async move {
            match policy_tasks::dispatch(state, ctx, doc, uri).await {
                Some(outcome) => outcome,
                // `URIS` is exactly what `dispatch` routes.
                None => unreachable!("policy_tasks::URIS names {uri}, which it does not route"),
            }
        }),
        uri if storage_tasks::URIS.contains(&uri) => Box::pin(async move {
            match Box::pin(storage_tasks::dispatch(state, ctx, doc, uri)).await {
                Some(outcome) => outcome,
                // `URIS` is exactly what `dispatch` routes.
                None => unreachable!("storage_tasks::URIS names {uri}, which it does not route"),
            }
        }),
        uri if oid4vp_tasks::URIS.contains(&uri) => Box::pin(async move {
            match Box::pin(oid4vp_tasks::dispatch(state, ctx, doc, uri)).await {
                Some(outcome) => outcome,
                // `URIS` is exactly what `dispatch` routes.
                None => unreachable!("oid4vp_tasks::URIS names {uri}, which it does not route"),
            }
        }),
        uri if directory_tasks::URIS.contains(&uri) => Box::pin(async move {
            match Box::pin(directory_tasks::dispatch(state, ctx, doc, uri)).await {
                Some(outcome) => outcome,
                // `URIS` is exactly what `dispatch` routes.
                None => unreachable!("directory_tasks::URIS names {uri}, which it does not route"),
            }
        }),
        uri if community_room_tasks::URIS.contains(&uri) => Box::pin(async move {
            match Box::pin(community_room_tasks::dispatch(state, ctx, doc, uri)).await {
                Some(outcome) => outcome,
                // `URIS` is exactly what `dispatch` routes.
                None => {
                    unreachable!("community_room_tasks::URIS names {uri}, which it does not route")
                }
            }
        }),
        uri if room_admin_tasks::URIS.contains(&uri) => Box::pin(async move {
            match Box::pin(room_admin_tasks::dispatch(state, ctx, doc, uri)).await {
                Some(outcome) => outcome,
                // `URIS` is exactly what `dispatch` routes.
                None => unreachable!("room_admin_tasks::URIS names {uri}, which it does not route"),
            }
        }),
        uri if role_tasks::URIS.contains(&uri) => Box::pin(async move {
            match Box::pin(role_tasks::dispatch(state, ctx, doc, uri)).await {
                Some(outcome) => outcome,
                // `URIS` is exactly what `dispatch` routes.
                None => unreachable!("role_tasks::URIS names {uri}, which it does not route"),
            }
        }),
        uri if community_tasks::URIS.contains(&uri) => Box::pin(async move {
            match community_tasks::dispatch(state, ctx, doc, uri).await {
                Some(outcome) => outcome,
                // `URIS` is exactly what `dispatch` routes.
                None => {
                    unreachable!("community_tasks::URIS names {uri}, which it does not route")
                }
            }
        }),
        uri if step_up_passkey_tasks::URIS.contains(&uri) => Box::pin(async move {
            match step_up_passkey_tasks::dispatch(state, ctx, doc, uri).await {
                Some(outcome) => outcome,
                // `URIS` is exactly what `dispatch` routes.
                None => {
                    unreachable!("step_up_passkey_tasks::URIS names {uri}, which it does not route")
                }
            }
        }),
        uri if step_up_approver_tasks::URIS.contains(&uri) => Box::pin(async move {
            match step_up_approver_tasks::dispatch(state, ctx, doc, uri).await {
                Some(outcome) => outcome,
                // `URIS` is exactly what `dispatch` routes.
                None => {
                    unreachable!(
                        "step_up_approver_tasks::URIS names {uri}, which it does not route"
                    )
                }
            }
        }),
        uri if capability_module_tasks::URIS.contains(&uri) => Box::pin(async move {
            match capability_module_tasks::dispatch(state, ctx, doc, uri).await {
                Some(outcome) => outcome,
                // `URIS` is exactly what `dispatch` routes.
                None => unreachable!(
                    "capability_module_tasks::URIS names {uri}, which it does not route"
                ),
            }
        }),
        uri if admission_tasks::URIS.contains(&uri) => Box::pin(async move {
            match admission_tasks::dispatch(state, ctx, doc, uri).await {
                Some(outcome) => outcome,
                // `URIS` is exactly what `dispatch` routes.
                None => unreachable!("admission_tasks::URIS names {uri}, which it does not route"),
            }
        }),
        uri if member_tasks::URIS.contains(&uri) => Box::pin(async move {
            match member_tasks::dispatch(state, ctx, doc, uri).await {
                Some(outcome) => outcome,
                // `URIS` is exactly what `dispatch` routes.
                None => unreachable!("member_tasks::URIS names {uri}, which it does not route"),
            }
        }),
        uri if crate::git_ns::tasks::serves(uri) => Box::pin(async move {
            crate::git_ns::tasks::dispatch(
                state,
                doc,
                ctx.verified_signer.as_deref(),
                ctx.sender_did.as_deref(),
            )
            .await
        }),
        PERSONHOOD_CHALLENGE_TYPE => {
            Box::pin(async move { handle_personhood_challenge(state, ctx, doc).await })
        }
        PERSONHOOD_ASSERT_TYPE => {
            Box::pin(async move { handle_personhood_assert(state, ctx, doc).await })
        }
        // The admin-facing member verbs. Each is authorized from the verified
        // signer's ACL entry — never from a bearer token, which this endpoint
        // does not read — see [`admin_signer`].
        MEMBER_CREDENTIALS_TYPE => {
            Box::pin(async move { handle_member_credentials(state, ctx, doc).await })
        }
        MEMBER_UPDATE_TYPE => Box::pin(async move { handle_member_update(state, ctx, doc).await }),
        MEMBER_ADMIN_REMOVE_TYPE => {
            Box::pin(async move { handle_member_admin_remove(state, ctx, doc).await })
        }
        MEMBER_PURGE_TYPE => Box::pin(async move { handle_member_purge(state, ctx, doc).await }),
        JOIN_DECIDE_TYPE => Box::pin(async move { handle_join_decide(state, ctx, doc).await }),
        COMMUNITY_PROFILE_UPDATE_TYPE => {
            Box::pin(async move { handle_community_profile_update(state, ctx, doc).await })
        }
        CONFIG_EXPORT_TYPE => Box::pin(async move { handle_config_export(state, ctx, doc).await }),
        CONFIG_IMPORT_TYPE => Box::pin(async move { handle_config_import(state, ctx, doc).await }),
        ENDORSEMENT_TYPE_REGISTER_TYPE => {
            Box::pin(async move { handle_endorsement_type_register(state, ctx, doc).await })
        }
        ENDORSEMENT_TYPE_DELETE_TYPE => {
            Box::pin(async move { handle_endorsement_type_delete(state, ctx, doc).await })
        }
        BACKUP_EXPORT_TYPE => Box::pin(async move { handle_backup_export(state, ctx, doc).await }),
        ACL_GRANT_TYPE => Box::pin(async move { acl_tasks::handle_grant(state, ctx, doc).await }),
        ACL_CHANGE_ROLE_TYPE => {
            Box::pin(async move { acl_tasks::handle_change_role(state, ctx, doc).await })
        }
        ACL_SHOW_TYPE => Box::pin(async move { acl_tasks::handle_show(state, ctx, doc).await }),
        ACL_LIST_TYPE => Box::pin(async move { acl_tasks::handle_list(state, ctx, doc).await }),
        ACL_UPDATE_TYPE => Box::pin(async move { acl_tasks::handle_update(state, ctx, doc).await }),
        ACL_REVOKE_TYPE => Box::pin(async move { acl_tasks::handle_revoke(state, ctx, doc).await }),
        ACL_GRANT_V0_2_TYPE => {
            Box::pin(async move { acl_tasks::handle_grant_v0_2(state, ctx, doc).await })
        }
        ACL_CHANGE_ROLE_V0_2_TYPE => {
            Box::pin(async move { acl_tasks::handle_change_role_v0_2(state, ctx, doc).await })
        }
        ACL_SHOW_V0_2_TYPE => {
            Box::pin(async move { acl_tasks::handle_show_v0_2(state, ctx, doc).await })
        }
        ACL_LIST_V0_2_TYPE => {
            Box::pin(async move { acl_tasks::handle_list_v0_2(state, ctx, doc).await })
        }
        ACL_UPDATE_V0_2_TYPE => {
            Box::pin(async move { acl_tasks::handle_update_v0_2(state, ctx, doc).await })
        }
        ACL_REVOKE_V0_2_TYPE => {
            Box::pin(async move { acl_tasks::handle_revoke_v0_2(state, ctx, doc).await })
        }
        ACL_SWAP_KEY_TYPE => {
            Box::pin(async move { acl_tasks::handle_swap_key(state, ctx, doc).await })
        }
        STEP_UP_APPROVE_RESPONSE_TYPE => {
            Box::pin(async move { handle_step_up_approve_response(state, ctx, doc).await })
        }
        STEP_UP_APPROVE_RESPONSE_V0_5_TYPE => {
            Box::pin(async move { handle_step_up_approve_response_v0_5(state, ctx, doc).await })
        }
        STEP_UP_APPROVE_RESPONSE_V0_6_TYPE => {
            Box::pin(async move { handle_step_up_approve_response_v0_6(state, ctx, doc).await })
        }
        // Boxed: a decision that completes an action re-enters this dispatcher
        // with the parked document.
        crate::acl::admin_consent::DECISION_TYPE
        | crate::acl::admin_consent::DECISION_V0_2_TYPE => {
            Box::pin(async move { action_tasks::handle_decision(state, ctx, doc).await })
        }
        event_tasks::SUBSCRIBE_TYPE | event_tasks::SUBSCRIBE_V0_2_TYPE => {
            Box::pin(async move { event_tasks::handle_subscribe(state, ctx, doc).await })
        }
        uri if action_tasks::URIS.contains(&uri) => Box::pin(async move {
            match Box::pin(action_tasks::dispatch(state, ctx, doc, uri)).await {
                Some(outcome) => outcome,
                // `URIS` is exactly what `dispatch` routes.
                None => unreachable!("action_tasks::URIS names {uri}, which it does not route"),
            }
        }),
        discovery::DISCOVERY_V0_3_TYPE => Box::pin(async move { discovery::handle(ctx, doc) }),
        other => Box::pin(async move { unsupported_type_or_version(&doc, other) }),
    }
}

/// The spine's document-level gate: VTI-OPS-020 (a proof by the issuer),
/// VTI-OPS-021 / -093 (the same requirements on every transport), VTI-OPS-024
/// (the acceptance window) and VTI-OPS-025…027 (the replay record).
///
/// # What this module used to say, and why it no longer does
///
/// It held one test, `a_transport_authenticated_task_declares_a_proof_it_does_
/// not_carry`, whose assertion was deliberately inverted: it recorded that
/// `join-requests/submit` declares a proof REQUIRED *while this service accepts
/// it without one*, so that "the next person to reach for `spec_policy_for` as
/// an enforcement gate meets it as a failing test rather than as a total
/// outage."
///
/// The warning was right about the consequence and wrong about the conclusion.
/// Three documents refuse the leniency outright — VTI-OPS-021, VTI-OPS-093, and
/// the DIDComm binding's own §5 ("a *Trust Task specification* that declares
/// `proof` as REQUIRED overrides this binding-level allowance"). So the gate is
/// now the specification's, and the outage it predicted was real for exactly
/// one client: `openvtc-core`, which sent five of these documents unsigned.
///
/// #1641 met that by gating the refusal behind `[trust_tasks]
/// require_declared_proof`, default `false`, whose rustdoc carried an exact
/// removal condition — "when `openvtc-core` signs the five documents above, the
/// default flips and this field goes with it". openvtc#371 signs them, so the
/// gate is gone and every test here now asserts against the requirement
/// directly, on all three transports.
///
/// See `docs/05-design-notes/vtc-trust-task-proof-enforcement.md`.
#[cfg(test)]
mod spine_proof_tests {
    use super::*;
    use crate::test_support::{TEST_VTC_DID, build_test_vtc};
    use serde_json::json;

    // One holder: a `did:key` and the private key behind it, minted the same
    // way the rooms fixtures mint theirs.
    use vti_rooms_dtg::test_support::Party as Holder;

    fn holder() -> Holder {
        Holder::new()
    }

    /// The unsigned document, exactly as it goes on the wire minus the proof.
    /// `build_unsigned` is the SDK's own builder, so `issuer`, `recipient` and
    /// `issuedAt` are set the way every real producer sets them and the tests
    /// vary only what they mean to.
    fn unsigned(h: &Holder, uri: &str, payload: Value) -> TrustTask<Value> {
        vta_sdk::trust_task_sign::build_unsigned(uri, payload, &h.did, TEST_VTC_DID)
            .expect("build the document")
    }

    async fn signed(h: &Holder, doc: TrustTask<Value>) -> TrustTask<Value> {
        let mut doc = doc;
        let key = vta_sdk::trust_task_sign::HolderKey::from_did_key(&h.did, &h.secret_multibase)
            .expect("a did:key names its own verification method");
        vta_sdk::trust_task_sign::sign_in_place_with(&mut doc, &key)
            .await
            .expect("sign the document");
        doc
    }

    /// The `code` of the `trust-task-error` an outcome carries, or `None` when
    /// the outcome is not an error document.
    fn error_code(out: &TrustTaskOutcome) -> Option<String> {
        let doc: Value = serde_json::from_slice(&out.body).ok()?;
        doc.pointer("/payload/code")?.as_str().map(str::to_string)
    }

    async fn dispatch(state: &AppState, doc: &TrustTask<Value>) -> TrustTaskOutcome {
        let body = serde_json::to_vec(doc).expect("a document serialises");
        dispatch_trust_task_core(state, &JoinAuthCtx::rest(), &body).await
    }

    /// The URI these tests drive. `vtc/join-requests/status/0.1` declares
    /// `proof` REQUIRED and needs no seeded community state to reach its
    /// handler, so what the spine does is the only thing that varies.
    const UNDER_TEST: &str = jr::JOIN_REQUEST_STATUS_TYPE;

    /// The premise the rest of this module rests on. If the registry ever
    /// relaxes the declaration, these tests are asserting nothing and this one
    /// says so first.
    #[test]
    fn the_task_under_test_declares_a_proof_required() {
        let policy = trust_tasks_rs::schema_index::spec_policy_for(UNDER_TEST)
            .expect("the task under test has a published spec policy");
        assert!(
            policy.is_proof_required,
            "{UNDER_TEST} no longer declares proof REQUIRED — these tests now \
             assert nothing, and the design note should be re-read"
        );
    }

    /// **VTI-OPS-020 / VTI-OPS-021.** A task whose specification declares
    /// `proof` REQUIRED is refused when it carries none, with the framework's
    /// own code for exactly that.
    #[tokio::test]
    async fn vti_ops_020_a_proof_required_task_is_refused_without_a_proof() {
        let tv = build_test_vtc().await;
        let h = holder();
        let out = dispatch(&tv.state, &unsigned(&h, UNDER_TEST, json!({}))).await;

        assert_eq!(
            error_code(&out).as_deref(),
            Some("proofRequired"),
            "SPEC §7.2 item 7 names the code: {}",
            String::from_utf8_lossy(&out.body)
        );
    }

    /// …and accepted with one. "Accepted" here means the spine let it through
    /// to the handler, which is the whole of what the spine decides — the
    /// handler then answers for a status poll on a request that does not
    /// exist, and that answer is not this module's business.
    #[tokio::test]
    async fn vti_ops_020_the_same_document_is_accepted_once_it_is_signed() {
        let tv = build_test_vtc().await;
        let h = holder();
        let doc = signed(&h, unsigned(&h, UNDER_TEST, json!({}))).await;
        let out = dispatch(&tv.state, &doc).await;

        assert_ne!(
            error_code(&out).as_deref(),
            Some("proofRequired"),
            "a signed document must reach its handler: {}",
            String::from_utf8_lossy(&out.body)
        );
        assert_ne!(
            error_code(&out).as_deref(),
            Some("proofInvalid"),
            "the spine must accept a proof it can verify: {}",
            String::from_utf8_lossy(&out.body)
        );
    }

    /// **VTI-OPS-020.** SPEC §4.7: the proof's `verificationMethod` "MUST
    /// resolve to verification material controlled by the *party* identified by
    /// the document's `issuer`". A valid signature by some *other* holder is
    /// not a proof by the issuer, and before #1641 it satisfied the
    /// requirement — establishing only that somebody signed something, which is
    /// not what `verified_signer` is read as downstream.
    #[tokio::test]
    async fn vti_ops_020_a_proof_by_a_key_the_issuer_does_not_control_is_refused() {
        let tv = build_test_vtc().await;
        let issuer = holder();
        let impostor = holder();

        // Addressed from `issuer`, signed by `impostor`.
        let doc = signed(&impostor, unsigned(&issuer, UNDER_TEST, json!({}))).await;
        let out = dispatch(&tv.state, &doc).await;

        assert_eq!(
            error_code(&out).as_deref(),
            Some("proofInvalid"),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
    }

    /// **VTI-OPS-024.** A document issued longer ago than the acceptance
    /// window is outside it, and `expired` is the code for a document that was
    /// once acceptable and no longer is.
    #[tokio::test]
    async fn vti_ops_024_an_issued_at_older_than_the_window_is_refused() {
        let tv = build_test_vtc().await;
        let h = holder();
        let mut doc = unsigned(&h, UNDER_TEST, json!({}));
        doc.issued_at = Some(chrono::Utc::now() - chrono::TimeDelta::hours(2));
        let doc = signed(&h, doc).await;

        assert_eq!(
            error_code(&dispatch(&tv.state, &doc).await).as_deref(),
            Some("expired"),
        );
    }

    /// **VTI-OPS-024**, the other end of the window, and the skew tolerance
    /// that bounds it. SPEC §7.2 item 13 makes a future-dated document
    /// `malformedRequest` rather than `expired`: it was never acceptable, so
    /// telling the producer to wait would be wrong — it must reissue.
    #[tokio::test]
    async fn vti_ops_024_a_future_dated_issued_at_is_malformed_not_expired() {
        let tv = build_test_vtc().await;
        let h = holder();
        let mut doc = unsigned(&h, UNDER_TEST, json!({}));
        doc.issued_at = Some(chrono::Utc::now() + chrono::TimeDelta::minutes(30));
        let doc = signed(&h, doc).await;

        assert_eq!(
            error_code(&dispatch(&tv.state, &doc).await).as_deref(),
            Some("malformedRequest"),
        );
    }

    /// …and a document inside the skew tolerance is not. 30 seconds ahead of
    /// this consumer's clock is an ordinary clock disagreement, and refusing it
    /// would make the window depend on whose NTP is better.
    #[tokio::test]
    async fn vti_ops_024_a_document_inside_the_skew_tolerance_is_accepted() {
        let tv = build_test_vtc().await;
        let h = holder();
        let mut doc = unsigned(&h, UNDER_TEST, json!({}));
        doc.issued_at = Some(chrono::Utc::now() + chrono::TimeDelta::seconds(30));
        let doc = signed(&h, doc).await;
        let out = dispatch(&tv.state, &doc).await;

        assert_ne!(
            error_code(&out).as_deref(),
            Some("malformedRequest"),
            "60s of skew is SPEC §4.2's own tolerance: {}",
            String::from_utf8_lossy(&out.body)
        );
    }

    /// Give `h` an open join request, so a status poll from them **succeeds**.
    ///
    /// The replay tests below need that: the spine releases a claim whose
    /// dispatch failed — deliberately, so a corrected resend under the same
    /// `id` is not refused as a conflict for the rest of the retention window
    /// — and a test driving a failing task would therefore assert against a
    /// record that was never kept.
    async fn seed_open_request(state: &AppState, h: &Holder) {
        let request =
            crate::join::JoinRequest::new(h.did.clone(), serde_json::json!({ "vp": "x" }));
        crate::join::storage::store_join_request(&state.join_requests_ks, &request)
            .await
            .expect("seed an open join request");
    }

    /// **VTI-OPS-020's replay half (VTI-OPS-025…027), SPEC §7.2 item 11.** The
    /// same document delivered twice executes once. A duplicate is answered
    /// with the original result rather than an error — "in no case is a
    /// duplicate reported as `taskFailed`; the task did not fail, it already
    /// happened" — so the assertion is that the second answer is the first.
    ///
    /// Compared as parsed JSON rather than as bytes: the duplicate path
    /// re-serialises the recorded `Value`, and `serde_json` without
    /// `preserve_order` alphabetises a `Map`'s keys, so the two are the same
    /// document and not the same bytes.
    #[tokio::test]
    async fn vti_ops_025_a_replayed_document_is_answered_not_executed_again() {
        let tv = build_test_vtc().await;
        let h = holder();
        seed_open_request(&tv.state, &h).await;
        let doc = signed(&h, unsigned(&h, UNDER_TEST, json!({}))).await;

        let first = dispatch(&tv.state, &doc).await;
        assert!(
            first.status.is_success(),
            "the fixture must reach a succeeding handler, or the claim is \
             released and the second dispatch runs fresh: {}",
            String::from_utf8_lossy(&first.body)
        );

        let second = dispatch(&tv.state, &doc).await;
        assert_eq!(first.status, second.status);

        let as_json = |out: &TrustTaskOutcome| -> Value {
            serde_json::from_slice(&out.body).expect("the answer is a document")
        };
        assert_eq!(
            as_json(&first),
            as_json(&second),
            "a redelivery is the same document, so it gets the same answer"
        );
    }

    /// **SPEC §7.2 item 11's conflict half.** A *different* document under an
    /// already-spent `id` is `idConflict`, never absorbed as a retry — which is
    /// why the record is keyed by digest rather than by `id` alone.
    #[tokio::test]
    async fn vti_ops_025_a_different_document_reusing_an_id_is_a_conflict() {
        let tv = build_test_vtc().await;
        let h = holder();
        seed_open_request(&tv.state, &h).await;

        let first = signed(&h, unsigned(&h, UNDER_TEST, json!({}))).await;
        let out = dispatch(&tv.state, &first).await;
        assert!(
            out.status.is_success(),
            "{}",
            String::from_utf8_lossy(&out.body)
        );

        // Same `id`, different content: a different document, not a retry.
        let mut second = unsigned(&h, UNDER_TEST, json!({}));
        second.id = first.id.clone();
        second.issued_at = Some(chrono::Utc::now() - chrono::TimeDelta::seconds(1));
        let second = signed(&h, second).await;

        assert_eq!(
            error_code(&dispatch(&tv.state, &second).await).as_deref(),
            Some("idConflict"),
        );
    }

    /// **VTI-OPS-024 + VTI-OPS-026.** Acceptance and retention are one bound.
    /// `record_expiry` takes a producer-supplied `expiresAt` verbatim, so
    /// without the cap a document stamped ten years out would pin its `id`
    /// for ten years — retention long past the last instant the document could
    /// still be accepted, crowding out the records that can be drawn on.
    #[test]
    fn vti_ops_026_retention_is_capped_at_the_end_of_the_acceptance_window() {
        let h = holder();
        let now = chrono::Utc::now();
        let mut doc = unsigned(&h, UNDER_TEST, json!({}));
        doc.issued_at = Some(now);
        doc.expires_at = Some(now + chrono::TimeDelta::days(3650));

        let policy = freshness_policy();
        let until = retain_until(&doc, now).expect("a document with an issuedAt is boundable");

        assert_eq!(
            until,
            now + policy.max_age.expect("the window is set") + policy.skew,
            "retention may not outlast the window in which the document is \
             still executable"
        );
    }

    /// …and it never moves the instant *earlier* than that window. Shortening
    /// retention below acceptance is the direction §7.2 forbids: a replay
    /// arriving while the document is still acceptable, with its record
    /// already dropped, executes twice.
    #[test]
    fn vti_ops_026_a_short_expiry_does_not_shorten_retention_below_the_window() {
        let h = holder();
        let now = chrono::Utc::now();
        let mut doc = unsigned(&h, UNDER_TEST, json!({}));
        doc.issued_at = Some(now);
        doc.expires_at = Some(now + chrono::TimeDelta::seconds(30));

        let until = retain_until(&doc, now).expect("boundable");
        assert_eq!(
            until,
            now + chrono::TimeDelta::seconds(30),
            "a producer that says its document lapses in 30s has said the \
             record may be dropped then — it is unacceptable after that too"
        );
    }

    /// **VTI-OPS-021 / VTI-OPS-093.** One unsigned document, offered on every
    /// transport this service accepts, refused on every one of them.
    ///
    /// # Why this replaced three tests, and why the conclusion moved
    ///
    /// #1641 shipped this ground as three: a REST document was refused; the
    /// same document over DIDComm, carrying an authcrypt sender, was
    /// **accepted** under the shipped default; and it was refused once the
    /// operator set `[trust_tasks] require_declared_proof = true`. The middle
    /// one existed to pin a transitional allowance, so that flipping the
    /// default would be "a visible change to a test rather than a silent
    /// change in behaviour". This is that change, made visible.
    ///
    /// The allowance had exactly one reason: `openvtc-core` built
    /// `join-requests/{submit,status}`, `members/{self-remove,vmc}` and
    /// `members/personhood/assert` with no proof attached. openvtc#371 signs
    /// all five, which is the removal condition #1659 wrote down. So the
    /// assertion is not relaxed to match the code — it is inverted to match a
    /// requirement that never had a transport term in it: "a node MUST apply
    /// the same document requirements on every transport", and a transport that
    /// authenticates its sender "MUST NOT be treated as relieving a producer of
    /// addressing or signing the document it sends".
    ///
    /// Driving all three transports from one body is the point rather than
    /// thoroughness: the old tests each asserted about a single transport, so
    /// between them they could have agreed with VTI-OPS-021 on two and
    /// disagreed on the third without anything noticing.
    #[tokio::test]
    async fn vti_ops_021_a_missing_proof_is_refused_on_every_transport() {
        let tv = build_test_vtc().await;
        let h = holder();
        let body =
            serde_json::to_vec(&unsigned(&h, UNDER_TEST, json!({}))).expect("serialise document");

        for ctx in [
            JoinAuthCtx::rest(),
            JoinAuthCtx::didcomm(h.did.clone()),
            // TSP, whose sender VID is authenticated the way authcrypt's sender
            // is. It has no constructor — the messaging bridge builds one
            // inline — so this is that shape, written out.
            JoinAuthCtx {
                transport: JoinTransport::Tsp,
                sender_did: Some(h.did.clone()),
                verified_signer: None,
            },
        ] {
            let transport = ctx.transport.as_str();
            let out = dispatch_trust_task_core(&tv.state, &ctx, &body).await;

            assert_eq!(
                error_code(&out).as_deref(),
                Some("proofRequired"),
                "{transport}: an authenticated sender is not a proof by the issuer: {}",
                String::from_utf8_lossy(&out.body),
            );
        }
    }

    /// …and the refusal is about the missing proof, not about the transport.
    ///
    /// Without this, the test above would pass equally on a spine that refused
    /// every DIDComm and TSP document outright — which is a way of satisfying
    /// "the same requirements on every transport" that takes the community
    /// offline. Each iteration signs a fresh document: the same one dispatched
    /// three times is a replay, and the second answer would be a replay of the
    /// first rather than a new decision.
    #[tokio::test]
    async fn vti_ops_021_the_same_document_signed_is_accepted_on_every_transport() {
        let tv = build_test_vtc().await;
        let h = holder();

        for ctx in [
            JoinAuthCtx::rest(),
            JoinAuthCtx::didcomm(h.did.clone()),
            JoinAuthCtx {
                transport: JoinTransport::Tsp,
                sender_did: Some(h.did.clone()),
                verified_signer: None,
            },
        ] {
            let transport = ctx.transport.as_str();
            let doc = signed(&h, unsigned(&h, UNDER_TEST, json!({}))).await;
            let body = serde_json::to_vec(&doc).expect("serialise document");
            let out = dispatch_trust_task_core(&tv.state, &ctx, &body).await;

            assert_ne!(
                error_code(&out).as_deref(),
                Some("proofRequired"),
                "{transport}: a signed document must reach its handler: {}",
                String::from_utf8_lossy(&out.body),
            );
            assert_ne!(
                error_code(&out).as_deref(),
                Some("proofInvalid"),
                "{transport}: the spine must accept a proof it can verify: {}",
                String::from_utf8_lossy(&out.body),
            );
        }
    }

    /// Keyring VTI-09: a bare payload — no document around it — is refused as
    /// `malformedRequest`, naming the missing `id`, on every transport. This is
    /// the answer the VTA gives too (`vta-service`'s `keyring_vti_09_27`
    /// tests); the finding was that the two disagreed.
    #[tokio::test]
    async fn vti_09_a_bare_payload_is_refused_as_malformed_on_every_transport() {
        let tv = build_test_vtc().await;
        let h = holder();
        let body = serde_json::to_vec(&json!({ "requestId": "urn:uuid:bare" })).unwrap();

        for ctx in [
            JoinAuthCtx::rest(),
            JoinAuthCtx::didcomm(h.did.clone()),
            JoinAuthCtx {
                transport: JoinTransport::Tsp,
                sender_did: Some(h.did.clone()),
                verified_signer: None,
            },
        ] {
            let transport = ctx.transport.as_str();
            let out = dispatch_trust_task_core(&tv.state, &ctx, &body).await;
            let doc: Value = serde_json::from_slice(&out.body).expect("an error document");
            assert_eq!(
                error_code(&out).as_deref(),
                Some("malformedRequest"),
                "{transport}: {doc}"
            );
            assert!(
                doc.pointer("/payload/message")
                    .and_then(Value::as_str)
                    .is_some_and(|m| m.contains("missing field `id`")),
                "{transport}: {doc}"
            );
        }
    }

    /// The rooms family, where the requirement was already enforced by the
    /// arms in `dispatch_typed` before the spine took it on. Kept because the
    /// arms' guard is now belt to the spine's brace, and a specification that
    /// relaxed the declaration would leave that guard standing alone.
    #[test]
    fn every_rooms_task_declares_the_proof_its_arm_requires() {
        for uri in vti_rooms::wire::ROOMS_DISPATCHED_URIS {
            let policy = trust_tasks_rs::schema_index::spec_policy_for(uri)
                .unwrap_or_else(|| panic!("{uri} has no published spec policy"));
            assert!(
                policy.is_proof_required,
                "{uri}: its arm refuses without a verified signer, so the \
                 specification had better agree that one is required"
            );
        }
    }

    /// Every dispatched URI whose specification declares no proof — named here
    /// with the reason an unsigned caller is still refused, so that adding (or
    /// removing) a task from this list is a decision somebody took rather than
    /// a side effect of editing a specification.
    ///
    /// A URI belongs here only because its *handler* enforces identity some
    /// other way — an ACL row, a WebAuthn assertion, a bearer refresh token —
    /// not because nobody got round to it. [`the_dispatched_set_declares_the_proofs_the_design_note_records`]
    /// fails the build the moment a listed URI starts declaring a proof (a
    /// stale entry) or an unlisted one stops (an unreasoned one).
    const DISPATCHED_WITHOUT_PROOF: &[(&str, &str)] = &[
        (
            jr::JOIN_REQUEST_MANIFEST_TYPE,
            "a public read of the community's join criteria; names no identity to authorize",
        ),
        (
            vetting_wire::VETTING_VETTER_LIST_TYPE,
            "a public read of the vetter registry",
        ),
        (
            role_tasks::LIST_TYPE,
            "reads the role vocabulary; the handler authorizes from the signer's own entry, so an unsigned caller is refused regardless",
        ),
        (
            role_tasks::SHOW_TYPE,
            "reads one role; the handler authorizes from the signer's own entry, so an unsigned caller is refused regardless",
        ),
        (
            storage_tasks::LIST_TYPE,
            "reads the storage configs; the handler authorizes vtc.rooms.admin from the signer's own entry, so an unsigned caller is refused regardless",
        ),
        (
            storage_tasks::GET_TYPE,
            "reads one storage config; the handler authorizes vtc.rooms.admin from the signer's own entry, so an unsigned caller is refused regardless",
        ),
        (
            storage_tasks::PROBE_TYPE,
            "probes one storage config; the handler authorizes vtc.rooms.admin from the signer's own entry, so an unsigned caller is refused regardless",
        ),
        (
            room_admin_tasks::GET_TYPE,
            "reads one room's storage, limits and usage; the handler authorizes vtc.rooms.admin from the signer's own entry, so an unsigned caller is refused regardless",
        ),
        (
            community_room_tasks::LIST_TYPE,
            "lists the rooms the community owns; the handler authorizes vtc.rooms.manage from the signer's own entry, so an unsigned caller is refused regardless",
        ),
        (
            community_room_tasks::GET_TYPE,
            "reads one room the community owns; the handler authorizes vtc.rooms.manage from the signer's own entry, so an unsigned caller is refused regardless",
        ),
        (
            community_room_tasks::LIST_V0_2_TYPE,
            "lists the rooms the community owns, with their details; the handler authorizes vtc.rooms.manage from the signer's own entry, so an unsigned caller is refused regardless",
        ),
        (
            community_room_tasks::GET_V0_2_TYPE,
            "reads one room the community owns, with its details; the handler authorizes vtc.rooms.manage from the signer's own entry, so an unsigned caller is refused regardless",
        ),
        (
            room_admin_tasks::USAGE_TYPE,
            "reads rooms' usage; the handler authorizes vtc.rooms.admin from the signer's own entry, so an unsigned caller is refused regardless",
        ),
        (
            vetting_wire::VETTING_VETTER_SHOW_TYPE,
            "a public read of the vetter registry",
        ),
        (
            admin_tasks::AUDIT_VERIFY_TYPE,
            "a read; the handler's admin bearer/ACL check refuses an unsigned caller regardless",
        ),
        (
            install_tasks::CLAIM_START_TYPE,
            "first-admin onboarding, before any ACL entry exists to sign with; the one-time install token the handler requires is the credential",
        ),
        (
            install_tasks::CLAIM_FINISH_TYPE,
            "first-admin onboarding, before any ACL entry exists to sign with; the one-time install token the handler requires is the credential",
        ),
        (
            install_tasks::CLAIM_START_V0_3_TYPE,
            "opens a claim and changes nothing; the install token and its claim code are the gate, and control of the founder's DID is proven by the finish, whose proof the specification requires",
        ),
        (
            install_tasks::BOOTSTRAP_TYPE,
            "first-admin onboarding, before any ACL entry exists to sign with; the one-time install token the handler requires is the credential",
        ),
        (
            recognise_tasks::CHALLENGE_TYPE,
            "names no identity to authorize — it is the first message of the cross-community handshake",
        ),
        (
            recognise_tasks::RECOGNISE_TYPE,
            "the peer VTC's answer is authenticated via the Trust Registry lookup the handler performs, not a request-level proof",
        ),
        (
            discovery::DISCOVERY_V0_3_TYPE,
            "a public discovery read; names no identity to authorize",
        ),
        (
            ACL_SHOW_TYPE,
            "reads the caller's own ACL row; the handler authorizes from the signer's entry, so an unsigned caller is refused regardless",
        ),
        (
            ACL_LIST_TYPE,
            "reads ACL rows; the handler authorizes from the signer's own entry, so an unsigned caller is refused regardless",
        ),
        (
            ACL_SHOW_V0_2_TYPE,
            "reads an ACL row; the handler authorizes from the signer's own entry, so an unsigned caller is refused regardless",
        ),
        (
            ACL_LIST_V0_2_TYPE,
            "reads ACL rows; the handler authorizes from the signer's own entry, so an unsigned caller is refused regardless",
        ),
        (
            member_tasks::RELATIONSHIPS_LIST_TYPE,
            "a read; the handler refuses an unsigned caller regardless",
        ),
        (
            member_tasks::ENDORSEMENTS_LIST_TYPE,
            "a read; the handler refuses an unsigned caller regardless",
        ),
        (
            member_tasks::ENDORSEMENTS_SHOW_TYPE,
            "a read; the handler refuses an unsigned caller regardless",
        ),
        (
            STEP_UP_APPROVE_RESPONSE_TYPE,
            "its gate is the WebAuthn assertion it carries — the handler still requires the approver's assertionMethod proof via `verify_approval_proof`, which is not the request-level `proof` this flag governs",
        ),
        (
            step_up_passkey_tasks::REDEEM_START_TYPE,
            "redeems a single-use invite token; the handler requires a proof regardless (VTI-APV passkey redemption), the token itself being the thing that makes an unsigned attempt refusable",
        ),
        (
            step_up_passkey_tasks::REDEEM_FINISH_TYPE,
            "redeems a single-use invite token; the handler requires a proof regardless (VTI-APV passkey redemption), the token itself being the thing that makes an unsigned attempt refusable",
        ),
        (
            admin_tasks::DIAGNOSTICS_TYPE,
            "a read; the handler's admin bearer/ACL check refuses an unsigned caller regardless",
        ),
        (
            admin_tasks::SYNC_JOBS_LIST_TYPE,
            "a read; the handler's admin bearer/ACL check refuses an unsigned caller regardless",
        ),
        (
            admin_tasks::RECORDS_LIST_TYPE,
            "a read; the handler's admin bearer/ACL check refuses an unsigned caller regardless",
        ),
        (
            admin_tasks::CONFIG_SHOW_TYPE,
            "a read; the handler's admin bearer/ACL check refuses an unsigned caller regardless",
        ),
        (
            admin_tasks::INVITES_LIST_TYPE,
            "a read; the handler's admin bearer/ACL check refuses an unsigned caller regardless",
        ),
        (
            community_tasks::PROFILE_SHOW_TYPE,
            "a public/community read; the handler refuses an unsigned caller where that read is gated at all",
        ),
        (
            community_tasks::CEREMONIES_LIST_TYPE,
            "a community read; the handler refuses an unsigned caller where that read is gated at all",
        ),
        (
            community_tasks::DIRECTORY_QUERY_TYPE,
            "a community read; the handler refuses an unsigned caller where that read is gated at all",
        ),
        (
            directory_tasks::FIELDS_LIST_TYPE,
            "reads the directory schema; the handler authorizes from the signer's own standing, so an unsigned caller is refused regardless",
        ),
        (
            directory_tasks::CARD_SHOW_TYPE,
            "reads the signer's own card; the handler matches the signer to their membership, so an unsigned caller is refused regardless",
        ),
        (
            directory_tasks::ENTRIES_LIST_TYPE,
            "reads the directory projected for the signer; the handler authorizes from the signer's own standing, so an unsigned caller is refused regardless",
        ),
        (
            directory_tasks::ENTRIES_SHOW_TYPE,
            "reads one entry projected for the signer; the handler authorizes from the signer's own standing, so an unsigned caller is refused regardless",
        ),
        (
            community_tasks::ENDORSEMENT_TYPES_LIST_TYPE,
            "a community read; the handler refuses an unsigned caller where that read is gated at all",
        ),
        (
            community_tasks::RECOGNITION_CHECK_TYPE,
            "a community read; the handler refuses an unsigned caller where that read is gated at all",
        ),
        (
            community_tasks::MEMBERS_LIST_TYPE,
            "an admin read; the handler's admin ACL check refuses an unsigned caller regardless",
        ),
        (
            community_tasks::MEMBERS_REMOVED_TYPE,
            "an admin read; the handler's admin ACL check refuses an unsigned caller regardless",
        ),
        (
            community_tasks::MEMBERS_SHOW_TYPE,
            "an admin read; the handler's admin ACL check refuses an unsigned caller regardless",
        ),
        (
            community_tasks::MEMBERS_SOLICIT_VMC_TYPE,
            "an admin action; the handler's admin ACL check refuses an unsigned caller regardless",
        ),
        (
            community_tasks::JOIN_REQUESTS_LIST_TYPE,
            "an admin read; the handler's admin ACL check refuses an unsigned caller regardless",
        ),
        (
            community_tasks::JOIN_REQUESTS_SHOW_TYPE,
            "an admin read; the handler's admin ACL check refuses an unsigned caller regardless",
        ),
        (
            community_tasks::RELATIONSHIPS_GRAPH_TYPE,
            "an admin read; the handler's admin ACL check refuses an unsigned caller regardless",
        ),
        (
            community_tasks::INVITATIONS_LIST_TYPE,
            "an admin read; the handler's admin ACL check refuses an unsigned caller regardless",
        ),
        (
            policy_tasks::POLICY_LIST_TYPE,
            "a read; the handler's admin ACL check refuses an unsigned caller regardless",
        ),
        (
            policy_tasks::POLICY_GET_TYPE,
            "a read; the handler's admin ACL check refuses an unsigned caller regardless",
        ),
        (
            policy_tasks::POLICY_ACTIVE_TYPE,
            "a read; the handler's admin ACL check refuses an unsigned caller regardless",
        ),
        (
            policy_tasks::POLICY_TEST_TYPE,
            "a dry-run read; the handler's admin ACL check refuses an unsigned caller regardless",
        ),
        (
            policy_tasks::DID_REGISTER_TYPE,
            "declares no request-level proof as a specification matter; the handler's own authorization refuses an unsigned caller regardless",
        ),
        (surface_tasks::BRANDING_SHOW_TYPE, "a public read"),
        (
            surface_tasks::THEME_SHOW_TYPE,
            "a public read, answered to an unidentified caller too: the sign-in pages draw the theme before the visitor has an identity",
        ),
        (surface_tasks::REQUESTED_SHOW_TYPE, "a public read"),
        (surface_tasks::JOIN_DISCOVERY_SHOW_TYPE, "a public read"),
        (surface_tasks::SCHEMAS_LIST_TYPE, "a public read"),
        (surface_tasks::SCHEMAS_SHOW_TYPE, "a public read"),
        (surface_tasks::ACCEPTS_LIST_TYPE, "a public read"),
        (surface_tasks::ACCEPTS_SHOW_TYPE, "a public read"),
        (
            surface_tasks::VETTER_GRANTS_LIST_TYPE,
            "an admin read; the handler's admin ACL check refuses an unsigned caller regardless",
        ),
        (
            surface_tasks::AUTO_GRANT_SHOW_TYPE,
            "an admin read; the handler's admin ACL check refuses an unsigned caller regardless",
        ),
        (
            surface_tasks::REVOCATIONS_LIST_TYPE,
            "an admin read; the handler's admin ACL check refuses an unsigned caller regardless",
        ),
        (
            surface_tasks::JOIN_VETTING_SHOW_TYPE,
            "an admin read; the handler's admin ACL check refuses an unsigned caller regardless",
        ),
        (
            surface_tasks::ROOMS_LIST_TYPE,
            "lists the hosted rooms; the handler authorizes vtc.rooms.admin from the signer's own entry, so an unsigned caller is refused regardless",
        ),
        (
            capability_module_tasks::LIST_TYPE,
            "a member read; `acting_party` refuses an unsigned caller as `proofRequired`",
        ),
        (
            auth_tasks::CHALLENGE_TYPE,
            "names no identity to authorize — it is the first message of the handshake",
        ),
        (
            auth_tasks::REFRESH_V0_2_TYPE,
            "the refresh token itself is the credential, not a request-level proof",
        ),
        #[cfg(feature = "website")]
        (website_tasks::FILES_SHOW_TYPE, "a public read"),
        #[cfg(feature = "website")]
        (
            website_tasks::FILES_LIST_TYPE,
            "an admin read; `admin_signer` refuses an unsigned caller regardless",
        ),
        #[cfg(feature = "website")]
        (
            website_tasks::GENERATIONS_LIST_TYPE,
            "an admin read; `admin_signer` refuses an unsigned caller regardless",
        ),
    ];

    /// Every dispatched URI either has its spec's `is_proof_required` enforced
    /// by the universal check `dispatch_trust_task_core` runs — once, before
    /// any handler, for every type with a published policy (see the long
    /// comment above `spec_policy_for` in this module) — or is named in
    /// [`DISPATCHED_WITHOUT_PROOF`] with the reason it is refused some other
    /// way when unsigned.
    ///
    /// This replaces a hand-counted total that broke on every addition or
    /// removal whether or not the change was reasoned about. The property it
    /// keeps is the one that mattered: nothing is dispatched unsigned by
    /// accident.
    #[test]
    fn the_dispatched_set_declares_the_proofs_the_design_note_records() {
        let dispatched: Vec<&str> = DISPATCHED_URIS
            .iter()
            .copied()
            .chain(crate::rooms::handlers::served_uris())
            .collect();

        let mut unexplained = Vec::new();
        let mut stale = Vec::new();
        for &uri in &dispatched {
            let required = spec_policy_for(uri).is_some_and(|p| p.is_proof_required);
            let allow_listed = DISPATCHED_WITHOUT_PROOF.iter().any(|&(u, _)| u == uri);
            match (required, allow_listed) {
                (false, false) => unexplained.push(uri),
                (true, true) => stale.push(uri),
                _ => {}
            }
        }
        assert!(
            unexplained.is_empty(),
            "dispatched, no proof required by spec, and not reasoned about in \
             DISPATCHED_WITHOUT_PROOF — either its specification should require a proof, or \
             add an entry there with the reason an unsigned caller is refused some other way: \
             {unexplained:#?}"
        );
        assert!(
            stale.is_empty(),
            "DISPATCHED_WITHOUT_PROOF entries whose specification now requires a proof — \
             remove the stale entries: {stale:#?}"
        );

        for &(uri, reason) in DISPATCHED_WITHOUT_PROOF {
            assert!(
                dispatched.contains(&uri),
                "`{uri}` is in DISPATCHED_WITHOUT_PROOF ({reason}) but is not dispatched any \
                 more — remove the stale entry"
            );
        }
    }

    // ── An approver's decision is an attestation ────────────────────────────
    //
    // A `task-consent/decision` and a step-up `approve-response` are held to
    // `verify_approval_proof`: a proof made for `assertionMethod`, by a key the
    // signer lists under `assertionMethod`, from a DID that resolves.

    /// A `did:peer:2` whose one Ed25519 key is published under
    /// `purpose_code` (`A` = assertionMethod only, `D` = capabilityDelegation
    /// only), and its signing secret. Resolved locally, no network.
    fn peer(purpose_code: char, seed: u8) -> (String, affinidi_secrets_resolver::secrets::Secret) {
        use affinidi_secrets_resolver::secrets::Secret;
        let probe = Secret::generate_ed25519(None, Some(&[seed; 32]));
        let mb = probe.get_public_keymultibase().expect("public key");
        let did = format!("did:peer:2.{purpose_code}{mb}");
        let secret = Secret::generate_ed25519(Some(&format!("{did}#key-1")), Some(&[seed; 32]));
        (did, secret)
    }

    /// A `did:key` signer and its secret, the verification method named the
    /// way a `did:key` names its own.
    fn key_signer(seed: u8) -> (String, affinidi_secrets_resolver::secrets::Secret) {
        use affinidi_secrets_resolver::secrets::Secret;
        let mut secret = Secret::generate_ed25519(None, Some(&[seed; 32]));
        let mb = secret.get_public_keymultibase().expect("public key");
        let did = format!("did:key:{mb}");
        secret.id = format!("{did}#{mb}");
        (did, secret)
    }

    /// `uri` issued by `issuer`, signed by `secret` with `purpose`.
    async fn approval(
        uri: &str,
        payload: Value,
        issuer: &str,
        secret: &affinidi_secrets_resolver::secrets::Secret,
        purpose: &str,
    ) -> TrustTask<Value> {
        use affinidi_data_integrity::{DataIntegrityProof, SignOptions};
        let doc = vta_sdk::trust_task_sign::build_unsigned(uri, payload, issuer, TEST_VTC_DID)
            .expect("build the document");
        let mut doc = serde_json::to_value(doc).unwrap();
        doc.as_object_mut().unwrap().remove("proof");
        let proof =
            DataIntegrityProof::sign(&doc, secret, SignOptions::new().with_proof_purpose(purpose))
                .await
                .expect("sign the approval");
        doc["proof"] = serde_json::to_value(proof).unwrap();
        serde_json::from_value(doc).unwrap()
    }

    fn decision_payload() -> Value {
        json!({
            "challenge": "9c1f4b7a2e6d80f35a4c9b1e7d2f6083",
            "payloadDigest": "zQmSK9pGKFnmc77pqyNAPJyPKt8rMqctngfg3vwuMArwGYZ",
            "decision": "approve",
        })
    }

    fn approve_response_payload(subject: &str) -> Value {
        json!({
            "subject": subject,
            "challenge": "c2VjcmV0LWNoYWxsZW5nZS12YWx1ZQ",
            "decision": "approved",
        })
    }

    /// The refusal came from the proof check.
    fn refused_at_the_proof(out: &TrustTaskOutcome) -> bool {
        let body = String::from_utf8_lossy(&out.body);
        error_code(out).as_deref() == Some("permissionDenied") && body.contains("proof")
    }

    // ── VTI-45: the proof is verified over the document as received ─────────

    /// Sign `doc` **exactly as it stands** — the JSON a JavaScript producer sends —
    /// with seed `seed`'s Ed25519 key under `vm`, for `purpose`, the proof's
    /// `created` set to the string given, verbatim (VTI-45).
    fn sign_received(doc: &mut Value, seed: u8, vm: &str, purpose: &str, created: &str) {
        use affinidi_data_integrity::crypto_suites::CryptoSuite;
        use affinidi_data_integrity::{DataIntegrityProof, prepare_sign_input};
        use ed25519_dalek::Signer as _;
        let mut di = DataIntegrityProof::new(
            CryptoSuite::EddsaJcs2022,
            vm.to_string(),
            purpose.to_string(),
            None,
            Some(created.to_string()),
            None,
        );
        doc.as_object_mut().expect("an object").remove("proof");
        let input = prepare_sign_input(&*doc, &di, CryptoSuite::EddsaJcs2022).expect("sign input");
        let sk = ed25519_dalek::SigningKey::from_bytes(&[seed; 32]);
        di.proof_value = Some(multibase::encode(
            multibase::Base::Base58Btc,
            sk.sign(&input).to_bytes(),
        ));
        doc["proof"] = serde_json::to_value(&di).expect("proof serialises");
    }

    /// Now, on a whole second, as JavaScript's `toISOString()` writes it.
    fn javascript_whole_second_now() -> String {
        format!("{}.000Z", chrono::Utc::now().format("%Y-%m-%dT%H:%M:%S"))
    }

    /// `uri` from `issuer` as a JavaScript producer sends it on a whole second
    /// — `.000Z` timestamps, a `null` `threadId` — signed as received.
    fn vti_45_document(
        uri: &str,
        payload: Value,
        issuer: &str,
        seed: u8,
        vm: &str,
        purpose: &str,
    ) -> Value {
        let now = javascript_whole_second_now();
        let mut doc = json!({
            "id": format!("urn:uuid:{}", uuid::Uuid::new_v4()),
            "type": uri,
            "issuer": issuer,
            "recipient": TEST_VTC_DID,
            "issuedAt": now,
            "threadId": null,
            "payload": payload,
        });
        sign_received(&mut doc, seed, vm, purpose, &now);
        doc
    }

    async fn dispatch_received(state: &AppState, doc: &Value) -> TrustTaskOutcome {
        let body = serde_json::to_vec(doc).expect("a document serialises");
        dispatch_trust_task_core(state, &JoinAuthCtx::rest(), &body).await
    }

    /// VTI-45 at the spine: a correctly signed `.000Z` / `threadId: null`
    /// document reaches its handler — and the typed re-serialisation the spine
    /// used to verify would have refused it.
    #[tokio::test]
    async fn vti_45_a_javascript_whole_second_document_passes_the_spine() {
        let tv = build_test_vtc().await;
        let (did, secret) = key_signer(0x45);
        let doc = vti_45_document(
            UNDER_TEST,
            json!({}),
            &did,
            0x45,
            &secret.id,
            "assertionMethod",
        );

        let typed: TrustTask<Value> = serde_json::from_value(doc.clone()).unwrap();
        assert!(
            vti_common::auth::verify_trust_task_proof(&typed)
                .await
                .is_err(),
            "the typed form must be what this document breaks"
        );

        let out = dispatch_received(&tv.state, &doc).await;
        for code in ["proofRequired", "proofInvalid"] {
            assert_ne!(
                error_code(&out).as_deref(),
                Some(code),
                "{}",
                String::from_utf8_lossy(&out.body)
            );
        }

        let mut tampered = doc;
        tampered["payload"] = json!({ "requestId": "someone-elses" });
        let out = dispatch_received(&tv.state, &tampered).await;
        assert!(
            refused_at_the_proof(&out),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
    }

    /// VTI-45 on the approval path, which holds a proof to `assertionMethod`:
    /// a `.000Z` decision gets past the proof, and an `authentication` one is
    /// still refused there.
    #[tokio::test]
    async fn vti_45_a_javascript_whole_second_approval_is_held_to_its_purpose() {
        let tv = build_test_vtc().await;
        let (did, secret) = peer('A', 0x46);
        for uri in [
            crate::acl::admin_consent::DECISION_TYPE,
            STEP_UP_APPROVE_RESPONSE_TYPE,
        ] {
            let payload = if uri == STEP_UP_APPROVE_RESPONSE_TYPE {
                approve_response_payload(&did)
            } else {
                decision_payload()
            };
            let ok = vti_45_document(
                uri,
                payload.clone(),
                &did,
                0x46,
                &secret.id,
                "assertionMethod",
            );
            let out = dispatch_received(&tv.state, &ok).await;
            assert!(
                !refused_at_the_proof(&out),
                "{uri}: {}",
                String::from_utf8_lossy(&out.body)
            );

            let operational =
                vti_45_document(uri, payload, &did, 0x46, &secret.id, "authentication");
            let out = dispatch_received(&tv.state, &operational).await;
            assert!(
                refused_at_the_proof(&out),
                "{uri}: {}",
                String::from_utf8_lossy(&out.body)
            );
        }
    }

    #[tokio::test]
    async fn an_approval_signed_for_authentication_is_refused() {
        let tv = build_test_vtc().await;
        let (did, secret) = key_signer(0x51);
        for (uri, payload) in [
            (crate::acl::admin_consent::DECISION_TYPE, decision_payload()),
            (
                STEP_UP_APPROVE_RESPONSE_TYPE,
                approve_response_payload(&did),
            ),
            (
                STEP_UP_APPROVE_RESPONSE_V0_5_TYPE,
                approve_response_payload(&did),
            ),
        ] {
            let doc = approval(uri, payload, &did, &secret, "authentication").await;
            let out = dispatch(&tv.state, &doc).await;
            let body = String::from_utf8_lossy(&out.body);
            assert!(refused_at_the_proof(&out), "{uri}: {body}");
            assert!(body.contains("assertionMethod"), "{uri}: {body}");
        }
    }

    /// Declared `assertionMethod`, by a key the signer lists only under
    /// `capabilityDelegation`: the signature is valid, but the key is not
    /// authorised for the purpose the proof declares (VTI-KEY-022), so neither
    /// the general verifier nor the approval path accepts it.
    #[tokio::test]
    async fn an_approval_by_a_key_not_listed_under_assertion_method_is_refused() {
        let tv = build_test_vtc().await;
        let (did, secret) = peer('D', 0x52);
        for (uri, payload) in [
            (crate::acl::admin_consent::DECISION_TYPE, decision_payload()),
            (
                STEP_UP_APPROVE_RESPONSE_TYPE,
                approve_response_payload(&did),
            ),
            (
                STEP_UP_APPROVE_RESPONSE_V0_5_TYPE,
                approve_response_payload(&did),
            ),
        ] {
            let doc = approval(uri, payload, &did, &secret, "assertionMethod").await;
            let err = vti_common::auth::verify_trust_task_proof(&doc)
                .await
                .unwrap_err();
            assert!(
                err.cause().is_some_and(|c| c.contains("assertionMethod")),
                "{uri}: {err:?}"
            );
            let out = dispatch(&tv.state, &doc).await;
            assert!(
                refused_at_the_proof(&out),
                "{uri}: {}",
                String::from_utf8_lossy(&out.body)
            );
        }
    }

    /// A signer DID this service cannot resolve is refused, never passed
    /// through to the handler.
    #[tokio::test]
    async fn an_approval_whose_signer_does_not_resolve_is_refused() {
        use affinidi_secrets_resolver::secrets::Secret;
        let tv = build_test_vtc().await;
        let did = "did:web:approver.invalid";
        let secret = Secret::generate_ed25519(Some(&format!("{did}#key-1")), Some(&[0x53; 32]));
        for (uri, payload) in [
            (crate::acl::admin_consent::DECISION_TYPE, decision_payload()),
            (STEP_UP_APPROVE_RESPONSE_TYPE, approve_response_payload(did)),
            (
                STEP_UP_APPROVE_RESPONSE_V0_5_TYPE,
                approve_response_payload(did),
            ),
        ] {
            let doc = approval(uri, payload, did, &secret, "assertionMethod").await;
            let out = dispatch(&tv.state, &doc).await;
            assert!(
                refused_at_the_proof(&out),
                "{uri}: {}",
                String::from_utf8_lossy(&out.body)
            );
        }
    }

    /// The same approvals made for `assertionMethod` by an assertion key get
    /// past the proof, to be refused only by the handler (here the signer is
    /// no admin of this community).
    #[tokio::test]
    async fn an_assertion_method_approval_passes_the_proof() {
        let tv = build_test_vtc().await;
        let signers = [key_signer(0x54), peer('A', 0x55)];
        for (did, secret) in &signers {
            for (uri, payload) in [
                (crate::acl::admin_consent::DECISION_TYPE, decision_payload()),
                (STEP_UP_APPROVE_RESPONSE_TYPE, approve_response_payload(did)),
                (
                    STEP_UP_APPROVE_RESPONSE_V0_5_TYPE,
                    approve_response_payload(did),
                ),
            ] {
                let doc = approval(uri, payload, did, secret, "assertionMethod").await;
                let out = dispatch(&tv.state, &doc).await;
                let body = String::from_utf8_lossy(&out.body);
                assert!(
                    !body.contains("proof"),
                    "{uri} by {did} passes the proof check: {body}"
                );
            }
        }
    }

    /// An unsigned approve-response is heard only as an approval carrying a
    /// console user's passkey assertion; one with no evidence is refused before
    /// any pending step-up is consulted.
    #[tokio::test]
    async fn an_unsigned_approve_response_is_refused() {
        let tv = build_test_vtc().await;
        let h = holder();
        for uri in [
            STEP_UP_APPROVE_RESPONSE_TYPE,
            STEP_UP_APPROVE_RESPONSE_V0_5_TYPE,
        ] {
            let doc = unsigned(&h, uri, approve_response_payload(&h.did));
            let out = dispatch(&tv.state, &doc).await;
            assert_eq!(
                error_code(&out).as_deref(),
                Some("proofRequired"),
                "{uri}: {}",
                String::from_utf8_lossy(&out.body)
            );
        }
    }

    /// 0.5's payload schema is the same wire document as 0.4's — only the
    /// `Response` schema's description text differs — which is what licenses
    /// [`super::handle_step_up_approve_response_v0_5`] to convert a 0.5
    /// payload into 0.4's generated type and reach the one verifier rather
    /// than forking it.
    #[test]
    fn the_0_5_payload_schema_is_wire_identical_to_0_4() {
        let filled = json!({
            "subject": "did:key:zAlice",
            "challenge": "Y2hhbGxlbmdlLWNoYWxsZW5nZS1jaGFsbGVuZ2U",
            "sessionId": "9c2e1f7a-6b3d-4c8e-9a1b-2d3e4f5a6b7c",
            "decision": "approved",
            "grantedAcr": "aal2",
            "evidence": {
                "kind": "webauthn",
                "assertion": {
                    "id": "Y3JlZF8xYTJiM2M",
                    "rawId": "Y3JlZF8xYTJiM2M",
                    "type": "public-key",
                    "response": {
                        "clientDataJSON": "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0In0",
                        "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAAAQ",
                        "signature": "MEUCIQDx",
                    },
                },
            },
        });
        let v5: step_up_approve_response_v0_5::Payload =
            serde_json::from_value(filled.clone()).expect("a 0.5 payload parses");
        let v4: step_up_approve_response::Payload = serde_json::to_value(&v5)
            .and_then(serde_json::from_value)
            .unwrap_or_else(|e| {
                panic!("0.5 payload does not convert to 0.4's shape: {e}\n{filled:#}")
            });
        assert_eq!(
            serde_json::to_value(&v4).unwrap(),
            filled,
            "round-tripping through 0.4's type must not drop or rename a member"
        );
    }
}

/// The family of a Trust Task Type URI: everything before its trailing version
/// segment.
///
/// `…/spec/vtc/join-requests/submit/0.2` → `…/spec/vtc/join-requests/submit`.
/// The version is always the last path segment (SPEC §3.1), so a plain
/// `rsplit_once('/')` is the whole rule — no version grammar to parse, and a
/// URI with no `/` simply has no family rather than panicking.
fn task_family(type_uri: &str) -> Option<&str> {
    type_uri.rsplit_once('/').map(|(family, _version)| family)
}

/// Reject a type URI this dispatcher has no arm for, distinguishing the two
/// failures that used to wear one code.
///
/// "I have never heard of this task" and "I know this task, at a different
/// version" send the operator to completely different places — the first to
/// whether the verb exists at all, the second to which side is out of date —
/// and only the second is recoverable by upgrading something.
///
/// So a URI whose family this VTC *does* dispatch is rejected as
/// `unsupportedVersion` — SPEC's code for exactly this, "the consumer
/// recognizes the type but not at this MAJOR.MINOR" — naming the versions
/// actually served in `message` and in `details.servedVersions`. Anything else
/// stays `unsupportedType`.
///
/// This is the VTC half of #1220, which did the same on the VTA after an
/// operator spent an hour reading `unsupported type: …/provision/integration/0.3`
/// as "this agent cannot provision" when it meant "this agent is older than
/// your client". The VTC is more exposed to that reading, not less: its
/// `spec/vtc/*` families are mid-migration, so a member client and a community
/// can legitimately be at different versions of the same verb.
///
/// Both `details` members are bounded by construction — `servedVersions` comes
/// from a `const` of seven, and `requestedType` echoes a `TypeUri` the
/// framework already parsed and already puts in `message` — but they still go
/// through `reject_with_code`'s `bound_details`, because "bounded by
/// construction" is a property of today's callers rather than of the funnel.
fn unsupported_type_or_version(doc: &TrustTask<Value>, type_uri: &str) -> TrustTaskOutcome {
    use trust_tasks_rs::{StandardCode, TrustTaskCode};
    use vta_sdk::protocols::trust_task_reject_details as details;

    let family = task_family(type_uri);
    // Both halves of what this service serves: the URIs still routed by the
    // match below, and the ones the rooms dispatcher derives from its
    // registrations. The second used to be a `const` array copied by hand from
    // the arms — this reads the routing table itself, so a version hint cannot
    // name a task nobody serves, nor omit one that is served.
    let mut served: Vec<&str> = DISPATCHED_URIS
        .iter()
        .copied()
        .chain(crate::rooms::handlers::served_uris())
        .chain(crate::git_ns::tasks::served_uris())
        .filter(|uri| family.is_some() && task_family(uri) == family)
        .collect();
    served.sort_unstable();
    served.dedup();

    if served.is_empty() {
        // Message kept byte-identical to the framework's own
        // `RejectReason::UnsupportedType` rendering so a consumer matching on
        // it does not break; `details.requestedType` is the same fact
        // machine-readably, which is the half the framework's shape leaves out.
        return reject_with_code(
            doc,
            TrustTaskCode::Standard(StandardCode::UnsupportedType),
            format!("unsupported type: {type_uri}"),
            Some(serde_json::json!({ details::REQUESTED_TYPE: type_uri })),
        );
    }

    reject_with_code(
        doc,
        TrustTaskCode::Standard(StandardCode::UnsupportedVersion),
        format!(
            "unsupported version: {type_uri} — this VTC serves {}",
            served.join(", ")
        ),
        Some(serde_json::json!({
            details::REQUESTED_TYPE: type_uri,
            details::SERVED_VERSIONS: served,
        })),
    )
}

/// The Trust Task URIs this dispatcher routes. Kept in lockstep with the
/// `match` above by the `dispatcher_routes_every_dispatched_uri` test.
///
/// This set is also exactly what is reachable **over TSP**, since the TSP
/// inbound path (#833) hands every frame to this dispatcher and has no
/// protocol-message surface behind it. A verb that is not here is a verb a
/// member cannot perform over TSP.
///
/// Read at runtime as well as by the parity test:
/// [`unsupported_type_or_version`] answers an unrouted URI from this list, so
/// the migration hint a client receives cannot name a version this VTC does
/// not actually serve.
pub(crate) const DISPATCHED_URIS: &[&str] = &[
    jr::JOIN_REQUEST_SUBMIT_TYPE,
    // 0.3: every criterion states its admission, in the order the community
    // decides by.
    jr::JOIN_REQUEST_MANIFEST_TYPE,
    jr::JOIN_REQUEST_STATUS_TYPE,
    // The applicant closing their own request. Paired with `status` above: the
    // poll is how they learn the community asked for more, and this is how
    // they decline to supply it.
    jr::JOIN_REQUEST_WITHDRAW_TYPE,
    // The applicant answering the community's request for more, against the
    // request they already have open. The third of the trio a deferral needs:
    // `status` is how they learn what is wanted, this is how they supply it,
    // and `withdraw` is how they decline to.
    jr::JOIN_REQUEST_SUPPLEMENT_TYPE,
    // Evidence from a wallet that speaks OpenID4VP and no Trust Task: the
    // applicant opens a session for a criterion and reads its outcome (#1988).
    jr::JOIN_REQUEST_WALLET_SESSION_START_TYPE,
    jr::JOIN_REQUEST_WALLET_SESSION_STATUS_TYPE,
    jr::MEMBER_SELF_REMOVE_TYPE,
    mem::MEMBER_VMC_TYPE,
    // The two credential-exchange steps a holder sends: `request` redeems an
    // offer, `present` answers a join query. Each is answered by the VTC pushing
    // the next step (`issue`, `join-requests/submit-receipt`); see
    // `credential_exchange`.
    vta_sdk::protocols::credential_exchange::REQUEST,
    vta_sdk::protocols::credential_exchange::PRESENT,
    // A vetter withdrawing a statement (OpenVTC vetting design §9.6).
    vetting_wire::VETTING_REVOKE_STATEMENT_TYPE,
    // An admin naming a vetter. It has no REST route.
    vetting_wire::VETTING_VETTER_GRANT_TYPE,
    // The vetter registry: a vetter publishing a profile, anyone identified
    // finding vetters, and a vetter asking for their grant credential again.
    // `0.2` adds the administrator's route (`memberDid`), which is what let
    // the admin-only REST resend route retire (tt-tf#689).
    vetting_wire::VETTING_VETTER_PROFILE_TYPE,
    vetting_wire::VETTING_VETTER_LIST_TYPE,
    vetting_wire::VETTING_VETTER_SHOW_TYPE,
    vetting_wire::VETTING_VETTER_RESEND_TYPE,
    vetting_wire::VETTING_VETTER_RESEND_0_2_TYPE,
    // Hidden vetting: enrolment, the drip, event mode, and the applicant's challenge.
    #[cfg(feature = "vetting-pcs")]
    crate::vetting::pcs_tasks::PCS_ROOT_TYPE,
    #[cfg(feature = "vetting-pcs")]
    crate::vetting::pcs_tasks::PCS_TOKENS_TYPE,
    #[cfg(feature = "vetting-pcs")]
    crate::vetting::pcs_tasks::EVENT_MODE_TYPE,
    #[cfg(feature = "vetting-pcs")]
    crate::vetting::pcs_tasks::PCS_CHALLENGE_TYPE,
    // The admin publish that turns hidden vetting on. Was `POST /vetting/hidden`.
    #[cfg(feature = "vetting-pcs")]
    crate::vetting::pcs_tasks::HIDDEN_PUBLISH_TYPE,
    // And the admin's off switch and stored-configuration read.
    #[cfg(feature = "vetting-pcs")]
    crate::vetting::pcs_tasks::HIDDEN_WITHDRAW_TYPE,
    #[cfg(feature = "vetting-pcs")]
    crate::vetting::pcs_tasks::HIDDEN_SHOW_TYPE,
    PERSONHOOD_CHALLENGE_TYPE,
    PERSONHOOD_ASSERT_TYPE,
    // The admin-facing member verbs (#1641 phase 2): the binding that holds the
    // document requirements their specifications declare — proof, recipient,
    // `issuedAt`, and the accepted-id record. None has a REST route.
    MEMBER_CREDENTIALS_TYPE,
    MEMBER_UPDATE_TYPE,
    MEMBER_ADMIN_REMOVE_TYPE,
    MEMBER_PURGE_TYPE,
    // Direct admission (`crate::ceremony::admission`), on the generated
    // `vtc/members/{admit,make-membership}` types (trust-tasks-tf #784).
    admission_tasks::ADMIT_TYPE,
    admission_tasks::MAKE_MEMBERSHIP_TYPE,
    // Batch 2: the join decision and the community-profile edit, on the same
    // terms. Neither has a REST route.
    JOIN_DECIDE_TYPE,
    COMMUNITY_PROFILE_UPDATE_TYPE,
    // Batch 3: the portable-configuration pair, on the same terms.
    CONFIG_EXPORT_TYPE,
    CONFIG_IMPORT_TYPE,
    // Batch 4: the endorsement-type writes, which have no REST route. `list`
    // declares no proof and stays on its bearer route.
    ENDORSEMENT_TYPE_REGISTER_TYPE,
    ENDORSEMENT_TYPE_DELETE_TYPE,
    // Batch 5: the backup export. `import` carries the whole envelope and
    // cannot fit a 64 KiB document; it waits for a chunked transfer.
    BACKUP_EXPORT_TYPE,
    // The first verb here that confers administrative authority. Its passkey
    // gesture is bound to the one grant rather than read from a session, which
    // a signed document does not have. No ACL verb has a REST route.
    ACL_GRANT_TYPE,
    // A role transition; promotion to admin takes the same bound gesture.
    ACL_CHANGE_ROLE_TYPE,
    // The rest of the canonical family.
    ACL_SHOW_TYPE,
    ACL_LIST_TYPE,
    ACL_UPDATE_TYPE,
    ACL_REVOKE_TYPE,
    // AclEntry 0.2: role-based administration — explicit act scope,
    // capabilities with resource qualifiers, approve scope
    // (`docs/05-design-notes/vtc-admin-roles.md`). 0.1 keeps working by the
    // CONVENTIONS §8 mapping (`routes::acl` module docs).
    ACL_GRANT_V0_2_TYPE,
    ACL_CHANGE_ROLE_V0_2_TYPE,
    ACL_SHOW_V0_2_TYPE,
    ACL_LIST_V0_2_TYPE,
    ACL_UPDATE_V0_2_TYPE,
    ACL_REVOKE_V0_2_TYPE,
    // The gesture that operation-bound step-up asks for.
    STEP_UP_APPROVE_RESPONSE_TYPE,
    // 0.5: identical wire shape, but every response now carries the
    // approver's own proof — the spine's `is_proof_required` enforces that
    // before this ever dispatches.
    STEP_UP_APPROVE_RESPONSE_V0_5_TYPE,
    // 0.6: a step-up approver's signed statement as the factor
    // (`approverSigned`), for an administrator who signs in with a wallet.
    STEP_UP_APPROVE_RESPONSE_V0_6_TYPE,
    // Another admin's decision on a parked action (VTI-APV-014, -017). The
    // request it answers is pushed by this service, never dispatched here.
    // 0.2 adds the optional extra factor and the `actionId` locator.
    crate::acl::admin_consent::DECISION_TYPE,
    crate::acl::admin_consent::DECISION_V0_2_TYPE,
    // The action list: what is waiting, one action, withdrawing one, and
    // acknowledging an operator's write (no producer yet).
    action_tasks::LIST_TYPE,
    action_tasks::SHOW_TYPE,
    action_tasks::CANCEL_TYPE,
    action_tasks::ACKNOWLEDGE_TYPE,
    // 0.2: the same requests, answered with `_shared/0.2` Actions — a
    // cooling-off as category `coolingOff` with `landsAt` (trust-tasks-tf #719).
    action_tasks::LIST_V0_2_TYPE,
    action_tasks::SHOW_V0_2_TYPE,
    action_tasks::CANCEL_V0_2_TYPE,
    action_tasks::ACKNOWLEDGE_V0_2_TYPE,
    // The console's live channel (hints only): its success opens an event
    // stream, which only the HTTPS door can carry — every other transport is
    // answered `streamUnavailable`. 0.2 adds the `rooms` topic; 0.1 is still
    // answered, at its own version.
    event_tasks::SUBSCRIBE_TYPE,
    event_tasks::SUBSCRIBE_V0_2_TYPE,
    // Members' step-up passkeys: the invite, its redemption, an
    // administrator's revocation for the member, and an administrator's
    // listing of them. No REST route serves them.
    step_up_passkey_tasks::INVITE_TYPE,
    step_up_passkey_tasks::REDEEM_START_TYPE,
    step_up_passkey_tasks::REDEEM_FINISH_TYPE,
    step_up_passkey_tasks::REVOKE_START_TYPE,
    step_up_passkey_tasks::REVOKE_FINISH_TYPE,
    step_up_passkey_tasks::ADMIN_LIST_TYPE,
    // Step-up approvers (VTI-APV-015, VTI-APV-016): an administrator's invite,
    // its redemption by the invited subject, self-service enrolment behind a
    // factor already held, listing and revocation. No REST route serves them.
    step_up_approver_tasks::INVITE_TYPE,
    step_up_approver_tasks::REDEEM_START_TYPE,
    step_up_approver_tasks::REDEEM_FINISH_TYPE,
    step_up_approver_tasks::ENROLL_TYPE,
    step_up_approver_tasks::LIST_TYPE,
    step_up_approver_tasks::REVOKE_TYPE,
    // Custom administrative roles (`vtc-admin-roles.md` §6.2): reads for any
    // administrator, writes through the action list. No REST route.
    role_tasks::DEFINE_TYPE,
    role_tasks::LIST_TYPE,
    role_tasks::SHOW_TYPE,
    role_tasks::DELETE_TYPE,
    // Where room files are stored (`data-rooms-files.md` §7): reads and the probe for
    // a holder of `vtc.rooms.admin`, changes through the action list. No REST route.
    storage_tasks::LIST_TYPE,
    storage_tasks::GET_TYPE,
    storage_tasks::CREATE_TYPE,
    storage_tasks::UPDATE_TYPE,
    storage_tasks::RETIRE_TYPE,
    storage_tasks::PROBE_TYPE,
    storage_tasks::ASSIGN_TYPE,
    // What the rooms store and may store (`data-rooms-files.md` §6): reads and limit
    // overrides for a holder of `vtc.rooms.admin`, overrides audited. No REST route.
    room_admin_tasks::GET_TYPE,
    room_admin_tasks::USAGE_TYPE,
    room_admin_tasks::LIMITS_SET_TYPE,
    // Rooms the community owns (`data-rooms-files.md` §8.4): an administrator's
    // create, reads and membership changes under `vtc.rooms.manage`, the changes
    // behind the requester's bound gesture; a member's offers on their own DID. No
    // REST route. The details administrators keep a room by (`update`, and the 0.2 reads
    // and create that carry them) take no gesture: they reach no key holder.
    community_room_tasks::CREATE_TYPE,
    community_room_tasks::CREATE_V0_2_TYPE,
    community_room_tasks::CREATE_V0_3_TYPE,
    community_room_tasks::LIST_TYPE,
    community_room_tasks::LIST_V0_2_TYPE,
    community_room_tasks::GET_TYPE,
    community_room_tasks::GET_V0_2_TYPE,
    community_room_tasks::UPDATE_TYPE,
    community_room_tasks::UPDATE_V0_2_TYPE,
    community_room_tasks::MEMBERS_ADD_TYPE,
    community_room_tasks::MEMBERS_REMOVE_TYPE,
    community_room_tasks::MEMBERS_REMOVE_V0_2_TYPE,
    community_room_tasks::MEMBERS_LIST_TYPE,
    community_room_tasks::OFFERS_LIST_TYPE,
    community_room_tasks::OFFERS_LIST_V0_2_TYPE,
    community_room_tasks::OFFERS_ACCEPT_TYPE,
    community_room_tasks::MEMBERSHIPS_LIST_TYPE,
    // The OpenID4VP verifier identities, as a holder of `vtc.config.admin`
    // sees them (#1988). A read; no REST route.
    oid4vp_tasks::IDENTITIES_LIST_TYPE,
    // A subject rolling its own admin entry to a new key (VTI-CLT-025 – 032).
    ACL_SWAP_KEY_TYPE,
    // Capability modules (`vtc-capability-modules.md`): a member's listing of
    // what the community has enabled — OpenVTC's Capabilities panel — and an
    // administrator turning one on or off, which this VTC then projects to its
    // Trust Registry. No REST route.
    capability_module_tasks::LIST_TYPE,
    capability_module_tasks::ENABLE_TYPE,
    capability_module_tasks::DISABLE_TYPE,
    // backup/* — the chunked transfer `vtc/backup/import` could never be,
    // because its envelope does not fit one document.
    backup_tasks::INITIATE_EXPORT_TYPE,
    backup_tasks::GET_CHUNK_TYPE,
    backup_tasks::COMPLETE_EXPORT_TYPE,
    backup_tasks::INITIATE_IMPORT_TYPE,
    backup_tasks::PUT_CHUNK_TYPE,
    backup_tasks::FINALIZE_IMPORT_TYPE,
    backup_tasks::ABORT_TYPE,
    // The member-facing verbs: renewal and DID rotation (the member's own),
    // personhood revocation (the subject or an admin), the relationship
    // graph's list / publish / revoke (`0.1` direct-issuer-or-admin, `0.2`
    // adding the pairwise `pop` route), and the endorsement verbs an Admin or
    // Issuer performs. None has a REST route any more. Before these, a member
    // on TSP or DIDComm could join and then do none of this.
    member_tasks::RENEW_TYPE,
    member_tasks::ROTATE_CHALLENGE_TYPE,
    member_tasks::ROTATE_TYPE,
    member_tasks::PERSONHOOD_REVOKE_TYPE,
    member_tasks::RELATIONSHIPS_LIST_TYPE,
    member_tasks::RELATIONSHIPS_PUBLISH_TYPE,
    member_tasks::RELATIONSHIPS_REVOKE_TYPE,
    member_tasks::RELATIONSHIPS_REVOKE_0_2_TYPE,
    member_tasks::ENDORSEMENTS_ISSUE_TYPE,
    member_tasks::ENDORSEMENTS_LIST_TYPE,
    member_tasks::ENDORSEMENTS_SHOW_TYPE,
    member_tasks::ENDORSEMENTS_REVOKE_TYPE,
    // The administrator's operational verbs, which had only bearer REST: the
    // registry reconciler, the audit log, the runtime configuration, admin
    // invites, and the auth service's sessions. None has a REST route.
    admin_tasks::DIAGNOSTICS_TYPE,
    admin_tasks::SYNC_JOBS_LIST_TYPE,
    admin_tasks::SYNC_JOBS_RETRY_TYPE,
    admin_tasks::SYNC_JOBS_RETRY_0_2_TYPE,
    admin_tasks::SYNC_JOBS_DISCARD_TYPE,
    admin_tasks::RECORDS_LIST_TYPE,
    admin_tasks::AUDIT_LIST_TYPE,
    admin_tasks::AUDIT_VERIFY_TYPE,
    admin_tasks::CONFIG_SHOW_TYPE,
    admin_tasks::CONFIG_PATCH_TYPE,
    admin_tasks::CONFIG_RELOAD_TYPE,
    admin_tasks::CONFIG_RESTART_TYPE,
    admin_tasks::INVITES_LIST_TYPE,
    admin_tasks::INVITES_CREATE_TYPE,
    admin_tasks::INVITES_REVOKE_TYPE,
    admin_tasks::SESSIONS_LIST_TYPE,
    admin_tasks::REVOKE_SESSION_TYPE,
    // Pre-session auth — replaced the dedicated, header-gated REST mounts at
    // `POST /v1/auth/{challenge,,refresh}`. The bare `/auth/` path served
    // `authenticate`; `refresh`'s cookie-bound REST route stays for the admin
    // console's own session renewal (see `auth_tasks`'s module doc).
    // Wallet sign-in started by a trigger link (`oob_tasks`). `identify` and
    // `grant` are carried inside `prove` and `respond` only.
    crate::member_portal::oob::types::REQUEST_TYPE,
    crate::member_portal::oob::types::CLAIM_TYPE,
    crate::member_portal::oob::types::PROVE_TYPE,
    crate::member_portal::oob::types::RESPOND_TYPE,
    crate::member_portal::oob::types::REDEEM_TYPE,
    crate::member_portal::oob::types::CANCEL_TYPE,
    auth_tasks::CHALLENGE_TYPE,
    auth_tasks::AUTHENTICATE_V0_2_TYPE,
    auth_tasks::AUTHENTICATE_V0_3_TYPE,
    auth_tasks::REFRESH_V0_2_TYPE,
    // First-admin onboarding — replaced the bearer REST routes at
    // `POST /v1/install/claim/{start,finish}` and `POST /v1/admin/bootstrap`.
    install_tasks::CLAIM_START_TYPE,
    install_tasks::CLAIM_FINISH_TYPE,
    // 0.3: claim under a DID the founder already controls, with a step-up
    // approver as their factor (approver design note §6b).
    install_tasks::CLAIM_START_V0_3_TYPE,
    install_tasks::CLAIM_FINISH_V0_3_TYPE,
    install_tasks::BOOTSTRAP_TYPE,
    // Cross-community recognition — replaced the bearer REST routes at
    // `POST /v1/auth/recognise/challenge` and `POST /v1/auth/recognise`.
    recognise_tasks::CHALLENGE_TYPE,
    recognise_tasks::RECOGNISE_TYPE,
    // The administrator's community verbs, which had only bearer REST. None
    // has a REST route now.
    community_tasks::PROFILE_SHOW_TYPE,
    community_tasks::CEREMONIES_LIST_TYPE,
    community_tasks::DIRECTORY_QUERY_TYPE,
    // The member directory (`crate::directory`).
    directory_tasks::FIELDS_LIST_TYPE,
    directory_tasks::FIELDS_DEFINE_TYPE,
    directory_tasks::FIELDS_UPDATE_TYPE,
    directory_tasks::FIELDS_RETIRE_TYPE,
    directory_tasks::CARD_SHOW_TYPE,
    directory_tasks::CARD_UPDATE_TYPE,
    directory_tasks::CARD_ASSERT_TYPE,
    directory_tasks::ENTRIES_LIST_TYPE,
    directory_tasks::ENTRIES_SHOW_TYPE,
    community_tasks::ENDORSEMENT_TYPES_LIST_TYPE,
    community_tasks::RECOGNITION_CHECK_TYPE,
    community_tasks::MEMBERS_LIST_TYPE,
    community_tasks::MEMBERS_REMOVED_TYPE,
    community_tasks::MEMBERS_SHOW_TYPE,
    community_tasks::MEMBERS_SOLICIT_VMC_TYPE,
    community_tasks::JOIN_REQUESTS_LIST_TYPE,
    community_tasks::JOIN_REQUESTS_SHOW_TYPE,
    community_tasks::RELATIONSHIPS_GRAPH_TYPE,
    community_tasks::INVITATIONS_ISSUE_TYPE,
    community_tasks::INVITATIONS_LIST_TYPE,
    community_tasks::INVITATIONS_REVOKE_TYPE,
    community_tasks::INVITATIONS_DELIVER_TYPE,
    // The policy log and the community's own DID log. None has a REST route.
    policy_tasks::POLICY_LIST_TYPE,
    policy_tasks::POLICY_GET_TYPE,
    policy_tasks::POLICY_ACTIVE_TYPE,
    policy_tasks::POLICY_UPSERT_TYPE,
    policy_tasks::POLICY_ACTIVATE_TYPE,
    policy_tasks::POLICY_TEST_TYPE,
    policy_tasks::DID_REGISTER_TYPE,
    // The administration surfaces that had only bearer REST. The branding,
    // requested attributes, vetter grants, automatic grant and withdrawal
    // notices keep their routes while `vtc-client` calls them.
    surface_tasks::BRANDING_SHOW_TYPE,
    surface_tasks::BRANDING_UPDATE_TYPE,
    surface_tasks::THEME_SHOW_TYPE,
    surface_tasks::THEME_UPDATE_TYPE,
    surface_tasks::REQUESTED_SHOW_TYPE,
    surface_tasks::REQUESTED_UPDATE_TYPE,
    surface_tasks::JOIN_DISCOVERY_SHOW_TYPE,
    surface_tasks::JOIN_DISCOVERY_UPDATE_TYPE,
    surface_tasks::SCHEMAS_REGISTER_TYPE,
    surface_tasks::SCHEMAS_LIST_TYPE,
    surface_tasks::SCHEMAS_SHOW_TYPE,
    surface_tasks::SCHEMAS_DELETE_TYPE,
    surface_tasks::ACCEPTS_REGISTER_TYPE,
    surface_tasks::ACCEPTS_LIST_TYPE,
    surface_tasks::ACCEPTS_SHOW_TYPE,
    surface_tasks::ACCEPTS_DELETE_TYPE,
    surface_tasks::VETTER_GRANTS_LIST_TYPE,
    surface_tasks::AUTO_GRANT_SHOW_TYPE,
    surface_tasks::AUTO_GRANT_UPDATE_TYPE,
    surface_tasks::REVOCATIONS_LIST_TYPE,
    surface_tasks::RELATIONSHIPS_SUSPEND_TYPE,
    surface_tasks::RELATIONSHIPS_RESTORE_TYPE,
    surface_tasks::JOIN_VETTING_SHOW_TYPE,
    surface_tasks::JOIN_QUERY_TYPE,
    surface_tasks::ROOMS_LIST_TYPE,
    // The console's signing keys, which replaced `/v1/admin/console-keys`.
    signing_key_tasks::ENROLL_TYPE,
    // 0.2: the identity's own signed `authorization` in place of the step-up,
    // and `replaces` at the cap. `authorize/0.1` is never dispatched alone.
    signing_key_tasks::ENROLL_V0_2_TYPE,
    signing_key_tasks::LIST_TYPE,
    signing_key_tasks::REVOKE_TYPE,
    // An administrator's own login passkeys, which replaced the
    // `/v1/admin/passkeys/*` bearer routes (#1641). Each change takes a
    // user-verified assertion of an existing passkey beside the signer's
    // authority.
    admin_passkey_tasks::LIST_TYPE,
    admin_passkey_tasks::ENROLL_START_TYPE,
    admin_passkey_tasks::ENROLL_FINISH_TYPE,
    admin_passkey_tasks::REVOKE_START_TYPE,
    admin_passkey_tasks::REVOKE_FINISH_TYPE,
    // The console's bearer → cookie bridge, which replaced
    // `POST /v1/auth/admin-session` (#1641): signed by the token's subject.
    admin_session_tasks::ADMIN_SESSION_TYPE,
    // Session introspection, which replaced `GET /v1/auth/whoami` (#1641):
    // signed by the key bound to the session at sign-in.
    whoami_tasks::WHOAMI_TYPE,
    // The website's content, which replaced the raw-byte routes.
    #[cfg(feature = "website")]
    website_tasks::BEGIN_TYPE,
    #[cfg(feature = "website")]
    website_tasks::CHUNK_TYPE,
    #[cfg(feature = "website")]
    website_tasks::COMMIT_TYPE,
    #[cfg(feature = "website")]
    website_tasks::ABORT_TYPE,
    #[cfg(feature = "website")]
    website_tasks::DEPLOY_TYPE,
    #[cfg(feature = "website")]
    website_tasks::FILES_SHOW_TYPE,
    // The website's listing, delete, generation history and rollback —
    // replaced `GET /v1/website/files`, `DELETE /v1/website/files/{*path}`,
    // `GET /v1/website/generations`, `POST /v1/website/rollback/{gen_num}`.
    #[cfg(feature = "website")]
    website_tasks::FILES_LIST_TYPE,
    #[cfg(feature = "website")]
    website_tasks::FILES_DELETE_TYPE,
    #[cfg(feature = "website")]
    website_tasks::GENERATIONS_LIST_TYPE,
    #[cfg(feature = "website")]
    website_tasks::ROLLBACK_TYPE,
    // rooms/* — top-level, not `spec/vtc/*`: a room's protocol is host-neutral, so
    // filing it under a service prefix would encode into the URI the one thing the
    // design exists to avoid. The vtc conformance sweep scopes to `spec/vtc/` and so
    // does not cover these; they are pinned by `rooms_dispatch_matches_wire` below.
    //
    // Discovery, with this VTC's acceptance window (VTI-TRN-047).
    discovery::DISCOVERY_V0_3_TYPE,
];

/// `vtc/members/personhood/challenge/0.1` — mint the single-use nonce
/// the assert presentation must be bound to.
pub(crate) const PERSONHOOD_CHALLENGE_TYPE: &str =
    <pc::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `vtc/members/personhood/assert/0.2` — present the evidence, with the outcome evidence of
/// each witnessing session a VWC in it cites (`outcomeEvidence`). 0.1, which had no member for
/// that evidence, is not served.
pub(crate) const PERSONHOOD_ASSERT_TYPE: &str = <pa::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `vtc/members/credentials/0.1` — read one member's credential bodies.
pub(crate) const MEMBER_CREDENTIALS_TYPE: &str =
    <member_credentials::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `vtc/members/update/0.1` — update a member's role or metadata.
pub(crate) const MEMBER_UPDATE_TYPE: &str =
    <member_update::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `vtc/members/admin-remove/0.1` — an administrator removes another member.
pub(crate) const MEMBER_ADMIN_REMOVE_TYPE: &str =
    <member_admin_remove::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `vtc/members/purge/0.1` — irreversibly erase a member record.
pub(crate) const MEMBER_PURGE_TYPE: &str =
    <member_purge::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `vtc/join-requests/decide/0.1` — admit or refuse a pending applicant.
pub(crate) const JOIN_DECIDE_TYPE: &str =
    <join_decide::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `vtc/community/profile/update/0.1` — edit the community's public profile.
pub(crate) const COMMUNITY_PROFILE_UPDATE_TYPE: &str =
    <community_profile_update::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `vtc/config/export/0.1` — the community's portable configuration.
pub(crate) const CONFIG_EXPORT_TYPE: &str =
    <config_export::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `vtc/config/import/0.1` — preview or apply a portable configuration.
pub(crate) const CONFIG_IMPORT_TYPE: &str =
    <config_import::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `vtc/endorsement-types/register/0.1` — register an endorsement type.
pub(crate) const ENDORSEMENT_TYPE_REGISTER_TYPE: &str =
    <endorsement_type_register::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `vtc/endorsement-types/delete/0.1` — delete an unreferenced endorsement type.
pub(crate) const ENDORSEMENT_TYPE_DELETE_TYPE: &str =
    <endorsement_type_delete::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `vtc/backup/export/0.1` — an encrypted full-state backup.
pub(crate) const BACKUP_EXPORT_TYPE: &str =
    <backup_export::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `acl/grant/0.1` — the entry the maintainer should hold for a subject.
pub(crate) const ACL_GRANT_TYPE: &str = <acl_grant::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `acl/change-role/0.1` — move a subject between roles, compare-and-swap on
/// `fromRole`.
pub(crate) const ACL_CHANGE_ROLE_TYPE: &str =
    <acl_change_role::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `acl/show/0.1` — one entry, as the caller may see it.
pub(crate) const ACL_SHOW_TYPE: &str = <acl_show::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `acl/list/0.1` — the entries the caller may see, filtered and paged.
pub(crate) const ACL_LIST_TYPE: &str = <acl_list::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `acl/update/0.1` — amend an existing entry's non-role attributes.
pub(crate) const ACL_UPDATE_TYPE: &str = <acl_update::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `acl/revoke/0.1` — remove an entry, or reduce its scopes.
pub(crate) const ACL_REVOKE_TYPE: &str = <acl_revoke::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `acl/grant/0.2` — AclEntry 0.2: an administrative role, explicit act scope,
/// capabilities and approve scope.
pub(crate) const ACL_GRANT_V0_2_TYPE: &str =
    <trust_tasks_rs::specs::acl::grant::v0_2::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `acl/change-role/0.2` — move the administrative role, compare-and-swap.
pub(crate) const ACL_CHANGE_ROLE_V0_2_TYPE: &str =
    <trust_tasks_rs::specs::acl::change_role::v0_2::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `acl/show/0.2` — one entry, every axis stated.
pub(crate) const ACL_SHOW_V0_2_TYPE: &str =
    <trust_tasks_rs::specs::acl::show::v0_2::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `acl/list/0.2` — the entries, filterable by capability and resource.
pub(crate) const ACL_LIST_V0_2_TYPE: &str =
    <trust_tasks_rs::specs::acl::list::v0_2::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `acl/update/0.2` — amend act, capabilities, approve, label, expiry.
pub(crate) const ACL_UPDATE_V0_2_TYPE: &str =
    <trust_tasks_rs::specs::acl::update::v0_2::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `acl/revoke/0.2` — remove an entry, or narrow its act scope.
pub(crate) const ACL_REVOKE_V0_2_TYPE: &str =
    <trust_tasks_rs::specs::acl::revoke::v0_2::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `acl/swap-key/0.1` — a subject rolls its own entry to a new key, its
/// authority exactly preserved (VTI-CLT-025 – 032, VTI-ACL-052).
pub(crate) const ACL_SWAP_KEY_TYPE: &str =
    <trust_tasks_rs::specs::acl::swap_key::v0_1::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `auth/step-up/approve-response/0.4` — the passkey gesture an
/// operation-bound step-up asks for.
pub(crate) const STEP_UP_APPROVE_RESPONSE_TYPE: &str =
    <step_up_approve_response::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `auth/step-up/approve-response/0.5` — same wire shape as 0.4, but the
/// approver's `assertionMethod` proof is REQUIRED on every response, webauthn
/// evidence included. Served alongside 0.4; see
/// [`handle_step_up_approve_response_v0_5`].
pub(crate) const STEP_UP_APPROVE_RESPONSE_V0_5_TYPE: &str =
    <step_up_approve_response_v0_5::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `auth/step-up/approve-response/0.6` — adds a step-up approver's statement
/// (`evidence.kind = approverSigned`) as the factor (VTI-APV-015).
pub(crate) const STEP_UP_APPROVE_RESPONSE_V0_6_TYPE: &str =
    <step_up_approve_response_v0_6::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `vtc/join-requests/submit:presentationInvalid` — the presentation is not
/// the applicant's own.
pub(crate) const SUBMIT_ERR_PRESENTATION_INVALID: &str =
    jr::JOIN_REQUEST_SUBMIT_ERR_PRESENTATION_INVALID;

/// Resolve the proven holder DID for a holder-bound verb. DIDComm → the
/// authcrypt sender; REST → the document proof signer. When the document
/// carries an `issuer`, it must match the proven identity (anti-spoof).
async fn resolve_holder(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: &TrustTask<Value>,
) -> Result<String, TrustTaskOutcome> {
    // REST: the spine has already verified the document's proof over the JSON
    // as received and bound it to the issuer (`verified_signer`). Verifying it
    // again here, over the typed `doc`, would re-serialise it and refuse what
    // the producer actually signed (VTI-45). With no verified signer there is
    // no proof, and the typed call refuses that the same way it always has.
    let proven = match (&ctx.sender_did, &ctx.verified_signer) {
        (Some(did), _) => did.clone(),
        (None, Some(signer)) => signer.clone(),
        (None, None) => match verify_trust_task_proof(state, doc).await {
            Ok(did) => did,
            Err(e) => return Err(app_error_to_reject(doc, &e)),
        },
    };
    if let Some(issuer) = doc.issuer.as_deref() {
        let issuer_base = issuer.split('#').next().unwrap_or(issuer);
        if issuer_base != proven {
            return Err(reject_with(
                doc,
                RejectReason::PermissionDenied {
                    reason: format!(
                        "document issuer ({issuer_base}) does not match the authenticated holder ({proven})"
                    ),
                },
            ));
        }
    }
    Ok(proven)
}

// ─── submit / request ────────────────────────────────────────────────────

async fn handle_submit(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let applicant_did = match resolve_holder(state, ctx, &doc).await {
        Ok(did) => did,
        Err(reject) => return reject,
    };
    let body: JoinRequestSubmitBody = match parse_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };

    // Both transports authenticate the holder (REST proof / DIDComm sender)
    // and bind audience + freshness via the document recipient + expiry, so
    // the spine runs with no separate holder-binding signature.
    let outcome = match crate::join::submit_inner(
        state,
        applicant_did,
        body.vp,
        body.registry_consent,
        body.extensions,
        body.attributes
            .into_iter()
            .map(|a| crate::join::SubmittedAttribute {
                r#type: a.claim_type,
                value: a.value,
            })
            .collect(),
        body.criterion,
        None,
        ctx.transport,
    )
    .await
    {
        Ok(o) => o,
        // The applicant already has an open request. Answered as a typed code
        // with a machine-readable annex rather than the bare `taskFailed` the
        // generic mapping would produce: the whole defect Keyring reported
        // (VTI-04) was that a client could not tell this apart from any other
        // submit failure, nor learn which request was in the way, without
        // parsing English prose.
        //
        // `vtc/join-requests/submit` declares no code for this, so the code is
        // consumer-minted under the slug of the request being processed, which
        // SPEC.md §8.5 permits explicitly. A client that does not recognise it
        // falls back to `taskFailed` by the same section's rule, so this is
        // additive for every existing caller.
        Err(crate::join::SubmitRefusal::AlreadyOpen { request_id, status }) => {
            let refusal = crate::join::SubmitRefusal::AlreadyOpen { request_id, status };
            return reject_with_code_because(
                &doc,
                extended_code(jr::JOIN_REQUEST_SUBMIT_ERR_REQUEST_ALREADY_OPEN),
                AppError::from(refusal).to_string(),
                Some(serde_json::json!({
                    "requestId": request_id.to_string(),
                    "status": status.to_string(),
                })),
                reasons::CONFLICT,
            );
        }
        // The specification's own codes, with the types in `details`, so a
        // client can ask the applicant for exactly what is missing — or drop
        // exactly what it over-shared — without parsing a sentence.
        Err(crate::join::SubmitRefusal::AttributesMissing(types)) => {
            let details = serde_json::json!({ "types": types });
            return reject_with_code(
                &doc,
                extended_code(jr::JOIN_REQUEST_SUBMIT_ERR_ATTRIBUTES_MISSING),
                AppError::from(crate::join::SubmitRefusal::AttributesMissing(types)).to_string(),
                Some(details),
            );
        }
        Err(crate::join::SubmitRefusal::AttributesUnrequested(types)) => {
            let details = serde_json::json!({ "types": types });
            return reject_with_code(
                &doc,
                extended_code(jr::JOIN_REQUEST_SUBMIT_ERR_ATTRIBUTES_UNREQUESTED),
                AppError::from(crate::join::SubmitRefusal::AttributesUnrequested(types))
                    .to_string(),
                Some(details),
            );
        }
        Err(crate::join::SubmitRefusal::PresentationInvalid(reason)) => {
            return reject_with_code(
                &doc,
                extended_code(SUBMIT_ERR_PRESENTATION_INVALID),
                reason,
                None,
            );
        }
        // The community's criteria are its join rules; with none published it
        // accepts nobody, and says so rather than queueing what it will never
        // decide.
        Err(crate::join::SubmitRefusal::NotAccepting) => {
            return reject_with_code(
                &doc,
                extended_code(jr::JOIN_REQUEST_SUBMIT_ERR_NOT_ACCEPTING),
                AppError::from(crate::join::SubmitRefusal::NotAccepting).to_string(),
                None,
            );
        }
        Err(crate::join::SubmitRefusal::CriterionUnknown(digest)) => {
            let details = serde_json::json!({ "criterion": digest });
            return reject_with_code(
                &doc,
                extended_code(jr::JOIN_REQUEST_SUBMIT_ERR_CRITERION_UNKNOWN),
                AppError::from(crate::join::SubmitRefusal::CriterionUnknown(digest)).to_string(),
                Some(details),
            );
        }
        Err(crate::join::SubmitRefusal::Challenge(r)) => {
            return challenge_reject(
                &doc,
                crate::vetting::challenge_refusal::ChallengeTask::Submit,
                &r,
            );
        }
        Err(crate::join::SubmitRefusal::Other(e)) => return app_error_to_reject(&doc, &e),
    };

    match outcome_to_verdict(&outcome) {
        Ok(v) => verdict_response(&doc, v),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

/// A refused hidden-vetting challenge, answered under its own code.
///
/// Until these codes existed every way a challenge could fail went out as one
/// `malformedRequest`, and a client could not tell an applicant whether they
/// had simply taken too long or were sending a proof built over the wrong
/// challenge. Neither `submit` nor `supplement` declares a code for it, so the
/// codes are consumer-minted under the task's own slug (SPEC §8.5, as
/// `requestAlreadyOpen` is), with the generic `details.reason` marker beside
/// them for a client that does not know the code, and `expiredAt` for an
/// expired one. The message never carries the challenge value.
fn challenge_reject<P>(
    doc: &TrustTask<P>,
    task: crate::vetting::challenge_refusal::ChallengeTask,
    refusal: &crate::vetting::challenge_refusal::ChallengeRefusal,
) -> TrustTaskOutcome {
    reject_with_code_because(
        doc,
        extended_code(refusal.code(task)),
        refusal.to_string(),
        refusal.details(),
        refusal.marker(),
    )
}

/// Map the ceremony spine's [`JoinSubmitOutcome`] onto the wire
/// [`VerdictResponse`]. Auto-admit → `allow` (credentials inline);
/// `Pending` → `refer`; `Deferred` → `request_more`; `Rejected` → `deny`.
fn outcome_to_verdict(outcome: &JoinSubmitOutcome) -> Result<VerdictResponse, AppError> {
    use crate::ceremony::verdict::Verdict as PolicyVerdict;

    let request_id = outcome.request.id;

    if let Some(admit) = &outcome.admit {
        let role = outcome
            .request
            .policy_decision
            .clone()
            .and_then(|pd| serde_json::from_value::<PolicyVerdict>(pd).ok())
            .and_then(|v| match v {
                PolicyVerdict::Allow(a) => a.role,
                _ => None,
            });
        let vmc = serde_json::to_value(&admit.vmc)
            .map_err(|e| AppError::Internal(format!("serialise VMC: {e}")))?;
        let role_vac = serde_json::to_value(&admit.role_vac)
            .map_err(|e| AppError::Internal(format!("serialise role VAC: {e}")))?;
        return Ok(VerdictResponse::allow(
            request_id,
            role,
            Some(vmc),
            Some(role_vac),
        ));
    }

    // No auto-admit: shape the verdict from the persisted decision.
    let decision = outcome
        .request
        .policy_decision
        .clone()
        .and_then(|pd| serde_json::from_value::<PolicyVerdict>(pd).ok());

    let verdict = match decision {
        Some(PolicyVerdict::RequestMore(rm)) => VerdictResponse {
            request_id,
            verdict: jr::Verdict {
                effect: jr::VerdictEffect::RequestMore,
                with: jr::VerdictWith {
                    needs: rm.needs,
                    presentation_definition: Some(rm.presentation_definition),
                    ..Default::default()
                },
            },
        },
        Some(PolicyVerdict::Deny(d)) => VerdictResponse::deny(request_id, d.code, d.reason),
        Some(PolicyVerdict::Refer(r)) => {
            VerdictResponse::refer(request_id, r.queue, r.reason.unwrap_or_default())
        }
        // A `Pending` request with an `Allow`/absent decision (no auto-admit
        // path) is still queued for an admin: surface as `refer`.
        _ => VerdictResponse::refer(
            request_id,
            "admin-review",
            "queued for an admin decision (approve/reject)",
        ),
    };
    Ok(verdict)
}

// ─── vetting statement withdrawal ──────────────────────────────────────────

/// `vtc/vetting/revoke-statement/0.1` — a vetter withdraws a statement.
///
/// The sender is the proven signer (REST document proof or DIDComm authcrypt).
/// What a notice may do, and who may send one, is decided in
/// [`crate::vetting::revocation::withdraw`].
async fn handle_revoke_statement(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let vetter_did = match resolve_holder(state, ctx, &doc).await {
        Ok(did) => did,
        Err(reject) => return reject,
    };
    let body: revoke_statement::Payload = match parse_checked_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };
    let answer = crate::vetting::revocation::withdraw(state, &vetter_did, &body)
        .await
        .and_then(|notice| {
            revoke_statement::Response::try_from(
                revoke_statement::Response::builder().recorded_at(notice.recorded_at),
            )
            .map_err(|e| AppError::Internal(format!("revoke-statement response: {e}")).into())
        });
    match answer {
        Ok(response) => success_response(&doc, response),
        Err(e) => task_error_to_reject(&doc, &e),
    }
}

/// `vtc/vetting/vetters/grant/0.1` — an admin names a member a vetter.
///
/// The acting administrator is resolved as for every other administrative
/// task — the proven signer, or the administrator a console key acts for
/// ([`admin_signer`]) — and held to `vtc.vetting.manage` (VTI-ACL-030).
/// Whom (a current member) is decided in [`crate::vetting::vetters::grant`],
/// the same path `POST /v1/vetting/vetters` takes. Resolving the bare signer
/// here, as this handler once did, refused every grant the console made: the
/// console signs with its own `did:key`, which holds no entry of its own.
async fn handle_vetter_grant(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let admin_did = match capable_signer(
        state,
        ctx,
        &doc,
        crate::acl::Capability::VettingManage,
        None,
    )
    .await
    {
        Ok(claims) => claims.did,
        Err(reject) => return reject,
    };
    let body: vetting_wire::vetters::grant::v0_1::Payload = match parse_checked_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };
    match crate::vetting::vetters::grant(state, &admin_did, &body).await {
        Ok(grant) => success_response(&doc, grant.response),
        Err(e) => task_error_to_reject(&doc, &e),
    }
}

/// `vtc/vetting/vetters/pcs-root/0.1` — a vetter enrols for a class label.
///
/// The sender is the proven signer, and it is the member the community checks its records for:
/// a live vetter grant, no credential under this label yet, and the identifier they were bound
/// to. Every one of those is [`crate::vetting::pcs_issue::enrol`]'s, read from the store.
#[cfg(feature = "vetting-pcs")]
async fn handle_pcs_root(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let member_did = match resolve_holder(state, ctx, &doc).await {
        Ok(did) => did,
        Err(reject) => return reject,
    };
    match crate::vetting::pcs_tasks::handle_pcs_root(state, &member_did, &doc).await {
        Ok(response) => success_response(&doc, response),
        Err(e) => task_error_to_reject(&doc, &e),
    }
}

/// `vtc/vetting/vetters/pcs-tokens/0.1` — a vetter draws its tick of the drip.
#[cfg(feature = "vetting-pcs")]
async fn handle_pcs_tokens(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let member_did = match resolve_holder(state, ctx, &doc).await {
        Ok(did) => did,
        Err(reject) => return reject,
    };
    match crate::vetting::pcs_tasks::handle_pcs_tokens(state, &member_did, &doc).await {
        Ok(response) => success_response(&doc, response),
        Err(e) => task_error_to_reject(&doc, &e),
    }
}

/// `vtc/vetting/vetters/event-mode/0.1` — a vetter asks to vet at a named event.
///
/// The request is only ever a request. Approving it is an act by an admin of the community,
/// through the criterion that publishes the event — deliberately not a Trust Task, because a task
/// the vetter could send is a task a vetter could be made to send.
#[cfg(feature = "vetting-pcs")]
async fn handle_event_mode(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let member_did = match resolve_holder(state, ctx, &doc).await {
        Ok(did) => did,
        Err(reject) => return reject,
    };
    match crate::vetting::pcs_tasks::handle_event_mode(state, &member_did, &doc).await {
        Ok(response) => success_response(&doc, response),
        Err(e) => task_error_to_reject(&doc, &e),
    }
}

/// `vtc/vetting/pcs-challenge/0.1` — an applicant asks for the nonce its proof must bind.
///
/// Open to any party the community would take a submission from, which is the same entitlement
/// that admits them to apply: the challenge confers no standing, it only makes one submission
/// unrepeatable.
#[cfg(feature = "vetting-pcs")]
async fn handle_pcs_challenge(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let applicant_did = match resolve_holder(state, ctx, &doc).await {
        Ok(did) => did,
        Err(reject) => return reject,
    };
    match crate::vetting::pcs_tasks::handle_pcs_challenge(state, &applicant_did, &doc).await {
        Ok(response) => success_response(&doc, response),
        Err(e) => task_error_to_reject(&doc, &e),
    }
}

/// `vtc/vetting/hidden/publish/0.1` — turn on (or rotate) hidden-vetter admission for a
/// criterion. Admin only, read from the signer's ACL entry — the same `VtcRole::Admin` the REST
/// route's `AdminAuth` demanded, and the only gate that route applied. Was `POST /vetting/hidden`;
/// the derivation itself is
/// [`crate::routes::vetting_hidden::publish_hidden_vetting_core`], shared with that route.
#[cfg(feature = "vetting-pcs")]
async fn handle_hidden_publish(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    // The signer is kept: an event approval it adds must name it (publish/0.1 item 9), and the
    // consent gate (VTI-APV-023) is the signer's.
    let actor = match capable_signer(
        state,
        ctx,
        &doc,
        crate::acl::Capability::VettingManage,
        None,
    )
    .await
    {
        Ok(claims) => claims,
        Err(reject) => return reject,
    };
    let payload: trust_tasks_rs::specs::vtc::vetting::hidden::publish::v0_1::Payload =
        match parse_spec_payload(&doc) {
            Ok(p) => p,
            Err(reject) => return reject,
        };
    let live_periods = payload
        .live_periods
        .iter()
        .map(|p| p.to_string())
        .collect::<Vec<_>>();
    let live_token_labels = payload
        .live_token_labels
        .iter()
        .map(|l| l.to_string())
        .collect::<Vec<_>>();
    let events = if payload.events.is_empty() {
        None
    } else {
        match serde_json::to_value(&payload.events) {
            Ok(v) => Some(v),
            Err(e) => {
                return app_error_to_reject(
                    &doc,
                    &AppError::Internal(format!("encode events: {e}")),
                );
            }
        }
    };
    match crate::routes::vetting_hidden::publish_hidden_vetting_core(
        state,
        &actor,
        &doc,
        payload.criterion_id.to_string(),
        if live_periods.is_empty() {
            None
        } else {
            Some(live_periods)
        },
        if live_token_labels.is_empty() {
            None
        } else {
            Some(live_token_labels)
        },
        payload.drip_per_tick.map(|n| n.get() as usize),
        payload.tick_length.as_ref().map(|t| t.to_string()),
        events,
    )
    .await
    {
        Ok(response) => success_response(&doc, response),
        Err(crate::routes::vetting_hidden::Halted::Refused(e)) => task_error_to_reject(&doc, &e),
        Err(crate::routes::vetting_hidden::Halted::Gate(outcome)) => outcome,
    }
}

/// `vtc/vetting/hidden/withdraw/0.1` — turn hidden-vetter admission off for a criterion. The
/// same gate as publish, `VettingManage`, read from the signer's ACL entry.
#[cfg(feature = "vetting-pcs")]
async fn handle_hidden_withdraw(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let actor = match capable_signer(
        state,
        ctx,
        &doc,
        crate::acl::Capability::VettingManage,
        None,
    )
    .await
    {
        Ok(claims) => claims,
        Err(reject) => return reject,
    };
    let payload: trust_tasks_rs::specs::vtc::vetting::hidden::withdraw::v0_1::Payload =
        match parse_spec_payload(&doc) {
            Ok(p) => p,
            Err(reject) => return reject,
        };
    match crate::routes::vetting_hidden::withdraw_hidden_vetting_core(
        state,
        &actor,
        &doc,
        payload.criterion_id.to_string(),
    )
    .await
    {
        Ok(response) => success_response(&doc, response),
        Err(crate::routes::vetting_hidden::Halted::Refused(e)) => task_error_to_reject(&doc, &e),
        Err(crate::routes::vetting_hidden::Halted::Gate(outcome)) => outcome,
    }
}

/// `vtc/vetting/hidden/show/0.1` — a criterion's stored hidden-vetting configuration, with the
/// enrolment and event-demand counts. Administrators only (`VettingManage`): it names who
/// approved each event.
#[cfg(feature = "vetting-pcs")]
async fn handle_hidden_show(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(reject) = capable_signer(
        state,
        ctx,
        &doc,
        crate::acl::Capability::VettingManage,
        None,
    )
    .await
    {
        return reject;
    }
    let payload: trust_tasks_rs::specs::vtc::vetting::hidden::show::v0_1::Payload =
        match parse_spec_payload(&doc) {
            Ok(p) => p,
            Err(reject) => return reject,
        };
    match crate::routes::vetting_hidden::show_hidden_vetting_core(
        state,
        payload.criterion_id.to_string(),
    )
    .await
    {
        Ok(response) => success_response(&doc, response),
        Err(e) => task_error_to_reject(&doc, &e),
    }
}

/// Parse a published task's payload as received: the JSON is validated against
/// the published schema before it is parsed — a generated constructor can
/// normalise what it reads — and then the rules no schema can state are applied
/// ([`vetting_wire::read_checked`]). A payload failing any of it is
/// `malformedRequest`.
fn parse_checked_payload<P>(doc: &TrustTask<Value>) -> Result<P, TrustTaskOutcome>
where
    P: trust_tasks_rs::Payload + serde::de::DeserializeOwned + vetting_wire::CheckShape,
{
    vetting_wire::read_checked::<P>(&doc.payload).map_err(|e| {
        reject_with(
            doc,
            RejectReason::MalformedRequest {
                reason: format!("payload: {e}"),
            },
        )
    })
}

/// `vtc/vetting/vetters/profile/0.1` — a vetter publishes their profile.
///
/// The sender is the proven signer and the only vetter whose profile it can
/// write. Who may publish is decided in [`crate::vetting::profiles::publish`];
/// a sender without a live grant is refused with the task's `notEligible`.
async fn handle_vetter_profile(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let vetter_did = match resolve_holder(state, ctx, &doc).await {
        Ok(did) => did,
        Err(reject) => return reject,
    };
    let body: vetting_wire::vetters::profile::v0_1::Payload = match parse_checked_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };
    match crate::vetting::profiles::publish(state, &vetter_did, &body, doc.issued_at).await {
        Ok(response) => success_response(&doc, response),
        Err(AppError::Forbidden(reason)) => reject_with_code(
            &doc,
            extended_code(vetting_wire::VETTING_VETTER_PROFILE_ERR_NOT_ELIGIBLE),
            reason,
            None,
        ),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

/// `vtc/vetting/vetters/list/0.1` — find listed vetters.
///
/// Any identified caller, member or applicant. [`resolve_holder`] is what
/// refuses an unidentified one — no proof over REST, no authenticated sender
/// otherwise — with `permissionDenied`, before anything is read.
async fn handle_vetter_list(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(reject) = resolve_holder(state, ctx, &doc).await {
        return reject;
    }
    let body: vetting_wire::vetters::list::v0_1::Payload = match parse_checked_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };
    match crate::vetting::profiles::list(state, &body).await {
        Ok(response) => success_response(&doc, response),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

/// `vtc/vetting/vetters/show/0.1` — one vetter's grant status, by DID.
///
/// Identified callers only, like the listing: the answer is about a named
/// third party's standing in this community.
async fn handle_vetter_show(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(reject) = resolve_holder(state, ctx, &doc).await {
        return reject;
    }
    let body: vetting_wire::vetters::show::v0_1::Payload = match parse_checked_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };
    match crate::vetting::profiles::show(state, &body).await {
        Ok(response) => success_response(&doc, response),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

/// `vtc/vetting/vetters/resend/0.1` — a vetter asks for their grant credential
/// again. Always the sender's own grant.
async fn handle_vetter_resend(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    use trust_tasks_rs::{StandardCode, TrustTaskCode};

    let vetter_did = match resolve_holder(state, ctx, &doc).await {
        Ok(did) => did,
        Err(reject) => return reject,
    };
    if let Err(reject) = parse_checked_payload::<vetting_wire::vetters::resend::v0_1::Payload>(&doc)
    {
        return reject;
    }
    match crate::vetting::vetters::resend(state, &vetter_did, &vetter_did).await {
        Ok(response) => success_response(&doc, response),
        // `notGranted` is a `NotFound` underneath, and its local part is not
        // `notFound`, so #1602's client-side rule does not recover it — the
        // marker is the only thing that does.
        Err(AppError::NotFound(reason)) => reject_with_code_because(
            &doc,
            extended_code(vetting_wire::VETTING_VETTER_RESEND_ERR_NOT_GRANTED),
            reason,
            None,
            reasons::NOT_FOUND,
        ),
        Err(AppError::ServiceError { status, message })
            if status == axum::http::StatusCode::SERVICE_UNAVAILABLE =>
        {
            reject_with_code(
                &doc,
                TrustTaskCode::Standard(StandardCode::Unavailable),
                message,
                None,
            )
        }
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

/// `vtc/vetting/vetters/resend/0.2` — a vetter asks for their grant credential
/// again, or an administrator asks on a named vetter's behalf.
///
/// Absent `memberDid`, this is exactly `handle_vetter_resend`'s `0.1` behaviour:
/// the sender identified by the document's own proof (`resolve_holder`),
/// resending their own grant. Present, [`admin_signer`] establishes the
/// sender holds the community-administrator capability — refusing with
/// `permissionDenied` otherwise, per the specification's Conformance item 2 —
/// and honours a console-key delegation exactly as the other admin verbs do;
/// the resend then concerns `memberDid`'s grant, not the sender's own. Either
/// way the actor recorded on the `VetterGrantResent` audit entry is the
/// sender, never the subject, so an administrator's resend is attributable to
/// the administrator who asked for it.
async fn handle_vetter_resend_v0_2(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    use trust_tasks_rs::{StandardCode, TrustTaskCode};

    let body: vetting_wire::vetters::resend::v0_2::Payload = match parse_checked_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };
    let (actor_did, subject_did) = match body.member_did.as_ref() {
        Some(member_did) => {
            let admin = match capable_signer(
                state,
                ctx,
                &doc,
                crate::acl::Capability::VettingManage,
                None,
            )
            .await
            {
                Ok(a) => a,
                Err(reject) => return reject,
            };
            (admin.did, member_did.to_string())
        }
        None => {
            let vetter_did = match resolve_holder(state, ctx, &doc).await {
                Ok(did) => did,
                Err(reject) => return reject,
            };
            (vetter_did.clone(), vetter_did)
        }
    };
    match crate::vetting::vetters::resend(state, &actor_did, &subject_did).await {
        // `notGranted` is a `NotFound` underneath, and its local part is not
        // `notFound`, so #1602's client-side rule does not recover it — the
        // marker is the only thing that does. `0.1` and `0.2` declare the
        // identical code text, so `0.1`'s constant witnesses both.
        Err(AppError::NotFound(reason)) => reject_with_code_because(
            &doc,
            extended_code(vetting_wire::VETTING_VETTER_RESEND_ERR_NOT_GRANTED),
            reason,
            None,
            reasons::NOT_FOUND,
        ),
        Err(AppError::ServiceError { status, message })
            if status == axum::http::StatusCode::SERVICE_UNAVAILABLE =>
        {
            reject_with_code(
                &doc,
                TrustTaskCode::Standard(StandardCode::Unavailable),
                message,
                None,
            )
        }
        Err(e) => app_error_to_reject(&doc, &e),
        Ok(response) => success_response(&doc, response),
    }
}

// ─── manifest (public by default) ──────────────────────────────────────────

/// Whether this caller is one the community can name.
///
/// Either proof of identity will do, because the two transports prove it
/// differently and both are real: over REST a signed document names its signer
/// (`verified_signer`), over DIDComm the authcrypt envelope names its sender
/// (`sender_did`). Requiring the REST form on a DIDComm caller — or the reverse
/// — would refuse a party the transport has already identified.
fn caller_is_identified(ctx: &JoinAuthCtx) -> bool {
    ctx.verified_signer.is_some() || ctx.sender_did.is_some()
}

/// The join manifest (`vtc/join-requests/manifest/0.3`).
///
/// Public unless the community has turned public discovery off, in which case
/// an unidentified caller is refused and an identified one is answered exactly
/// as before — see [`JoinDiscovery`](crate::community::profile::JoinDiscovery).
/// The refusal is `permissionDenied` with a sentence saying *how* to ask rather
/// than only that this failed: a client that reads "not public" and stops has
/// been told the wrong thing, because the same question over an identified
/// transport still answers.
async fn handle_manifest(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    use crate::routes::join_requests::manifest::manifest_v0_3;
    if !caller_is_identified(ctx) {
        let public = match crate::community::join_discovery::load_join_discovery(
            &state.community_ks,
        )
        .await
        {
            Ok(setting) => setting.public,
            // A setting that cannot be read is not a reason to stop answering a
            // question that has always been public: failing open keeps a
            // storage fault from looking like a closed community, and the
            // manifest carries nothing that was not already published.
            Err(e) => {
                tracing::warn!(error = %e, "join discovery unreadable; answering the manifest");
                true
            }
        };
        if !public {
            return reject_with(
                &doc,
                RejectReason::PermissionDenied {
                    reason: "this community does not publish its join requirements to callers \
                             it cannot identify — ask over DIDComm, or with a signed Trust Task \
                             document"
                        .to_string(),
                },
            );
        }
    }
    manifest_v0_3(state)
        .await
        .map(|r| success_response(&doc, r))
        .unwrap_or_else(|e| app_error_to_reject(&doc, &e))
}

// ─── status ────────────────────────────────────────────────────────────────

async fn handle_status(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let applicant_did = match resolve_holder(state, ctx, &doc).await {
        Ok(did) => did,
        Err(reject) => return reject,
    };
    let body: JoinRequestStatusBody = match parse_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };

    // No `requestId` means "what is my open request?" — the applicant is already
    // authenticated by the authcrypt sender, and at most one request per
    // applicant is open (the submit dedup), so the community can resolve it.
    //
    // This is the only form of the poll available to an applicant whose first
    // correlated reply was lost: the id it would otherwise quote is the
    // community's, learned from that reply, so it holds nothing this VTC
    // recognises. The response carries `requestId`, so answering once also
    // repairs the applicant's record for every later poll.
    let result = match body.request_id {
        Some(request_id) => {
            crate::routes::join_requests::status::status_inner(
                state,
                request_id,
                applicant_did,
                body.resend_credentials,
            )
            .await
        }
        None => {
            crate::routes::join_requests::status::status_by_applicant(
                state,
                applicant_did,
                body.resend_credentials,
            )
            .await
        }
    };

    match result {
        Ok(resp) => success_response(&doc, resp),
        Err(e) => task_error_to_reject(&doc, &e),
    }
}

// ─── members ─────────────────────────────────────────────────────────────

/// `members/self-remove/0.1` as a Trust Task document — the member-initiated
/// leave (R-L-1).
///
/// Actor == subject, and the leave policy allows self-leave unconditionally
/// (spec §10.2) with the no-last-admin invariant still enforced in the effect
/// stage. A member performs it over any transport this dispatcher serves —
/// over DIDComm, in the binding envelope.
///
/// The bare-body DIDComm handler that predated this (typed as the task, with
/// none of the spine's freshness, recipient or proof checks) was retired for
/// Keyring VTI-42; this is now the only path.
/// `vtc/join-requests/supplement/0.1` — the applicant answers the community's
/// request for more evidence, against the request they already have open.
///
/// Holder-bound like `withdraw`: [`resolve_holder`] proves the caller, and
/// that proven identity is the authorization, because ownership of the request
/// is the entitlement and an applicant holds nothing else to check.
///
/// The success path deliberately runs through [`outcome_to_verdict`] and
/// [`verdict_response`] — submit's own — because a supplement's response *is*
/// submit's response. A second projection here would be a second place for the
/// four verdict effects to be rendered, and they would drift.
async fn handle_supplement(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    use crate::join::SupplementRefusal;

    let applicant_did = match resolve_holder(state, ctx, &doc).await {
        Ok(did) => did,
        Err(reject) => return reject,
    };
    let body: jr::supplement::v0_1::Payload = match parse_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };

    let request_id = match body.request_id.as_ref().map(|r| uuid::Uuid::parse_str(r)) {
        None => None,
        Some(Ok(id)) => Some(id),
        Some(Err(e)) => {
            return reject_with(
                &doc,
                RejectReason::MalformedRequest {
                    reason: format!("requestId is not a UUID: {e}"),
                },
            );
        }
    };

    let outcome = match crate::join::supplement_inner(
        state,
        &applicant_did,
        request_id,
        Value::Object(body.vp.clone()),
        Value::Object(body.extensions.clone()),
        ctx.transport,
    )
    .await
    {
        Ok(o) => o,
        // All three are spec-declared, so each goes out as itself. The generic
        // mapping would flatten them into one `taskFailed`, and "nothing to
        // supplement", "nothing has been asked of you" and "already decided"
        // are three different things for an applicant to do next.
        Err(e @ SupplementRefusal::NotFound(_)) => {
            return reject_with_code_because(
                &doc,
                extended_code(jr::JOIN_REQUEST_SUPPLEMENT_ERR_NOT_FOUND),
                AppError::from(e).to_string(),
                None,
                reasons::NOT_FOUND,
            );
        }
        Err(SupplementRefusal::NotAwaitingEvidence { request_id, status }) => {
            let refusal = SupplementRefusal::NotAwaitingEvidence { request_id, status };
            return reject_with_code_because(
                &doc,
                extended_code(jr::JOIN_REQUEST_SUPPLEMENT_ERR_NOT_AWAITING_EVIDENCE),
                AppError::from(refusal).to_string(),
                Some(serde_json::json!({
                    "requestId": request_id.to_string(),
                    "status": status.to_string(),
                })),
                reasons::CONFLICT,
            );
        }
        Err(SupplementRefusal::AlreadyDecided { request_id, status }) => {
            let refusal = SupplementRefusal::AlreadyDecided { request_id, status };
            return reject_with_code_because(
                &doc,
                extended_code(jr::JOIN_REQUEST_SUPPLEMENT_ERR_ALREADY_DECIDED),
                AppError::from(refusal).to_string(),
                Some(serde_json::json!({
                    "requestId": request_id.to_string(),
                    "status": status.to_string(),
                })),
                reasons::GONE,
            );
        }
        Err(SupplementRefusal::Challenge(r)) => {
            return challenge_reject(
                &doc,
                crate::vetting::challenge_refusal::ChallengeTask::Supplement,
                &r,
            );
        }
        Err(SupplementRefusal::Other(e)) => return app_error_to_reject(&doc, &e),
    };

    match outcome_to_verdict(&outcome) {
        Ok(v) => verdict_response(&doc, v),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

/// `vtc/join-requests/withdraw/0.1` — the applicant closes their own request.
///
/// Holder-bound like `self-remove`: [`resolve_holder`] proves the caller
/// (authcrypt sender on DIDComm, document proof signer on REST) and refuses a
/// document whose `issuer` names anyone else. That proven identity *is* the
/// authorization — the spec's entitlement is ownership of the request, and an
/// applicant holds no membership or capability to check instead.
async fn handle_withdraw(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let applicant_did = match resolve_holder(state, ctx, &doc).await {
        Ok(did) => did,
        Err(reject) => return reject,
    };
    let body: jr::withdraw::v0_1::Payload = match parse_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };

    // Every member is optional, so an empty payload is the common case: the
    // proven caller identifies the applicant and at most one request is open.
    let request_id = match body.request_id.as_ref().map(|r| uuid::Uuid::parse_str(r)) {
        None => None,
        Some(Ok(id)) => Some(id),
        Some(Err(e)) => {
            return reject_with(
                &doc,
                RejectReason::MalformedRequest {
                    reason: format!("requestId is not a UUID: {e}"),
                },
            );
        }
    };

    match crate::join::orchestrate::withdraw_inner(
        state,
        &applicant_did,
        request_id,
        body.reason.as_ref().map(|r| r.to_string()),
    )
    .await
    {
        Ok(request) => {
            // Built through the generated builder rather than a JSON literal,
            // so the response cannot drift from the schema that defines it.
            let response = match jr::withdraw::v0_1::Response::builder()
                .request_id(request.id.to_string())
                .status(jr::withdraw::v0_1::ResponseStatus::Withdrawn)
                .try_into()
            {
                Ok(r) => r,
                Err(e) => {
                    return reject_with(
                        &doc,
                        RejectReason::InternalError {
                            reason: format!("withdraw response failed its own schema: {e}"),
                        },
                    );
                }
            };
            success_response::<_, jr::withdraw::v0_1::Response>(&doc, response)
        }
        // The spec declares both of these, so they go out as themselves. The
        // generic `app_error_to_reject` would flatten each into a bare
        // `taskFailed` carrying only English, which is precisely what an
        // applicant's client cannot branch on — and telling "nothing to
        // withdraw" apart from "already decided" is the whole point of
        // declaring two codes.
        Err(e @ AppError::NotFound(_)) => reject_with_code_because(
            &doc,
            extended_code(jr::JOIN_REQUEST_WITHDRAW_ERR_NOT_FOUND),
            e.to_string(),
            None,
            reasons::NOT_FOUND,
        ),
        Err(e @ AppError::Gone(_)) => reject_with_code_because(
            &doc,
            extended_code(jr::JOIN_REQUEST_WITHDRAW_ERR_ALREADY_DECIDED),
            e.to_string(),
            None,
            reasons::GONE,
        ),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

async fn handle_self_remove(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let member_did = match resolve_holder(state, ctx, &doc).await {
        Ok(did) => did,
        Err(reject) => return reject,
    };
    let body: jr::SelfRemoveBody = match parse_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };
    let disposition = match body
        .disposition
        .as_deref()
        .map(crate::messaging::parse_disposition)
        .transpose()
    {
        Ok(d) => d,
        Err(reason) => return reject_with(&doc, RejectReason::MalformedRequest { reason }),
    };

    match crate::ceremony::orchestrate::remove_inner(
        state,
        &member_did,
        &member_did,
        disposition,
        String::new(),
        // A self-leave: nobody else's authority ends, so nothing to bind.
        None,
    )
    .await
    {
        Ok(outcome) => success_response(
            &doc,
            jr::SelfRemoveReceiptBody {
                did: outcome.did,
                disposition: outcome.disposition,
                removed: outcome.removed,
            },
        ),
        Err(e) => task_error_to_reject(&doc, &e),
    }
}

// ─── the admin-facing member verbs (#1641 phase 2) ───────────────────────

/// The administrator a signed admin document is authorized as.
///
/// # Why this is not the bearer route's gate, and why it is not weaker
///
/// The REST routes these four verbs also sit on take `AdminAuth`: a live
/// session whose JWT says `role: admin`. That claim was itself written from the
/// caller's ACL row — `map_vtc_role_to_auth_role` admits only `VtcRole::Admin`
/// — at the moment the session was minted, and nothing re-reads it afterwards.
///
/// Here there is no session, because a signed document is not a session: the
/// proof says who authored *this document*, and **VTI-OPS-020** is satisfied by
/// that rather than by a transport. So authority is read from the ACL entry
/// [`crate::acl::resolve_auth_role`] finds for the verified signer, **at the
/// time the document is executed**. That is the same rule the bearer route
/// applies, evaluated later: a row removed, expired, or demoted since the
/// session began refuses here and would not have refused there.
///
/// What does change is the revocation lever. A bearer session is killed by
/// revoking the session; a signed document is refused by removing or expiring
/// the ACL row, which is the only authority it ever rested on. That is
/// deliberate — `docs/05-design-notes/vtc-trust-task-proof-enforcement.md` §1
/// — and it is why nothing here consults `sessions_ks`.
///
/// The signer is taken from [`JoinAuthCtx::verified_signer`], which the spine
/// filled in from the proof it verified against the document's own `issuer`
/// (SPEC §4.7) — never from the transport. All four of these specifications
/// declare `proof` REQUIRED, so the spine has already refused a document
/// carrying none; the `None` arm is belt to that brace, exactly as the
/// `rooms/*` arm keeps its own.
///
/// # Acting as, via a console-key delegation (#1684)
///
/// A signer with **no ACL row of its own** may still be a console signing key
/// — a `did:key` the admin SPA generated in the browser and enrolled as a
/// credential of the operator's admin DID, so the console can author a signed
/// document at all. Then the delegation names an admin DID and *that* DID's
/// ACL row is resolved, here, at execution time. Nothing in the paragraphs
/// above changes: a delegation carries no role, the row is still the whole
/// authority, and a row removed, demoted or expired since the key was enrolled
/// refuses exactly as it would for a direct signer. `sessions_ks` is still not
/// consulted.
///
/// **The fall-through is only for a signer with no row at all.** A signer that
/// *has* one is answered by it, including when it refuses. The design note
/// sketches falling through on `Forbidden` too; that would let a delegation
/// route around a row that has since been demoted or expired, which is the one
/// thing "authority is the ACL row" exists to prevent.
/// [`crate::acl::console_key`] carries the matching enrolment refusal, so the
/// two halves cannot drift.
///
/// # What a delegated key may *not* do, and why nothing here enforces it
///
/// Two escalations are worth naming, because both are closed structurally and
/// a later change could quietly open either.
///
/// - **It cannot enrol another delegation.** `POST /v1/admin/console-keys` is a
///   bearer route under `AdminAuth`, and a bearer session is minted only for a
///   DID that `resolve_auth_role` admits — which a console DID, holding no ACL
///   row, never is. A console key therefore cannot authenticate at all, let
///   alone reach the enrolment door. `tests/admin_console_keys.rs::
///   a_console_key_gains_no_bearer_authority` pins that.
/// - **It cannot spend a session's step-up, or make a gesture.** These claims
///   carry `session_id: ""` (the `Default`), so
///   `AuthClaims::require_fresh_step_up` finds no session and refuses. A verb
///   on this door that confers administrative authority (`acl/grant`) asks
///   [`crate::acl::bound_step_up`] instead, for a gesture bound to that one
///   operation. A delegated key can *redeem* such a gesture — it acts as its
///   admin — but only the admin's own user-verified passkey can *record* one
///   (`vtc-operation-bound-step-up.md`).
async fn admin_signer(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: &TrustTask<Value>,
) -> Result<vti_common::auth::extractor::AuthClaims, TrustTaskOutcome> {
    let Some(signer) = ctx.verified_signer.clone() else {
        return Err(reject_with(doc, RejectReason::ProofRequired));
    };

    // The signer's own row first — unchanged for the CLI, integrations and
    // wallets, which is every caller that is not a browser.
    let has_own_row = crate::acl::get_acl_entry(&state.acl_ks, &signer)
        .await
        .map_err(|e| app_error_to_reject(doc, &e))?
        .is_some();

    if !has_own_row
        && let Some(delegation) =
            crate::acl::console_key::resolve_delegated_admin(&state.console_keys_ks, &signer)
                .await
                .map_err(|e| app_error_to_reject(doc, &e))?
    {
        // Resolve the delegating admin's row *before* stamping last-used, so
        // the stamp records an authorized use rather than an attempt.
        let claims = resolve_admin_claims(state, doc, &delegation.admin_did).await?;
        crate::acl::console_key::touch_last_used(&state.console_keys_ks, &delegation).await;
        tracing::info!(
            console_did = %signer,
            admin_did = %delegation.admin_did,
            task = %doc.type_uri,
            "authorizing a signed document under a console-key delegation"
        );
        return Ok(claims);
    }

    // Not delegated, or delegated and revoked/expired. Falls through to the
    // ordinary resolve, so the refusal is the same `permissionDenied` an
    // unknown signer has always got — a distinct code here would tell a prober
    // which DIDs are, or once were, console keys.
    resolve_admin_claims(state, doc, &signer).await
}

/// [`admin_signer`], held to **the capability the operation needs**
/// (`vtc-admin-roles.md` §4 "Gates"; **VTI-ACL-030**, **-034**, **-036**).
///
/// The capability is read from the acting administrator's live entry — the
/// signer's own, or the delegating administrator's for a console key — at
/// execution time, through the one authorization question,
/// [`crate::acl::VtcAclEntry::can`]. Never from the claims: every
/// administrator's claims look alike (`crate::acl::resolve_auth_role`).
/// `resource` narrows the question to one resource (`None` = community-wide).
pub(crate) async fn capable_signer(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: &TrustTask<Value>,
    cap: crate::acl::Capability,
    resource: Option<&crate::acl::ResourceQualifier>,
) -> Result<vti_common::auth::extractor::AuthClaims, TrustTaskOutcome> {
    let claims = admin_signer(state, ctx, doc).await?;
    crate::acl::require_capability(&state.acl_ks, &claims.did, cap, resource)
        .await
        .map_err(|e| app_error_to_reject(doc, &e))?;
    Ok(claims)
}

/// The administrative verbs a suspended subject may still send: reading the
/// action list, where it sees the reduction about itself (VTI-APV-019), and
/// withdrawing a request of its own — which reduces nothing, and is refused
/// for any action it did not ask for.
const SUSPENDED_MAY_SEND: &[&str] = &[
    action_tasks::LIST_TYPE,
    action_tasks::LIST_V0_2_TYPE,
    action_tasks::SHOW_TYPE,
    action_tasks::SHOW_V0_2_TYPE,
    action_tasks::CANCEL_TYPE,
    action_tasks::CANCEL_V0_2_TYPE,
];

/// Read `did`'s ACL row and shape it into the claims the admin verbs take.
///
/// Split out of [`admin_signer`] because the delegated arm needs the identical
/// resolution, and "identical" has to be structural rather than remembered.
async fn resolve_admin_claims(
    state: &AppState,
    doc: &TrustTask<Value>,
    did: &str,
) -> Result<vti_common::auth::extractor::AuthClaims, TrustTaskOutcome> {
    let (role, allowed_contexts) = crate::acl::resolve_auth_role(&state.acl_ks, did)
        .await
        .map_err(|e| app_error_to_reject(doc, &e))?;
    // A subject whose reduction is cooling off is suspended
    // (`vtc-action-list.md` §8.2): it may read the action list — to see the
    // action about itself (VTI-APV-019) — and nothing else, whatever the
    // operation. One refusal here, naming the action and when it lands, for
    // every administrative verb; the capability checks behind it refuse too.
    if !SUSPENDED_MAY_SEND.contains(&doc.type_uri.to_string().as_str())
        && let Some(s) = crate::acl::storage::get_suspension(&state.acl_ks, did)
            .await
            .map_err(|e| app_error_to_reject(doc, &e))?
    {
        return Err(app_error_to_reject(doc, &s.refusal(did)));
    }
    Ok(vti_common::auth::extractor::AuthClaims {
        did: did.to_string(),
        role,
        allowed_contexts,
        ..Default::default()
    })
}

/// Validate a payload against its published schema and hand back the
/// generated type.
///
/// The generated `Payload` carries `deny_unknown_fields` and the required set,
/// and `validate_value` adds what serde cannot see — `const`, `enum`,
/// `pattern`, `minLength`. The bearer routes get the first half from their
/// hand-written bodies and the second from nothing at all, so this door is the
/// stricter of the two.
fn parse_spec_payload<P>(doc: &TrustTask<Value>) -> Result<P, TrustTaskOutcome>
where
    P: trust_tasks_rs::validate::ValidatedPayload + serde::de::DeserializeOwned,
{
    if let Err(e) = P::validate_value(&doc.payload) {
        return Err(reject_with(
            doc,
            RejectReason::MalformedRequest {
                reason: format!("payload: {e}"),
            },
        ));
    }
    parse_payload::<P>(doc)
}

/// `vtc/members/credentials/0.1` — the membership pair's bodies for one member.
///
/// Administrator only. The read is audited against the **signer**, which is the
/// point of the task declaring a proof: the specification's own rationale is
/// that "the record of who read a member's credentials is the only thing that
/// makes the disclosure accountable afterwards", and a bearer token names a
/// session rather than a key.
async fn handle_member_credentials(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let actor = match capable_signer(
        state,
        ctx,
        &doc,
        crate::acl::Capability::MembersManage,
        None,
    )
    .await
    {
        Ok(a) => a,
        Err(reject) => return reject,
    };
    let body: member_credentials::Payload = match parse_spec_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };
    match crate::routes::members::credentials::read_member_credentials(
        state,
        &actor.did,
        body.did.as_str(),
    )
    .await
    {
        Ok(response) => success_response(&doc, response),
        // The task's one declared code, carried as a code rather than flattened
        // into `taskFailed` (SPEC §8.5) — the same distinction the REST route's
        // `CredentialsError` makes in its body.
        Err(crate::routes::members::credentials::CredentialsError::NotFound(message)) => {
            task_error_to_reject(
                &doc,
                &crate::error::TaskError::declared(
                    crate::routes::members::credentials::MEMBER_CREDENTIALS_ERR_NOT_FOUND,
                    AppError::NotFound(message),
                ),
            )
        }
        Err(crate::routes::members::credentials::CredentialsError::Other(e)) => {
            app_error_to_reject(&doc, &e)
        }
    }
}

/// `vtc/members/update/0.1` — update a member's role or metadata.
///
/// Administrator only, and `role: admin` is refused with the task's own
/// `adminRoleForbidden` — the gate is on the transition, not on the route, so
/// it holds identically on both doors.
///
/// # Why the payload is read twice
///
/// The generated `Payload` types `extensions` as a plain map with `default`, so
/// an absent `extensions` and an empty one are the same value once parsed —
/// and the operation's rule is that an absent field leaves the member's
/// extensions **unchanged** while an empty object replaces them. Reading the
/// same JSON into the route's own `UpdateMemberRequest`, whose fields are
/// `Option`, keeps that distinction. The generated parse still runs, and runs
/// first, because it is what validates the document against its published
/// schema.
async fn handle_member_update(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let actor = match capable_signer(
        state,
        ctx,
        &doc,
        crate::acl::Capability::MembersManage,
        None,
    )
    .await
    {
        Ok(a) => a,
        Err(reject) => return reject,
    };
    let checked: member_update::Payload = match parse_spec_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };
    let req: crate::routes::members::update::UpdateMemberRequest = match parse_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };
    match crate::routes::members::update::update_member_inner(
        state,
        &actor,
        checked.did.as_str(),
        req,
    )
    .await
    {
        Ok(envelope) => success_response(&doc, envelope),
        Err(e) => task_error_to_reject(&doc, &e),
    }
}

/// `vtc/members/admin-remove/0.1` — an administrator removes another member.
async fn handle_member_admin_remove(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let actor = match capable_signer(
        state,
        ctx,
        &doc,
        crate::acl::Capability::MembersManage,
        None,
    )
    .await
    {
        Ok(a) => a,
        Err(reject) => return reject,
    };
    let checked: member_admin_remove::Payload = match parse_spec_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };
    // Same reason as `update` above: `disposition` and `reason` are optional
    // and the route's body type is the one that says so.
    let body: crate::routes::members::remove::RemoveBody = match parse_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };
    match crate::routes::members::remove::admin_remove_inner(
        state,
        &actor,
        checked.did.as_str(),
        body,
        crate::acl::admin_consent::Operation {
            type_uri: &doc.type_uri.to_string(),
            payload: &doc.payload,
        },
    )
    .await
    {
        Ok(outcome) => success_response(
            &doc,
            crate::routes::members::remove::RemoveResponse::from(outcome),
        ),
        Err(e) => task_error_to_reject(&doc, &e),
    }
}

/// `vtc/members/purge/0.1` — irreversibly erase a member record.
///
/// **Super-administrator only**, which is a stricter gate than the other three
/// and must stay one: the bearer route takes `SuperAdminAuth`, so the signed
/// door asks [`AuthClaims::require_super_admin`] the same question —
/// `Role::Admin` **and** an unrestricted [`vti_common::acl::ActScope`]. Reading
/// `allowed_contexts.is_empty()` here instead would be the exact inversion
/// `CLAUDE.md` names: empty means *unrestricted* for an admin and *authorized
/// nowhere* for anybody else.
async fn handle_member_purge(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let actor = match capable_signer(
        state,
        ctx,
        &doc,
        crate::acl::Capability::MembersManage,
        None,
    )
    .await
    {
        Ok(a) => a,
        Err(reject) => return reject,
    };
    let checked: member_purge::Payload = match parse_spec_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };
    // The REST route validates the path segment; here the DID rides the
    // payload, and `purge_member` does not validate it for us.
    if let Err(e) = vti_common::identifier::validate_did("did", checked.did.as_str()) {
        return app_error_to_reject(&doc, &e);
    }
    match crate::ceremony::purge_member(state, &actor.did, checked.did.as_str()).await {
        Ok(outcome) => success_response(
            &doc,
            crate::routes::members::remove::RemoveResponse::from(outcome),
        ),
        Err(e) => task_error_to_reject(&doc, &e),
    }
}

// ─── the join decision + the community profile (#1641 phase 2, batch 2) ──

/// `vtc/join-requests/decide/0.1` — admit or refuse a pending applicant.
///
/// Administrator only, read from the signer's ACL entry — the same
/// `VtcRole::Admin` the REST route's `AdminAuth` demanded, and the only gate
/// that route applies. There is no context scoping on either door: a VTC
/// community is one scope, and a join request belongs to the community rather
/// than to a context within it.
///
/// # Why the double-issue this task could suffer is already closed
///
/// Approving issues a membership credential and a role endorsement. Executed
/// twice, it issues two of each — and a redelivery from the mediator is the
/// routine case, not an attack (SPEC §7.2 item 11). The spine claims the
/// document's `id` **before** dispatching here and settles it after, so a
/// redelivery is answered with the *recorded* response and never reaches this
/// function. That is the ordering §6a of the design note requires, and it is
/// why this arm is not the place to add an idempotency check of its own: a
/// check-then-act at the handler is the TOCTOU the claim exists to close.
///
/// The `notPending` refusal is a second line rather than that guard. It
/// catches a *second, different* decision document aimed at a request already
/// decided — which is a conflict the operator should see, not a duplicate to
/// absorb.
async fn handle_join_decide(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let actor =
        match capable_signer(state, ctx, &doc, crate::acl::Capability::JoinDecide, None).await {
            Ok(a) => a,
            Err(reject) => return reject,
        };
    let checked: join_decide::Payload = match parse_spec_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };
    // The REST route takes the request id as a typed path segment; here it
    // rides the payload as a string, so the parse is this arm's to make. A
    // non-UUID id never named a request, so it is a malformed payload rather
    // than the task's declared `notFound` — which would tell an operator a
    // request had been deleted when what they sent was not an id at all.
    let id = match uuid::Uuid::parse_str(checked.id.as_str()) {
        Ok(id) => id,
        Err(e) => {
            return app_error_to_reject(
                &doc,
                &AppError::Validation(format!("`id` is not a join-request id: {e}")),
            );
        }
    };
    let decision = match &checked.decision {
        join_decide::PayloadDecision::Approved => {
            crate::routes::join_requests::decide::Decision::Approved
        }
        join_decide::PayloadDecision::Rejected => {
            crate::routes::join_requests::decide::Decision::Rejected
        }
        // `PayloadDecision` is `#[non_exhaustive]`, so a later registry version
        // may add an outcome this build has no handling for. Refusing is the
        // only honest answer: mapping an unknown decision onto either of the
        // two known ones would admit or foreclose an applicant on a decision
        // nobody made.
        other => {
            return app_error_to_reject(
                &doc,
                &AppError::Validation(format!("unsupported `decision`: {other}")),
            );
        }
    };
    let body = crate::routes::join_requests::decide::DecideBody {
        decision,
        reason: checked.reason.as_ref().map(|r| r.as_str().to_string()),
    };
    match crate::routes::join_requests::decide::decide_inner(
        state,
        &actor.did,
        ctx.transport.as_str(),
        id,
        body,
    )
    .await
    {
        Ok(response) => success_response(&doc, response),
        Err(e) => task_error_to_reject(&doc, &e),
    }
}

/// `vtc/community/profile/update/0.1` — edit the community's public profile.
///
/// Administrator only, from the signer's ACL entry — `AdminAuth`'s question,
/// and the only one the REST route asks.
///
/// # Why the payload is read twice
///
/// The same reason `members/update` reads it twice. The generated `Payload`
/// types `extensions` as a map with `default`, so once parsed an **absent**
/// bag and an empty one are the same value — and this task's rule is that
/// absent leaves the field unchanged while a supplied value replaces it.
/// Mapping the generated type straight through would clear the community's
/// extensions on every update that did not mention them. The route's own
/// `CommunityProfileUpdate` types it `Option<Value>` and keeps the
/// distinction. The generated parse still runs, and runs first, because it is
/// what validates the document against its published schema.
///
/// The nullable members (`logoUrl`, `publicUrl`, `contactEmail`) are a
/// *different* case and the double read does not rescue them: the published
/// task says an explicit `null` clears them, and
/// `CommunityProfileUpdate`'s `Option<Option<String>>` has no double-option
/// deserializer, so serde folds `null` onto the outer `None` and the operation
/// reads it as "unchanged". That is the store's behaviour, identical on the
/// bearer route, and it is pinned by
/// `an_explicit_null_does_not_yet_clear_a_nullable_member` rather than left
/// for a client to find.
async fn handle_community_profile_update(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let actor =
        match capable_signer(state, ctx, &doc, crate::acl::Capability::SurfaceAdmin, None).await {
            Ok(a) => a,
            Err(reject) => return reject,
        };
    let _checked: community_profile_update::Payload = match parse_spec_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };
    let update: crate::community::CommunityProfileUpdate = match parse_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };
    match crate::routes::community::profile::update_profile_inner(state, &actor.did, update).await {
        Ok(response) => success_response(&doc, response),
        Err(e) => task_error_to_reject(&doc, &e),
    }
}

// ─── the portable-configuration pair (#1641 phase 2, batch 3) ────────────

/// `vtc/config/export/0.1` — the community's portable configuration.
///
/// Administrator only, from the signer's ACL entry — the `AdminAuth` question
/// the removed bearer route asked, and the only one. A read, but not a
/// harmless one: the document carries every db-layer config override and the
/// full community profile, which is why the task declares a proof. As on the
/// removed route, it writes no audit row.
///
/// # This is the task's only binding
///
/// Unlike batches 1 and 2, the pair's bearer routes were removed in the same
/// change rather than kept as transitional paths. Nothing called them: the
/// admin console has no screen for either (`vtc-console-signing.md` §7), and
/// neither `vtc-client`, `cnm` nor openvtc reaches them.
async fn handle_config_export(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    // The gate the console's live `config` topic shares (`admin_events`).
    let cap = crate::admin_events::read_capability(crate::admin_events::Topic::Config)
        .unwrap_or(crate::acl::Capability::ConfigAdmin);
    if let Err(reject) = capable_signer(state, ctx, &doc, cap, None).await {
        return reject;
    }
    let _checked: config_export::Payload = match parse_spec_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };
    match crate::routes::admin::config::export_inner(state).await {
        Ok(response) => success_response(&doc, response),
        Err(e) => app_error_to_reject(&doc, &e),
    }
}

/// `vtc/config/import/0.1` — preview (`confirm: false`, the default) or apply
/// a portable configuration.
///
/// An **unrestricted** administrator only, from the signer's ACL entry. The
/// removed bearer route asked only `AdminAuth`, but an import writes the same
/// community-wide overrides `config/patch` does — the unrestricted-admin
/// consent threshold among them — so it takes what `config/patch` takes, or a
/// context admin could reach through the import what the patch refuses it. The
/// audit rows name the signer. This is the task's only binding; see
/// [`handle_config_export`].
///
/// # Why the payload is read twice
///
/// The generated parse runs first because it is what validates the document
/// against its published schema. The operation then reads the payload as
/// `ImportRequest`, the type the import has always diffed from, rather than
/// mapping the generated `CommunityProfileSnapshot` across member by member:
/// the diff compares the incoming profile with the stored `CommunityProfile`,
/// and building that from the JSON with the stored type's own deserializer is
/// what keeps an unchanged profile reading as unchanged.
///
/// # Size
///
/// This door caps a document at 64 KiB where the removed route allowed 1 MB.
/// The payload is a community profile plus at most five small config
/// overrides, and the profile is the one §6b of the design note measured for
/// `community/profile/update`, at about 44 KiB at the worst encoding. So any
/// import whose profile is within those caps fits, and the cap refuses with
/// 413 rather than truncating.
async fn handle_config_import(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let actor =
        match capable_signer(state, ctx, &doc, crate::acl::Capability::ConfigAdmin, None).await {
            Ok(a) => a,
            Err(reject) => return reject,
        };
    let _checked: config_import::Payload = match parse_spec_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };
    let request: crate::routes::admin::config::ImportRequest = match parse_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };
    // VTI-APV-020: an applied import that lowers the consent threshold takes
    // the gesture and the consent of the threshold as it stands, as
    // `config/patch` does. A preview writes nothing and asks nothing, and a
    // document the import refuses outright asks for no gesture.
    if request.confirm
        && request.document.schema_version == crate::routes::admin::config::EXPORT_SCHEMA_VERSION
    {
        // VTI-CMP-090: an import that changes the trusted-witness list takes
        // the gesture and the consent `config/patch` does.
        if let Err(refusal) = acl_tasks::settle_witness_list_gate(
            state,
            &actor,
            &doc,
            &request.document.config_overrides,
            ", by configuration import",
        )
        .await
        {
            return refusal;
        }
        match crate::routes::admin::config::lowered_threshold(
            state,
            &request.document.config_overrides,
        )
        .await
        {
            Ok(None) => {}
            Ok(Some((from, to))) => {
                if let Err(refusal) = acl_tasks::settle_consent_gate(
                    state,
                    &actor,
                    &doc,
                    crate::acl::admin_consent::Act::LowerThreshold,
                    crate::config_store::UNRESTRICTED_ADMIN_CONSENT_THRESHOLD,
                    &format!(
                        "Import a configuration that lowers the unrestricted-admin consent \
                         threshold from {from} to {to}"
                    ),
                    &format!(
                        "Lower the number of administrators who must consent to a new \
                         unrestricted administrator from {from} to {to}, by configuration import"
                    ),
                )
                .await
                {
                    return refusal;
                }
            }
            Err(e) => return app_error_to_reject(&doc, &e),
        }
    }
    match crate::routes::admin::config::import_inner(state, &actor.did, request).await {
        Ok(response) => success_response(&doc, response),
        Err(e) => task_error_to_reject(&doc, &e),
    }
}

// ─── the endorsement-type writes (#1641 phase 2, batch 4) ────────────────

/// `vtc/endorsement-types/register/0.1` — register an endorsement type.
///
/// Administrator only, from the signer's ACL entry — `AdminAuth`'s question,
/// and the only one the REST route asks. `createdByDid` and the audit row name
/// the signer.
///
/// # Why the payload is read twice
///
/// The generated parse runs first because it is what validates the document
/// against its published schema. The operation then reads the payload as the
/// route's `RegisterBody`, because the generated type folds an **absent**
/// `claimSchema` and an empty one into the same default map, and the stored
/// row keeps them apart. Issuance treats the two alike — `{}` admits any
/// claim — but a listing shows which one the operator registered, and the
/// bearer route stores what it was sent, so this door does too.
///
/// # Size
///
/// `claimSchema` is operator-authored and the task publishes no bound for it,
/// so the operation caps it at 32 KiB serialised on both doors
/// (`CLAIM_SCHEMA_MAX_BYTES`). With `typeUri` ≤ 512 and `description` ≤ 1024
/// characters, every registration that passes fits this door's 64 KiB cap.
async fn handle_endorsement_type_register(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let actor =
        match capable_signer(state, ctx, &doc, crate::acl::Capability::SurfaceAdmin, None).await {
            Ok(a) => a,
            Err(reject) => return reject,
        };
    let _checked: endorsement_type_register::Payload = match parse_spec_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };
    let body: crate::routes::endorsement_types::RegisterBody = match parse_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };
    match crate::routes::endorsement_types::register_inner(state, &actor.did, body).await {
        Ok(response) => success_response(&doc, response),
        Err(e) => task_error_to_reject(&doc, &e),
    }
}

/// `vtc/endorsement-types/delete/0.1` — delete an endorsement type nothing
/// references.
///
/// Administrator only, from the signer's ACL entry — `AdminAuth`'s question,
/// and the only one the REST route asks. The REST route takes the type URI as
/// a path segment; here it is the payload's `typeUri`, and both reach the same
/// `delete_inner`, so the `notFound` / `inUse` refusals are the same codes on
/// each.
async fn handle_endorsement_type_delete(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let actor =
        match capable_signer(state, ctx, &doc, crate::acl::Capability::SurfaceAdmin, None).await {
            Ok(a) => a,
            Err(reject) => return reject,
        };
    let checked: endorsement_type_delete::Payload = match parse_spec_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };
    match crate::routes::endorsement_types::delete_inner(
        state,
        &actor.did,
        checked.type_uri.to_string(),
    )
    .await
    {
        Ok(response) => success_response(&doc, response),
        Err(e) => task_error_to_reject(&doc, &e),
    }
}

// ─── the backup export (#1641 phase 2, batch 5) ──────────────────────────

/// `vtc/backup/export/0.1` — an encrypted full-state backup.
///
/// **Super-admin only**, like `members/purge`: the bearer route demanded
/// `SuperAdminAuth`, so the signer's ACL entry must be an unrestricted admin
/// (`require_super_admin`), not merely an admin — a context-scoped admin is
/// refused here exactly as there. The audit row names the signer.
///
/// # The password in the document
///
/// The export password rides in the payload, so it is in a document that is
/// signed but not encrypted. That is no worse than the bearer route's body:
/// the REST binding is TLS, DIDComm and TSP encrypt end to end, and the spine
/// records a document's identifier and digest — never its payload. The digest
/// is over a document carrying a fresh `id` and `issuedAt`, so it is no oracle
/// for the password.
///
/// # The reply is recorded in full
///
/// The spine records a successful reply against the document's `id`, so a
/// redelivery is answered with the same envelope rather than a second export
/// under a fresh salt and nonce. That keeps a second, password-encrypted copy
/// of the backup in `accepted_ids` for the acceptance window. The keyspace is
/// excluded from backup, so a copy never ends up inside a later export.
///
/// Only the export moved. `vtc/backup/import/0.1` carries the whole envelope in
/// its request, which a 64 KiB document cannot hold; it is not served, and the
/// chunked `backup/*` family ([`backup_tasks`]) is the restore — §6b of the
/// design note.
async fn handle_backup_export(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let actor =
        match capable_signer(state, ctx, &doc, crate::acl::Capability::BackupExport, None).await {
            Ok(a) => a,
            Err(reject) => return reject,
        };
    if let Err(reject) = refuse_hop_by_hop_backup(ctx, &doc, "export") {
        return reject;
    }
    let checked: backup_export::Payload = match parse_spec_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };
    match crate::routes::backup::export_inner(
        state,
        &actor.did,
        checked.password.as_str(),
        checked.include_audit,
    )
    .await
    {
        Ok(response) => success_response(&doc, response),
        Err(e) => task_error_to_reject(&doc, &e),
    }
}

/// Refuse a backup export or import that arrived over the REST binding.
///
/// The export and `finalize-import` carry the password that opens a complete
/// copy of the community, and the export's reply (or `initiate-export`'s
/// manifest) is the bundle it opens. Over REST both exist in plaintext
/// wherever TLS terminates. So these tasks are served only over a channel
/// confidential end-to-end between the administrator and this VTC: DIDComm or
/// TSP (the backup family's Channel requirement,
/// trustoverip/dtgwg-trust-tasks-tf#646). Checked after the super-admin check
/// and before any state is serialized, a slot is opened or a key is derived.
/// The chunks themselves are ciphertext and are not affected.
pub(super) fn refuse_hop_by_hop_backup(
    ctx: &JoinAuthCtx,
    doc: &TrustTask<Value>,
    what: &str,
) -> Result<(), TrustTaskOutcome> {
    match ctx.transport {
        JoinTransport::DIDComm | JoinTransport::Tsp => Ok(()),
        JoinTransport::Rest => Err(app_error_to_reject(
            doc,
            &AppError::Forbidden(format!(
                "a backup {what} is refused over REST: the backup password and the bundle \
                 would exist in plaintext wherever TLS terminates. Send it over DIDComm or TSP"
            )),
        )),
    }
}

/// `auth/step-up/approve-response/0.4` — the passkey gesture an
/// operation-bound step-up asked for.
///
/// Two gates, by one approver. The WebAuthn assertion, which only the actor's
/// own authenticator — a session passkey, or a member's step-up passkey
/// (`crate::step_up_passkey`) — can produce over this service's challenge. And
/// the document's own proof where it has one: an `assertionMethod` proof
/// ([`verify_received_approval_proof`], checked by the spine) by the subject itself —
/// never by a delegated signing key, which the spine refuses. A member's
/// step-up passkey is always beside the member's proof; a console user's
/// session passkey may answer unsigned, the one gate its browser holds. What the gesture authorizes is read from this
/// service's record of the refusal, never from this document. See
/// [`crate::acl::bound_step_up::approve`].
///
/// This service only issues bound step-ups on this door, so the answer is
/// `recorded` or `rejected` — never `elevated`.
async fn handle_step_up_approve_response(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    use crate::acl::bound_step_up::{self, ApproveError, Approved};
    use step_up_approve_response::error_codes as codes;

    let payload: step_up_approve_response::Payload = match parse_spec_payload(&doc) {
        Ok(p) => p,
        Err(reject) => return reject,
    };
    let refuse = |code: trust_tasks_rs::DeclaredErrorCode, message: &str, hint: Option<&str>| {
        reject_with_code(
            &doc,
            extended_code(code.code),
            message,
            hint.map(|h| serde_json::json!({ "reason": h })),
        )
    };
    // Who answers. A signed answer is the subject's own attestation: its
    // signer must be the subject the step-up was asked of — and it need not be
    // an administrator: a member answers the step-ups asked of them (a
    // break-glass) with a step-up passkey, signing the answer themselves. A
    // delegated key's proof never reaches here (the spine refuses it). An
    // unsigned answer carries only the WebAuthn gate (approve-response 0.4), so
    // it may only approve, with a console user's session passkey registered to
    // the subject — which is how the console answers, holding no key of the
    // subject's ([`bound_step_up::approve`]).
    let signed_by_subject = match ctx.verified_signer.as_deref() {
        Some(signer) if signer == payload.subject.as_str() => true,
        Some(_) => {
            return refuse(
                codes::SUBJECT_MISMATCH,
                "the approve-response is not signed by the subject of the step-up",
                None,
            );
        }
        None => false,
    };
    // Settled before the pending step-up is touched, so a refused answer
    // leaves the challenge for the right one.
    if !signed_by_subject && !unsigned_answer_admissible(state, &payload).await {
        return reject_with(&doc, RejectReason::ProofRequired);
    }
    match bound_step_up::approve(state, &payload, signed_by_subject).await {
        Ok(Approved::Recorded { bound_to }) => success_response(
            &doc,
            serde_json::json!({ "status": "recorded", "boundTo": bound_to }),
        ),
        Ok(Approved::Declined { reason }) => success_response(
            &doc,
            serde_json::json!({ "status": "rejected", "reason": reason }),
        ),
        Err(ApproveError::ChallengeUnknown) => refuse(
            codes::CHALLENGE_UNKNOWN,
            "no pending step-up matches this challenge",
            None,
        ),
        Err(ApproveError::ChallengeExpired) => refuse(
            codes::CHALLENGE_EXPIRED,
            "the step-up this challenge belonged to has expired; send the operation again",
            None,
        ),
        Err(ApproveError::SubjectMismatch) => refuse(
            codes::SUBJECT_MISMATCH,
            "the subject or session does not match the pending step-up",
            None,
        ),
        Err(ApproveError::NoGate) => refuse(
            codes::NO_GATE,
            "this step-up accepts only a passkey assertion (evidence.kind = webauthn)",
            None,
        ),
        Err(ApproveError::AssertionInvalid(hint)) => refuse(
            codes::ASSERTION_INVALID,
            "the passkey assertion did not verify",
            Some(hint),
        ),
        Err(ApproveError::ProofRequired) => reject_with(&doc, RejectReason::ProofRequired),
        // 0.4 carries no `approverSigned`, so neither arises on this door; a
        // gate it did not offer is `noGate`.
        Err(ApproveError::StatementInvalid | ApproveError::ApproverNotBound) => refuse(
            codes::NO_GATE,
            "this version carries no step-up approver statement",
            None,
        ),
        Err(ApproveError::Internal(e)) => app_error_to_reject(&doc, &e),
    }
}

/// `auth/step-up/approve-response/0.6`, served alongside 0.4 and 0.5. It adds
/// `evidence.kind = approverSigned` — a step-up approver's statement as the
/// factor (VTI-APV-015 as amended; design note `vtc-approver-step-up.md` §5).
///
/// Its proof is REQUIRED by the specification, so the spine has already
/// refused an unsigned document and verified this one's proof — made for
/// `assertionMethod`, by a key the signer lists under `assertionMethod`, and
/// never by a console key's delegation (the spine refuses a delegated signing
/// key on every approval type before dispatch). Here, before the pending
/// step-up is looked up (0.6 consumer item 1a):
///
/// - the signer must be `payload.subject` itself — `subjectMismatch` otherwise;
///   for `approverSigned` that is the subject's **own** DID, the one key that
///   says the subject answered, never a delegation;
/// - an approval carrying `approverSigned` goes to
///   [`crate::acl::bound_step_up::approve_with_statement`]; everything else
///   (`webauthn`, a refusal) is the 0.5 path, reached through the 0.4 type the
///   one verifier takes — the wire shapes of those members are the same.
async fn handle_step_up_approve_response_v0_6(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    use crate::acl::bound_step_up::{self, ApproveError, Approved};
    use step_up_approve_response_v0_6::error_codes as codes;

    let payload: step_up_approve_response_v0_6::Payload = match parse_spec_payload(&doc) {
        Ok(p) => p,
        Err(reject) => return reject,
    };
    let refuse = |code: trust_tasks_rs::DeclaredErrorCode, message: &str, hint: Option<&str>| {
        reject_with_code(
            &doc,
            extended_code(code.code),
            message,
            hint.map(|h| serde_json::json!({ "reason": h })),
        )
    };
    match ctx.verified_signer.as_deref() {
        Some(signer) if signer == payload.subject.as_str() => {}
        Some(_) => {
            return refuse(
                codes::SUBJECT_MISMATCH,
                "an approve-response must be signed by the subject's own DID",
                None,
            );
        }
        None => return reject_with(&doc, RejectReason::ProofRequired),
    }

    let approver_signed = matches!(
        payload.evidence,
        Some(step_up_approve_response_v0_6::Evidence::ApproverSigned { .. })
    );
    let outcome = if approver_signed {
        if payload.decision != step_up_approve_response_v0_6::PayloadDecision::Approved {
            // A refusal is the subject's signed statement (0.6 producer item
            // 6); it carries no factor.
            return refuse(
                codes::NO_GATE,
                "a refusal is signed by the subject and carries no approver statement \
                 (evidence.kind = didSigned)",
                None,
            );
        }
        // The statement exactly as received: `doc.payload` is the JSON the
        // bytes parsed to, so the approver's proof is checked over the members
        // it signed (VTI-45), never over a re-serialisation of the typed
        // `AttestStatement`.
        let Some(statement) = doc.payload.pointer("/evidence/statement") else {
            return refuse(codes::STATEMENT_INVALID, "no statement", None);
        };
        bound_step_up::approve_with_statement(
            state,
            payload.subject.as_str(),
            payload.challenge.as_str(),
            payload.session_id.is_some(),
            statement,
        )
        .await
    } else {
        match serde_json::from_value::<step_up_approve_response::Payload>(doc.payload.clone()) {
            Ok(v0_4) => bound_step_up::approve(state, &v0_4, true).await,
            Err(e) => {
                return app_error_to_reject(
                    &doc,
                    &AppError::Internal(format!(
                        "approve-response 0.6 payload does not convert to 0.4's shape: {e}"
                    )),
                );
            }
        }
    };
    match outcome {
        Ok(Approved::Recorded { bound_to }) => success_response(
            &doc,
            serde_json::json!({ "status": "recorded", "boundTo": bound_to }),
        ),
        Ok(Approved::Declined { reason }) => success_response(
            &doc,
            serde_json::json!({ "status": "rejected", "reason": reason }),
        ),
        Err(ApproveError::ChallengeUnknown) => refuse(
            codes::CHALLENGE_UNKNOWN,
            "no pending step-up matches this challenge",
            None,
        ),
        Err(ApproveError::ChallengeExpired) => refuse(
            codes::CHALLENGE_EXPIRED,
            "the step-up this challenge belonged to has expired; send the operation again",
            None,
        ),
        Err(ApproveError::SubjectMismatch) => refuse(
            codes::SUBJECT_MISMATCH,
            "the subject or session does not match the pending step-up",
            None,
        ),
        Err(ApproveError::NoGate) => refuse(
            codes::NO_GATE,
            "this step-up did not accept that kind of evidence; answer with one the request's \
             `accepts` lists",
            None,
        ),
        Err(ApproveError::AssertionInvalid(hint)) => refuse(
            codes::ASSERTION_INVALID,
            "the passkey assertion did not verify",
            Some(hint),
        ),
        Err(ApproveError::StatementInvalid) => refuse(
            codes::STATEMENT_INVALID,
            "the step-up approver's statement is not valid for this step-up",
            None,
        ),
        Err(ApproveError::ApproverNotBound) => refuse(
            codes::APPROVER_NOT_BOUND,
            "the statement is not signed by a step-up approver bound to the subject",
            None,
        ),
        Err(ApproveError::ProofRequired) => reject_with(&doc, RejectReason::ProofRequired),
        Err(ApproveError::Internal(e)) => app_error_to_reject(&doc, &e),
    }
}

/// Whether an **unsigned** approve-response may be heard at all: an approval
/// (a refusal is an approver-signed statement), carrying a WebAuthn assertion,
/// from a console user's session passkey. A member's step-up passkey is only
/// ever beside the member's own proof. [`crate::acl::bound_step_up::approve`]
/// checks the credential again once the assertion has verified.
async fn unsigned_answer_admissible(
    state: &AppState,
    payload: &step_up_approve_response::Payload,
) -> bool {
    use base64::Engine as _;
    if payload.decision != step_up_approve_response::PayloadDecision::Approved {
        return false;
    }
    let Some(step_up_approve_response::Evidence::Webauthn(assertion)) = payload.evidence.as_ref()
    else {
        return false;
    };
    let Ok(raw) = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(&assertion.raw_id) else {
        return false;
    };
    matches!(
        vti_common::auth::passkey::store::get_passkey_user_by_cred(
            &state.passkey_ks,
            &hex::encode(raw)
        )
        .await,
        Ok(Some(_))
    )
}

/// `auth/step-up/approve-response/0.5`, served alongside 0.4.
///
/// The wire shape is unchanged from 0.4 (only the schema's `description`
/// text differs — verified by `the_0_5_payload_schema_is_wire_identical_to_0_4`
/// below); the one behavioural change is that 0.5 declares its framework
/// `proof` REQUIRED (`step_up_approve_response_v0_5::Payload::IS_PROOF_REQUIRED`),
/// so the spine's own policy check already refused an unsigned 0.5 document
/// before dispatch ever reaches here — there is no `unsigned_answer_admissible`
/// path to repeat. Every other check is [`handle_step_up_approve_response`]'s:
/// the signer must be the step-up's own subject (self step-up is all this
/// service implements), and the gate is [`bound_step_up::approve`].
///
/// The payload is converted to the 0.4 generated type to reach that one
/// verifier rather than forking it: the two schemas describe the same wire
/// document, and a second copy of the verification logic is exactly the kind
/// of drift a spec bump should not risk.
async fn handle_step_up_approve_response_v0_5(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    use crate::acl::bound_step_up::{self, ApproveError, Approved};
    use step_up_approve_response_v0_5::error_codes as codes;

    let payload: step_up_approve_response_v0_5::Payload = match parse_spec_payload(&doc) {
        Ok(p) => p,
        Err(reject) => return reject,
    };
    let refuse = |code: trust_tasks_rs::DeclaredErrorCode, message: &str, hint: Option<&str>| {
        reject_with_code(
            &doc,
            extended_code(code.code),
            message,
            hint.map(|h| serde_json::json!({ "reason": h })),
        )
    };
    // The spine's `spec_policy_for` already refused an unsigned document
    // (0.5 declares `proof` REQUIRED), so `ctx.verified_signer` is always
    // `Some` here in practice; the `None` arm is defence in depth, not a
    // reachable path.
    match ctx.verified_signer.as_deref() {
        Some(signer) if signer == payload.subject.as_str() => {}
        Some(_) => {
            return refuse(
                codes::SUBJECT_MISMATCH,
                "the approve-response is not signed by the subject of the step-up",
                None,
            );
        }
        None => return reject_with(&doc, RejectReason::ProofRequired),
    }
    let v0_4_payload: step_up_approve_response::Payload =
        match serde_json::to_value(&payload).and_then(serde_json::from_value) {
            Ok(p) => p,
            Err(e) => {
                return app_error_to_reject(
                    &doc,
                    &AppError::Internal(format!(
                        "approve-response 0.5 payload does not convert to 0.4's shape: {e}"
                    )),
                );
            }
        };
    match bound_step_up::approve(state, &v0_4_payload, true).await {
        Ok(Approved::Recorded { bound_to }) => success_response(
            &doc,
            serde_json::json!({ "status": "recorded", "boundTo": bound_to }),
        ),
        Ok(Approved::Declined { reason }) => success_response(
            &doc,
            serde_json::json!({ "status": "rejected", "reason": reason }),
        ),
        Err(ApproveError::ChallengeUnknown) => refuse(
            codes::CHALLENGE_UNKNOWN,
            "no pending step-up matches this challenge",
            None,
        ),
        Err(ApproveError::ChallengeExpired) => refuse(
            codes::CHALLENGE_EXPIRED,
            "the step-up this challenge belonged to has expired; send the operation again",
            None,
        ),
        Err(ApproveError::SubjectMismatch) => refuse(
            codes::SUBJECT_MISMATCH,
            "the subject or session does not match the pending step-up",
            None,
        ),
        Err(ApproveError::NoGate) => refuse(
            codes::NO_GATE,
            "this step-up accepts only a passkey assertion (evidence.kind = webauthn)",
            None,
        ),
        Err(ApproveError::AssertionInvalid(hint)) => refuse(
            codes::ASSERTION_INVALID,
            "the passkey assertion did not verify",
            Some(hint),
        ),
        Err(ApproveError::ProofRequired) => reject_with(&doc, RejectReason::ProofRequired),
        // 0.5 carries no `approverSigned`; answer with 0.6 for that.
        Err(ApproveError::StatementInvalid | ApproveError::ApproverNotBound) => refuse(
            codes::NO_GATE,
            "this version carries no step-up approver statement; use approve-response 0.6",
            None,
        ),
        Err(ApproveError::Internal(e)) => app_error_to_reject(&doc, &e),
    }
}

// ─── personhood ──────────────────────────────────────────────────────────

/// `vtc/members/personhood/challenge/0.1` — mint the single-use nonce the
/// assert presentation must carry.
///
/// The caller must be a member of this community: over REST the route sits
/// behind `AuthClaims`, and the membership check here is what that means on
/// a transport with no session. The *subject* may be another member, which
/// is the in-person ceremony — an administrator mints the challenge, reads
/// the derived match code to the person in front of them, and that person's
/// own client answers it.
///
/// Minting for someone else confers nothing on its own. The nonce is bound
/// to the subject DID, and the only thing that can spend it is a
/// presentation signed by that DID's key.
async fn handle_personhood_challenge(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let caller = match resolve_holder(state, ctx, &doc).await {
        Ok(did) => did,
        Err(reject) => return reject,
    };
    let body: pc::Payload = match parse_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };

    // Membership check on the *caller*, standing in for the REST route's
    // session. A stranger who can reach the mediator is not a member.
    match crate::acl::get_acl_entry(&state.acl_ks, &caller).await {
        Ok(Some(_)) => {}
        Ok(None) => {
            return reject_with(
                &doc,
                RejectReason::PermissionDenied {
                    reason: format!("{caller} is not a member of this community"),
                },
            );
        }
        Err(e) => return app_error_to_reject(&doc, &e),
    }

    match crate::routes::members::personhood::challenge_inner(state, &body.did).await {
        Ok(res) => success_response(&doc, res),
        Err(e) => task_error_to_reject(&doc, &e),
    }
}

/// `vtc/members/personhood/assert/0.2` — present the evidence and, if the
/// community's policy accepts it, take the personhood flag.
///
/// The proven sender must be the subject. `assert/0.2` declares
/// `exposure.actsAsSubject: true` — "the asserting member is the subject …
/// exercising their own authority over their own personhood state" — so on
/// a transport that proves who sent the bytes, the party executing is the
/// party being asserted about.
///
/// That check is belt-and-braces rather than the gate. The gate is the
/// presentation, exactly as the published task says: its `holder` must
/// equal the subject and its `proof.challenge` must be the paired nonce,
/// and [`challenge_inner`](crate::routes::members::personhood::challenge_inner)'s
/// counterpart enforces both regardless of who relayed the document.
async fn handle_personhood_assert(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let caller = match resolve_holder(state, ctx, &doc).await {
        Ok(did) => did,
        Err(reject) => return reject,
    };
    let body: pa::Payload = match parse_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };

    if *body.did != caller {
        return reject_with(
            &doc,
            RejectReason::PermissionDenied {
                reason: format!(
                    "personhood is asserted by its subject; {caller} cannot assert for {}",
                    *body.did
                ),
            },
        );
    }

    let presentation = match serde_json::to_value(&body.presentation) {
        Ok(v) => v,
        Err(e) => {
            return reject_with(
                &doc,
                RejectReason::MalformedRequest {
                    reason: format!("presentation is not representable as JSON: {e}"),
                },
            );
        }
    };

    // The outcome evidence of each witnessing session a VWC in the presentation
    // cites (VTI-CMP-023), in the payload's own `outcomeEvidence`, read as
    // received: each document's proof and task digest are taken over its members.
    let evidence = match crate::credentials::witness::outcome_evidence_from_payload(&doc.payload) {
        Ok(e) => e,
        Err(e) => {
            return reject_with(
                &doc,
                RejectReason::MalformedRequest {
                    reason: e.to_string(),
                },
            );
        }
    };

    match crate::routes::members::personhood::assert_inner(
        state,
        &body.did,
        &presentation,
        &evidence,
    )
    .await
    {
        Ok(res) => success_response(&doc, res),
        Err(e) => task_error_to_reject(&doc, &e),
    }
}

/// `members/vmc/0.1` as a Trust Task document — a member submits their
/// reciprocal VMC (the member → community half of the membership pair),
/// optionally closing an approved join request via `requestId` (the retired
/// `join-requests/accept` semantics).
///
/// Same spine as the DIDComm handler: `receive_member_vmc_inner` verifies the
/// issuer / subject binding and the DI proof before storing it on the member
/// row. The proven member comes from [`resolve_holder`], so the authenticated
/// identity is the transport's (DIDComm authcrypt sender / TSP sender VID) or
/// the document proof signer — never a self-asserted `issuer`.
async fn handle_member_vmc(
    state: &AppState,
    ctx: &JoinAuthCtx,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let member_did = match resolve_holder(state, ctx, &doc).await {
        Ok(did) => did,
        Err(reject) => return reject,
    };
    let body: MemberVmcBody = match parse_payload(&doc) {
        Ok(b) => b,
        Err(reject) => return reject,
    };
    // `request_id` travels as a string (the SDK's `members` module compiles
    // featureless, without `uuid`); a malformed id is a framework reject, not
    // a lookup miss.
    let request_id = match body
        .request_id
        .as_deref()
        .map(uuid::Uuid::parse_str)
        .transpose()
    {
        Ok(r) => r,
        Err(e) => {
            return reject_with(
                &doc,
                RejectReason::MalformedRequest {
                    reason: format!("requestId is not a UUID: {e}"),
                },
            );
        }
    };

    match crate::members::inbound_vmc::receive_member_vmc_inner(
        state, member_did, body.vc, request_id,
    )
    .await
    {
        Ok(outcome) => success_response(
            &doc,
            MemberVmcReceiptBody {
                member_did: outcome.member_did,
                vmc_id: outcome.vmc_id,
                status: "stored".to_string(),
                request_id: outcome.request_id.map(|u| u.to_string()),
            },
        ),
        Err(e) => task_error_to_reject(&doc, &e),
    }
}

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

    fn error_doc(outcome: TrustTaskOutcome) -> Value {
        serde_json::from_slice(&outcome.body).expect("rejection is a framework error document")
    }

    /// A request document to reject from. Its own type is irrelevant — the
    /// rejection is built from the URI passed in, not from this.
    fn request_doc() -> TrustTask<Value> {
        let uri: trust_tasks_rs::TypeUri = jr::JOIN_REQUEST_MANIFEST_TYPE
            .parse()
            .expect("manifest uri");
        TrustTask::new("urn:uuid:test", uri, serde_json::json!({}))
    }

    /// A family split on its trailing version segment, nothing else.
    ///
    /// Written against synthetic paths: a `trusttasks.org/spec/` literal
    /// anywhere under `vtc-service/src` is read by `trust_task_manifest`'s
    /// census as an assertion that the registry publishes that task, and a
    /// test fixture is not one.
    #[test]
    fn task_family_strips_only_the_version_segment() {
        assert_eq!(
            task_family("scheme://host/spec/vtc/a/b/0.2"),
            Some("scheme://host/spec/vtc/a/b")
        );
        assert_eq!(task_family("no-slashes-at-all"), None);
    }

    /// A verb this VTC has never heard of still gets `unsupportedType`.
    ///
    /// The version arm must not swallow the plain case: "I do not implement
    /// this" and "I implement this at another version" are different answers
    /// and only the second is fixed by upgrading something.
    #[test]
    fn an_unknown_family_is_still_unsupported_type() {
        let outcome =
            unsupported_type_or_version(&request_doc(), "scheme://host/spec/vtc/nope/1.0");
        let doc = error_doc(outcome);
        assert_eq!(doc["payload"]["code"], "unsupportedType");
        assert!(doc["payload"]["details"].get("servedVersions").is_none());
    }

    /// A known family at an unknown version names the versions served.
    ///
    /// The VTC half of #1220. Its `spec/vtc/*` families are mid-migration, so
    /// a member client and a community can legitimately sit at different
    /// versions of the same verb — which makes a bare `unsupported type` read
    /// as "this community cannot do this" when it means "one of us is older".
    ///
    /// Built from `DISPATCHED_URIS` rather than a literal, so the fixture
    /// cannot claim a version this VTC does not serve.
    #[test]
    fn a_known_family_at_an_unknown_version_names_what_is_served() {
        let real = DISPATCHED_URIS
            .first()
            .expect("the dispatcher routes at least one URI");
        let family = task_family(real).expect("a task URI has a family");
        let bogus = format!("{family}/99.99");

        let doc = error_doc(unsupported_type_or_version(&request_doc(), &bogus));

        assert_eq!(doc["payload"]["code"], "unsupportedVersion");
        let message = doc["payload"]["message"].as_str().expect("a message");
        assert!(
            message.contains(real),
            "the message must name the served version; got {message}"
        );
        assert_eq!(doc["payload"]["details"]["servedVersions"][0], *real);
        assert_eq!(doc["payload"]["details"]["requestedType"], bogus);
    }

    /// The migration hint never names a *neighbouring* family.
    ///
    /// `join-requests/submit` and `join-requests/status` share a long prefix
    /// and are different verbs; offering one as the version to migrate onto
    /// would send a client at a task that cannot serve its request.
    #[test]
    fn a_neighbouring_family_is_not_offered_as_a_version() {
        let real = DISPATCHED_URIS
            .first()
            .expect("the dispatcher routes at least one URI");
        let family = task_family(real).expect("a task URI has a family");
        let bogus = format!("{family}/99.99");

        let doc = error_doc(unsupported_type_or_version(&request_doc(), &bogus));
        let served = doc["payload"]["details"]["servedVersions"]
            .as_array()
            .expect("servedVersions is an array");

        for entry in served {
            let uri = entry.as_str().expect("a URI string");
            assert_eq!(
                task_family(uri),
                Some(family),
                "{uri} is a different family and must not be offered as a version of {family}"
            );
        }
    }

    /// Every URI the dispatcher declares as routed must be a known Trust Task
    /// request URI — one the spec registry can answer a policy for — so a
    /// typo or a URI nobody published can never silently reach `dispatch_typed`.
    ///
    /// This used to also assert `DISPATCHED_URIS` against a second,
    /// hand-retyped copy of itself (`declared`), which caught nothing a
    /// typo in one of the two copies couldn't equally cause to agree by
    /// accident. There is no registry API to enumerate every published URI
    /// (only to look one up), so the derivable half of the old check — ask
    /// the registry, don't retype it — is what is left, and it is the half
    /// that actually protects a member: an unrouted URI already fails in
    /// `dispatch_typed`, but a routed one the registry has never heard of
    /// would route a document none of the framework's SPEC §7.2 checks
    /// (`is_proof_required`, `recipient`, `issuedAt`, ...) are enforced for.
    #[test]
    fn dispatcher_routes_every_dispatched_uri() {
        for uri in DISPATCHED_URIS {
            assert!(
                spec_policy_for(uri).is_some(),
                "`{uri}` is dispatched but the spec registry has no policy for it — either it \
                 is misspelled, or its specification is not published where \
                 `trust_tasks_rs::schema_index` can answer `spec_policy_for` for it (or, for a \
                 task bound ahead of its specification, a local policy stands in for it)"
            );
        }
    }

    /// The rooms dispatcher serves every URI `vti_rooms` puts on the wire.
    ///
    /// The one thing registration-by-type cannot check for itself: that no verb
    /// was *forgotten*. A missing `.on_async` is silent — the task simply is not
    /// served — so this compares the dispatcher's own list against the family's
    /// wire constants, which `vti-rooms/tests/schema_conformance.rs` in turn
    /// pins against the published `TYPE_URI`s.
    #[test]
    fn rooms_dispatcher_serves_every_wire_uri() {
        let served = crate::rooms::handlers::served_uris();
        for uri in vti_rooms::wire::ROOMS_DISPATCHED_URIS {
            assert!(
                served.contains(uri),
                "`{uri}` is on the wire but no handler is registered for it — a \
                 client would be told it is unsupported at every version"
            );
        }
        assert_eq!(
            served.len(),
            vti_rooms::wire::ROOMS_DISPATCHED_URIS.len(),
            "the dispatcher serves something the wire module does not name: {served:?}"
        );
    }

    /// The request URIs must parse as framework `TypeUri`s (the `/spec/`
    /// path shape), otherwise an inbound document would never deserialise.
    #[test]
    fn dispatched_uris_are_canonical_type_uris() {
        for u in DISPATCHED_URIS {
            let parsed: Result<trust_tasks_rs::TypeUri, _> = u.parse();
            assert!(
                parsed.is_ok(),
                "dispatched URI is not a canonical TypeUri: {u}"
            );
        }
    }

    /// The two member verbs are what #185 needs over TSP, and the TSP inbound
    /// path reaches a verb only through this dispatcher — so their absence
    /// would be an `UnsupportedType` on the wire, not a compile error.
    #[test]
    fn member_verbs_are_dispatched() {
        for u in [jr::MEMBER_SELF_REMOVE_TYPE, mem::MEMBER_VMC_TYPE] {
            assert!(
                DISPATCHED_URIS.contains(&u),
                "member verb not reachable over TSP: {u}"
            );
        }
    }

    /// The whole point of routing personhood here: a member client that
    /// speaks Trust Tasks over messaging can run the ceremony. Before this,
    /// personhood was REST-only, so `openvtc` — which talks to the VTC over
    /// DIDComm/TSP and holds no bearer token — could not reach it at all.
    #[test]
    fn personhood_verbs_are_dispatched() {
        for u in [PERSONHOOD_CHALLENGE_TYPE, PERSONHOOD_ASSERT_TYPE] {
            assert!(
                DISPATCHED_URIS.contains(&u),
                "personhood verb not reachable over TSP: {u}"
            );
        }
    }

    mod personhood {
        use super::*;
        use crate::acl::{VtcAclEntry, VtcRole, store_acl_entry};
        use crate::test_support::TestVtc;
        use serde_json::json;
        use vti_rooms_dtg::test_support::Party;

        const MEMBER: &str = "did:key:zPersonhoodMember";

        /// A community with signers and [`MEMBER`] seeded as a member.
        async fn fixture() -> TestVtc {
            let vtc = TestVtc::builder().with_signers(true).build().await;
            seed_member(&vtc, MEMBER).await;
            vtc
        }

        /// Seed `did` as a member of `vtc`.
        async fn seed_member(vtc: &TestVtc, did: &str) {
            store_acl_entry(
                &vtc.state.acl_ks,
                &VtcAclEntry {
                    did: did.into(),
                    role: VtcRole::Member,
                    label: None,
                    admin: VtcRole::Member.implied_authority(),
                    delegated_by: None,
                    created_at: 0,
                    created_by: "did:key:vtc-install".into(),
                    updated_at: None,
                    updated_by: None,
                    expires_at: None,
                    resource_grants: Vec::new(),
                    label_set_by_subject: false,
                    suspension: None,
                },
            )
            .await
            .expect("seed member ACL");
        }

        /// The fixture leaves `vtc_did` unset, so `validate_basic`'s
        /// recipient binding is skipped — these tests are about the per-verb
        /// auth the handlers add. Every document here is signed: over DIDComm
        /// the spine accepts a document only when its proof binds it to the
        /// sender, whatever the task's own proof requirement.
        ///
        /// A document issued by `from` and carrying `from`'s Data-Integrity
        /// proof — what a producer sends for a task that declares `proof`
        /// REQUIRED. Both `vtc/members/personhood/challenge/0.1` (since
        /// trust-tasks 0.23) and `assert/0.2` do.
        ///
        /// `from` is a real `did:key` with the secret behind it, because the
        /// spine verifies the proof against the document's own `issuer`
        /// (SPEC §4.7): a placeholder string like [`MEMBER`] can address a
        /// document but cannot sign one.
        async fn signed_document(
            from: &Party,
            type_uri: &str,
            payload: serde_json::Value,
        ) -> Vec<u8> {
            let mut doc = vta_sdk::trust_task_sign::build_unsigned(
                type_uri,
                payload,
                &from.did,
                crate::test_support::TEST_VTC_DID,
            )
            .expect("build the document");
            let key = vta_sdk::trust_task_sign::HolderKey::from_did_key(
                &from.did,
                &from.secret_multibase,
            )
            .expect("a did:key names its own verification method");
            vta_sdk::trust_task_sign::sign_in_place_with(&mut doc, &key)
                .await
                .expect("sign the document");
            serde_json::to_vec(&doc).expect("serialize document")
        }

        /// The reply body as text. `TrustTaskOutcome` keeps raw bytes so the
        /// wire output is byte-identical to direct serialisation.
        fn rendered(out: &TrustTaskOutcome) -> String {
            String::from_utf8_lossy(&out.body).into_owned()
        }

        /// Happy path over messaging: a member mints their own challenge and
        /// the reply carries the spoken match code, same as over REST.
        #[tokio::test]
        async fn a_member_can_mint_a_challenge_over_messaging() {
            let vtc = fixture().await;
            let member = Party::new();
            seed_member(&vtc, &member.did).await;
            let out = dispatch_trust_task_core(
                &vtc.state,
                &JoinAuthCtx::didcomm(member.did.clone()),
                &signed_document(
                    &member,
                    PERSONHOOD_CHALLENGE_TYPE,
                    json!({ "did": member.did }),
                )
                .await,
            )
            .await;

            let body = rendered(&out);
            assert!(
                body.contains("challengeId"),
                "expected a challenge in the reply, got: {body}"
            );
            assert!(
                body.contains(crate::members::match_code::MATCH_CODE_EXT_KEY),
                "the messaging reply must carry the match code the REST reply does, got: {body}"
            );
        }

        /// **Every success response carries this community's proof.**
        ///
        /// SPEC §7.3 item 7: a specification declaring a single
        /// `proofRequirement: REQUIRED` binds its *response* as well as its
        /// request — "an omission can never weaken a variant" — and 265
        /// published specifications declare exactly that. This service attached
        /// a proof to none of them until the spine started signing.
        ///
        /// Nothing caught it because no consumer verifies one either, which is
        /// why the guard is here rather than left to a client: a mutually
        /// consistent silence between producer and consumer stays silent.
        #[tokio::test]
        async fn a_success_response_is_signed() {
            let vtc = fixture().await;
            let member = Party::new();
            seed_member(&vtc, &member.did).await;
            let out = dispatch_trust_task_core(
                &vtc.state,
                &JoinAuthCtx::didcomm(member.did.clone()),
                &signed_document(
                    &member,
                    PERSONHOOD_CHALLENGE_TYPE,
                    json!({ "did": member.did }),
                )
                .await,
            )
            .await;

            let doc: serde_json::Value =
                serde_json::from_slice(&out.body).expect("the reply is a JSON document");
            let proof = doc.get("proof").unwrap_or_else(|| {
                panic!(
                    "a success response carries no proof, so nothing this community says is \
                     attributable: {}",
                    rendered(&out)
                )
            });
            assert_eq!(
                proof.get("cryptosuite").and_then(|v| v.as_str()),
                Some("eddsa-jcs-2022"),
                "unexpected cryptosuite: {proof}"
            );
            assert!(
                proof.get("proofValue").and_then(|v| v.as_str()).is_some(),
                "the proof carries no signature: {proof}"
            );
        }

        /// A community with no signer answers **unsigned rather than failing**.
        ///
        /// It has nothing to sign with, and refusing would make an
        /// unprovisioned VTC unusable rather than merely unattributable — the
        /// wrong direction to err in, since the operation itself succeeded.
        #[tokio::test]
        async fn a_community_with_no_signer_still_answers() {
            let vtc = TestVtc::builder().with_signers(false).build().await;
            let member = Party::new();
            seed_member(&vtc, &member.did).await;

            let out = dispatch_trust_task_core(
                &vtc.state,
                &JoinAuthCtx::didcomm(member.did.clone()),
                &signed_document(
                    &member,
                    PERSONHOOD_CHALLENGE_TYPE,
                    json!({ "did": member.did }),
                )
                .await,
            )
            .await;

            assert!(
                out.status.is_success(),
                "an unsigned answer is still an answer: {}",
                rendered(&out)
            );
            let doc: serde_json::Value =
                serde_json::from_slice(&out.body).expect("the reply is a JSON document");
            assert!(doc.get("proof").is_none(), "signed without a signer");
        }

        /// The membership check standing in for the REST route's session.
        /// Without it, anyone who can reach the mediator could mint
        /// challenges against this community's members.
        #[tokio::test]
        async fn a_stranger_cannot_mint_a_challenge() {
            let vtc = fixture().await;
            let stranger = Party::new();
            let out = dispatch_trust_task_core(
                &vtc.state,
                &JoinAuthCtx::didcomm(stranger.did.clone()),
                &signed_document(
                    &stranger,
                    PERSONHOOD_CHALLENGE_TYPE,
                    json!({ "did": MEMBER }),
                )
                .await,
            )
            .await;

            let body = rendered(&out);
            assert!(
                !body.contains("challengeId"),
                "a non-member minted a challenge: {body}"
            );
            assert!(
                body.contains("not a member"),
                "expected a permission refusal naming membership, got: {body}"
            );
        }

        /// A refusal is signed, for `authentication`, like a result.
        #[tokio::test]
        async fn a_refusal_is_signed() {
            let vtc = fixture().await;
            let stranger = Party::new();
            let out = dispatch_trust_task_core(
                &vtc.state,
                &JoinAuthCtx::didcomm(stranger.did.clone()),
                &signed_document(
                    &stranger,
                    PERSONHOOD_CHALLENGE_TYPE,
                    json!({ "did": stranger.did }),
                )
                .await,
            )
            .await;
            assert!(!out.status.is_success(), "{}", rendered(&out));
            let doc: serde_json::Value = serde_json::from_slice(&out.body).expect("JSON reply");
            assert_eq!(
                doc["proof"]["proofPurpose"], "authentication",
                "a refusal must carry this community's proof: {doc}"
            );

            // So is one refused before dispatch — here an unsigned document.
            let mut unsigned: serde_json::Value = serde_json::from_slice(
                &signed_document(
                    &stranger,
                    PERSONHOOD_CHALLENGE_TYPE,
                    json!({ "did": stranger.did }),
                )
                .await,
            )
            .unwrap();
            unsigned.as_object_mut().unwrap().remove("proof");
            let out = dispatch_trust_task_core(
                &vtc.state,
                &JoinAuthCtx::didcomm(stranger.did.clone()),
                &serde_json::to_vec(&unsigned).unwrap(),
            )
            .await;
            let doc: serde_json::Value = serde_json::from_slice(&out.body).expect("JSON reply");
            assert_eq!(doc["proof"]["proofPurpose"], "authentication", "{doc}");
        }

        /// `assert/0.2` declares `actsAsSubject: true`. On a transport that
        /// proves the sender, one member must not be able to assert
        /// personhood in another's name — even though the presentation gate
        /// would also stop them, because a caller should be refused before
        /// the daemon starts verifying someone else's credentials.
        ///
        /// The document is **signed**, and that is the point of the fixture
        /// change #1672 made here. `assert/0.2` declares `proof` REQUIRED; this
        /// test used to send an unsigned one over DIDComm, which reached the
        /// handler only through the transitional allowance the same change
        /// removes. Left alone it would now stop at `proofRequired` and go on
        /// passing for a reason that has nothing to do with subject binding —
        /// a green test asserting nothing. Signing it puts the caller's
        /// identity where the handler reads it from (`verified_signer`, bound
        /// to the document's own `issuer`), so the refusal under test is still
        /// the one being produced.
        #[tokio::test]
        async fn one_member_cannot_assert_personhood_for_another() {
            let vtc = fixture().await;
            let stranger = Party::new();
            let out = dispatch_trust_task_core(
                &vtc.state,
                &JoinAuthCtx::didcomm(stranger.did.clone()),
                &signed_document(
                    &stranger,
                    PERSONHOOD_ASSERT_TYPE,
                    json!({
                        "did": MEMBER,
                        "presentation": { "type": ["VerifiablePresentation"], "holder": MEMBER },
                    }),
                )
                .await,
            )
            .await;

            let body = rendered(&out);
            assert!(
                body.contains("asserted by its subject"),
                "expected the subject-binding refusal, got: {body}"
            );
        }
    }
}

#[cfg(test)]
mod join_discovery_tests {
    //! The predicate the manifest gate rests on.
    use super::*;

    fn ctx(sender: Option<&str>, signer: Option<&str>) -> JoinAuthCtx {
        JoinAuthCtx {
            transport: JoinTransport::Rest,
            sender_did: sender.map(str::to_string),
            verified_signer: signer.map(str::to_string),
        }
    }

    /// Both transports prove who is asking, in their own way, and either is
    /// enough. Requiring the REST form of the proof from a DIDComm caller
    /// would refuse a party the envelope already named.
    #[test]
    fn either_transports_proof_of_who_is_asking_counts() {
        assert!(caller_is_identified(&ctx(None, Some("did:key:zSigner"))));
        assert!(caller_is_identified(&ctx(Some("did:peer:sender"), None)));
        assert!(caller_is_identified(&ctx(
            Some("did:peer:sender"),
            Some("did:key:zSigner")
        )));
    }

    /// The anonymous read — no signature, no envelope — is the only one the
    /// setting can turn off, and the only one it needs to.
    #[test]
    fn a_caller_that_proves_nothing_is_unidentified() {
        assert!(!caller_is_identified(&ctx(None, None)));
    }
}

/// The helpers below are `pub(super)` so [`join_decide_profile_tests`] — batch
/// 2's tests — build and dispatch documents exactly as these do. Two harnesses
/// for one binding would diverge, and the first thing to drift would be what
/// "signed" means.
///
/// The admin-facing member verbs, served as signed Trust Task documents —
/// **#1641 phase 2, batch 1**.
///
/// Four tasks (`vtc/members/{credentials,update,admin-remove,purge}`) whose
/// specifications declare `proof` REQUIRED were served only as flat-payload
/// REST behind a bearer JWT, so they got none of what the spine enforces: no
/// proof, no recipient binding, no acceptance window, and nothing in the
/// accepted-id record. They are now bound here as well.
///
/// What these tests hold, and why each one is here:
///
/// - **VTI-OPS-020** — the document carries a proof by its issuer, and that
///   issuer's **ACL entry** is what authorizes the operation. A bearer token is
///   not read on this endpoint at all.
/// - **VTI-OPS-025 / -026 / -027** — a redelivered document is answered with
///   the recorded outcome rather than executed again, a *different* document
///   under a spent `id` is `idConflict`, and the record is the shared
///   store-backed one. All three come from the spine's claim; these drive them
///   through a real admin verb, because the failure they guard against
///   ("purge executed twice") is only visible at a verb with an effect.
/// - **The gate the bearer route applied must still refuse what it refused.**
///   Losing one silently is the risk in the whole migration, so each refusal
///   the REST extractors made has a test here: not an admin (`AdminAuth`), and
///   for `purge` a context-scoped admin who is not a super-admin
///   (`SuperAdminAuth`). Plus the operations' own refusals — unknown member,
///   `role: admin`.
#[cfg(test)]
mod members_admin_tests {
    use super::*;
    use crate::acl::{VtcAclEntry, VtcRole, get_acl_entry, store_acl_entry};
    use crate::members::{Member, get_member, store_member};
    use crate::test_support::{TEST_VTC_DID, TestVtc};
    use serde_json::json;
    use vti_rooms_dtg::test_support::Party;

    /// The member these documents act on. Never one of the signers, so an
    /// `admin-remove` cannot collide with the "use /members/me" guard.
    const TARGET: &str = "did:key:zTargetMember";

    struct Fixture {
        vtc: TestVtc,
        /// `VtcRole::Admin`, unrestricted — a super-admin, so every verb here
        /// including `purge` is open to them.
        admin: Party,
        /// `VtcRole::Admin` **scoped to one context** — an admin, but not a
        /// super-admin. `SuperAdminAuth` refuses this caller and `AdminAuth`
        /// does not, which is the distinction `purge` rests on.
        scoped_admin: Party,
        /// `VtcRole::Member` — authenticated, authorized for none of this.
        member: Party,
    }

    pub(super) async fn seed_acl(vtc: &TestVtc, did: &str, role: VtcRole, contexts: Vec<String>) {
        store_acl_entry(
            &vtc.state.acl_ks,
            &VtcAclEntry {
                did: did.into(),
                admin: crate::acl::legacy_seed_authority(&role, &contexts),
                delegated_by: None,
                role,
                label: None,
                created_at: 0,
                created_by: "did:key:vtc-install".into(),
                updated_at: None,
                updated_by: None,
                expires_at: None,
                resource_grants: Vec::new(),
                label_set_by_subject: false,
                suspension: None,
            },
        )
        .await
        .expect("seed ACL row");
    }

    async fn fixture() -> Fixture {
        // `with_audit` because every one of these verbs writes an audit row and
        // refuses rather than acting when it cannot; `with_signers` because the
        // removal ceremony re-mints credentials and the spine signs its replies.
        let vtc = TestVtc::builder()
            .with_audit(true)
            .with_signers(true)
            .build()
            .await;
        crate::policy::default::install_defaults(
            &vtc.state.policies_ks,
            &vtc.state.active_policies_ks,
        )
        .await
        .expect("install default policies");

        let admin = Party::new();
        let scoped_admin = Party::new();
        let member = Party::new();
        seed_acl(&vtc, &admin.did, VtcRole::Admin, vec![]).await;
        seed_acl(
            &vtc,
            &scoped_admin.did,
            VtcRole::Admin,
            vec!["ctx-a".to_string()],
        )
        .await;
        seed_acl(&vtc, &member.did, VtcRole::Member, vec![]).await;

        // The subject these documents name: a member row *and* an ACL row,
        // which is what `members/credentials` means by "is a member".
        seed_acl(&vtc, TARGET, VtcRole::Member, vec![]).await;
        store_member(&vtc.state.members_ks, &Member::fresh(TARGET))
            .await
            .expect("seed target member");

        Fixture {
            vtc,
            admin,
            scoped_admin,
            member,
        }
    }

    /// The document as a real producer builds it — `issuer`, `recipient` and
    /// `issuedAt` set by the SDK's own builder — but unsigned.
    pub(super) fn unsigned(from: &Party, type_uri: &str, payload: Value) -> TrustTask<Value> {
        vta_sdk::trust_task_sign::build_unsigned(type_uri, payload, &from.did, TEST_VTC_DID)
            .expect("build the document")
    }

    pub(super) async fn sign(from: &Party, mut doc: TrustTask<Value>) -> TrustTask<Value> {
        let key =
            vta_sdk::trust_task_sign::HolderKey::from_did_key(&from.did, &from.secret_multibase)
                .expect("a did:key names its own verification method");
        vta_sdk::trust_task_sign::sign_in_place_with(&mut doc, &key)
            .await
            .expect("sign the document");
        doc
    }

    pub(super) async fn signed(from: &Party, type_uri: &str, payload: Value) -> TrustTask<Value> {
        sign(from, unsigned(from, type_uri, payload)).await
    }

    pub(super) async fn dispatch(vtc: &TestVtc, doc: &TrustTask<Value>) -> TrustTaskOutcome {
        let body = serde_json::to_vec(doc).expect("a document serialises");
        dispatch_trust_task_core(&vtc.state, &JoinAuthCtx::rest(), &body).await
    }

    /// As [`dispatch`], delivered over DIDComm with the document's issuer as
    /// the authcrypt sender — for the tasks served only end to end.
    pub(super) async fn dispatch_didcomm(
        vtc: &TestVtc,
        doc: &TrustTask<Value>,
    ) -> TrustTaskOutcome {
        let body = serde_json::to_vec(doc).expect("a document serialises");
        let sender = doc
            .issuer
            .clone()
            .expect("the test document names its issuer");
        dispatch_trust_task_core(&vtc.state, &JoinAuthCtx::didcomm(sender), &body).await
    }

    pub(super) fn body_of(out: &TrustTaskOutcome) -> Value {
        serde_json::from_slice(&out.body).unwrap_or(Value::Null)
    }

    /// The `code` of a `trust-task-error` reply, or `None` when the reply is a
    /// success document.
    pub(super) fn error_code(out: &TrustTaskOutcome) -> Option<String> {
        body_of(out)
            .pointer("/payload/code")?
            .as_str()
            .map(str::to_string)
    }

    pub(super) fn payload_of(out: &TrustTaskOutcome) -> Value {
        body_of(out)
            .pointer("/payload")
            .cloned()
            .unwrap_or(Value::Null)
    }

    /// Validate a success reply's payload against the task's published
    /// `#response` schema.
    ///
    /// The router-level `response_conformance` layer that guards every REST
    /// route keys on the `Trust-Task` **header**, which the document endpoint
    /// does not use — so it does not reach these replies, and this is what
    /// stands in for it. It matters most for `update`, whose arm answers with
    /// the route's own `MemberEnvelope` rather than the generated type: a drift
    /// between the two would otherwise be invisible until a client hit it.
    pub(super) fn assert_conforms<R: trust_tasks_rs::validate::ValidatedPayload>(
        out: &TrustTaskOutcome,
    ) {
        let payload = payload_of(out);
        R::validate_value(&payload).unwrap_or_else(|e| {
            panic!("response does not match its published schema: {e}\n{payload}")
        });
    }

    // ─── the premise ─────────────────────────────────────────────────────

    /// If the registry ever relaxed one of these declarations, every test below
    /// would be asserting nothing. This one says so first.
    #[test]
    fn every_moved_task_declares_the_proof_these_tests_assume() {
        for uri in [
            MEMBER_CREDENTIALS_TYPE,
            MEMBER_UPDATE_TYPE,
            MEMBER_ADMIN_REMOVE_TYPE,
            MEMBER_PURGE_TYPE,
        ] {
            let policy = trust_tasks_rs::schema_index::spec_policy_for(uri)
                .unwrap_or_else(|| panic!("{uri} has no published spec policy"));
            assert!(
                policy.is_proof_required,
                "{uri} no longer declares proof REQUIRED — these tests now assert \
                 nothing, and the design note should be re-read"
            );
        }
    }

    // ─── VTI-OPS-020: a proof by the issuer, authorized from their ACL ────

    /// **VTI-OPS-020.** A signed document from an admin is accepted and
    /// answered with the task's own response shape.
    #[tokio::test]
    async fn vti_ops_020_a_signed_admin_document_reads_member_credentials() {
        let fix = fixture().await;
        let doc = signed(
            &fix.admin,
            MEMBER_CREDENTIALS_TYPE,
            json!({ "did": TARGET }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;

        assert!(
            out.status.is_success(),
            "a signed admin document must be accepted: {}",
            String::from_utf8_lossy(&out.body)
        );
        assert_eq!(payload_of(&out)["did"], TARGET);
        assert_eq!(payload_of(&out)["memberVmcBound"], false);
        assert_conforms::<member_credentials::Response>(&out);
    }

    /// **VTI-OPS-020.** The *same* document with its proof stripped is refused
    /// with the framework's own code — the transport proved nothing and there
    /// is nothing else to authorize against.
    #[tokio::test]
    async fn vti_ops_020_an_unsigned_admin_document_is_refused() {
        let fix = fixture().await;
        for uri in [
            MEMBER_CREDENTIALS_TYPE,
            MEMBER_UPDATE_TYPE,
            MEMBER_ADMIN_REMOVE_TYPE,
            MEMBER_PURGE_TYPE,
        ] {
            let doc = unsigned(&fix.admin, uri, json!({ "did": TARGET }));
            let out = dispatch(&fix.vtc, &doc).await;
            assert_eq!(
                error_code(&out).as_deref(),
                Some("proofRequired"),
                "{uri}: SPEC §7.2 item 7 names the code: {}",
                String::from_utf8_lossy(&out.body)
            );
        }
        // …and nothing was removed by the unsigned `admin-remove` / `purge`.
        assert!(
            get_member(&fix.vtc.state.members_ks, TARGET)
                .await
                .expect("read member")
                .is_some(),
            "an unsigned document must not have had an effect"
        );
    }

    /// Authorization is the **signer's ACL entry**, not a bearer token: a
    /// correctly signed document from a DID with no admin row is refused, which
    /// is what `AdminAuth` refused on the REST route.
    #[tokio::test]
    async fn a_non_admin_signer_is_refused_every_admin_member_verb() {
        let fix = fixture().await;
        for uri in [
            MEMBER_CREDENTIALS_TYPE,
            MEMBER_UPDATE_TYPE,
            MEMBER_ADMIN_REMOVE_TYPE,
            MEMBER_PURGE_TYPE,
        ] {
            let doc = signed(&fix.member, uri, json!({ "did": TARGET })).await;
            let out = dispatch(&fix.vtc, &doc).await;
            assert_eq!(
                error_code(&out).as_deref(),
                Some("permissionDenied"),
                "{uri}: a member is not an administrator: {}",
                String::from_utf8_lossy(&out.body)
            );
        }
    }

    /// A DID with **no ACL row at all** is refused the same way — the signature
    /// verifies, and verifying a signature is not authorization.
    #[tokio::test]
    async fn a_signer_with_no_acl_row_is_refused() {
        let fix = fixture().await;
        let stranger = Party::new();
        let doc = signed(&stranger, MEMBER_CREDENTIALS_TYPE, json!({ "did": TARGET })).await;
        let out = dispatch(&fix.vtc, &doc).await;
        assert_eq!(error_code(&out).as_deref(), Some("permissionDenied"));
    }

    /// An **expired** ACL row no longer authorizes, which the bearer route
    /// could not notice: its JWT was minted while the row was live and nothing
    /// re-reads it. This is the one place the signed door is strictly stricter.
    #[tokio::test]
    async fn an_expired_admin_acl_row_no_longer_authorizes() {
        let fix = fixture().await;
        let lapsed = Party::new();
        store_acl_entry(
            &fix.vtc.state.acl_ks,
            &VtcAclEntry {
                did: lapsed.did.clone(),
                role: VtcRole::Admin,
                label: None,
                admin: VtcRole::Admin.implied_authority(),
                delegated_by: None,
                created_at: 0,
                created_by: "did:key:vtc-install".into(),
                updated_at: None,
                updated_by: None,
                expires_at: Some(1),
                resource_grants: Vec::new(),
                label_set_by_subject: false,
                suspension: None,
            },
        )
        .await
        .expect("seed a lapsed admin row");

        let doc = signed(&lapsed, MEMBER_CREDENTIALS_TYPE, json!({ "did": TARGET })).await;
        let out = dispatch(&fix.vtc, &doc).await;
        assert_eq!(error_code(&out).as_deref(), Some("permissionDenied"));
    }

    // ─── the scope gate `purge` rests on ─────────────────────────────────

    // ─── the capability `purge` rests on ─────────────────────────────────

    /// An administrator of this community, with a role, who does not hold
    /// `vtc.members.manage`: an auditor.
    async fn auditor(vtc: &TestVtc) -> Party {
        let p = Party::new();
        store_acl_entry(
            &vtc.state.acl_ks,
            &VtcAclEntry {
                admin: crate::acl::AdminAuthority::for_role(crate::acl::AdminRole::Auditor),
                ..VtcAclEntry::new(
                    &p.did,
                    VtcRole::Member,
                    crate::acl::AdminAuthority::none(),
                    "test",
                )
            },
        )
        .await
        .expect("seed an auditor");
        p
    }

    /// **`purge` takes `vtc.members.manage`** (`vtc-admin-roles.md` §4). An
    /// administrator without it — an auditor — is refused, and nothing is
    /// erased (VTI-ACL-030).
    #[tokio::test]
    async fn vti_acl_030_purge_needs_vtc_members_manage() {
        let fix = fixture().await;
        let auditor = auditor(&fix.vtc).await;
        let doc = signed(&auditor, MEMBER_PURGE_TYPE, json!({ "did": TARGET })).await;
        let out = dispatch(&fix.vtc, &doc).await;

        assert_eq!(
            error_code(&out).as_deref(),
            Some("permissionDenied"),
            "purge takes vtc.members.manage: {}",
            String::from_utf8_lossy(&out.body)
        );
        assert!(
            get_member(&fix.vtc.state.members_ks, TARGET)
                .await
                .expect("read member")
                .is_some(),
            "the refused purge must not have erased the member"
        );
    }

    /// …and the same caller *is* an administrator for the other three, exactly
    /// as `AdminAuth` admitted them. A gate copied one notch too tight is as
    /// much a regression as one copied too loose.
    #[tokio::test]
    async fn a_context_scoped_admin_may_still_read_credentials() {
        let fix = fixture().await;
        let doc = signed(
            &fix.scoped_admin,
            MEMBER_CREDENTIALS_TYPE,
            json!({ "did": TARGET }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;
        assert!(
            out.status.is_success(),
            "a context-scoped admin passes AdminAuth and must pass here: {}",
            String::from_utf8_lossy(&out.body)
        );
    }

    // ─── console-key delegations: acting as, and the four ways it stops ──
    //
    // #1684. A console signing key is a credential of an admin DID, not an
    // identity — it holds no ACL row and confers nothing. These drive the one
    // property that makes that safe: the delegation is *only* a name lookup,
    // and everything that decides authority is still the ACL row, read at
    // execution time. Four separate levers must each stop it dead.

    /// Enrol a console key for an admin directly in the store, the way
    /// `POST /v1/admin/console-keys` does behind its step-up. The route's own
    /// gates are exercised in `tests/admin_console_keys.rs`; these tests are
    /// about what the *verifier* does with the record afterwards.
    async fn delegate(vtc: &TestVtc, console: &Party, admin_did: &str) {
        crate::acl::console_key::enrol_delegation(
            &vtc.state.console_keys_ks,
            &vtc.state.acl_ks,
            &console.did,
            admin_did,
            Some("test browser".into()),
            None,
        )
        .await
        .expect("enrol the delegation");
    }

    /// The point of the whole change: a document signed by a key with **no ACL
    /// row of its own** is accepted, because the key is enrolled as a
    /// credential of a DID that has one.
    #[tokio::test]
    async fn a_delegated_console_key_acts_as_its_admin() {
        let fix = fixture().await;
        let console = Party::new();
        delegate(&fix.vtc, &console, &fix.admin.did).await;

        let doc = signed(&console, MEMBER_CREDENTIALS_TYPE, json!({ "did": TARGET })).await;
        let out = dispatch(&fix.vtc, &doc).await;
        assert!(
            out.status.is_success(),
            "a delegated console key must authorize as its admin: {}",
            String::from_utf8_lossy(&out.body)
        );
        assert_eq!(payload_of(&out)["did"], TARGET);
    }

    /// Lever 1 — **revocation, effective on the next document.** Nothing is
    /// cached, so there is no window in which a revoked browser still works.
    #[tokio::test]
    async fn a_revoked_delegation_stops_authorizing_immediately() {
        let fix = fixture().await;
        let console = Party::new();
        delegate(&fix.vtc, &console, &fix.admin.did).await;

        // It works…
        let first = signed(&console, MEMBER_CREDENTIALS_TYPE, json!({ "did": TARGET })).await;
        assert!(dispatch(&fix.vtc, &first).await.status.is_success());

        crate::acl::console_key::revoke_delegation(
            &fix.vtc.state.console_keys_ks,
            &console.did,
            &fix.admin.did,
        )
        .await
        .expect("revoke");

        // …and then it does not, with no restart, no re-login and no sweep.
        let second = signed(&console, MEMBER_CREDENTIALS_TYPE, json!({ "did": TARGET })).await;
        let out = dispatch(&fix.vtc, &second).await;
        assert_eq!(
            error_code(&out).as_deref(),
            Some("permissionDenied"),
            "a revoked console key must be refused: {}",
            String::from_utf8_lossy(&out.body)
        );
    }

    /// Lever 2 — **the delegating admin's ACL row is removed.** The row was
    /// always the authority; dropping it kills every key delegated from it at
    /// once, which is why a delegation needs no separate cascade.
    #[tokio::test]
    async fn removing_the_admins_acl_row_stops_the_delegated_key() {
        let fix = fixture().await;
        let console = Party::new();
        delegate(&fix.vtc, &console, &fix.admin.did).await;

        crate::acl::delete_acl_entry(&fix.vtc.state.acl_ks, &fix.admin.did)
            .await
            .expect("remove the admin row");

        let doc = signed(&console, MEMBER_CREDENTIALS_TYPE, json!({ "did": TARGET })).await;
        assert_eq!(
            error_code(&dispatch(&fix.vtc, &doc).await).as_deref(),
            Some("permissionDenied")
        );
    }

    /// Lever 3 — **the delegating admin is demoted.** `resolve_auth_role`
    /// admits only `VtcRole::Admin`, and it runs against the row as it is now,
    /// not as it was when the key was enrolled.
    #[tokio::test]
    async fn demoting_the_admin_stops_the_delegated_key() {
        let fix = fixture().await;
        let console = Party::new();
        delegate(&fix.vtc, &console, &fix.admin.did).await;

        seed_acl(&fix.vtc, &fix.admin.did, VtcRole::Member, vec![]).await;

        let doc = signed(&console, MEMBER_CREDENTIALS_TYPE, json!({ "did": TARGET })).await;
        assert_eq!(
            error_code(&dispatch(&fix.vtc, &doc).await).as_deref(),
            Some("permissionDenied")
        );
    }

    /// Lever 4 — **the delegating admin's row expires.** Same read, same
    /// instant, same refusal.
    #[tokio::test]
    async fn an_expired_admin_row_stops_the_delegated_key() {
        let fix = fixture().await;
        let console = Party::new();
        delegate(&fix.vtc, &console, &fix.admin.did).await;

        store_acl_entry(
            &fix.vtc.state.acl_ks,
            &VtcAclEntry {
                did: fix.admin.did.clone(),
                role: VtcRole::Admin,
                label: None,
                admin: VtcRole::Admin.implied_authority(),
                delegated_by: None,
                created_at: 0,
                created_by: "did:key:vtc-install".into(),
                updated_at: None,
                updated_by: None,
                expires_at: Some(1),
                resource_grants: Vec::new(),
                label_set_by_subject: false,
                suspension: None,
            },
        )
        .await
        .expect("expire the admin row");

        let doc = signed(&console, MEMBER_CREDENTIALS_TYPE, json!({ "did": TARGET })).await;
        assert_eq!(
            error_code(&dispatch(&fix.vtc, &doc).await).as_deref(),
            Some("permissionDenied")
        );
    }

    /// **A delegation cannot reach further than the admin it acts for.** A key
    /// delegated by an auditor is refused `purge` exactly as the auditor is —
    /// the delegation is a name lookup, not a widening.
    #[tokio::test]
    async fn a_delegation_inherits_its_admins_ceiling_and_no_more() {
        let fix = fixture().await;
        let auditor = auditor(&fix.vtc).await;
        let console = Party::new();
        delegate(&fix.vtc, &console, &auditor.did).await;

        let purge = signed(&console, MEMBER_PURGE_TYPE, json!({ "did": TARGET })).await;
        assert_eq!(
            error_code(&dispatch(&fix.vtc, &purge).await).as_deref(),
            Some("permissionDenied"),
            "purge takes vtc.members.manage, delegation or not"
        );
        // …and a moderator's delegation reaches what the moderator holds.
        let moderating = Party::new();
        delegate(&fix.vtc, &moderating, &fix.scoped_admin.did).await;
        let read = signed(
            &moderating,
            MEMBER_CREDENTIALS_TYPE,
            json!({ "did": TARGET }),
        )
        .await;
        assert!(dispatch(&fix.vtc, &read).await.status.is_success());
    }

    /// **A signer with a row of its own is answered by that row, even when the
    /// row refuses.** This is where the implementation is deliberately tighter
    /// than the design note's sketch: falling through to a delegation on
    /// `Forbidden` would let a stale delegation route around a demotion, which
    /// is the exact thing "authority is the ACL row" exists to prevent. Paired
    /// with `console_key`'s enrolment refusal, so the two halves cannot drift.
    #[tokio::test]
    async fn a_signer_holding_its_own_row_is_never_answered_by_a_delegation() {
        let fix = fixture().await;
        let console = Party::new();
        delegate(&fix.vtc, &console, &fix.admin.did).await;
        // Someone gives the console DID a row of its own, at a role that
        // authorizes nothing here.
        seed_acl(&fix.vtc, &console.did, VtcRole::Member, vec![]).await;

        let doc = signed(&console, MEMBER_CREDENTIALS_TYPE, json!({ "did": TARGET })).await;
        assert_eq!(
            error_code(&dispatch(&fix.vtc, &doc).await).as_deref(),
            Some("permissionDenied"),
            "the row is the answer, and it says no"
        );
    }

    /// An *undelegated* stranger is refused with the same code a delegated one
    /// gets after revocation — so the refusal is not an oracle for which DIDs
    /// are, or once were, console keys.
    #[tokio::test]
    async fn an_undelegated_signer_is_refused_indistinguishably() {
        let fix = fixture().await;
        let stranger = Party::new();
        let doc = signed(&stranger, MEMBER_CREDENTIALS_TYPE, json!({ "did": TARGET })).await;
        assert_eq!(
            error_code(&dispatch(&fix.vtc, &doc).await).as_deref(),
            Some("permissionDenied")
        );
    }

    // ─── the operations' own refusals ────────────────────────────────────

    /// The declared `notFound`, carried as a code rather than flattened into
    /// `taskFailed` — the same code the REST route puts in its body.
    #[tokio::test]
    async fn an_unknown_member_is_the_declared_not_found() {
        let fix = fixture().await;
        let doc = signed(
            &fix.admin,
            MEMBER_CREDENTIALS_TYPE,
            json!({ "did": "did:key:zNobodyAtAll" }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;
        assert_eq!(
            error_code(&out).as_deref(),
            Some(crate::routes::members::credentials::MEMBER_CREDENTIALS_ERR_NOT_FOUND),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
    }

    /// `role: admin` is refused with the task's `adminRoleForbidden` on this
    /// door too. The gate is on the transition, not on the route (#1645), so
    /// adding a second door must not add a second way past it.
    #[tokio::test]
    async fn update_still_refuses_promotion_to_admin() {
        let fix = fixture().await;
        let doc = signed(
            &fix.admin,
            MEMBER_UPDATE_TYPE,
            json!({ "did": TARGET, "role": "admin" }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;

        assert_eq!(
            error_code(&out).as_deref(),
            Some(crate::routes::members::update::UPDATE_ERR_ADMIN_ROLE_FORBIDDEN),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
        let acl = get_acl_entry(&fix.vtc.state.acl_ks, TARGET)
            .await
            .expect("read ACL")
            .expect("the target still has a row");
        assert_eq!(acl.role, VtcRole::Member, "and nothing was changed");
    }

    /// Registry consent is the member's to give: an administrator's
    /// `publishConsent: true` for a member who has not consented is refused
    /// with `consentGrantForbidden`, and nothing in the request is applied.
    #[tokio::test]
    async fn update_refuses_to_grant_registry_consent() {
        let fix = fixture().await;
        let doc = signed(
            &fix.admin,
            MEMBER_UPDATE_TYPE,
            json!({ "did": TARGET, "publishConsent": true, "label": "Ada Lovelace" }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;
        assert_eq!(
            error_code(&out).as_deref(),
            Some(crate::routes::members::update::UPDATE_ERR_CONSENT_GRANT_FORBIDDEN),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
        let member = get_member(&fix.vtc.state.members_ks, TARGET)
            .await
            .expect("read member")
            .expect("row");
        assert!(!member.publish_consent, "consent was not granted");
        let acl = get_acl_entry(&fix.vtc.state.acl_ks, TARGET)
            .await
            .expect("read ACL")
            .expect("row");
        assert_eq!(
            acl.label, None,
            "and nothing else in the request was applied"
        );
    }

    /// Withdrawing consent (`true → false`) is an administrator's to make, and
    /// re-stating the current value is a no-op rather than a grant.
    #[tokio::test]
    async fn update_withdraws_registry_consent_and_accepts_a_no_op() {
        let fix = fixture().await;
        let mut member = Member::fresh(TARGET);
        member.publish_consent = true;
        store_member(&fix.vtc.state.members_ks, &member)
            .await
            .expect("seed consent");

        // `true → true`: nothing changes, nothing is refused.
        let doc = signed(
            &fix.admin,
            MEMBER_UPDATE_TYPE,
            json!({ "did": TARGET, "publishConsent": true }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;
        assert!(
            out.status.is_success(),
            "{}",
            String::from_utf8_lossy(&out.body)
        );

        // `true → false`: the takedown.
        let doc = signed(
            &fix.admin,
            MEMBER_UPDATE_TYPE,
            json!({ "did": TARGET, "publishConsent": false }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;
        assert!(
            out.status.is_success(),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
        let after = get_member(&fix.vtc.state.members_ks, TARGET)
            .await
            .expect("read member")
            .expect("row");
        assert!(!after.publish_consent, "consent was withdrawn");

        // `false → false`: still a no-op.
        let doc = signed(
            &fix.admin,
            MEMBER_UPDATE_TYPE,
            json!({ "did": TARGET, "publishConsent": false }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;
        assert!(
            out.status.is_success(),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
    }

    /// A metadata update a signed document really does apply.
    #[tokio::test]
    async fn update_applies_a_metadata_change_from_a_signed_document() {
        let fix = fixture().await;
        let doc = signed(
            &fix.admin,
            MEMBER_UPDATE_TYPE,
            json!({ "did": TARGET, "label": "Ada Lovelace", "departurePreference": "purge" }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;
        assert!(
            out.status.is_success(),
            "{}",
            String::from_utf8_lossy(&out.body)
        );

        assert_conforms::<member_update::Response>(&out);

        let acl = get_acl_entry(&fix.vtc.state.acl_ks, TARGET)
            .await
            .expect("read ACL")
            .expect("row");
        assert_eq!(acl.label.as_deref(), Some("Ada Lovelace"));
        // The ACL row records *the signer* as the author of the change, which
        // is the attribution the task's proof requirement exists for.
        assert_eq!(acl.updated_by.as_deref(), Some(fix.admin.did.as_str()));
    }

    /// An **omitted** `extensions` leaves the member's own extensions alone.
    ///
    /// The generated payload types `extensions` as a plain map with `default`,
    /// so absent and empty are one value once parsed — and mapping that
    /// straight through would silently clear the bag on every update that did
    /// not mention it. The handler reads the raw payload for exactly this.
    #[tokio::test]
    async fn an_omitted_extensions_member_does_not_clear_the_bag() {
        let fix = fixture().await;
        let mut member = Member::fresh(TARGET);
        member.extensions = json!({ "org": "acme" });
        store_member(&fix.vtc.state.members_ks, &member)
            .await
            .expect("seed extensions");

        let doc = signed(
            &fix.admin,
            MEMBER_UPDATE_TYPE,
            json!({ "did": TARGET, "departurePreference": "purge" }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;
        assert!(
            out.status.is_success(),
            "{}",
            String::from_utf8_lossy(&out.body)
        );

        let after = get_member(&fix.vtc.state.members_ks, TARGET)
            .await
            .expect("read member")
            .expect("row");
        assert_eq!(after.extensions, json!({ "org": "acme" }));
    }

    /// An administrator removing another member, over the signed door.
    #[tokio::test]
    async fn admin_remove_departs_the_member_from_a_signed_document() {
        let fix = fixture().await;
        let doc = signed(
            &fix.admin,
            MEMBER_ADMIN_REMOVE_TYPE,
            json!({ "did": TARGET, "reason": "ToS violation" }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;

        assert!(
            out.status.is_success(),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
        assert_eq!(payload_of(&out)["did"], TARGET);
        assert_eq!(payload_of(&out)["removed"], true);
        assert_conforms::<member_admin_remove::Response>(&out);
        assert!(
            get_acl_entry(&fix.vtc.state.acl_ks, TARGET)
                .await
                .expect("read ACL")
                .is_none(),
            "the departed member keeps no authorization"
        );
    }

    /// A super-admin purging a member, over the signed door.
    #[tokio::test]
    async fn purge_erases_the_member_from_a_signed_document() {
        let fix = fixture().await;
        let doc = signed(&fix.admin, MEMBER_PURGE_TYPE, json!({ "did": TARGET })).await;
        let out = dispatch(&fix.vtc, &doc).await;

        assert!(
            out.status.is_success(),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
        assert_conforms::<member_purge::Response>(&out);
        assert!(
            get_member(&fix.vtc.state.members_ks, TARGET)
                .await
                .expect("read member")
                .is_none(),
            "purge erases the row"
        );
    }

    // ─── VTI-OPS-025 / -026 / -027: the accepted-id record ───────────────

    /// **VTI-OPS-025.** A redelivered document is answered with the outcome
    /// already recorded for it, not executed a second time.
    ///
    /// Driven through `purge`, because that is where a second execution would
    /// actually show: the member is gone after the first, so re-running would
    /// answer the declared `notFound` instead of the original success.
    #[tokio::test]
    async fn vti_ops_025_a_redelivered_document_is_answered_not_re_executed() {
        let fix = fixture().await;
        let doc = signed(&fix.admin, MEMBER_PURGE_TYPE, json!({ "did": TARGET })).await;

        let first = dispatch(&fix.vtc, &doc).await;
        assert!(
            first.status.is_success(),
            "{}",
            String::from_utf8_lossy(&first.body)
        );

        let second = dispatch(&fix.vtc, &doc).await;
        assert!(
            second.status.is_success(),
            "the redelivery must be answered, not refused: {}",
            String::from_utf8_lossy(&second.body)
        );
        assert_eq!(
            payload_of(&second),
            payload_of(&first),
            "the recorded outcome is what a redelivery is answered with"
        );
    }

    /// **VTI-OPS-026.** A *different* document under an already-spent `id` is
    /// `idConflict` — not absorbed as a retry, and not executed.
    #[tokio::test]
    async fn vti_ops_026_a_different_document_under_a_spent_id_conflicts() {
        let fix = fixture().await;
        let second_target = "did:key:zSecondTarget";
        seed_acl(&fix.vtc, second_target, VtcRole::Member, vec![]).await;
        store_member(&fix.vtc.state.members_ks, &Member::fresh(second_target))
            .await
            .expect("seed second member");

        let first = signed(&fix.admin, MEMBER_PURGE_TYPE, json!({ "did": TARGET })).await;
        let out = dispatch(&fix.vtc, &first).await;
        assert!(
            out.status.is_success(),
            "{}",
            String::from_utf8_lossy(&out.body)
        );

        // Same `id`, different subject — the shape the record exists to catch.
        let mut collider = unsigned(
            &fix.admin,
            MEMBER_PURGE_TYPE,
            json!({ "did": second_target }),
        );
        collider.id.clone_from(&first.id);
        let collider = sign(&fix.admin, collider).await;
        let out = dispatch(&fix.vtc, &collider).await;

        assert_eq!(
            error_code(&out).as_deref(),
            Some("idConflict"),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
        assert!(
            get_member(&fix.vtc.state.members_ks, second_target)
                .await
                .expect("read member")
                .is_some(),
            "the conflicting document must not have executed"
        );
    }

    /// **VTI-OPS-027.** The record these verbs consult is the shared,
    /// store-backed one, reachable from any binding — not a map private to this
    /// dispatcher. Read back through `AppState::accepted_ids`, which is the
    /// handle a second binding would use.
    #[tokio::test]
    async fn vti_ops_027_the_spent_id_is_visible_to_any_binding() {
        let fix = fixture().await;
        let doc = signed(
            &fix.admin,
            MEMBER_CREDENTIALS_TYPE,
            json!({ "did": TARGET }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;
        assert!(
            out.status.is_success(),
            "{}",
            String::from_utf8_lossy(&out.body)
        );

        let now = chrono::Utc::now();
        let again = fix
            .vtc
            .state
            .accepted_ids()
            .claim(&doc, retain_until(&doc, now), now)
            .await
            .expect("the record is readable");
        assert!(
            matches!(again, accepted_ids::Acceptance::Duplicate { .. }),
            "a second binding must see the id the dispatcher spent"
        );
    }
}

/// The join decision and the community-profile edit, served as signed Trust
/// Task documents — **#1641 phase 2, batch 2**.
///
/// `vtc/join-requests/decide/0.1` and `vtc/community/profile/update/0.1` both
/// declare `proof` REQUIRED and were served only as flat-payload REST behind a
/// bearer JWT. They are now bound here as well, on batch 1's terms.
///
/// What these tests hold beyond batch 1's, and why:
///
/// - **`decide` has a consequence a replay would duplicate.** Approving issues
///   a membership credential and a role endorsement, so a decision executed
///   twice issues two of each — the first migrated verb where a second
///   execution is materially wrong rather than merely redundant.
///   `vti_ops_025_a_replayed_decision_does_not_issue_a_second_credential`
///   drives the redelivery through the issuance path and checks the credential
///   the member ends up holding, not only the reply.
/// - **The gate each bearer route applied must still refuse what it refused.**
///   Both routes apply exactly `AdminAuth` and nothing further — no
///   super-admin bar, no context scoping — so the tests hold that shape: a
///   member is refused, a context-scoped admin is *not*.
/// - **The `#response` schema.** Both arms answer with the route's own
///   response struct, so a drift from the published schema would be invisible
///   until a client hit it; the document endpoint does not carry the
///   router-level `response_conformance` layer that covers the REST doors.
#[cfg(test)]
mod join_decide_profile_tests {
    use super::members_admin_tests::{
        assert_conforms, dispatch, error_code, payload_of, seed_acl, sign, signed, unsigned,
    };
    use super::*;
    use crate::acl::VtcRole;
    use crate::community::{CommunityProfile, load_profile, store_profile};
    use crate::join::{JoinRequest, JoinStatus, get_join_request, store_join_request};
    use crate::members::get_member;
    use crate::test_support::{TEST_VTC_DID, TestVtc};
    use serde_json::json;
    use vti_rooms_dtg::test_support::Party;

    const APPLICANT: &str = "did:key:zApplicant";
    const PUBLIC_URL: &str = "https://vtc.example.com";

    struct Fixture {
        vtc: TestVtc,
        /// `VtcRole::Admin`, unrestricted.
        admin: Party,
        /// `VtcRole::Admin` scoped to one context. Still an administrator —
        /// neither of these verbs asks the super-admin question, so this
        /// caller must be admitted, and a gate copied one notch too tight is
        /// as much a regression as one copied too loose.
        scoped_admin: Party,
        /// `VtcRole::Member` — authenticated, authorized for none of this.
        member: Party,
    }

    async fn fixture() -> Fixture {
        // `with_audit` because both verbs refuse rather than act when they
        // cannot record what they did; `with_signers` because approving mints
        // a VMC and a role VAC, and the spine signs its replies;
        // `with_public_url` because the credentials name the status list by
        // URL.
        let vtc = TestVtc::builder()
            .with_audit(true)
            .with_signers(true)
            .with_public_url(PUBLIC_URL)
            .build()
            .await;
        crate::policy::default::install_defaults(
            &vtc.state.policies_ks,
            &vtc.state.active_policies_ks,
        )
        .await
        .expect("install default policies");
        // Both status lists, as `server::run` seeds them at boot: approving
        // allocates a slot in each, and an unseeded list fails the issuance
        // as an internal error rather than as anything a caller could read.
        for purpose in [
            affinidi_status_list::StatusPurpose::Revocation,
            affinidi_status_list::StatusPurpose::Suspension,
        ] {
            crate::status_list::ensure_initial(
                &vtc.state.status_lists_ks,
                purpose,
                format!("{PUBLIC_URL}/v1/status-lists/{purpose}"),
            )
            .await
            .expect("seed the status list");
        }
        store_profile(
            &vtc.state.community_ks,
            &CommunityProfile::new(TEST_VTC_DID, "Example Community"),
        )
        .await
        .expect("seed the community profile");

        let admin = Party::new();
        let scoped_admin = Party::new();
        let member = Party::new();
        seed_acl(&vtc, &admin.did, VtcRole::Admin, vec![]).await;
        seed_acl(
            &vtc,
            &scoped_admin.did,
            VtcRole::Admin,
            vec!["ctx-a".to_string()],
        )
        .await;
        seed_acl(&vtc, &member.did, VtcRole::Member, vec![]).await;

        Fixture {
            vtc,
            admin,
            scoped_admin,
            member,
        }
    }

    /// A pending join request from `APPLICANT`, ready to be decided.
    async fn pending_request(vtc: &TestVtc) -> uuid::Uuid {
        let req = JoinRequest::new(APPLICANT, json!({}));
        let id = req.id;
        store_join_request(&vtc.state.join_requests_ks, &req)
            .await
            .expect("seed a pending join request");
        id
    }

    // ─── the premise ─────────────────────────────────────────────────────

    /// If the registry ever relaxed one of these declarations, every test
    /// below would be asserting nothing. This one says so first.
    #[test]
    fn every_moved_task_declares_the_proof_these_tests_assume() {
        for uri in [JOIN_DECIDE_TYPE, COMMUNITY_PROFILE_UPDATE_TYPE] {
            let policy = trust_tasks_rs::schema_index::spec_policy_for(uri)
                .unwrap_or_else(|| panic!("{uri} has no published spec policy"));
            assert!(
                policy.is_proof_required,
                "{uri} no longer declares proof REQUIRED — these tests now assert \
                 nothing, and the design note should be re-read"
            );
        }
    }

    // ─── VTI-OPS-020: a proof by the issuer, authorized from their ACL ────

    /// **VTI-OPS-020.** A signed admin document admits the applicant, and the
    /// reply is the task's own response shape.
    #[tokio::test]
    async fn vti_ops_020_a_signed_admin_document_approves_a_join_request() {
        let fix = fixture().await;
        let id = pending_request(&fix.vtc).await;

        let doc = signed(
            &fix.admin,
            JOIN_DECIDE_TYPE,
            json!({ "id": id.to_string(), "decision": "approved" }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;

        assert!(
            out.status.is_success(),
            "a signed admin document must be accepted: {}",
            String::from_utf8_lossy(&out.body)
        );
        assert_eq!(payload_of(&out)["requestId"], id.to_string());
        assert_eq!(payload_of(&out)["status"], "approved");
        assert!(
            payload_of(&out)["vmc"].is_object(),
            "approval delivers the membership credential inline"
        );
        assert_conforms::<join_decide::Response>(&out);

        let member = get_member(&fix.vtc.state.members_ks, APPLICANT)
            .await
            .expect("read member")
            .expect("the applicant is now a member");
        assert!(member.current_vmc_id.is_some());
    }

    /// **VTI-OPS-020.** A signed admin document edits the community profile,
    /// and the reply conforms to the published `#response`.
    #[tokio::test]
    async fn vti_ops_020_a_signed_admin_document_updates_the_profile() {
        let fix = fixture().await;
        let doc = signed(
            &fix.admin,
            COMMUNITY_PROFILE_UPDATE_TYPE,
            json!({ "name": "Renamed Community", "description": "A better blurb." }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;

        assert!(
            out.status.is_success(),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
        assert_eq!(payload_of(&out)["profile"]["name"], "Renamed Community");
        assert_conforms::<community_profile_update::Response>(&out);

        let stored = load_profile(&fix.vtc.state.community_ks)
            .await
            .expect("read profile")
            .expect("row");
        assert_eq!(stored.name, "Renamed Community");
        assert_eq!(stored.description, "A better blurb.");
    }

    /// **VTI-OPS-020.** The same documents with their proofs stripped are
    /// refused with the framework's own code, and nothing happens.
    #[tokio::test]
    async fn vti_ops_020_an_unsigned_admin_document_is_refused() {
        let fix = fixture().await;
        let id = pending_request(&fix.vtc).await;

        for (uri, payload) in [
            (
                JOIN_DECIDE_TYPE,
                json!({ "id": id.to_string(), "decision": "approved" }),
            ),
            (COMMUNITY_PROFILE_UPDATE_TYPE, json!({ "name": "Hijacked" })),
        ] {
            let doc = unsigned(&fix.admin, uri, payload);
            let out = dispatch(&fix.vtc, &doc).await;
            assert_eq!(
                error_code(&out).as_deref(),
                Some("proofRequired"),
                "{uri}: SPEC §7.2 item 7 names the code: {}",
                String::from_utf8_lossy(&out.body)
            );
        }

        assert_eq!(
            get_join_request(&fix.vtc.state.join_requests_ks, id)
                .await
                .expect("read request")
                .expect("row")
                .status,
            JoinStatus::Pending,
            "an unsigned decision must not have decided anything"
        );
        assert_eq!(
            load_profile(&fix.vtc.state.community_ks)
                .await
                .expect("read profile")
                .expect("row")
                .name,
            "Example Community",
        );
    }

    /// Authorization is the **signer's ACL entry**, not a bearer token: a
    /// correctly signed document from a member is refused, which is what
    /// `AdminAuth` refused on both REST routes.
    #[tokio::test]
    async fn a_non_admin_signer_is_refused_both_verbs() {
        let fix = fixture().await;
        let id = pending_request(&fix.vtc).await;

        for (uri, payload) in [
            (
                JOIN_DECIDE_TYPE,
                json!({ "id": id.to_string(), "decision": "approved" }),
            ),
            (COMMUNITY_PROFILE_UPDATE_TYPE, json!({ "name": "Hijacked" })),
        ] {
            let doc = signed(&fix.member, uri, payload).await;
            let out = dispatch(&fix.vtc, &doc).await;
            assert_eq!(
                error_code(&out).as_deref(),
                Some("permissionDenied"),
                "{uri}: a member is not an administrator: {}",
                String::from_utf8_lossy(&out.body)
            );
        }
        assert!(
            get_member(&fix.vtc.state.members_ks, APPLICANT)
                .await
                .expect("read member")
                .is_none(),
            "the refused decision must not have admitted anybody"
        );
    }

    /// A DID with **no ACL row at all** is refused the same way — the
    /// signature verifies, and verifying a signature is not authorization.
    #[tokio::test]
    async fn a_signer_with_no_acl_row_is_refused() {
        let fix = fixture().await;
        let stranger = Party::new();
        let doc = signed(
            &stranger,
            COMMUNITY_PROFILE_UPDATE_TYPE,
            json!({ "name": "Hijacked" }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;
        assert_eq!(error_code(&out).as_deref(), Some("permissionDenied"));
    }

    /// **Each verb takes its own capability** (`vtc-admin-roles.md` §4): a
    /// moderator holds `vtc.join.decide` and decides, and does not hold
    /// `vtc.surface.admin`, so it may not edit the profile.
    #[tokio::test]
    async fn a_moderator_may_decide_and_may_not_edit_the_profile() {
        let fix = fixture().await;
        let id = pending_request(&fix.vtc).await;

        let doc = signed(
            &fix.scoped_admin,
            JOIN_DECIDE_TYPE,
            json!({ "id": id.to_string(), "decision": "rejected", "reason": "not this time" }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;
        assert!(
            out.status.is_success(),
            "a moderator holds vtc.join.decide: {}",
            String::from_utf8_lossy(&out.body)
        );
        assert_eq!(payload_of(&out)["status"], "rejected");

        let doc = signed(
            &fix.scoped_admin,
            COMMUNITY_PROFILE_UPDATE_TYPE,
            json!({ "name": "Scoped Rename" }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;
        assert_eq!(
            error_code(&out).as_deref(),
            Some("permissionDenied"),
            "the profile takes vtc.surface.admin: {}",
            String::from_utf8_lossy(&out.body)
        );
    }

    // ─── the operations' own refusals ────────────────────────────────────

    /// The declared `notFound`, carried as a code rather than flattened into
    /// `taskFailed` — the same code the REST route puts in its body.
    #[tokio::test]
    async fn an_unknown_request_is_the_declared_not_found() {
        let fix = fixture().await;
        let doc = signed(
            &fix.admin,
            JOIN_DECIDE_TYPE,
            json!({ "id": uuid::Uuid::new_v4().to_string(), "decision": "approved" }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;
        assert_eq!(
            error_code(&out).as_deref(),
            Some(crate::routes::join_requests::decide::DECIDE_ERR_NOT_FOUND),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
    }

    /// An `id` that is not a join-request id is a **malformed payload**, not
    /// the declared `notFound`. Answering `notFound` would tell an operator a
    /// request had been deleted when what they sent was never an id.
    #[tokio::test]
    async fn an_id_that_is_not_an_id_is_malformed_not_not_found() {
        let fix = fixture().await;
        let doc = signed(
            &fix.admin,
            JOIN_DECIDE_TYPE,
            json!({ "id": "not-a-uuid", "decision": "approved" }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;
        assert_eq!(
            error_code(&out).as_deref(),
            Some("malformedRequest"),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
    }

    /// A *second, different* decision aimed at an already-decided request is
    /// the declared `notPending`. This is not the duplicate guard — it is the
    /// conflict an operator should see.
    #[tokio::test]
    async fn a_second_decision_on_a_decided_request_is_not_pending() {
        let fix = fixture().await;
        let id = pending_request(&fix.vtc).await;

        let first = signed(
            &fix.admin,
            JOIN_DECIDE_TYPE,
            json!({ "id": id.to_string(), "decision": "approved" }),
        )
        .await;
        let out = dispatch(&fix.vtc, &first).await;
        assert!(
            out.status.is_success(),
            "{}",
            String::from_utf8_lossy(&out.body)
        );

        // A fresh document — new `id`, so the accepted-id record has nothing
        // to say about it — carrying the opposite decision.
        let second = signed(
            &fix.admin,
            JOIN_DECIDE_TYPE,
            json!({ "id": id.to_string(), "decision": "rejected" }),
        )
        .await;
        assert_ne!(first.id, second.id, "these must be distinct documents");
        let out = dispatch(&fix.vtc, &second).await;
        assert_eq!(
            error_code(&out).as_deref(),
            Some(crate::routes::join_requests::decide::DECIDE_ERR_NOT_PENDING),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
    }

    /// A field failing validation is the task's own `validationFailed`.
    #[tokio::test]
    async fn a_bad_profile_field_is_the_declared_validation_failure() {
        let fix = fixture().await;
        let doc = signed(
            &fix.admin,
            COMMUNITY_PROFILE_UPDATE_TYPE,
            // Not an http(s) URL — refused so it cannot reach an `<img src>`
            // on the public page.
            json!({ "logoUrl": "javascript:alert(1)" }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;
        assert_eq!(
            error_code(&out).as_deref(),
            Some(crate::routes::community::profile::PROFILE_UPDATE_ERR_VALIDATION_FAILED),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
    }

    /// An **omitted** member leaves the stored value alone — the distinction
    /// the double parse exists for.
    ///
    /// The generated `Payload` types `extensions` as a map with `default`, so
    /// once parsed an absent bag and an empty one are the same value, and
    /// mapping that straight through would clear the community's extensions on
    /// every update that did not mention them. The handler reads the raw
    /// payload for exactly this.
    #[tokio::test]
    async fn an_omitted_member_does_not_clear_what_it_did_not_mention() {
        let fix = fixture().await;
        let set = signed(
            &fix.admin,
            COMMUNITY_PROFILE_UPDATE_TYPE,
            json!({
                "logoUrl": "https://example.com/logo.png",
                "extensions": { "org": "acme" },
            }),
        )
        .await;
        assert!(dispatch(&fix.vtc, &set).await.status.is_success());

        let other = signed(
            &fix.admin,
            COMMUNITY_PROFILE_UPDATE_TYPE,
            json!({ "name": "Still Logoed" }),
        )
        .await;
        assert!(dispatch(&fix.vtc, &other).await.status.is_success());

        let stored = load_profile(&fix.vtc.state.community_ks)
            .await
            .expect("read profile")
            .expect("row");
        assert_eq!(
            stored.logo_url.as_deref(),
            Some("https://example.com/logo.png"),
            "an omitted `logoUrl` must leave the stored one alone"
        );
        assert_eq!(
            stored.extensions,
            json!({ "org": "acme" }),
            "and an omitted `extensions` must not clear the bag"
        );
    }

    /// An explicit `null` **does not** clear a nullable member, on either
    /// door — a divergence from the published task, recorded here rather than
    /// left for a client to discover.
    ///
    /// `vtc/community/profile/update/0.1` says the nullable members "may be
    /// explicitly set to `null` to clear them". They cannot be:
    /// `CommunityProfileUpdate` types them `Option<Option<String>>` but
    /// declares no double-option deserializer, and serde maps an explicit
    /// `null` onto the *outer* `None` — which this operation reads as "leave
    /// unchanged". That is the store's behaviour rather than the transport's,
    /// so it predates this binding and holds identically on the bearer route.
    /// What #1641 phase 2 is answerable for is that the two doors agree, and
    /// they do; fixing it is a change to `CommunityProfileUpdate` that moves
    /// both doors at once and belongs in its own.
    #[tokio::test]
    async fn an_explicit_null_does_not_yet_clear_a_nullable_member() {
        let fix = fixture().await;
        let set = signed(
            &fix.admin,
            COMMUNITY_PROFILE_UPDATE_TYPE,
            json!({ "logoUrl": "https://example.com/logo.png" }),
        )
        .await;
        assert!(dispatch(&fix.vtc, &set).await.status.is_success());

        let clear = signed(
            &fix.admin,
            COMMUNITY_PROFILE_UPDATE_TYPE,
            json!({ "logoUrl": null }),
        )
        .await;
        let out = dispatch(&fix.vtc, &clear).await;
        assert!(
            out.status.is_success(),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
        assert_eq!(
            load_profile(&fix.vtc.state.community_ks)
                .await
                .expect("read profile")
                .expect("row")
                .logo_url
                .as_deref(),
            Some("https://example.com/logo.png"),
            "the logo survives a `null` the specification says should clear it"
        );
    }

    // ─── VTI-OPS-025 / -026: the accepted-id record, on a verb that issues ─

    /// **VTI-OPS-025 — the one this batch exists to get right.**
    ///
    /// A redelivered approval is answered with the outcome already recorded
    /// for it, and **does not issue a second membership credential**. The
    /// mediator re-pushes an undelivered inbox as a matter of routine, so this
    /// is the ordinary case rather than an attack, and without the spine's
    /// claim-before-execute the applicant would end up holding two VMCs with
    /// two status-list slots — one of which nobody could later revoke, because
    /// only the last write is on the member row.
    #[tokio::test]
    async fn vti_ops_025_a_replayed_decision_does_not_issue_a_second_credential() {
        let fix = fixture().await;
        let id = pending_request(&fix.vtc).await;
        let doc = signed(
            &fix.admin,
            JOIN_DECIDE_TYPE,
            json!({ "id": id.to_string(), "decision": "approved" }),
        )
        .await;

        let first = dispatch(&fix.vtc, &doc).await;
        assert!(
            first.status.is_success(),
            "{}",
            String::from_utf8_lossy(&first.body)
        );
        let issued = get_member(&fix.vtc.state.members_ks, APPLICANT)
            .await
            .expect("read member")
            .expect("the applicant is a member");
        let first_vmc_id = issued.current_vmc_id.clone().expect("a VMC was issued");
        let first_slot = issued.status_list_index;

        let second = dispatch(&fix.vtc, &doc).await;
        assert!(
            second.status.is_success(),
            "the redelivery must be answered, not refused: {}",
            String::from_utf8_lossy(&second.body)
        );
        assert_eq!(
            payload_of(&second),
            payload_of(&first),
            "the recorded outcome is what a redelivery is answered with — a \
             second execution would have answered `notPending` instead"
        );

        let after = get_member(&fix.vtc.state.members_ks, APPLICANT)
            .await
            .expect("read member")
            .expect("row");
        assert_eq!(
            after.current_vmc_id.as_deref(),
            Some(first_vmc_id.as_str()),
            "the member still holds the credential the first execution issued"
        );
        assert_eq!(
            after.status_list_index, first_slot,
            "and no second status-list slot was burned"
        );
    }

    /// **VTI-OPS-026.** A *different* document under an already-spent `id` is
    /// `idConflict` — not absorbed as a retry, and not executed.
    #[tokio::test]
    async fn vti_ops_026_a_different_document_under_a_spent_id_conflicts() {
        let fix = fixture().await;
        let first = signed(
            &fix.admin,
            COMMUNITY_PROFILE_UPDATE_TYPE,
            json!({ "name": "First Name" }),
        )
        .await;
        let out = dispatch(&fix.vtc, &first).await;
        assert!(
            out.status.is_success(),
            "{}",
            String::from_utf8_lossy(&out.body)
        );

        let mut collider = unsigned(
            &fix.admin,
            COMMUNITY_PROFILE_UPDATE_TYPE,
            json!({ "name": "Second Name" }),
        );
        collider.id.clone_from(&first.id);
        let collider = sign(&fix.admin, collider).await;
        let out = dispatch(&fix.vtc, &collider).await;

        assert_eq!(
            error_code(&out).as_deref(),
            Some("idConflict"),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
        assert_eq!(
            load_profile(&fix.vtc.state.community_ks)
                .await
                .expect("read profile")
                .expect("row")
                .name,
            "First Name",
            "the conflicting document must not have executed"
        );
    }
}

/// The portable-configuration pair, served as signed Trust Task documents —
/// **#1641 phase 2, batch 3**.
///
/// `vtc/config/export/0.1` and `vtc/config/import/0.1` both declare `proof`
/// REQUIRED and were served only as flat-payload REST behind a bearer JWT.
/// They are now bound here as well, on batches 1 and 2's terms.
///
/// What these tests hold, and why:
///
/// - **The gate each bearer route applied must still refuse what it refused.**
///   Both routes apply exactly `AdminAuth` — no super-admin bar, no context
///   scoping — so a member is refused and a context-scoped admin is not.
/// - **A preview writes nothing.** `confirm` defaults to `false`, and the safe
///   direction of that default is the whole point of it; a door that applied
///   on a preview would overwrite a live community's configuration.
/// - **An exported document imports as a no-op.** The pair exists to move a
///   configuration between hosts, so what one verb emits the other must read
///   back unchanged.
/// - **The published `ext` members are accepted.** The route's hand-written
///   types refused them under `deny_unknown_fields`, which the generated
///   schema permits; a schema-valid document refused as malformed is the
///   divergence this batch closed on both doors.
#[cfg(test)]
mod config_pair_tests {
    use super::members_admin_tests::{
        assert_conforms, dispatch, error_code, payload_of, seed_acl, signed, unsigned,
    };
    use super::*;
    use crate::acl::VtcRole;
    use crate::community::{CommunityProfile, load_profile, store_profile};
    use crate::config_store::ConfigStore;
    use crate::routes::admin::config::{
        IMPORT_ERR_COMMUNITY_DID_MISMATCH, IMPORT_ERR_UNSUPPORTED_SCHEMA_VERSION, export_inner,
    };
    use crate::test_support::{TEST_VTC_DID, TestVtc};
    use serde_json::json;
    use vti_rooms_dtg::test_support::Party;

    struct Fixture {
        vtc: TestVtc,
        /// `VtcRole::Admin`, unrestricted.
        admin: Party,
        /// `VtcRole::Admin` scoped to one context — still an administrator,
        /// and neither verb asks the super-admin question.
        scoped_admin: Party,
        /// `VtcRole::Member` — authenticated, authorized for none of this.
        member: Party,
    }

    async fn fixture() -> Fixture {
        // `with_audit` because an applied import refuses rather than acts when
        // it cannot record what it changed; `with_signers` because the spine
        // signs its replies.
        let vtc = TestVtc::builder()
            .with_audit(true)
            .with_signers(true)
            .build()
            .await;
        store_profile(
            &vtc.state.community_ks,
            &CommunityProfile::new(TEST_VTC_DID, "Example Community"),
        )
        .await
        .expect("seed the community profile");

        let admin = Party::new();
        let scoped_admin = Party::new();
        let member = Party::new();
        seed_acl(&vtc, &admin.did, VtcRole::Admin, vec![]).await;
        seed_acl(
            &vtc,
            &scoped_admin.did,
            VtcRole::Admin,
            vec!["ctx-a".to_string()],
        )
        .await;
        seed_acl(&vtc, &member.did, VtcRole::Member, vec![]).await;

        Fixture {
            vtc,
            admin,
            scoped_admin,
            member,
        }
    }

    /// This community's own export, renamed and carrying one override — a
    /// document that differs from what is stored in exactly two places.
    async fn changed_document(vtc: &TestVtc) -> Value {
        let mut document = serde_json::to_value(
            export_inner(&vtc.state)
                .await
                .expect("export the seeded community")
                .document,
        )
        .expect("the document serialises");
        document["communityProfile"]["name"] = json!("Imported Community");
        document["configOverrides"] = json!({ "log.level": "debug" });
        document
    }

    async fn stored_name(vtc: &TestVtc) -> String {
        load_profile(&vtc.state.community_ks)
            .await
            .expect("read profile")
            .expect("row")
            .name
    }

    async fn stored_log_level(vtc: &TestVtc) -> Option<Value> {
        ConfigStore::new(vtc.state.config_ks.clone())
            .get("log.level")
            .await
            .expect("read override")
    }

    // ─── the premise ─────────────────────────────────────────────────────

    /// If the registry ever relaxed one of these declarations, every test
    /// below would be asserting nothing. This one says so first.
    #[test]
    fn every_moved_task_declares_the_proof_these_tests_assume() {
        for uri in [CONFIG_EXPORT_TYPE, CONFIG_IMPORT_TYPE] {
            let policy = trust_tasks_rs::schema_index::spec_policy_for(uri)
                .unwrap_or_else(|| panic!("{uri} has no published spec policy"));
            assert!(
                policy.is_proof_required,
                "{uri} no longer declares proof REQUIRED — these tests now assert \
                 nothing, and the design note should be re-read"
            );
        }
    }

    // ─── VTI-OPS-020: a proof by the issuer, authorized from their ACL ────

    /// **VTI-OPS-020.** A signed admin document exports the configuration,
    /// and the reply conforms to the published `#response`.
    #[tokio::test]
    async fn vti_ops_020_a_signed_admin_document_exports_the_configuration() {
        let fix = fixture().await;
        ConfigStore::new(fix.vtc.state.config_ks.clone())
            .put("log.level", &json!("warn"))
            .await
            .expect("seed an override");

        let doc = signed(&fix.admin, CONFIG_EXPORT_TYPE, json!({})).await;
        let out = dispatch(&fix.vtc, &doc).await;

        assert!(
            out.status.is_success(),
            "a signed admin document must be accepted: {}",
            String::from_utf8_lossy(&out.body)
        );
        let document = &payload_of(&out)["document"];
        assert_eq!(document["communityProfile"]["name"], "Example Community");
        assert_eq!(document["configOverrides"]["log.level"], "warn");
        assert_conforms::<config_export::Response>(&out);
    }

    /// **VTI-OPS-020.** A signed import without `confirm` is a preview: it
    /// reports the change and writes nothing.
    #[tokio::test]
    async fn vti_ops_020_a_signed_import_previews_by_default_and_writes_nothing() {
        let fix = fixture().await;
        let document = changed_document(&fix.vtc).await;

        let doc = signed(
            &fix.admin,
            CONFIG_IMPORT_TYPE,
            json!({ "document": document }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;

        assert!(
            out.status.is_success(),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
        let payload = payload_of(&out);
        assert_eq!(payload["status"], "preview");
        assert_eq!(payload["profileChanges"][0]["key"], "name");
        assert_eq!(payload["overrideChanges"][0]["key"], "log.level");
        assert_conforms::<config_import::Response>(&out);

        assert_eq!(stored_name(&fix.vtc).await, "Example Community");
        assert_eq!(stored_log_level(&fix.vtc).await, None);
    }

    /// **VTI-OPS-020.** With `confirm: true` the same document is applied.
    #[tokio::test]
    async fn vti_ops_020_a_confirmed_signed_import_applies_the_document() {
        let fix = fixture().await;
        let document = changed_document(&fix.vtc).await;

        let doc = signed(
            &fix.admin,
            CONFIG_IMPORT_TYPE,
            json!({ "document": document, "confirm": true }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;

        assert!(
            out.status.is_success(),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
        assert_eq!(payload_of(&out)["status"], "imported");
        assert_conforms::<config_import::Response>(&out);

        assert_eq!(stored_name(&fix.vtc).await, "Imported Community");
        assert_eq!(stored_log_level(&fix.vtc).await, Some(json!("debug")));
    }

    /// The pair's purpose: what `export` emits, `import` reads back as no
    /// change at all. Both halves go through this door.
    #[tokio::test]
    async fn an_exported_document_imports_as_no_change() {
        let fix = fixture().await;
        let export = signed(&fix.admin, CONFIG_EXPORT_TYPE, json!({})).await;
        let out = dispatch(&fix.vtc, &export).await;
        assert!(out.status.is_success());
        let document = payload_of(&out)["document"].clone();

        let import = signed(
            &fix.admin,
            CONFIG_IMPORT_TYPE,
            json!({ "document": document, "confirm": true }),
        )
        .await;
        let out = dispatch(&fix.vtc, &import).await;
        assert!(
            out.status.is_success(),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
        let payload = payload_of(&out);
        assert_eq!(payload["profileChanges"], json!([]), "{payload}");
        assert_eq!(payload["overrideChanges"], json!([]), "{payload}");
        assert_eq!(payload["rejected"], json!([]), "{payload}");
    }

    /// **VTI-OPS-020.** The same documents unsigned are refused with the
    /// framework's own code, and nothing is written.
    #[tokio::test]
    async fn vti_ops_020_an_unsigned_config_document_is_refused() {
        let fix = fixture().await;
        let document = changed_document(&fix.vtc).await;

        for (uri, payload) in [
            (CONFIG_EXPORT_TYPE, json!({})),
            (
                CONFIG_IMPORT_TYPE,
                json!({ "document": document, "confirm": true }),
            ),
        ] {
            let doc = unsigned(&fix.admin, uri, payload);
            let out = dispatch(&fix.vtc, &doc).await;
            assert_eq!(
                error_code(&out).as_deref(),
                Some("proofRequired"),
                "{uri}: SPEC §7.2 item 7 names the code: {}",
                String::from_utf8_lossy(&out.body)
            );
        }
        assert_eq!(stored_name(&fix.vtc).await, "Example Community");
    }

    /// Authorization is the **signer's ACL entry**: a correctly signed
    /// document from a member, or from a DID with no row at all, is refused —
    /// what `AdminAuth` refused on both REST routes.
    #[tokio::test]
    async fn a_signer_who_is_not_an_admin_is_refused_both_verbs() {
        let fix = fixture().await;
        let stranger = Party::new();
        let document = changed_document(&fix.vtc).await;

        for signer in [&fix.member, &stranger] {
            for (uri, payload) in [
                (CONFIG_EXPORT_TYPE, json!({})),
                (
                    CONFIG_IMPORT_TYPE,
                    json!({ "document": document, "confirm": true }),
                ),
            ] {
                let doc = signed(signer, uri, payload).await;
                let out = dispatch(&fix.vtc, &doc).await;
                assert_eq!(
                    error_code(&out).as_deref(),
                    Some("permissionDenied"),
                    "{uri}: {}",
                    String::from_utf8_lossy(&out.body)
                );
            }
        }
        assert_eq!(stored_name(&fix.vtc).await, "Example Community");
        assert_eq!(stored_log_level(&fix.vtc).await, None);
    }

    /// **Both verbs take `vtc.config.admin`** (`vtc-admin-roles.md` §4). An
    /// administrator without it — a moderator — may do neither.
    #[tokio::test]
    async fn vti_acl_030_config_export_and_import_need_vtc_config_admin() {
        let fix = fixture().await;
        let document = changed_document(&fix.vtc).await;

        let doc = signed(&fix.scoped_admin, CONFIG_EXPORT_TYPE, json!({})).await;
        let out = dispatch(&fix.vtc, &doc).await;
        assert_eq!(
            error_code(&out).as_deref(),
            Some("permissionDenied"),
            "export takes vtc.config.admin: {}",
            String::from_utf8_lossy(&out.body)
        );

        // An import writes community-wide configuration (#1829): refused, and
        // nothing is stored.
        let doc = signed(
            &fix.scoped_admin,
            CONFIG_IMPORT_TYPE,
            json!({ "document": document, "confirm": true }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;
        assert_eq!(
            error_code(&out).as_deref(),
            Some("permissionDenied"),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
        assert_ne!(stored_name(&fix.vtc).await, "Imported Community");
    }

    // ─── the operation's own refusals ────────────────────────────────────

    /// A document taken from another community is the declared
    /// `communityDidMismatch`, carried as a code rather than flattened.
    #[tokio::test]
    async fn another_communitys_document_is_the_declared_mismatch() {
        let fix = fixture().await;
        let mut document = changed_document(&fix.vtc).await;
        document["communityProfile"]["communityDid"] = json!("did:web:elsewhere.example");

        let doc = signed(
            &fix.admin,
            CONFIG_IMPORT_TYPE,
            json!({ "document": document, "confirm": true }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;
        assert_eq!(
            error_code(&out).as_deref(),
            Some(IMPORT_ERR_COMMUNITY_DID_MISMATCH),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
        assert_eq!(stored_name(&fix.vtc).await, "Example Community");
    }

    /// A `schemaVersion` this build does not read is the declared
    /// `unsupportedSchemaVersion` — valid against the schema, refused by the
    /// operation before it diffs anything.
    #[tokio::test]
    async fn an_unknown_schema_version_is_the_declared_refusal() {
        let fix = fixture().await;
        let mut document = changed_document(&fix.vtc).await;
        document["schemaVersion"] = json!(2);

        let doc = signed(
            &fix.admin,
            CONFIG_IMPORT_TYPE,
            json!({ "document": document }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;
        assert_eq!(
            error_code(&out).as_deref(),
            Some(IMPORT_ERR_UNSUPPORTED_SCHEMA_VERSION),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
    }

    /// The published `ext` extension points — on the payload and on the
    /// document — are accepted. The route's types refused both under
    /// `deny_unknown_fields` until this batch, so a schema-valid document was
    /// answered as malformed.
    #[tokio::test]
    async fn the_published_ext_members_are_accepted() {
        let fix = fixture().await;
        let mut document = changed_document(&fix.vtc).await;
        document["ext"] = json!({ "org.example": { "note": "from staging" } });

        let doc = signed(
            &fix.admin,
            CONFIG_IMPORT_TYPE,
            json!({
                "document": document,
                "ext": { "org.example": { "ticket": "OPS-1" } },
            }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;
        assert!(
            out.status.is_success(),
            "a schema-valid document must not be refused as malformed: {}",
            String::from_utf8_lossy(&out.body)
        );
        assert_eq!(payload_of(&out)["status"], "preview");
    }
}

/// The endorsement-type registry's two writes, served as signed Trust Task
/// documents — **#1641 phase 2, batch 4**.
///
/// `vtc/endorsement-types/register/0.1` and `vtc/endorsement-types/delete/0.1`
/// declare `proof` REQUIRED and were served only as bearer REST. They are
/// served only here now: the admin console signs both, and their bearer
/// routes are gone.
///
/// What these tests hold beyond the earlier batches':
///
/// - **The size bounds both doors now share.** `claimSchema` is capped at
///   32 KiB serialised so every registration that passes fits the signed
///   door's 64 KiB document cap; the cap is the operation's, so the refusal is
///   the same code on either door.
/// - **An absent `claimSchema` stays absent.** The generated payload folds
///   absent into an empty map; the arm reads the raw payload so the stored row
///   records what the operator sent.
/// - **`inUse` still reports both halves.** The refusal is the operation's,
///   reached through the same `delete_inner`.
#[cfg(test)]
mod endorsement_type_tests {
    use super::members_admin_tests::{
        assert_conforms, dispatch, error_code, payload_of, seed_acl, signed, unsigned,
    };
    use super::*;
    use crate::acl::VtcRole;
    use crate::endorsement_types::get_type;
    use crate::routes::endorsement_types::{
        CLAIM_SCHEMA_MAX_BYTES, DELETE_ERR_IN_USE, DELETE_ERR_NOT_FOUND, REGISTER_ERR_EXISTS,
        REGISTER_ERR_RESERVED,
    };
    use crate::test_support::TestVtc;
    use serde_json::json;
    use vti_rooms_dtg::test_support::Party;

    const TYPE: &str = "https://example.org/predicates/vetted/1";

    struct Fixture {
        vtc: TestVtc,
        admin: Party,
        scoped_admin: Party,
        member: Party,
    }

    async fn fixture() -> Fixture {
        let vtc = TestVtc::builder()
            .with_audit(true)
            .with_signers(true)
            .build()
            .await;
        let admin = Party::new();
        let scoped_admin = Party::new();
        let member = Party::new();
        seed_acl(&vtc, &admin.did, VtcRole::Admin, vec![]).await;
        seed_acl(
            &vtc,
            &scoped_admin.did,
            VtcRole::Admin,
            vec!["ctx-a".to_string()],
        )
        .await;
        seed_acl(&vtc, &member.did, VtcRole::Member, vec![]).await;
        Fixture {
            vtc,
            admin,
            scoped_admin,
            member,
        }
    }

    async fn register(fix: &Fixture, from: &Party, payload: Value) -> TrustTaskOutcome {
        let doc = signed(from, ENDORSEMENT_TYPE_REGISTER_TYPE, payload).await;
        dispatch(&fix.vtc, &doc).await
    }

    async fn delete(fix: &Fixture, from: &Party, type_uri: &str) -> TrustTaskOutcome {
        let doc = signed(
            from,
            ENDORSEMENT_TYPE_DELETE_TYPE,
            json!({ "typeUri": type_uri }),
        )
        .await;
        dispatch(&fix.vtc, &doc).await
    }

    async fn stored(fix: &Fixture) -> Option<crate::endorsement_types::EndorsementType> {
        get_type(&fix.vtc.state.endorsement_types_ks, TYPE)
            .await
            .expect("read type")
    }

    // ─── the premise ─────────────────────────────────────────────────────

    #[test]
    fn every_moved_task_declares_the_proof_these_tests_assume() {
        for uri in [ENDORSEMENT_TYPE_REGISTER_TYPE, ENDORSEMENT_TYPE_DELETE_TYPE] {
            let policy = trust_tasks_rs::schema_index::spec_policy_for(uri)
                .unwrap_or_else(|| panic!("{uri} has no published spec policy"));
            assert!(
                policy.is_proof_required,
                "{uri} no longer declares proof REQUIRED — these tests now assert \
                 nothing, and the design note should be re-read"
            );
        }
    }

    // ─── VTI-OPS-020: a proof by the issuer, authorized from their ACL ────

    /// **VTI-OPS-020.** A signed admin document registers a type, and the row
    /// names the signer.
    #[tokio::test]
    async fn vti_ops_020_a_signed_admin_document_registers_a_type() {
        let fix = fixture().await;
        let out = register(
            &fix,
            &fix.admin,
            json!({
                "typeUri": TYPE,
                "description": "Peer identity vetting",
                "claimSchema": { "type": "object" },
            }),
        )
        .await;
        assert!(
            out.status.is_success(),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
        assert_eq!(payload_of(&out)["endorsementType"]["typeUri"], TYPE);
        assert_conforms::<endorsement_type_register::Response>(&out);

        let row = stored(&fix).await.expect("the type is registered");
        assert_eq!(row.created_by_did, fix.admin.did);
        assert_eq!(row.claim_schema, Some(json!({ "type": "object" })));
    }

    /// **VTI-OPS-020.** A signed admin document deletes an unreferenced type.
    #[tokio::test]
    async fn vti_ops_020_a_signed_admin_document_deletes_a_type() {
        let fix = fixture().await;
        assert!(
            register(&fix, &fix.admin, json!({ "typeUri": TYPE }))
                .await
                .status
                .is_success()
        );

        let out = delete(&fix, &fix.admin, TYPE).await;
        assert!(
            out.status.is_success(),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
        assert_eq!(payload_of(&out)["typeUri"], TYPE);
        assert_conforms::<endorsement_type_delete::Response>(&out);
        assert!(stored(&fix).await.is_none());
    }

    /// **VTI-OPS-020.** Unsigned, both are refused with the framework's code.
    #[tokio::test]
    async fn vti_ops_020_an_unsigned_document_is_refused() {
        let fix = fixture().await;
        for (uri, payload) in [
            (ENDORSEMENT_TYPE_REGISTER_TYPE, json!({ "typeUri": TYPE })),
            (ENDORSEMENT_TYPE_DELETE_TYPE, json!({ "typeUri": TYPE })),
        ] {
            let out = dispatch(&fix.vtc, &unsigned(&fix.admin, uri, payload)).await;
            assert_eq!(
                error_code(&out).as_deref(),
                Some("proofRequired"),
                "{uri}: {}",
                String::from_utf8_lossy(&out.body)
            );
        }
        assert!(stored(&fix).await.is_none());
    }

    /// Authorization is the signer's ACL entry: a member, and a DID with no
    /// row, are refused both verbs — what `AdminAuth` refused on the REST
    /// routes.
    #[tokio::test]
    async fn a_signer_who_is_not_an_admin_is_refused_both_verbs() {
        let fix = fixture().await;
        let stranger = Party::new();
        for signer in [&fix.member, &stranger] {
            let out = register(&fix, signer, json!({ "typeUri": TYPE })).await;
            assert_eq!(error_code(&out).as_deref(), Some("permissionDenied"));
            let out = delete(&fix, signer, TYPE).await;
            assert_eq!(error_code(&out).as_deref(), Some("permissionDenied"));
        }
        assert!(stored(&fix).await.is_none());
    }

    /// Both verbs take `vtc.surface.admin` (`vtc-admin-roles.md` §4): a
    /// moderator, who holds no such capability, is refused both.
    #[tokio::test]
    async fn vti_acl_030_endorsement_types_need_vtc_surface_admin() {
        let fix = fixture().await;
        let out = register(&fix, &fix.scoped_admin, json!({ "typeUri": TYPE })).await;
        assert_eq!(error_code(&out).as_deref(), Some("permissionDenied"));
        let out = delete(&fix, &fix.scoped_admin, TYPE).await;
        assert_eq!(error_code(&out).as_deref(), Some("permissionDenied"));
    }

    // ─── the operations' own refusals ────────────────────────────────────

    /// The declared `reserved` and `exists`, carried as codes.
    #[tokio::test]
    async fn the_declared_register_refusals_are_carried_as_codes() {
        let fix = fixture().await;
        let out = register(
            &fix,
            &fix.admin,
            json!({ "typeUri": crate::endorsements::VETTER_GRANT_ROW_TYPE }),
        )
        .await;
        assert_eq!(error_code(&out).as_deref(), Some(REGISTER_ERR_RESERVED));

        assert!(
            register(&fix, &fix.admin, json!({ "typeUri": TYPE }))
                .await
                .status
                .is_success()
        );
        // A fresh document — a new `id` — so this is the operation refusing a
        // second registration, not the accepted-id record answering a replay.
        let out = register(&fix, &fix.admin, json!({ "typeUri": TYPE })).await;
        assert_eq!(error_code(&out).as_deref(), Some(REGISTER_ERR_EXISTS));
    }

    /// A `claimSchema` over the cap is refused, and nothing is stored. The
    /// document itself is under 64 KiB, so this is the operation's bound
    /// speaking, not the transport's.
    #[tokio::test]
    async fn a_claim_schema_over_the_cap_is_refused() {
        let fix = fixture().await;
        let padding = "x".repeat(CLAIM_SCHEMA_MAX_BYTES);
        let out = register(
            &fix,
            &fix.admin,
            json!({
                "typeUri": TYPE,
                "claimSchema": { "type": "object", "description": padding },
            }),
        )
        .await;
        assert_eq!(
            error_code(&out).as_deref(),
            Some("malformedRequest"),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
        assert!(stored(&fix).await.is_none());
    }

    /// A `claimSchema` that is not a JSON Schema is refused with the framework's
    /// `malformedRequest`, which the operation declares because the task has no
    /// code of its own for it. Before this batch, mapping that declared code
    /// panicked the dispatcher: it read every declared code as `<slug>:<local>`.
    #[tokio::test]
    async fn a_claim_schema_that_is_not_a_schema_is_malformed_not_a_panic() {
        let fix = fixture().await;
        let out = register(
            &fix,
            &fix.admin,
            json!({ "typeUri": TYPE, "claimSchema": { "type": "not-a-type" } }),
        )
        .await;
        assert_eq!(
            error_code(&out).as_deref(),
            Some("malformedRequest"),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
        assert!(stored(&fix).await.is_none());
    }

    /// An omitted `claimSchema` is stored as absent, not as an empty schema —
    /// the distinction the arm reads the raw payload for.
    #[tokio::test]
    async fn an_omitted_claim_schema_is_stored_as_absent() {
        let fix = fixture().await;
        assert!(
            register(&fix, &fix.admin, json!({ "typeUri": TYPE }))
                .await
                .status
                .is_success()
        );
        assert_eq!(stored(&fix).await.expect("row").claim_schema, None);
    }

    /// The declared `notFound`.
    #[tokio::test]
    async fn deleting_an_unknown_type_is_the_declared_not_found() {
        let fix = fixture().await;
        let out = delete(&fix, &fix.admin, TYPE).await;
        assert_eq!(error_code(&out).as_deref(), Some(DELETE_ERR_NOT_FOUND));
    }

    /// The declared `inUse`, for a type an Accepts criterion still requires —
    /// and the type is still there afterwards.
    #[tokio::test]
    async fn deleting_a_referenced_type_is_the_declared_in_use() {
        let fix = fixture().await;
        assert!(
            register(&fix, &fix.admin, json!({ "typeUri": TYPE }))
                .await
                .status
                .is_success()
        );
        let schemas_ks = &fix.vtc.state.schemas_ks;
        let entry: crate::schemas::SchemaEntry = serde_json::from_value(json!({
            "typeUri": "StatementCredential",
            "dtgType": "StatementCredential",
            "kind": "accepts",
            "createdAt": "2026-09-24T00:00:00Z",
            "createdByDid": fix.admin.did,
        }))
        .expect("schema entry");
        crate::schemas::storage::store_schema(schemas_ks, &entry)
            .await
            .expect("store the referenced schema");
        let criterion: crate::schemas::accepts::AcceptsCriterion = serde_json::from_value(json!({
            "id": "vetted",
            "admission": "automatic",
            "vetting": {
                "version": "0.1",
                "statementType": TYPE,
                "minStatements": 2,
                "minByMethod": { "inPerson": 1 },
                "acceptedMethods": ["inPerson", "video"],
                "maxStatementAge": "P120D",
                "eligibleVetters": { "role": "vetter" },
            },
            "createdAt": "2026-09-24T00:00:00Z",
            "createdByDid": fix.admin.did,
        }))
        .expect("criterion");
        crate::schemas::accepts::store_accepts(schemas_ks, &criterion)
            .await
            .expect("store the criterion");

        let out = delete(&fix, &fix.admin, TYPE).await;
        assert_eq!(
            error_code(&out).as_deref(),
            Some(DELETE_ERR_IN_USE),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
        assert!(stored(&fix).await.is_some());
    }
}

/// The backup export, served as a signed Trust Task document — **#1641
/// phase 2, batch 5**.
///
/// What these tests hold beyond the earlier batches':
///
/// - **The super-admin bar.** The bearer route took `SuperAdminAuth`, so a
///   context-scoped admin — admitted by every earlier batch's verbs — is
///   refused here, as `members/purge` refuses one.
/// - **A redelivery answers with the same envelope.** The spine records the
///   reply, so the second delivery of one document gets the first export back
///   rather than a second one under a fresh salt and nonce.
#[cfg(test)]
mod backup_export_tests {
    use super::members_admin_tests::{
        assert_conforms, dispatch, dispatch_didcomm, error_code, payload_of, seed_acl, signed,
        unsigned,
    };
    use super::*;
    use crate::acl::VtcRole;
    use crate::test_support::{TEST_VTC_DID, TestVtc};
    use serde_json::json;
    use vti_rooms_dtg::test_support::Party;

    const PASSWORD: &str = "a-long-enough-backup-password";

    struct Fixture {
        vtc: TestVtc,
        super_admin: Party,
        scoped_admin: Party,
        member: Party,
    }

    async fn fixture() -> Fixture {
        let vtc = TestVtc::builder()
            .vtc_did(TEST_VTC_DID)
            .with_audit(true)
            .with_signers(true)
            .build()
            .await;
        // The export reads the signing bundle from the configured secret
        // store. The default build compiles `keyring`, which a test cannot
        // reach, so name the plaintext backend and seed the store through the
        // same factory the route calls.
        let store = {
            let mut config = vtc.state.config.write().await;
            config.secrets.backend = Some(crate::config::SecretBackend::Plaintext);
            crate::keys::seed_store::create_secret_store(&config).expect("plaintext store")
        };
        store
            .set(b"signing-bundle")
            .await
            .expect("seed the secret store");

        let super_admin = Party::new();
        let scoped_admin = Party::new();
        let member = Party::new();
        seed_acl(&vtc, &super_admin.did, VtcRole::Admin, vec![]).await;
        seed_acl(
            &vtc,
            &scoped_admin.did,
            VtcRole::Admin,
            vec!["ctx-a".to_string()],
        )
        .await;
        seed_acl(&vtc, &member.did, VtcRole::Member, vec![]).await;
        Fixture {
            vtc,
            super_admin,
            scoped_admin,
            member,
        }
    }

    #[test]
    fn the_moved_task_declares_the_proof_these_tests_assume() {
        let policy = trust_tasks_rs::schema_index::spec_policy_for(BACKUP_EXPORT_TYPE)
            .expect("backup/export has a published spec policy");
        assert!(
            policy.is_proof_required,
            "backup/export no longer declares proof REQUIRED — these tests now \
             assert nothing, and the design note should be re-read"
        );
    }

    /// **VTI-OPS-020.** A signed super-admin document exports the community,
    /// and the reply conforms to the published `#response`.
    #[tokio::test]
    async fn vti_ops_020_a_signed_super_admin_document_exports() {
        let fix = fixture().await;
        let doc = signed(
            &fix.super_admin,
            BACKUP_EXPORT_TYPE,
            json!({ "password": PASSWORD }),
        )
        .await;
        let out = dispatch_didcomm(&fix.vtc, &doc).await;
        assert!(
            out.status.is_success(),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
        let envelope = &payload_of(&out)["envelope"];
        assert_eq!(envelope["sourceDid"], TEST_VTC_DID);
        assert!(
            envelope["ciphertext"]
                .as_str()
                .is_some_and(|c| !c.is_empty())
        );
        assert_conforms::<backup_export::Response>(&out);
    }

    /// The super-admin bar holds: a context-scoped admin is refused, as
    /// `SuperAdminAuth` refused them on the bearer route, and so is a member.
    #[tokio::test]
    async fn only_a_super_admin_may_export() {
        let fix = fixture().await;
        for signer in [&fix.scoped_admin, &fix.member] {
            let doc = signed(signer, BACKUP_EXPORT_TYPE, json!({ "password": PASSWORD })).await;
            let out = dispatch(&fix.vtc, &doc).await;
            assert_eq!(
                error_code(&out).as_deref(),
                Some("permissionDenied"),
                "{}",
                String::from_utf8_lossy(&out.body)
            );
        }
    }

    /// **VTI-OPS-020.** Unsigned, it is refused with the framework's code.
    #[tokio::test]
    async fn vti_ops_020_an_unsigned_export_is_refused() {
        let fix = fixture().await;
        let doc = unsigned(
            &fix.super_admin,
            BACKUP_EXPORT_TYPE,
            json!({ "password": PASSWORD }),
        );
        let out = dispatch(&fix.vtc, &doc).await;
        assert_eq!(error_code(&out).as_deref(), Some("proofRequired"));
    }

    /// A password under the minimum is the declared `passwordTooShort`.
    #[tokio::test]
    async fn a_short_password_is_the_declared_refusal() {
        let fix = fixture().await;
        let short = "x".repeat(vta_sdk::protocols::backup_management::MIN_BACKUP_PASSWORD_LEN - 1);
        let doc = signed(
            &fix.super_admin,
            BACKUP_EXPORT_TYPE,
            json!({ "password": short }),
        )
        .await;
        let out = dispatch_didcomm(&fix.vtc, &doc).await;
        assert_eq!(
            error_code(&out).as_deref(),
            Some(
                trust_tasks_rs::specs::vtc::backup::export::v0_1::error_codes::PASSWORD_TOO_SHORT
                    .code
            ),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
    }

    /// **VTI-OPS-025.** The same document delivered twice is answered with the
    /// same envelope: the spine recorded the first reply, so the second
    /// delivery does not run a second export under a fresh salt and nonce.
    #[tokio::test]
    async fn vti_ops_025_a_redelivered_export_answers_with_the_same_envelope() {
        let fix = fixture().await;
        let doc = signed(
            &fix.super_admin,
            BACKUP_EXPORT_TYPE,
            json!({ "password": PASSWORD }),
        )
        .await;
        let first = dispatch_didcomm(&fix.vtc, &doc).await;
        let second = dispatch_didcomm(&fix.vtc, &doc).await;
        assert!(first.status.is_success() && second.status.is_success());
        assert_eq!(
            payload_of(&first)["envelope"],
            payload_of(&second)["envelope"],
            "a redelivery must be answered with the recorded export"
        );
    }

    /// The backup password and the backup never cross a hop-by-hop channel:
    /// the same signed super-admin document is refused over REST.
    #[tokio::test]
    async fn an_export_over_rest_is_refused() {
        let fix = fixture().await;
        let doc = signed(
            &fix.super_admin,
            BACKUP_EXPORT_TYPE,
            json!({ "password": PASSWORD }),
        )
        .await;
        let out = dispatch(&fix.vtc, &doc).await;
        assert_eq!(
            error_code(&out).as_deref(),
            Some("permissionDenied"),
            "{}",
            String::from_utf8_lossy(&out.body)
        );
        assert!(String::from_utf8_lossy(&out.body).contains("DIDComm or TSP"));
    }

    /// With no audit trail to record it in, the export is refused rather than
    /// released unrecorded.
    #[tokio::test]
    async fn an_export_with_no_audit_trail_is_refused() {
        let vtc = TestVtc::builder()
            .vtc_did(TEST_VTC_DID)
            .with_audit(false)
            .with_signers(true)
            .build()
            .await;
        // Everything else an export needs is in place, so the audit trail is
        // the only thing missing.
        let store = {
            let mut config = vtc.state.config.write().await;
            config.secrets.backend = Some(crate::config::SecretBackend::Plaintext);
            crate::keys::seed_store::create_secret_store(&config).expect("plaintext store")
        };
        store.set(b"signing-bundle").await.expect("seed the store");
        let admin = Party::new();
        seed_acl(&vtc, &admin.did, VtcRole::Admin, vec![]).await;
        let doc = signed(&admin, BACKUP_EXPORT_TYPE, json!({ "password": PASSWORD })).await;
        let out = dispatch_didcomm(&vtc, &doc).await;
        // The reply masks internal detail; what matters is that no envelope
        // left.
        assert_eq!(error_code(&out).as_deref(), Some("internalError"));
        assert!(payload_of(&out).get("envelope").is_none());
    }
}

/// `vtc/vetting/vetters/grant/0.1` signed by a console key: the grant is the
/// administrator's, as for every other administrative task (VTI-ACL-030).
#[cfg(test)]
mod vetter_grant_console_key_tests {
    use super::members_admin_tests::{dispatch, error_code, signed};
    use super::*;
    use crate::acl::console_key::{ConsoleKeyDelegation, DelegationScope, store_delegation};
    use crate::acl::{AdminAuthority, VtcAclEntry, VtcRole, store_acl_entry};
    use crate::members::{Member, store_member};
    use crate::test_support::TestVtc;
    use serde_json::json;
    use vti_rooms_dtg::test_support::Party;

    const MEMBER: &str = "did:key:zVetterGrantConsoleKeyMember";

    async fn seed(vtc: &TestVtc, did: &str, role: VtcRole, admin: AdminAuthority) {
        store_acl_entry(
            &vtc.state.acl_ks,
            &VtcAclEntry {
                did: did.into(),
                role,
                label: None,
                admin,
                delegated_by: None,
                created_at: 0,
                created_by: "did:key:vtc-install".into(),
                updated_at: None,
                updated_by: None,
                expires_at: None,
                resource_grants: Vec::new(),
                label_set_by_subject: false,
                suspension: None,
            },
        )
        .await
        .expect("seed ACL row");
    }

    async fn delegate(vtc: &TestVtc, console: &Party, admin_did: &str) {
        store_delegation(
            &vtc.state.console_keys_ks,
            &ConsoleKeyDelegation {
                console_did: console.did.clone(),
                admin_did: admin_did.to_string(),
                scope: DelegationScope::Console,
                label: None,
                created_at: chrono::Utc::now(),
                expires_at: chrono::Utc::now() + chrono::Duration::days(1),
                last_used_at: None,
                revoked_at: None,
                revoked_by: None,
            },
        )
        .await
        .expect("store delegation");
    }

    /// A community with one community-admin and one member to name a vetter.
    async fn community() -> (TestVtc, Party) {
        let vtc = TestVtc::builder()
            .with_audit(true)
            .with_signers(true)
            .build()
            .await;
        let admin = Party::new();
        seed(
            &vtc,
            &admin.did,
            VtcRole::Admin,
            AdminAuthority::community_admin(),
        )
        .await;
        seed(&vtc, MEMBER, VtcRole::Member, AdminAuthority::none()).await;
        store_member(&vtc.state.members_ks, &Member::fresh(MEMBER))
            .await
            .expect("store member");
        // A grant issues a revocable vetter role credential.
        for purpose in [
            affinidi_status_list::StatusPurpose::Revocation,
            affinidi_status_list::StatusPurpose::Suspension,
        ] {
            crate::status_list::ensure_initial(
                &vtc.state.status_lists_ks,
                purpose,
                format!("https://vtc.example.com/v1/status-lists/{purpose}"),
            )
            .await
            .expect("provision status list");
        }
        (vtc, admin)
    }

    fn grant() -> Value {
        json!({ "memberDid": MEMBER })
    }

    #[tokio::test]
    async fn vti_acl_030_a_console_key_grants_a_vetter_as_its_community_admin() {
        let (vtc, admin) = community().await;
        let console = Party::new();
        delegate(&vtc, &console, &admin.did).await;
        let doc = signed(&console, vetting_wire::VETTING_VETTER_GRANT_TYPE, grant()).await;
        let out = dispatch(&vtc, &doc).await;
        assert_eq!(error_code(&out), None, "{out:?}");
        let rows = crate::vetting::vetters::grant_rows(&vtc.state)
            .await
            .expect("grant rows");
        assert!(
            rows.iter().any(|r| r.member_did == MEMBER && !r.revoked),
            "the member is a vetter: {rows:?}"
        );
    }

    #[tokio::test]
    async fn vti_acl_030_a_console_key_with_no_delegation_grants_nothing() {
        let (vtc, _admin) = community().await;
        let console = Party::new();
        let doc = signed(&console, vetting_wire::VETTING_VETTER_GRANT_TYPE, grant()).await;
        let out = dispatch(&vtc, &doc).await;
        assert!(error_code(&out).is_some(), "refused: {out:?}");
        let rows = crate::vetting::vetters::grant_rows(&vtc.state)
            .await
            .expect("grant rows");
        assert!(rows.is_empty(), "nothing granted: {rows:?}");
    }

    #[tokio::test]
    async fn vti_acl_030_a_console_key_of_an_admin_without_vetting_manage_grants_nothing() {
        let (vtc, _admin) = community().await;
        let moderator = Party::new();
        seed(
            &vtc,
            &moderator.did,
            VtcRole::Admin,
            AdminAuthority::for_role(crate::acl::AdminRole::Moderator),
        )
        .await;
        let console = Party::new();
        delegate(&vtc, &console, &moderator.did).await;
        let doc = signed(&console, vetting_wire::VETTING_VETTER_GRANT_TYPE, grant()).await;
        let out = dispatch(&vtc, &doc).await;
        assert!(error_code(&out).is_some(), "refused: {out:?}");
    }
}