vta-service 0.35.0

Service for Verifiable Trust Agents operating in Verifiable Trust Communities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
//! `POST /api/trust-tasks` — the VTA-side trust-task dispatcher.
//!
//! Mirrors `affinidi-webvh-service`'s `did-hosting-control` dispatcher
//! (`routes/trust_tasks.rs`) — body shape, error envelope, and routing
//! semantics are byte-equivalent.
//!
//! ## Module layout
//!
//! - [`helpers`]: shared wire-shape helpers (`parse_payload`,
//!   `reject_with`, `success_response`, `app_error_to_reject`, etc.)
//!   used by every slice's handler module. `pub(super)` only.
//! - One module per Phase 3 slice (`auth`, `acl`, `contexts`, `keys`,
//!   `seeds`, `audit`, `discovery`, …). Each module's handler
//!   functions are `pub(super) async fn handle_<op>(state, auth, doc)
//!   -> Response`. The dispatcher's match arms call them.
//! - The cross-crate URI parity harness lives in the test module
//!   below; it asserts every URI declared in `vta-sdk::trust_tasks`
//!   is either dispatched or on the `REST_ROUTED` allowlist.
//!
//! ## Adding a new URI
//!
//! 1. Add the `TASK_*` const to `vta-sdk::trust_tasks` and extend its
//!    `ALL_URIS` array.
//! 2. Add a `handle_*` function in the appropriate slice module
//!    (create a new one if no slice fits).
//! 3. Add one line to the [`dispatch_table!`] invocation: `TASK_* =>
//!    slice::handle_*`. That single declaration generates **both** the
//!    `dispatch_typed` match arm **and** the parity-harness entry — they
//!    can't drift, so there is no separate test array to update.
//!
//! ## Body-parse failures emit framework-conformant errors
//!
//! Like the webvh-service dispatcher, we accept the body as
//! `axum::body::Bytes` and parse to `TrustTask<Value>` by hand so a
//! malformed body produces a `trust-task-error` document (per
//! framework SPEC §8.5) instead of axum's plain-text 400 default.

use axum::extract::State;
use axum::response::{IntoResponse, Response};
use serde_json::Value;
use trust_tasks_rs::TrustTask;

use crate::auth::AuthClaims;
use crate::error::AppError;
use crate::server::AppState;

mod acl;
mod app_state;
mod audit;
#[cfg(test)]
mod audit_coverage;
mod auth;
mod backup;
/// The ceremony-task predicate + the zero-authority claim an unenrolled
/// approver is dispatched under. Shared by the PDP gate and every
/// intrinsic-sender transport, so the two gates in front of a handler cannot
/// disagree about what a ceremony task is.
pub(crate) mod ceremony;
mod config;
#[cfg(test)]
mod conformance;
mod consent;
mod consent_request;
mod contexts;
mod cred_vault;
mod credential_exchange;
mod credentials;
mod device;
mod did_templates;
mod discovery;
mod helpers;
mod idempotency;
mod keys;
mod management;
mod memory;
mod messaging;
#[cfg(all(feature = "webvh", feature = "didcomm"))]
mod passkey_vms;
pub mod pending_replies;
mod persona;
pub(crate) mod planner;
mod policy;
mod policy_gate;
#[cfg(test)]
mod produced_census;
#[cfg(feature = "webvh")]
mod provision_integration;
mod room_group;
mod room_keys;
mod room_owner;
mod seeds;
// `operations::protocol` — every service operation these handlers call — is
// `#[cfg(feature = "webvh")]`, because advertising a transport means editing
// the agent's did:webvh document. Without webvh there is no document to edit,
// so the whole family goes with it.
#[cfg(feature = "webvh")]
mod services;
mod task_consent;
pub(crate) mod transport;
// The step-up *ceremony*: minting an approve-request and consuming the
// approve-response that elevates a session. What decides a ceremony is needed
// is [`policy_gate`] and nothing else — the `RequireStepUp` extractor and its
// per-route op markers are gone with the config floors they read.
pub(crate) mod step_up;
// The PDP gate, callable from the REST routes. In-handler by necessity: the
// consent digest and the planner both need the parsed payload, which an axum
// extractor does not have.
pub(crate) use policy_gate::rest_gate;
mod vault;
#[cfg(feature = "webvh")]
pub(crate) mod webvh;
pub(crate) mod wire_v0_2;

/// The transport-neutral dispatch result — see [`helpers::TrustTaskOutcome`].
/// Re-exported so both transports (`routes`-mounted REST handler + DIDComm
/// `messaging::handlers::handle_trust_task`) can name `crate::trust_tasks::
/// TrustTaskOutcome`.
pub(crate) use helpers::TrustTaskOutcome;
/// Only the TSP binding refuses a payload whose *carriage* is wrong while its
/// document would have parsed — so this is gated with its one consumer. Without
/// the gate the default build re-exports something nothing uses, which is a
/// `-D warnings` failure rather than a lint nobody sees.
#[cfg(feature = "tsp")]
pub(crate) use helpers::malformed_request_response;
use helpers::{body_parse_error_response, method_not_found, reject_with};
// Used unconditionally by the replay-dedup reject + `reject_trust_task`, not just
// the didcomm path — keep the import ungated (previously `#[cfg(feature =
// "didcomm")]`, which broke `--features rest` without `didcomm`).
use trust_tasks_rs::RejectReason;

/// URIs that the VTA exposes through dedicated unauth REST routes
/// rather than the authenticated `/api/trust-tasks` dispatcher.
///
/// The canonical list lives in the SDK
/// ([`vta_sdk::trust_tasks::REST_ROUTED_URIS`]) so the dispatcher's parity
/// harness and any generic client catalog (e.g. the `vta-mcp` `vta_call`
/// gateway, which advertises [`vta_sdk::trust_tasks::dispatch_routed_uris`])
/// can't drift. Handlers live in `routes::auth` (passkey login, legacy
/// challenge/authenticate/refresh) and `routes::attestation` (TEE status /
/// report).
#[allow(dead_code)] // consumed by the dispatcher's test-only parity harness
const REST_ROUTED: &[&str] = vta_sdk::trust_tasks::REST_ROUTED_URIS;

/// URIs that vta-sdk declares but the dispatcher may not wire in
/// every build because they depend on `vta-service` feature flags
/// (e.g. `webvh`, `didcomm`, `tee`).
///
/// When their feature is **on**, the [`dispatch_table!`] entry is compiled, so
/// `dispatched_uris()` lists them. When the feature is **off**, the entry's
/// `#[cfg(...)]` excludes it from both the match and the parity list — so only
/// this allowlist keeps the parity harness from failing on them.
///
/// Adding a URI here is a deliberate act: it says "this URI's
/// dispatch lives behind a feature flag and may be unreachable in
/// some builds, but the URI is canonically declared in vta-sdk."
///
/// All entries are unconditional (don't change per cfg). They're
/// just statements that the dispatcher knows about them.
#[allow(dead_code)]
// consumed by the dispatcher's test-only parity harness
// Names deprecated URIs on purpose: this VTA still serves them, and the census
// is what proves an entry has not outlived its handler.
#[allow(deprecated)]
const KNOWN_FEATURE_GATED_URIS: &[&str] = &[
    // Passkey-VMs slice — requires `webvh` + `didcomm` features. The
    // `dispatch_table!` entries list the same URIs and are tracked by the
    // parity harness when both features are on; this allowlist covers builds
    // where either feature is off.
    vta_sdk::trust_tasks::TASK_PASSKEY_VMS_ENROLL_CHALLENGE_0_1,
    vta_sdk::trust_tasks::TASK_PASSKEY_VMS_ENROLL_SUBMIT_0_1,
    vta_sdk::trust_tasks::TASK_PASSKEY_VMS_LIST_0_1,
    vta_sdk::trust_tasks::TASK_PASSKEY_VMS_REVOKE_0_1,
    // Provision-integration — requires `webvh`.
    vta_sdk::trust_tasks::TASK_PROVISION_INTEGRATION_0_3,
    // WebVH-DID-lifecycle slice — requires `webvh`. The `dispatch_table!`
    // entries list the same URIs and are tracked by the parity harness when
    // `webvh` is on; this allowlist covers builds where `webvh` is off.
    vta_sdk::trust_tasks::TASK_WEBVH_SERVERS_LIST_1_0,
    vta_sdk::trust_tasks::TASK_WEBVH_SERVERS_REGISTER_1_0,
    vta_sdk::trust_tasks::TASK_WEBVH_SERVERS_REMOVE_1_0,
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_LIST_1_0,
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_CREATE_1_0,
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_GET_1_0,
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_DELETE_1_0,
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_UPDATE_1_0,
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_ROTATE_KEYS_1_0,
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_REGISTER_WITH_SERVER_1_0,
    vta_sdk::trust_tasks::TASK_WEBVH_AGENT_NAME_LIST_1_0,
    vta_sdk::trust_tasks::TASK_WEBVH_AGENT_NAME_CHECK_1_0,
    vta_sdk::trust_tasks::TASK_WEBVH_AGENT_NAME_SET_1_0,
    vta_sdk::trust_tasks::TASK_WEBVH_AGENT_NAME_REMOVE_1_0,
    vta_sdk::trust_tasks::TASK_WEBVH_AGENT_NAME_DISABLE_1_0,
    vta_sdk::trust_tasks::TASK_WEBVH_AGENT_NAME_ENABLE_1_0,
    // did-management Trust-Task spec URIs — declared in vta-sdk by
    // PR #139 ("PR 1 of N") as the shared vocabulary for the
    // cross-repo did-management migration (vta-sdk + vta-service +
    // affinidi-webvh-service all reference these). They are
    // **outbound producer URIs** — VTA's `webvh_didcomm.rs` sends
    // requests with these URIs to did-hosting, then matches
    // `<uri>#response` on the way back. They are not consumed by any
    // vta-service inbound dispatcher arm, so the parity harness
    // treats them like the feature-gated URIs above (declared
    // canonically, intentionally not in `DISPATCHED_URIS`). Removing
    // an entry here without a corresponding dispatcher addition will
    // surface as a parity-harness failure pointing back at this list.
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DID_REGISTER_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DID_PUBLISH_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DID_DELETE_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DID_ENABLE_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DID_DISABLE_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DID_LIST_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DID_INFO_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DID_CHECK_NAME_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DID_CHANGE_OWNER_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DID_ROLLBACK_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DID_PROBLEM_REPORT_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DOMAIN_CREATE_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DOMAIN_UPDATE_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DOMAIN_DISABLE_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DOMAIN_PURGE_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DOMAIN_SET_DEFAULT_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DOMAIN_ASSIGN_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DOMAIN_UNASSIGN_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_SERVER_REGISTER_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_SERVER_HEALTH_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_SERVER_STATS_SYNC_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_REGISTRY_ADMIN_REGISTER_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_REGISTRY_DEREGISTER_0_1,
];

/// URIs this dispatcher serves that the published Trust-Tasks registry does
/// NOT yet spec — the implementation→registry drift tracked by issue #854.
///
/// The forward parity harness below asserts every vta-sdk URI is served; the
/// reverse harness (`every_served_uri_has_a_published_spec_or_is_tracked_debt`)
/// asserts every *served* URI resolves in the published registry, using the
/// generated `trust_tasks_rs::schema_index` as the registry's vendored index
/// (the same source `validate_payload` consults at dispatch time, and the same
/// one the workspace-wide census in `vtc-service/tests/trust_task_manifest.rs`
/// checks against — that census counts per *family*; this list is per *URI*,
/// scoped to what this dispatcher actually serves).
///
/// Every entry is acknowledged debt with a disposition recorded in
/// `docs/05-design-notes/registry-drift-triage.md` (and the programme doc
/// `canonical-task-reduction.md`). The harness enforces monotonicity in both
/// directions: serving a NEW unspecced URI fails (add the spec upstream — do
/// not grow this list), and once a spec is published upstream the entry MUST
/// be removed (a stale entry also fails).
///
/// Tracking issue: OpenVTC/verifiable-trust-infrastructure#854.
#[allow(dead_code)] // consumed by the dispatcher's test-only parity harness
const UNSPECCED_DISPATCHED_URIS: &[&str] = &[
    // ─ vta/seeds/* — keep-and-spec under `vta/` (reduction plan §E).
    "https://trusttasks.org/spec/vta/seeds/list/1.0",
    "https://trusttasks.org/spec/vta/seeds/rotate/1.0",
    // ─ vta/audit retention pair — candidate `audit/retention/{show,update}`.
    "https://trusttasks.org/spec/vta/audit/get-retention/1.0",
    "https://trusttasks.org/spec/vta/audit/update-retention/1.0",
    // (`vta/discovery/capabilities/1.0` was here until #1043 retired the task;
    // its debt is discharged by deletion rather than by a spec. The management
    // singleton and all five of `vta/backup/*` left in the same way this
    // comment describes for the vault credentials family: specced upstream at
    // trustoverip/dtgwg-trust-tasks-tf#347, shipped in trust-tasks-rs 0.17.7,
    // so they now carry schemas and are validated on the spine like anything
    // else. The reduction plan's §D suggestion of a top-level `backup/*` was
    // not taken — the family is agent lifecycle, and `vta/` is where the rest
    // of it lives.)
    // ─ vta/attestation/* (REST-routed, unauthenticated) — keep-and-spec.
    "https://trusttasks.org/spec/vta/attestation/status/1.0",
    "https://trusttasks.org/spec/vta/attestation/report/1.0",
    // ─ vta/webvh/** — two-ends-of-one-wire decision pending (plan §B).
    //   `dids/update` is published; the rest are not.
    // ─ Vault archival lifecycle (#540) — generalise with a store
    //   discriminator instead of publishing twelve (reduction plan §C).
    "https://trusttasks.org/spec/vault/archive/0.1",
    "https://trusttasks.org/spec/vault/unarchive/0.1",
    "https://trusttasks.org/spec/vault/restore/0.1",
    "https://trusttasks.org/spec/vault/purge/0.1",
    //   The eight `vault/credentials/*` entries that sat here are gone: the
    //   family was specified upstream (trust-tasks-tf#338) and shipped in
    //   trust-tasks-rs 0.17.4, so it has a published schema, a conformance
    //   witness, and payload validation on the dispatch spine. Debt discharged
    //   by specification rather than by deletion.
];

/// Declarative Trust-Task dispatch table.
///
/// Each entry is `URI(s) => slice::handler`. From one list the macro generates
/// **both** [`dispatch_typed`]'s `match` arms **and** (test-only) the
/// `dispatched_uris()` parity list — so a handler and its parity entry are the
/// same declaration and cannot drift. Adding a slice is one line.
///
/// Supported per entry:
/// - `#[cfg(...)]` attributes (feature-gated arms contribute to the parity
///   list only when their cfg is active — mirrors the prior per-slice consts;
///   the URI must also sit in [`KNOWN_FEATURE_GATED_URIS`] for builds with the
///   feature off);
/// - `A | B => handler` for dual-accepted URIs sharing one handler.
///
/// Every handler has the uniform `(&AppState, &AuthClaims, TrustTask<Value>)
/// -> Response` signature; the dispatcher spine ([`dispatch_trust_task_core`])
/// keeps `validate_basic` + the 0.2 down/up-convert.
macro_rules! dispatch_table {
    (
        $(
            $(#[$meta:meta])*
            $($uri:path)|+ => $handler:path
                [ $se:ident $disc:ident $acts:literal ]
        ),+ $(,)?
    ) => {
        /// Type-dispatch over the inbound document's `type` URI; generated by
        /// [`dispatch_table!`]. Unknown URIs fall through to `method_not_found`,
        /// which answers `unsupportedVersion` naming the versions this VTA does
        /// serve when it knows the family, and `unsupported_type` when it does
        /// not.
        ///
        /// `#[allow(deprecated)]`: arms match deprecated `*_0_1` URI constants
        /// on purpose — the VTA keeps serving 0.1 during the migration; 0.2
        /// counterparts arrive pre-down-converted (see `wire_v0_2`).
        #[allow(deprecated)]
        async fn dispatch_typed(
            state: &AppState,
            auth: &AuthClaims,
            doc: TrustTask<Value>,
        ) -> TrustTaskOutcome {
            let type_uri = doc.type_uri.to_string();
            match type_uri.as_str() {
                $(
                    $(#[$meta])*
                    // `Box::pin` is load-bearing, not a style choice. An async
                    // fn's future is sized to its largest live state, and a
                    // `match` future is sized to its largest arm — so awaiting
                    // every handler *inline* here would size this one future to
                    // the sum-shaped worst case of every task the VTA dispatches
                    // (the backup/webvh/services handlers are each large on their
                    // own). Debug builds do not elide that layout, so the first
                    // inbound Trust Task overflowed the worker-thread stack —
                    // which reads as, but is not, infinite recursion. Boxing
                    // heap-allocates each handler's future so this dispatch frame
                    // stays pointer-sized per arm. Do NOT "simplify" this away.
                    $($uri)|+ => Box::pin($handler(state, auth, doc)).await,
                )+
                // A client mistakenly sending a REST-routed URI through the
                // envelope path gets `unsupported_type` here — correct from the
                // dispatcher's POV; the operation lives elsewhere. A client on
                // the wrong *version* of a family this dispatcher does own gets
                // `unsupportedVersion` plus the served versions instead.
                _ => method_not_found(doc, &type_uri),
            }
        }

        /// The authoritative SPEC §7.3 side-effect + exposure class of a
        /// dispatched task, declared inline next to its handler in the
        /// `[ SideEffect Disclose actsAsSubject ]` clause. This — NOT the
        /// published registry — is what the Policy Decision Point feeds into
        /// `PolicyInput`, so registry control cannot lower the consent bar
        /// (SPEC §7.3 items 13–14). `None` for a URI the dispatcher does not
        /// own; callers apply the fail-safe floor (treat as at least
        /// `mutating` / secret-disclosing act-as-subject).
        ///
        /// Every dispatch entry MUST carry a class — the macro grammar makes
        /// omission a compile error, so a new handler cannot be added without
        /// a deliberate classification.
        #[allow(deprecated, dead_code)]
        pub(crate) fn class_for(type_uri: &str) -> Option<$crate::policy::TaskClass> {
            match type_uri {
                $(
                    $(#[$meta])*
                    $($uri)|+ => Some($crate::policy::TaskClass::new(
                        $crate::policy::SideEffectLevel::$se,
                        $crate::policy::Discloses::$disc,
                        $acts,
                    )),
                )+
                _ => None,
            }
        }

        /// URIs wired into [`dispatch_typed`], collected from the same
        /// declarations that generate the match arms. Feature-gated arms
        /// contribute only when their cfg is active.
        ///
        /// Available at runtime, not just under `cfg(test)`, because
        /// `trust-task-discovery/0.1` answers with exactly this set. Deriving
        /// the answer from the dispatch table is the whole point: a
        /// hand-maintained list of "what we support" is a second source of
        /// truth, and it goes stale the first time someone adds a handler
        /// without remembering it exists. A discovery response that overstates
        /// the server is worse than none — a client believes a task is
        /// available and finds out otherwise on a live call.
        #[allow(deprecated)]
        pub(crate) fn dispatched_uris() -> Vec<&'static str> {
            let mut v: Vec<&'static str> = Vec::new();
            $(
                $(#[$meta])*
                v.extend([$($uri),+]);
            )+
            v
        }
    };
}

/// `POST /api/trust-tasks` handler.
///
/// Bearer-auth'd via [`AuthClaims`]; the caller's DID is the
/// transport-authenticated peer for SPEC.md §4.8.1 precedence inside
/// each typed handler.
///
/// Body is accepted as raw bytes so a parse failure surfaces as a
/// `trust-task-error` document with `code: malformed_request`
/// rather than axum's text/plain default. The route mount caps body
/// size separately (the workspace-wide 1 MB cap applies).
pub async fn dispatch_trust_task(
    auth: AuthClaims,
    State(state): State<AppState>,
    body: axum::body::Bytes,
) -> Result<Response, AppError> {
    // REST is hop-by-hop by construction: TLS terminates at whatever the
    // operator put in front of this process, and the plaintext exists there.
    Ok(dispatch_trust_task_core(
        &state,
        &auth,
        &body,
        transport::TransportConfidentiality::HopByHop,
    )
    .await
    .into_response())
}

/// Transport-agnostic trust-task dispatch core.
///
/// Parses the envelope bytes and dispatches by `type` URI, returning a
/// typed [`TrustTaskOutcome`] — the framework result/error document bytes
/// plus the status code from the framework's status table. Shared by:
/// - the REST route [`dispatch_trust_task`], which renders it via
///   `IntoResponse`, and
/// - the DIDComm trust-task handler
///   (`crate::messaging::handlers::handle_trust_task`), which reads
///   `outcome.body` straight as the reply envelope — no round-trip through
///   an `axum::Response` to re-extract the JSON.
///
/// `body` is the full `TrustTask<Value>` envelope JSON — the HTTP POST
/// body on REST, the DIDComm message body on DIDComm.
/// Validate `doc.payload` against the published schema for its Type URI.
///
/// `Some(outcome)` rejects; `None` proceeds.
///
/// Ceremony tasks are exempt for the same reason the policy gate exempts them:
/// they are the mechanism, not the operation, and a `task-consent/decision` that
/// could not be delivered because its own payload failed a check would strand
/// every task waiting on it.
async fn validate_payload(
    state: &AppState,
    type_uri: &str,
    doc: &TrustTask<Value>,
) -> Option<TrustTaskOutcome> {
    let Some(schema) = trust_tasks_rs::schema_index::schema_for(type_uri) else {
        // No published spec for this task. Many of the tasks this VTA dispatches
        // are in that position, so refusing them outright would break them — but
        // the gap is real, and an operator may prefer to fail closed.
        if state.config.read().await.policy.require_payload_schema {
            return Some(helpers::reject_with(
                doc,
                RejectReason::MalformedRequest {
                    reason: format!(
                        "no payload schema is known for `{type_uri}`, and this VTA is configured \
                         to refuse tasks it cannot validate"
                    ),
                },
            ));
        }
        tracing::debug!(
            type_uri,
            "no payload schema known — dispatching unvalidated (set \
             policy.require_payload_schema to refuse instead)"
        );
        return None;
    };

    match trust_tasks_rs::validate::against_schema(schema, &doc.payload) {
        Ok(()) => None,
        Err(e) => {
            tracing::info!(type_uri, error = %e, "payload failed schema validation");
            Some(helpers::reject_with(
                doc,
                RejectReason::MalformedRequest {
                    reason: format!("payload does not conform to {type_uri}: {e}"),
                },
            ))
        }
    }
}

/// Attach this agent's Data-Integrity proof to a success response.
///
/// # Why this was missing
///
/// 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`, and this agent attached a proof to none of
/// their responses. Nothing went red because no consumer verifies one either;
/// producers not signing and consumers not checking is a mutually consistent
/// silence.
///
/// # Why the resident secret and not `load_vta_issuer_secret`
///
/// That helper reads the keystore, derives, and **writes an audit entry per
/// access**. Signing every response through it would turn the record of "the
/// agent's issuer key was used" into one line per request — drowning a security
/// control in its own noise, which is a worse outcome than the gap being fixed.
///
/// `secrets_resolver` already holds the signing secret for the messaging layer,
/// keyed by [`AppState::signing_vm_id`]. Reading it costs nothing and audits
/// nothing, which is the right shape for something that happens on every
/// answer: the agent signing its own words is not a key *access* worth a line,
/// it is the agent speaking.
///
/// # Scope
///
/// Success responses only. An error response's `type` resolves to the
/// framework's `trust-task-error` specification, whose requirement is
/// RECOMMENDED rather than REQUIRED and whose variant §7.3 makes undeclarable
/// by a task.
///
/// # Two failures that look alike and mean opposite things
///
/// **No signing identity configured at all** — an agent before setup. It
/// answers unsigned, because it has nothing to sign with and refusing would
/// make an unprovisioned VTA unusable rather than merely unattributable. That
/// is unchanged and deliberate.
///
/// **Configured to sign, and cannot** — a resident secret that is missing, or a
/// signature that fails to attach. This used to answer unsigned too, on the
/// reasoning that "the work is done and the caller is entitled to the result,
/// attributable or not". That reasoning had a premise: that nobody checked. It
/// stopped being true when the client began verifying replies
/// (OpenVTC/verifiable-trust-infrastructure#1341), and the two halves compose
/// badly — this agent logs an error and answers 200, the caller refuses the
/// reply, and the message the operator reads blames *the reply* for something
/// that is wrong with *this agent's key*. The caller is not entitled to a
/// result they will discard; they are entitled to know why.
///
/// So a misconfiguration is now an error naming itself. It is a 500 because it
/// is this agent's fault and retrying the same call will not fix it.
async fn sign_success_response(state: &AppState, outcome: TrustTaskOutcome) -> TrustTaskOutcome {
    if !outcome.status.is_success() {
        return outcome;
    }
    let (Some(resolver), Some(vm_id)) = (
        state.secrets_resolver.as_ref(),
        state.signing_vm_id.as_ref(),
    ) else {
        return outcome;
    };
    use affinidi_tdk::secrets_resolver::SecretsResolver as _;
    let Some(secret) = resolver.get_secret(vm_id).await else {
        tracing::error!(%vm_id, "no resident secret for the signing key");
        return cannot_sign(vm_id, "its signing key is not resident");
    };

    match attach_proof(&secret, &outcome.body).await {
        Some(body) => TrustTaskOutcome {
            status: outcome.status,
            body,
        },
        None => {
            tracing::error!(%vm_id, "the signature would not attach");
            cannot_sign(vm_id, "its signature would not attach")
        }
    }
}

/// The answer when this agent is configured to sign and cannot.
///
/// Names the verification method, because that is the thing an operator can go
/// and look at, and says the work was done — a caller that retries a mutating
/// call on this error would repeat it.
fn cannot_sign(vm_id: &str, why: &str) -> TrustTaskOutcome {
    let body = serde_json::json!({
        "type": "https://trusttasks.org/spec/trust-task-error/0.5",
        "payload": {
            "code": "internalError",
            "message": format!(
                "this agent completed the request and could not sign its answer, because {why}                  ({vm_id}). The work is done — do not retry a change on this error. An unsigned                  answer is bytes rather than evidence, so it is withheld rather than sent."
            ),
            "retryable": false,
        },
    });
    TrustTaskOutcome {
        status: axum::http::StatusCode::INTERNAL_SERVER_ERROR,
        body: serde_json::to_vec(&body).unwrap_or_else(|_| b"{}".to_vec()),
    }
}

/// Sign `body` with `secret` and return the document with its `proof` attached.
///
/// Separated from the state plumbing so the cryptographic path is testable
/// without an `AppState` — the wiring above needs a booted agent, this needs a
/// key and some bytes.
async fn attach_proof(
    secret: &affinidi_secrets_resolver::secrets::Secret,
    body: &[u8],
) -> Option<Vec<u8>> {
    let mut doc: serde_json::Value = match serde_json::from_slice(body) {
        Ok(d) => d,
        Err(e) => {
            // The spine built this a moment ago, so this cannot happen without a
            // bug above.
            tracing::error!(error = %e, "success response is not JSON; returning it unsigned");
            return None;
        }
    };
    if !attach_proof_in_place(secret, &mut doc).await {
        return None;
    }
    serde_json::to_vec(&doc)
        .inspect_err(|e| tracing::error!(error = %e, "could not serialise the signed response"))
        .ok()
}

/// [`attach_proof`] over a document already parsed, signing it in place.
///
/// Split out so a harness that *stands in* for this agent can sign a document
/// it holds as JSON, without a serialise-and-reparse round trip on both sides —
/// `test_support::sign_response_document` is the one caller, and it exists
/// because a stand-in that signs differently from the thing it stands in for
/// tests the difference rather than the contract.
///
/// `false` when the signature will not attach; the caller decides what an
/// unsigned answer means, because the two callers disagree — this agent
/// refuses to send one, a harness has nothing to refuse with.
pub(crate) async fn attach_proof_in_place(
    secret: &affinidi_secrets_resolver::secrets::Secret,
    doc: &mut serde_json::Value,
) -> bool {
    // A proof never covers itself.
    let Some(obj) = doc.as_object_mut() else {
        return false;
    };
    obj.remove("proof");

    let proof = match affinidi_data_integrity::DataIntegrityProof::sign(
        &*doc,
        secret,
        affinidi_data_integrity::SignOptions::new(),
    )
    .await
    {
        Ok(p) => p,
        Err(e) => {
            tracing::error!(error = %e, "could not sign the success response; answering unsigned");
            return false;
        }
    };
    let Ok(proof_value) = serde_json::to_value(&proof)
        .inspect_err(|e| tracing::error!(error = %e, "could not serialise the response proof"))
    else {
        return false;
    };
    match doc.as_object_mut() {
        Some(obj) => {
            obj.insert("proof".into(), proof_value);
            true
        }
        None => false,
    }
}

/// Accept an inbound document from a transport that proved its sender itself
/// (TSP, DIDComm) rather than by a bearer token.
///
/// # Why this exists, and why the transports no longer decide anything
///
/// Authorization used to happen in each transport, *before* the spine saw the
/// document. That defeated the ordering [`dispatch_trust_task_inner`]
/// documents and relies on — "a reply carries no authority and asks for
/// nothing" — because a reply was already refused at the door by the time the
/// spine could recognise it as one. Under DIDComm the transport's own `thid`
/// correlation hid it; under TSP, whose binding has no request/response of its
/// own, a DID hosting server's answer to a task the VTA had itself sent came
/// back and was ACL-refused as though it were unsolicited. From the outside
/// that reads as a missing ACL entry, and granting one would hand a peer
/// standing to send *requests* when all it ever needed was to answer.
///
/// So a transport now hands over two things — the document, and the VID it
/// proved — and makes no policy decision at all. The spine asks what the
/// document *is* ([`vta_sdk::inbound`]) and only then decides what may be done
/// with it:
///
/// - an **error** is terminal: logged with its reason and answered with
///   nothing, because answering an error is what turns one failure into an
///   exchange that ends only when a mediator starts rate-limiting;
/// - a **response** belongs to whoever is waiting for it, and is authorized by
///   the fact that we asked for it;
/// - only a **request** reaches the ACL.
///
/// Every intrinsic-sender transport gets that at once, which is the property a
/// per-transport copy kept failing to have.
///
/// Gated exactly as [`reject_trust_task`] and `crate::messaging` are, and for
/// the same reason: the only callers are the two transports that prove their
/// own sender. A `rest`-only build has neither, and an ungated function
/// referencing them does not compile there.
#[cfg(any(feature = "didcomm", feature = "tsp"))]
pub(crate) async fn accept_from_proven_sender(
    state: &AppState,
    sender_vid: &str,
    body: &[u8],
    confidentiality: transport::TransportConfidentiality,
) -> TrustTaskOutcome {
    use vta_sdk::inbound::{Inbound, classify};

    // Nothing goes back. Every transport already reads an empty body as "no
    // reply" — `handle_tsp` drops one rather than sealing it.
    let silent = || TrustTaskOutcome {
        status: axum::http::StatusCode::NO_CONTENT,
        body: Vec::new(),
    };

    // Classified off a bare `Value`: it reads two fields and must not depend on
    // the document deserialising into `TrustTask<Value>`. A malformed *request*
    // still has to reach the spine to be refused the usual way, so a parse
    // failure falls through to `Request` rather than becoming a kind of its own.
    let kind = match serde_json::from_slice::<Value>(body) {
        Ok(v) => classify(&v),
        Err(_) => Inbound::Request,
    };

    // Release a waiter, if this document answers something we sent. Parsed
    // separately from the classification above because `complete` needs the
    // typed document; a response too malformed to type is one nobody can be
    // waiting on anyway.
    let deliver = |state: &AppState, body: &[u8]| -> bool {
        serde_json::from_slice::<TrustTask<Value>>(body)
            .map(|d| state.pending_replies.complete(&d))
            .unwrap_or(false)
    };

    match kind {
        Inbound::Error => {
            // The reason, not just the fact. A peer's error is often the only
            // account of what went wrong anywhere in the exchange, and dropping
            // it silently is how a live failure stayed undiagnosable for an
            // hour.
            let reason = serde_json::from_slice::<Value>(body)
                .ok()
                .and_then(|v| {
                    let p = v.get("payload")?;
                    let code = p.get("code").and_then(Value::as_str).unwrap_or("?");
                    let message = p.get("message").and_then(Value::as_str).unwrap_or("");
                    Some(format!("{code}: {message}"))
                })
                .unwrap_or_else(|| "<unreadable payload>".to_string());
            tracing::warn!(
                sender = %sender_vid,
                %reason,
                "inbound trust-task error from a peer — terminal, not answered"
            );
            // A failed request should fail now rather than sit out its timeout.
            deliver(state, body);
            silent()
        }
        // Threaded, so it *may* answer something we sent — but threading alone
        // does not make it a reply. A step-up `approve-response` and a
        // `task-consent/decision` both thread to the request that provoked them
        // and are nonetheless requests: they carry the approval, and dropping
        // them would strand every ceremony waiting on a human. So the waiter
        // decides. If one is holding this thread the document is its answer and
        // goes no further; if not, it is an ordinary request and falls through.
        Inbound::Response if deliver(state, body) => {
            tracing::debug!(sender = %sender_vid, "inbound response delivered to a waiting request");
            silent()
        }
        Inbound::Response | Inbound::Request => {
            match crate::messaging::auth::auth_for_trust_task_envelope(state, sender_vid, body)
                .await
            {
                Ok(auth) => dispatch_trust_task_core(state, &auth, body, confidentiality).await,
                Err(e) => reject_trust_task(
                    body,
                    trust_tasks_rs::RejectReason::PermissionDenied {
                        reason: e.to_string(),
                    },
                ),
            }
        }
    }
}
pub(crate) async fn dispatch_trust_task_core(
    state: &AppState,
    auth: &AuthClaims,
    body: &[u8],
    confidentiality: transport::TransportConfidentiality,
) -> TrustTaskOutcome {
    let outcome = transport::with_confidentiality(confidentiality, async move {
        dispatch_trust_task_inner(state, auth, body).await
    })
    .await;
    // Before the conformance observation below, so what that layer sees is what
    // ships rather than a document one proof short of it.
    let outcome = sign_success_response(state, outcome).await;
    // Observe the real response against the schema its own `type` names. Here
    // rather than in the REST route because REST is one of three transports
    // through this function — DIDComm and TSP read `outcome.body` directly, and
    // an HTTP-layer check would be blind to both. Compiled out of production
    // builds; see `test_support::response_conformance`.
    #[cfg(any(test, feature = "test-support"))]
    let outcome =
        match crate::test_support::response_conformance::observe(outcome.status, &outcome.body) {
            Some(body) => TrustTaskOutcome {
                status: axum::http::StatusCode::INTERNAL_SERVER_ERROR,
                body,
            },
            None => outcome,
        };
    outcome
}

/// The dispatch spine proper. Split from [`dispatch_trust_task_core`] only so
/// the transport scope wraps every path out of it, including the early
/// rejections — a handler that reads the transport must never see a scope that
/// was skipped because the envelope failed validation first.
///
/// This layer parses the envelope and attaches the superseded-task signal; the
/// checks and dispatch are in [`dispatch_trust_task_validated`], for the same
/// wrap-every-exit reason.
async fn dispatch_trust_task_inner(
    state: &AppState,
    auth: &AuthClaims,
    body: &[u8],
) -> TrustTaskOutcome {
    // 1. Parse the envelope.
    let doc: TrustTask<Value> = match serde_json::from_slice(body) {
        Ok(d) => d,
        // No `type` to attribute the request to, so nothing to count and no
        // successor to name. The one exit that legitimately carries no
        // deprecation signal.
        Err(e) => return body_parse_error_response(&e.to_string()),
    };

    // 2. Is this an answer rather than a question?
    //
    // A document that threads to a request this agent sent belongs to whoever
    // is waiting for it, not to the dispatcher. Checked here, before any
    // authorization or dispatch, because that is what it is: a reply carries no
    // authority and asks for nothing, and running it through the request
    // pipeline would at best refuse it and at worst execute it.
    //
    // Here rather than in a transport for two reasons. It is a fact about the
    // *document* (`threadId`, SPEC §4.9), and this is the one place documents
    // are read. And every transport gets it at once — TSP is what needs it,
    // because its binding has no request/response of its own, but nothing about
    // this is TSP-specific.
    //
    // An empty body is the "nothing goes back" signal the transports already
    // understand: `handle_tsp` drops an empty reply rather than sealing one.
    if state.pending_replies.complete(&doc) {
        tracing::debug!(
            thread_id = ?doc.thread_id,
            "inbound document delivered to a waiting request"
        );
        return TrustTaskOutcome {
            status: axum::http::StatusCode::NO_CONTENT,
            body: Vec::new(),
        };
    }

    // Superseded-task signalling wraps everything below, for the same reason
    // `mark_superseded` is a layer rather than a call inside each of the 56
    // REST handlers: [`dispatch_trust_task_validated`] has a dozen early
    // returns — expiry, wrong recipient, replay, schema validation, the policy
    // gate — and a signal applied at only some of them is worse than none.
    // Removal is gated on this counter reading zero; a URI that goes quiet
    // because its callers are all being rejected before the hook would read as
    // "nobody sends this any more" and be deleted out from under them.
    //
    // Read from the URI as it *arrived*, before the 0.2 down-convert rewrites
    // `doc.type_uri`: what is being measured is what the client sent, and
    // reading it after the rewrite would count every 0.2 caller as a 0.1 one
    // and hold the metric off zero permanently.
    let superseded = crate::deprecation::superseded_task(&doc.type_uri.to_string());

    // `Box::pin` rather than a bare `.await`: the callee's state machine
    // inlines every handler's future through `dispatch_typed`, so awaiting it
    // by value would nest that whole thing inside this frame as well. It does
    // not fit — a debug build of `--workspace` (where feature unification turns
    // on `tee` and the rest) overflowed the test-thread stack in
    // `tests/mock_vta.rs` the moment this split was introduced. Boxing puts the
    // large half on the heap and leaves a pointer here.
    // Audit context, captured before `doc` moves into dispatch.
    //
    // **This lives here, not in the callee, and that is the entire point.**
    // It used to sit inside `dispatch_trust_task_validated`, a few lines above
    // that function's `return outcome` — which meant it recorded the outcomes
    // that reached the bottom of the function and none of the ones that did
    // not. The comment two blocks up already names the problem from the
    // deprecation hook's side: that function "has a dozen early returns —
    // expiry, wrong recipient, replay, schema validation, the policy gate".
    // Every one of them skipped the audit.
    //
    // So the blanket vault audit's own doc-comment — "read or write, success
    // or denied — produces exactly one persisted audit row" — was true only of
    // denials the *handler* raised. A document refused at the envelope gate
    // left nothing at all, for any task in any family. That is the refusal an
    // incident review most wants: not "the handler said no", but "something
    // arrived claiming to be this, signed like this, and never got that far".
    //
    // Hoisting it one frame makes coverage structural rather than a property
    // of where the returns happen to be. A fourteenth early return added
    // tomorrow inherits it, which is the only version of this that stays true.
    let dispatch_audit = DispatchAudit::capture(&doc);

    let mut outcome = Box::pin(dispatch_trust_task_validated(state, auth, doc)).await;

    dispatch_audit.record(state, &auth.did, &outcome).await;

    if let Some(task) = superseded {
        // Whatever the outcome. A superseded task that was *rejected* is still
        // a client sending a URI we want to stop serving, and a client about to
        // retry is the one most in need of knowing what to retry onto.
        crate::deprecation::note_superseded_task(task);
        crate::deprecation::annotate_superseded(&mut outcome.body, task);
    }

    outcome
}

/// Everything after the envelope parses: framework checks, replay, schema
/// validation, idempotency, the policy gate, and typed dispatch.
///
/// Split from [`dispatch_trust_task_inner`] so the deprecation signal there
/// wraps every exit path out of this function, not just the last one.
/// How this consumer's transports map onto the Framework 0.5.0 document
/// lifecycle.
///
/// 0.5.0 adds a normative state table — `received` → `validated` → `accepted` →
/// {`executing`, `suspended`} → {`responded`, `errored`, `cancelled`,
/// `expired`} — and requires that **a transport binding map it onto its own
/// protocol**. The upstream work does that for the five published binding
/// crates; it does not reach here, because this workspace uses exactly one item
/// from them (`trust_tasks_https::status_for_code`) and dispatches through its
/// own spine. So the mapping is written down here, against the code that
/// actually implements it.
///
/// All three transports converge on [`dispatch_trust_task_core`], so the
/// state machine is **one** implementation with three renderings:
///
/// | state | where it happens | what the producer sees |
/// |---|---|---|
/// | `received` | the transport hands bytes to the spine | nothing |
/// | `validated` | `validate_freshness` → `validate_basic` → payload schema | nothing, or a `trust-task-error` |
/// | `accepted` | the `ReplayGuard` claim succeeds (`Fresh`) | nothing |
/// | `executing` | the handler runs | nothing |
/// | `responded` | `success_response` | `<type>#response` |
/// | `errored` | `reject_with` | `trust-task-error` |
/// | `expired` | `validate_freshness` / `validate_basic` refuse | `trust-task-error`, code `expired` |
///
/// Two states this service does not implement, named so their absence is a
/// decision rather than an oversight:
///
/// - **`suspended`** — there is no `trust-task-control` surface here, so no
///   document can suspend one in flight. A task runs to a terminal state or
///   fails.
/// - **`cancelled`** — nothing stops a task on the consumer's own initiative
///   once accepted. The nearest thing is a policy refusal, which happens
///   *before* acceptance and is therefore `errored`, not `cancelled`.
///
/// # Silence signifies no state
///
/// 0.5.0 settles four contradictory readings of an absent reply on one rule:
/// **the absence of a reply distinguishes no two states**, and a producer
/// **MUST NOT** infer any state from it.
///
/// This service has one place where silence is emitted deliberately, and it is
/// conformant: a duplicate whose first execution recorded no response is
/// answered with `204` ([`dispatch_trust_task_validated`]). That is the
/// fire-and-forget disposition of §7.2, not a claim about state — and the
/// in-flight case is `202` precisely so the two are not conflated.
///
/// The producer-side rule binds the **SDK**, not the spine: a client must not
/// read a timeout as failure and reissue a consequential task. That is what
/// `VtaClient::idempotent` and the delivery layer are for, and it is why
/// `receive_next` returns `Ok(None)` on timeout — "nothing arrived", not
/// "nothing happened".
mod lifecycle_mapping {}

/// How this consumer bounds a Trust Task document in time, and therefore how
/// long its duplicate-execution record must be kept.
///
/// The two are **one** decision, which is why `trust_tasks_rs` passes them as a
/// single `ConsumeChecks` argument and why `retain_until` is derived from this
/// rather than from a TTL of its own. SPEC §7.2 (*Bounding the record*) makes
/// the acceptance window and the record's retention the same bound: a consumer
/// "**MUST NOT** accept for execution a document older than the window over
/// which it retains records".
///
/// # Why a window at all
///
/// #1126 shipped this without one, leaving the record bounded by
/// [`InMemoryReplayGuard`]'s capacity. That is not "no expiry so entries live
/// forever" — it is LRU, which makes the window **load-dependent**: quiet
/// service, effectively unbounded protection; busy service, an eviction horizon
/// that can fall *below* any sensible acceptance window, so a replay arriving
/// after its `id` was evicted executes a second time. The defence was weakest
/// exactly when the service was busiest, which is the wrong way round and is
/// what this closes.
///
/// # Why ten minutes
///
/// The library's `DEFAULT_MAX_AGE` is five, "long enough to survive a mediator
/// queue, a retry with backoff, and a modest clock disagreement". This service
/// routes over a mediator that can hold a message while a recipient reconnects,
/// so it takes double that — the same 600s the retired
/// `replay::check_and_record` used as its dedup TTL, now bounding acceptance as
/// well as retention so the two cannot drift apart.
///
/// A deployment whose transport buffers for longer must widen this **and** the
/// guard's retention together; §7.2 makes them one bound, and widening either
/// alone reintroduces exactly the gap above.
///
/// # Why `issuedAt` is required
///
/// A window alone does not make every accepted document boundable, and the two
/// gaps it leaves both land on the producer as an answer it cannot act on.
///
/// **A document carrying neither timestamp is answered `expired`.** Under a
/// bare `with_max_age`, `validate_freshness` refuses it as
/// `Stale { detail: Unboundable }`, which the library maps to the wire code
/// `expired` because §8.3 defines no narrower one. But that check runs here,
/// at the top of [`dispatch_trust_task_validated`] — some 250 lines before
/// `schema_index::spec_policy_for(..).enforce(..)`, which for the 105 of 209
/// indexed specs that declare `IS_ISSUED_AT_REQUIRED` would have answered
/// `malformedRequest` naming `ISSUED_AT_REQUIRED_BY_SPEC`. The spec's own rule
/// — the one that names the missing member — was unreachable for every one of
/// them. `expired` names a document that was once acceptable and tells the
/// producer to wait; this one was never acceptable, and waiting then reissuing
/// the same shape loops. The crate says the same on `IS_ISSUED_AT_REQUIRED`:
/// `expired` "would misdescribe a document that was never acceptable". It is
/// the principle `a_future_dated_document_is_malformed_not_expired` pins.
///
/// **A document carrying only `expiresAt` has no bounded acceptance window.**
/// `validate_freshness` accepts it — an `expiresAt` does bound the record —
/// but the bound is then whatever instant the *producer* chose. `expiresAt =
/// now + 10 years` is accepted for ten years, and §7.2 makes the replay
/// record's retention that same bound, so the producer would unilaterally
/// decide how long this consumer must remember its `id`. Requiring `issuedAt`
/// makes the last instant any accepted document can return provable —
/// `issuedAt + max_age + skew` — which is what [`retain_until`] then caps on.
///
/// # What this refuses that a conforming producer may send
///
/// This is a **consumer posture, stricter than most specs**, and it is worth
/// being exact about the cost. 104 of the 209 URIs `spec_policy_for` answers
/// for — the read-shaped ones: `acl/list`, `auth/whoami`, `config/show`,
/// `device/heartbeat` — leave `issuedAt` OPTIONAL, so a producer of one may
/// legitimately omit it.
///
/// For all but one shape that costs nothing, because the refusal already
/// happens: a document with neither timestamp is refused today as `expired`,
/// and this only changes the code to one the producer can act on. The single
/// shape that moves from accepted to refused is **`expiresAt` present,
/// `issuedAt` absent** — refused now because its acceptance window, and
/// therefore this VTA's retention obligation, would be the producer's to set.
///
/// That is the posture `FreshnessPolicy::consequential` describes, at this
/// service's window. The crate scopes it to "any specification whose execution
/// is consequential, which is exactly the set for which item 11 applies" — and
/// this spine applies item 11 to **every** document it dispatches, `whoami`
/// included, so the qualifying set here is all of them.
fn freshness_policy() -> trust_tasks_rs::FreshnessPolicy {
    trust_tasks_rs::FreshnessPolicy::default()
        .with_max_age(chrono::TimeDelta::minutes(10))
        .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 [`REPLAY_GUARD`] for ten years — an entry held long past the
/// last moment it could be needed, crowding out the records that are, and
/// re-introducing the load-dependent eviction horizon [`freshness_policy`]
/// exists to close.
///
/// `require_issued_at` above makes the cap provable: `validate_freshness` has
/// already refused any document without an `issuedAt`, and will refuse this
/// one once `issuedAt + max_age + skew` has passed. Retention beyond that
/// instant is retention the guard can never draw on.
///
/// 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),
    }
}

/// The duplicate-execution record of SPEC §7.2 item 11.
///
/// In-memory and process-local, which is what the retired module was too.
/// Cross-restart replay is not the threat model: a document old enough to
/// outlive a restart is refused by the freshness bound above, and the two
/// bounds are the same bound.
static REPLAY_GUARD: std::sync::LazyLock<trust_tasks_rs::InMemoryReplayGuard> =
    std::sync::LazyLock::new(trust_tasks_rs::InMemoryReplayGuard::default);

async fn dispatch_trust_task_validated(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    // 2. Framework §7.2 items 4 + 5 — expiry + recipient
    //    enforcement. Closes L5 from the May 2026 security
    //    review: the hand-rolled dispatcher previously skipped
    //    these, so a Trust-Task envelope addressed at a
    //    different recipient would be silently accepted and an
    //    expired envelope would be honoured.
    //
    //    Audience binding (proof + recipient required for non-
    //    bearer specs, framework §7.2 item 8) is typed —
    //    `enforce_audience_binding` needs `P: Payload`, so each
    //    slice's typed handler runs it after `parse_payload`.
    // One instant for every temporal decision in this dispatch: the freshness
    // bound and the replay record's retention are the same bound (SPEC §7.2),
    // so reading the clock twice could place them on opposite sides of it.
    let now = chrono::Utc::now();
    {
        // SPEC §4.2 / §7.2 item 4 + Framework 0.5.0 Consumer Requirements item
        // 13. Checked before `validate_basic` 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* member
        // reads.
        //
        // This was a hand-rolled `check_freshness_bounds` between #1117 and
        // this change, because `trust-tasks-rs` 0.12 — which ships the real
        // thing — was blocked on an external crate. It is the library's now.
        if let Err(reason) = doc.validate_freshness(now, &freshness_policy()) {
            return reject_with(&doc, reason);
        }
        let vta_did = state.config.read().await.vta_did.clone();
        if let Some(my_vid) = vta_did.as_deref()
            && let Err(reason) = doc.validate_basic(now, my_vid)
        {
            return reject_with(&doc, reason);
        }
        // No vta_did configured → service is in setup; skip
        // the recipient check (no identity to bind against).
        // Production VTAs always have vta_did set by `vta setup`.
    }

    // 2b. SPEC §7.2 item 11 — the duplicate-execution record.
    //
    // Replaces this service's own `replay::check_and_record`, which keyed on
    // `(actor, id)` and kept no digest. Two consequences of that, both closed
    // here:
    //
    // - **`idConflict` was never produced.** Item 11 requires that a
    //   *different* document arriving under an already-accepted `id` be
    //   rejected, and requires it not be treated as a retry of the original.
    //   Without a digest the two are indistinguishable, so a different document
    //   was silently absorbed as a duplicate — the one outcome §8.4 and §7.2
    //   both rule out.
    // - **The key was wrong.** §7.2 (*Keying and comparison*) fixes the key as
    //   the document `id` alone; scoping it by actor let two callers each spend
    //   the same id.
    //
    // Record-before-dispatch is preserved: the claim happens before the handler
    // runs, so a crash between claiming and the effect landing leaves a retry
    // refused rather than double-applied — the safe direction for a mutating
    // task.
    // Kept because `doc` is moved into dispatch below, and closing out the
    // claim afterwards needs the key it was taken under.
    let doc_id = doc.id.clone();
    let digest = match trust_tasks_rs::document_digest(&doc) {
        Ok(d) => d,
        Err(e) => {
            return reject_with(
                &doc,
                RejectReason::InternalError {
                    reason: format!(
                        "cannot canonicalise the document to key its replay record: {e}"
                    ),
                },
            );
        }
    };
    let retain_until = retain_until(&doc, now);
    match trust_tasks_rs::ReplayGuard::claim(&*REPLAY_GUARD, &doc.id, &digest, retain_until, now)
        .await
    {
        Ok(trust_tasks_rs::ReplayVerdict::Fresh) => {}
        Ok(trust_tasks_rs::ReplayVerdict::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." This service used to answer one with exactly that.
            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}"),
                        },
                    ),
                },
                // Nothing recorded, and the two reasons need different
                // answers — which is why the verdict carries `in_flight`.
                None if in_flight => TrustTaskOutcome {
                    // §7.2: "Where the original execution is still in progress,
                    // the consumer SHOULD return or expose the existing
                    // execution state rather than begin another." `202` is the
                    // only honest code: `200` claims a result that does not
                    // exist yet, `409` a conflict that does not exist (it is
                    // the same document), and any error code reports a failure
                    // §7.2 forbids reporting for a duplicate.
                    status: axum::http::StatusCode::ACCEPTED,
                    body: Vec::new(),
                },
                // Fire-and-forget: the specification defines no success
                // response, so silence is the correct disposition. Never
                // `taskFailed` — the task did not fail, it already happened.
                None => TrustTaskOutcome {
                    status: axum::http::StatusCode::NO_CONTENT,
                    body: Vec::new(),
                },
            };
        }
        Ok(trust_tasks_rs::ReplayVerdict::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: the
        // producer should resend the identical document rather than treat this
        // as a permanent refusal.
        Err(e) => {
            return reject_with(
                &doc,
                RejectReason::Unavailable {
                    // No `retryAfter`: the guard is in-process, so there is no
                    // outage window to quote. The code alone already says
                    // "retryable", and inventing a deadline would be a guess
                    // the producer would act on.
                    retry_after: {
                        tracing::error!(error = %e, id = %doc.id, "replay guard unavailable");
                        None
                    },
                },
            );
        }
        // `ReplayVerdict` is `#[non_exhaustive]`. A verdict this build does not
        // know is refused rather than executed: every variant the enum has
        // gained so far is a reason *not* to run the task, and guessing the
        // permissive way on an unknown one is how a duplicate-execution defence
        // stops defending.
        Ok(other) => {
            return reject_with(
                &doc,
                RejectReason::Unavailable {
                    retry_after: {
                        tracing::error!(
                            verdict = ?other,
                            id = %doc.id,
                            "replay guard returned a verdict this build does not know",
                        );
                        None
                    },
                },
            );
        }
    }

    // 3. Session-pubkey binding pre-check.
    //
    // Once `AuthClaims` carries `session_pubkey_b58btc` (Phase 3 work,
    // mirrors `webvh-service`'s pattern) the dispatcher will enforce
    // that the proof's `verificationMethod` matches the JWT-bound
    // pubkey before any handler runs. Phase 2 scaffold elides this —
    // no passkey-bound sessions exist yet on the VTA side.
    let _ = auth;

    // 4. Dispatch by type URI.
    //
    // 0.2 dual-accept: bearer-authed specs whose only 0.1→0.2 delta is
    // enum-value casing are down-converted to their canonical 0.1 form,
    // dispatched through the existing 0.1 handler, and the response
    // up-converted back to 0.2 (see `wire_v0_2`). Signed-payload specs are NOT
    // routed here — they have typed 0.2 arms in `dispatch_typed`.
    // The negotiated wire version is scoped around `dispatch_typed` via a
    // `task_local` so the two JWE-sealing handlers (`vault/release`,
    // `vault/proxy-login`) can serialise the *sealed* cleartext in the right
    // casing — the edge transform can't reach inside ciphertext. Every other
    // handler ignores it.
    use wire_v0_2::{WIRE_VERSION, WireVersion};
    let type_uri = doc.type_uri.to_string();

    // Name every inbound trust task at the one point all three transports (TSP,
    // DIDComm, REST) converge, after the envelope parses. Without this the
    // per-transport dispatch logs report only sender + status, so you cannot
    // tell a `dids/update` submit from a `task-consent/decision` — which made a
    // consent loop (requester re-submits pile up, the approver's decision never
    // arrives) impossible to distinguish from the log alone.
    tracing::info!(
        type_uri = %type_uri,
        actor = %auth.did,
        id = %doc.id,
        "trust-task received"
    );

    // Payload schema validation — before the policy gate, and deliberately not
    // behind `policy.enforcement`.
    //
    // This is not a policy decision. It is the question of whether the document
    // means what its sender thinks it means, and it has to be answered before
    // anything else reads the payload: before the class is derived from it, before
    // a policy is evaluated on it, before a handler is dry-run against it to tell
    // a human what it will do.
    //
    // The bug that put this here: a caller sent `expectedVersionId` — the
    // optimistic-concurrency precondition — and the handler's type expected
    // `expected_version_id`. Serde matched no field, nothing rejected the unknown
    // member, and the precondition simply never applied. Updates published with no
    // lost-update protection while the caller's own source read as though the
    // danger were handled. The member was not *wrong*; it was **unrecognised**,
    // and nothing was watching for that.
    //
    // A silently-ignored member is worse than a rejected one. A rejected one you
    // find out about.
    if let Some(reject) = validate_payload(state, &type_uri, &doc).await {
        return reject;
    }

    // SPEC §7.2's *flag-driven* checks — the ones a specification declares
    // rather than a consumer chooses:
    //
    // * item 5b  — `recipient` REQUIRED
    // * item 7a  — `proof` REQUIRED
    // * item 8   — audience binding (proof present, no in-band recipient, on a
    //              non-bearer spec)
    // * §7.3 17  — `issuedAt` REQUIRED for a consequential task
    //
    // None of these were enforced. `enforce_spec_policy` reads them off the
    // typed payload's codegen-emitted constants, and this spine holds a
    // `TrustTask<Value>` — so the check sat behind a `P` nothing here has. The
    // comment further up still claimed "each slice's typed handler runs it
    // after `parse_payload`"; no handler did, and that comment was the only
    // occurrence of the name in this repo.
    //
    // `spec_policy_for` (trust-tasks-rs 0.17.1, trustoverip/dtgwg-trust-tasks-tf#321)
    // keys the same constants by URI, which is what a URI-dispatching consumer
    // can actually use. `SpecPolicy::enforce` is the same code path the typed
    // method takes, so the two cannot drift as new flag-driven rules land.
    //
    // Runs after schema validation, for the same reason schema validation runs
    // before the policy gate: a document that is not the shape it claims should
    // be refused for *that*, with the schema's own message, rather than for a
    // missing member the reader would then have to interpret.
    //
    // `None` means this build knows no spec for the URI — the unspecced-task
    // case `validate_payload` has already decided about, per
    // `policy.require_payload_schema`. Deciding it a second time here, with a
    // different default, would make one of the two answers unreachable.
    if let Some(policy) = trust_tasks_rs::schema_index::spec_policy_for(&type_uri)
        && let Err(reason) = policy.enforce(&doc)
    {
        tracing::info!(
            type_uri,
            ?reason,
            "document refused by its specification's policy"
        );
        return reject_with(&doc, reason);
    }

    // SPEC §7.2 item 7, *first* clause: "If the document carries a `proof`
    // member, verify it per §4.7 against the in-band `issuer` and reject the
    // document with `proofInvalid` on verification failure."
    //
    // The second clause — reject a *missing* proof where the spec requires one
    // — is `enforce_spec_policy` above. Only that half was implemented, which
    // is the worse way round to have it: a caller attaches a proof *because*
    // the task demands one, and until now any bytes in the member satisfied the
    // demand. A document signed by a key its issuer does not control reached
    // the handler.
    //
    // Verified here rather than per-handler for the reason the schema check is:
    // it must happen before anything reads the payload, and a slice that forgets
    // it is a slice with no proof checking at all. `step_up` and `task_consent`
    // keep their own calls — they bind the signer to a *specific* party (the
    // approver), which is a stronger claim than "the issuer signed this".
    if doc.proof.is_some() {
        match vti_common::auth::verify_trust_task_proof_with(&doc, &state.trust_task_vm_resolver())
            .await
        {
            Ok(signer) => {
                // A valid proof by some *other* DID is not a proof by the
                // issuer; without this the signature would establish only that
                // somebody signed something.
                if doc.issuer.as_deref() != Some(signer.as_str()) {
                    tracing::warn!(
                        type_uri,
                        issuer = ?doc.issuer,
                        signer = %signer,
                        "document proof verifies, but not as its issuer"
                    );
                    return reject_with(
                        &doc,
                        RejectReason::ProofInvalid {
                            reason: "the proof verifies as a DID other than the document's issuer"
                                .to_string(),
                        },
                    );
                }
            }
            Err(e) => {
                tracing::info!(type_uri, error = %e, "document proof failed verification");
                return reject_with(
                    &doc,
                    RejectReason::ProofInvalid {
                        reason: e.to_string(),
                    },
                );
            }
        }
    }

    // Idempotency claim. Only bites when the document carries an
    // `idempotencyKey` *and* the task is one where a second execution leaves a
    // second durable artefact (`vta_sdk::retry_safety`) — everything else
    // returns `Skip` and dispatches exactly as before.
    //
    // Placed after payload validation so a malformed request never consumes a
    // key, and before the policy gate so a *denied* request releases its claim
    // through the same `record_outcome` path every other failure takes. The
    // claim is written before the handler runs, which is what makes two
    // concurrent attempts safe: `insert_if_absent` is atomic, so one proceeds
    // and the other is told to wait rather than both passing a check.
    //
    // This is the layer `replay` (2b above) cannot be. That one keys on the
    // envelope id and so only catches a byte-identical resubmission; every SDK
    // path mints a fresh `urn:uuid:` per attempt, so a genuine retry sails past
    // it. The key here is stable across attempts of the same logical operation.
    let idem_claim = match idempotency::claim(&state.idempotency_ks, &auth.did, &doc).await {
        idempotency::Claim::Answer(outcome) => return *outcome,
        idempotency::Claim::Proceed { key, safety } => Some((key, safety)),
        idempotency::Claim::Skip => None,
    };

    // Policy Decision Point gate — evaluated before dispatch. A no-op unless
    // `config.policy.enforcement` is on; when a policy denies (or demands
    // step-up/consent), the task is rejected here and never reaches its handler.
    // A rejected task still flows through the audit tail below.
    // Filled by the gate only when a consumed consent grant *delegated* authority
    // the requester's own token lacked. When non-empty, this dispatch — and only
    // this dispatch — runs under the requester's identity widened to full admin
    // over the delegated context (`with_delegated_authority`), because the grant
    // authorizes the exact bound task in full. This is what lets a purely
    // unprivileged requester execute a task an approver blessed; the widening is
    // never written back to the session.
    let mut delegated_contexts: Vec<String> = Vec::new();
    let outcome =
        match policy_gate::policy_gate(state, auth, &type_uri, &doc, &mut delegated_contexts).await
        {
            Some(reject_outcome) => reject_outcome,
            None => {
                let delegated_auth = (!delegated_contexts.is_empty())
                    .then(|| auth.with_delegated_authority(&delegated_contexts));
                let auth = delegated_auth.as_ref().unwrap_or(auth);
                if let Some(spec) = wire_v0_2::lookup_0_2(&type_uri) {
                    let mut doc = doc;
                    wire_v0_2::downconvert_request(&mut doc.payload, spec);
                    if let Ok(uri_0_1) = spec.uri_0_1.parse() {
                        doc.type_uri = uri_0_1;
                    }
                    let outcome = WIRE_VERSION
                        .scope(WireVersion::V0_2, dispatch_typed(state, auth, doc))
                        .await;
                    wire_v0_2::upconvert_response(outcome, spec, &type_uri)
                } else {
                    WIRE_VERSION
                        .scope(WireVersion::V0_1, dispatch_typed(state, auth, doc))
                        .await
                }
            }
        };

    // Record what happened, so a retry carrying the same key converges on it.
    // A failed outcome *releases* the claim instead of recording it — the
    // effect this exists to deduplicate never happened, so the retry should be
    // allowed to actually run.
    if let Some((key, safety)) = idem_claim {
        idempotency::record_outcome(&state.idempotency_ks, &auth.did, &key, safety, &outcome).await;
    }

    // Close out the §7.2 item 11 claim taken at 2b. The same two dispositions
    // as the idempotency layer above, for the same reason:
    //
    // - **Succeeded** → record the response, so a §8.4 retry is *answered with
    //   the result* rather than absorbed in silence. Without this the guard
    //   still prevents the second execution, but every legitimate retry gets
    //   nothing back, which is the outcome §7.2 (*Disposition of a duplicate*)
    //   asks a consumer to avoid where it defines a success response.
    // - **Failed** → release the claim. A document refused downstream of the
    //   claim would otherwise burn its `id`, and a corrected resend under the
    //   same `id` would come back `idConflict` forever.
    {
        let guard: &dyn trust_tasks_rs::ReplayGuard = &*REPLAY_GUARD;
        if outcome.status.is_success() {
            let recorded = serde_json::from_slice::<serde_json::Value>(&outcome.body).ok();
            if let Err(e) = guard.record_response(&doc_id, recorded.as_ref()).await {
                // Not fatal: the effect happened and the claim stands, so item
                // 11 still holds. Only the *courtesy* of answering a retry with
                // the result is lost, and saying so beats failing a completed
                // task.
                tracing::warn!(error = %e, id = %doc_id, "replay guard: response not recorded");
            }
        } else if let Err(e) = guard.release(&doc_id, &digest).await {
            tracing::warn!(error = %e, id = %doc_id, "replay guard: claim not released");
        }
    }

    outcome
}

/// What a dispatched document needs recorded, captured before it is consumed.
///
/// Two dispositions, and the split is deliberate:
///
/// * **Vault family** — recorded on every outcome, success and refusal alike.
///   This is the pre-existing blanket audit, unchanged in behaviour; the vault
///   is the one family whose reads are worth a row on their own.
/// * **Everything else consequential** — recorded on **refusal only**. A
///   successful non-vault task is audited by its own handler, so recording it
///   here too would double every row in the trail. A refused one is audited by
///   nobody, which is the gap this closes.
///
/// Reads (`SideEffectLevel::None`) outside the vault family are not recorded.
/// Requiring a row for every `whoami` poll buries the signal the trail exists
/// to preserve.
struct DispatchAudit {
    /// `Some` for the vault family — the action string its blanket audit uses.
    vault_action: Option<String>,
    /// The URI as dispatched, for the refusal row's `resource`.
    type_uri: String,
    /// Whether a refusal is worth a row: consequential, or unclassified.
    ///
    /// An unrecognised URI counts as consequential. `class_for` returning
    /// `None` means this build knows no classification, and treating "we don't
    /// know" as "harmless" is the reading that loses the row that mattered.
    consequential: bool,
    resource: Option<String>,
    context_id: Option<String>,
    detail: Option<String>,
}

impl DispatchAudit {
    fn capture(doc: &TrustTask<Value>) -> Self {
        let type_uri = doc.type_uri.to_string();
        let consequential = class_for(&type_uri)
            .map(|class| class.side_effects != crate::policy::SideEffectLevel::None)
            .unwrap_or(true);
        Self {
            vault_action: vault_audit_action(&type_uri),
            resource: vault_audit_resource(&doc.payload),
            context_id: doc
                .payload
                .get("contextId")
                .and_then(Value::as_str)
                .map(str::to_string),
            // Operator-supplied rationale (the `reason` field that delete/
            // archive/restore/purge carry) — persisted so "audit the reason"
            // is satisfied.
            detail: doc
                .payload
                .get("reason")
                .and_then(Value::as_str)
                .map(str::to_string),
            type_uri,
            consequential,
        }
    }

    async fn record(&self, state: &AppState, actor: &str, outcome: &TrustTaskOutcome) {
        let label = vault_audit_outcome_label(outcome);

        // A refusal outside the vault family is recorded under one action
        // rather than the operation's own name, and the reason is honesty
        // rather than convenience.
        //
        // The handlers' action vocabulary is hand-chosen and does not follow
        // the URI: `acl/grant/0.1` audits as `acl.create`, `keys/create/0.1` as
        // `key.create`, `auth/revoke-session/0.1` as `session.revoke`. There is
        // no derivation, so matching it would need a table keyed by URI — 84
        // entries that go stale invisibly the first time someone adds a task.
        //
        // And a table would be recording the wrong thing anyway. These
        // refusals happen *before* dispatch: no ACL was consulted, no key was
        // touched, the operation never ran. Filing the row under `acl.create`
        // would put an event in the ACL's history that the ACL never saw.
        // `task.refused` with the URI as the resource says what actually
        // happened, and answers the question an incident review asks in one
        // query: what was turned away, and by whom.
        let (action, resource) = match (&self.vault_action, outcome.status.is_success()) {
            (Some(action), _) => (action.as_str(), self.resource.as_deref()),
            (None, false) if self.consequential => ("task.refused", Some(self.type_uri.as_str())),
            // A non-vault success: its handler owns the row. Recording here
            // too would duplicate every consequential task in the trail.
            (None, _) => return,
        };

        if let Err(e) = crate::audit::record_with_detail(
            &state.audit_sink,
            action,
            actor,
            resource,
            &label,
            Some(helpers::TRANSPORT_TRUST_TASK),
            self.context_id.as_deref(),
            self.detail.as_deref(),
        )
        .await
        {
            // Audit is best-effort: a failed write must never fail the op.
            tracing::warn!(error = %e, action, "dispatch audit record failed");
        }
    }
}

/// Audit action string for a vault-family Trust Task, or `None` for any task
/// outside the vault family (those audit through their own handlers/ops).
///
/// `…/spec/vault/<verb>/<ver>` → `vault.<verb>` (e.g. `vault.delete`);
/// `…/spec/vault/credentials/<verb>/<ver>` → `vault.cred.<verb>`. Version is
/// ignored, so a 0.2 password-vault URI and its 0.1 form audit identically.
fn vault_audit_action(type_uri: &str) -> Option<String> {
    let rest = type_uri.split("/spec/vault/").nth(1)?;
    let segs: Vec<&str> = rest.split('/').filter(|s| !s.is_empty()).collect();
    match segs.as_slice() {
        ["credentials", verb, ..] => Some(format!("vault.cred.{verb}")),
        [verb, ..] => Some(format!("vault.{verb}")),
        _ => None,
    }
}

/// Best-effort resource id for the audit row, pulled generically from the
/// request payload (`id` / `entryId` / `credentialId`). `None` for list/query
/// tasks that carry no single-entry id.
fn vault_audit_resource(payload: &Value) -> Option<String> {
    for key in ["id", "entryId", "credentialId"] {
        if let Some(v) = payload.get(key).and_then(Value::as_str) {
            return Some(v.to_string());
        }
    }
    None
}

/// Map a dispatch outcome to an audit outcome label: `"success"` on a 2xx,
/// otherwise `"denied:<code>"` with the framework reject code lifted from the
/// error document (falling back to `"denied"` if it can't be read). The audit
/// sink keys INFO vs ERROR on the `"success"` prefix.
fn vault_audit_outcome_label(outcome: &TrustTaskOutcome) -> String {
    if outcome.status.is_success() {
        return "success".to_string();
    }
    if let Ok(v) = serde_json::from_slice::<Value>(&outcome.body)
        && let Some(code) = v
            .get("payload")
            .and_then(|p| p.get("code"))
            .and_then(Value::as_str)
    {
        return format!("denied:{code}");
    }
    "denied".to_string()
}

/// Build a Trust-Task rejection `Response` for a request whose envelope
/// bytes are in `body`, WITHOUT dispatching it.
///
/// The DIDComm trust-task handler uses this when it can't authorize the
/// transport peer (no ACL entry), so the reply is still a proper
/// Trust-Task error document — not a DIDComm problem-report, which a
/// conformant Trust-Task client can't read. (On REST the JWT extractor
/// rejects unauthenticated callers before dispatch, so this gap is
/// DIDComm-only — hence the feature gate.)
// Either inbound transport rejects malformed work the same way — TSP frames
// arrive on the same mediator socket and go through the same spine.
#[cfg(any(feature = "didcomm", feature = "tsp"))]
pub(crate) fn reject_trust_task(body: &[u8], reason: RejectReason) -> TrustTaskOutcome {
    match serde_json::from_slice::<TrustTask<Value>>(body) {
        Ok(doc) => reject_with(&doc, reason),
        Err(e) => body_parse_error_response(&e.to_string()),
    }
}

// Note: `passkey-login-{start,finish}/1.0`, `challenge/1.0`,
// `authenticate/1.0`, and `refresh/1.0` are NOT in this table. They are
// UNAUTHENTICATED operations served as dedicated REST routes (`/auth/*`) — the
// user has no session JWT, so they can't pass `AuthClaims` through the
// dispatcher's extractor. The parity harness's `REST_ROUTED` allowlist tracks
// them.
dispatch_table! {
    // ─── Auth slice (authenticated operations) ───────────────────
    vta_sdk::trust_tasks::TASK_AUTH_REVOKE_SESSION_0_1 => auth::handle_revoke_session
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_AUTH_WHOAMI_0_1 => auth::handle_whoami
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_AUTH_SESSIONS_LIST_0_1 => auth::handle_sessions_list
        [ None Metadata false ],
    // All three versions route to the same typed handler, which normalises the
    // `evidence.kind` discriminator on a copy (the signed document is never
    // mutated). Not edge-transformed in `wire_v0_2` because the payload carries
    // the approver's signature.
    //
    // The REQUEST payloads are field-for-field identical across 0.1/0.2/0.3 —
    // 0.3 changed only the acknowledgement, adding `recorded`. What differs is
    // what the handler may ANSWER, and it reads `doc.type_uri` to decide: a
    // bound approval can be acknowledged honestly only to a 0.3 request,
    // because a response's type is the request's type plus `#response`.
    vta_sdk::trust_tasks::TASK_AUTH_STEP_UP_APPROVE_RESPONSE_0_1
        | vta_sdk::trust_tasks::TASK_AUTH_STEP_UP_APPROVE_RESPONSE_0_2
        | vta_sdk::trust_tasks::TASK_AUTH_STEP_UP_APPROVE_RESPONSE_0_3
        => step_up::handle_approve_response
        [ Mutating None false ],
    // ─── Policy slice (runtime PDP management) ────────────────────
    // Deliberately NOT exempt from the gate: an operator who wants two-person
    // control over changes to the gate itself writes a consent rule for
    // `policy/upsert`. The lockout that risks is answered by the offline
    // break-glass, not by making this surface ungateable.
    vta_sdk::trust_tasks::TASK_POLICY_LIST_0_2 => policy::handle_list
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_POLICY_GET_0_1 => policy::handle_get
        [ None Metadata false ],
    // Destructive: rewriting policy can remove every gate on this VTA.
    vta_sdk::trust_tasks::TASK_POLICY_UPSERT_0_2 => policy::handle_upsert
        [ Destructive None false ],
    vta_sdk::trust_tasks::TASK_POLICY_DELETE_0_1 => policy::handle_delete
        [ Destructive None false ],
    // ─── Consent slice ────────────────────────────────────────────
    vta_sdk::trust_tasks::TASK_CONSENT_REQUEST_1_0 => consent::handle_request
        [ None None false ],
    vta_sdk::trust_tasks::TASK_CONSENT_DECISION_1_0 => consent::handle_decision
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_CONSENT_REVOKE_1_0 => consent::handle_revoke
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_CONSENT_LIST_1_0 => consent::handle_list
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_CONSENT_APPROVER_SET_1_0 => consent::handle_approver_set
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_CONSENT_APPROVER_LIST_1_0 => consent::handle_approver_list
        [ None Metadata false ],
    // Task-execution consent decision (PDP requireConsent). Records approver
    // signatures; the gate exempts it from re-gating (see policy_gate) so
    // approving a task can't itself require consent.
    vta_sdk::trust_tasks::TASK_TASK_CONSENT_DECISION_0_1 => task_consent::handle_decision
        [ Mutating None false ],
    // ─── ACL slice ────────────────────────────────────────────────
    vta_sdk::trust_tasks::TASK_ACL_LIST_0_1 => acl::handle_list
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_ACL_GRANT_0_1 => acl::handle_create
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_ACL_SHOW_0_1 => acl::handle_get
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_ACL_UPDATE_0_1 => acl::handle_update
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_ACL_CHANGE_ROLE_0_1 => acl::handle_change_role
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_ACL_REVOKE_0_1 => acl::handle_delete
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_ACL_SWAP_KEY_0_1 => acl::handle_swap_key
        [ Destructive None false ],
    // ─── Device slice ─────────────────────────────────────────────
    vta_sdk::trust_tasks::TASK_DEVICE_REGISTER_0_1 => device::handle_register
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_DEVICE_HEARTBEAT_0_1 => device::handle_heartbeat
        [ None None false ],
    vta_sdk::trust_tasks::TASK_DEVICE_LIST_0_1 => device::handle_list
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_DEVICE_DISABLE_0_1 => device::handle_disable
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_DEVICE_WIPE_0_1 => device::handle_wipe
        [ Destructive None false ],
    vta_sdk::trust_tasks::TASK_DEVICE_SET_WAKE_0_1 => device::handle_set_wake
        [ Mutating None false ],
    // ─── Messaging slice ──────────────────────────────────────────
    vta_sdk::trust_tasks::TASK_MESSAGING_PING_0_1 => messaging::handle_ping
        [ None None false ],
    // ─── Services slice ──────────────────────────────────────────
    //
    // Metadata mirrors what each verb actually does to the agent's DID
    // document. `drain/cancel` is Destructive rather than Mutating: it discards
    // messages still in flight through the mediator, which is precisely what
    // the drain window existed to prevent.
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_SERVICES_LIST_1_0 => services::handle_list
        [ None Metadata false ],
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_SERVICES_GET_1_0 => services::handle_get
        [ None Metadata false ],
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_SERVICES_ENABLE_1_0 => services::handle_enable
        [ Mutating None false ],
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_SERVICES_UPDATE_1_0 => services::handle_update
        [ Mutating None false ],
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_SERVICES_DISABLE_1_0 => services::handle_disable
        [ Mutating None false ],
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_SERVICES_ROLLBACK_1_0 => services::handle_rollback
        [ Mutating None false ],
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_SERVICES_DRAIN_LIST_1_0 => services::handle_drain_list
        [ None Metadata false ],
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_SERVICES_DRAIN_CANCEL_1_0 => services::handle_drain_cancel
        [ Destructive None false ],
    // ─── Contexts slice ──────────────────────────────────────────
    vta_sdk::trust_tasks::TASK_CONTEXTS_LIST_1_0 => contexts::handle_list
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_CONTEXTS_CREATE_1_0 => contexts::handle_create
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_CONTEXTS_GET_1_0 => contexts::handle_get
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_CONTEXTS_UPDATE_1_0 => contexts::handle_update
        [ Mutating None false ],
    // `Secret`, not `Metadata`: the response carries private keys in the clear, and
    // this classification — not the published registry — is what the PDP feeds into
    // `PolicyInput`. Declaring it as a metadata read would lower the consent bar on the
    // single most disclosing task in the surface. `None` side effects is right: it reads
    // existing keys and mints, rotates and revokes nothing.
    vta_sdk::trust_tasks::TASK_CONTEXTS_SECRETS_1_0 => contexts::handle_secrets
        [ None Secret false ],
    vta_sdk::trust_tasks::TASK_CONTEXTS_UPDATE_DID_1_0 => contexts::handle_update_did
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_CONTEXTS_PREVIEW_DELETE_1_0 => contexts::handle_preview_delete
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_CONTEXTS_DELETE_1_0 => contexts::handle_delete
        [ Destructive None false ],
    // ─── Keys slice ──────────────────────────────────────────────
    vta_sdk::trust_tasks::TASK_KEYS_LIST_0_1 => keys::handle_list
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_KEYS_CREATE_0_1 => keys::handle_create
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_KEYS_IMPORT_0_1 => keys::handle_import
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_KEYS_SHOW_0_1 => keys::handle_get
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_KEYS_RENAME_0_1 => keys::handle_rename
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_KEYS_REVOKE_0_1 => keys::handle_revoke
        [ Destructive None false ],
    // `Mutating` and `Metadata`: it changes one member of a key record and
    // discloses only the record. It never reads or releases key material — the
    // task decides whether a *future* export may happen, and does not perform
    // one.
    vta_sdk::trust_tasks::TASK_KEYS_SET_EXPORTABILITY_0_1 => keys::handle_set_exportability
        [ Mutating Metadata false ],
    // `None Secret false`: it reads existing material and changes nothing, and
    // what it discloses is a private key. Same classification as
    // `vta/contexts/secrets`, for the same reason — the act is disclosure.
    vta_sdk::trust_tasks::TASK_KEYS_EXPORT_SECRET_0_1 => keys::handle_export_secret
        [ None Secret false ],
    vta_sdk::trust_tasks::TASK_KEYS_SIGN_0_1 => keys::handle_sign
        [ None None true ],
    vta_sdk::trust_tasks::TASK_KEYS_DERIVE_AND_SIGN_0_1 => keys::handle_derive_and_sign
        [ Mutating None true ],
    vta_sdk::trust_tasks::TASK_KEYS_DERIVE_AND_SIGN_DOCUMENT_0_1 => keys::handle_derive_and_sign_document
        [ Mutating None true ],
    // ─── Seeds slice ─────────────────────────────────────────────
    vta_sdk::trust_tasks::TASK_SEEDS_LIST_1_0 => seeds::handle_list
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_SEEDS_ROTATE_1_0 => seeds::handle_rotate
        [ Destructive None false ],
    // ─── Audit slice ─────────────────────────────────────────────
    vta_sdk::trust_tasks::TASK_AUDIT_LIST_0_1 => audit::handle_list_logs
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_AUDIT_VERIFY_0_1 => audit::handle_verify_chain
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_AUDIT_GET_RETENTION_1_0 => audit::handle_get_retention
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_AUDIT_UPDATE_RETENTION_1_0 => audit::handle_update_retention
        [ Mutating None false ],
    // ─── Discovery ───────────────────────────────────────────────
    vta_sdk::trust_tasks::TASK_TRUST_TASK_DISCOVERY_0_1 => discovery::handle_trust_task_discovery
        [ None None false ],
    // ─── Credential-exchange: deferred-presentation approval ─────
    //
    // The holder operator's out-of-band surface over deferred presentations.
    // The `credential-exchange/*` family keeps its URIs in
    // `vta_sdk::protocols::credential_exchange`, not the central `trust_tasks`
    // registry — so these sit outside the `ALL_URIS` parity harness (like the
    // `query`/`present` message types), but are still tracked by
    // `dispatched_uris()` (harmless extra entries).
    vta_sdk::protocols::credential_exchange::PENDING_LIST
        => credential_exchange::handle_pending_list
        [ None Metadata false ],
    vta_sdk::protocols::credential_exchange::PENDING_APPROVE
        => credential_exchange::handle_pending_approve
        [ Mutating None true ],
    vta_sdk::protocols::credential_exchange::PENDING_DENY
        => credential_exchange::handle_pending_deny
        [ Mutating None false ],
    // ─── Vault slice (public 0.1 spec) ──────────────────────────
    vta_sdk::trust_tasks::TASK_VAULT_LIST_0_1 => vault::handle_list
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_VAULT_GET_0_1 => vault::handle_get
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_VAULT_UPSERT_0_1 => vault::handle_upsert
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_VAULT_DELETE_0_1 => vault::handle_delete
        [ Destructive None false ],
    vta_sdk::trust_tasks::TASK_VAULT_RELEASE_0_1 => vault::handle_release
        [ Mutating Secret false ],
    vta_sdk::trust_tasks::TASK_VAULT_PROXY_LOGIN_0_1 => vault::handle_proxy_login
        [ Mutating Secret true ],
    vta_sdk::trust_tasks::TASK_VAULT_SIGN_TRUST_TASK_0_1 => vault::handle_sign_trust_task
        [ Mutating None true ],
    // Vault archival lifecycle (openvtc extension). `delete` above is now soft.
    vta_sdk::trust_tasks::TASK_VAULT_ARCHIVE_0_1 => vault::handle_archive
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_VAULT_UNARCHIVE_0_1 => vault::handle_unarchive
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_VAULT_RESTORE_0_1 => vault::handle_restore
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_VAULT_PURGE_0_1 => vault::handle_purge
        [ Destructive None false ],

    vta_sdk::trust_tasks::TASK_VAULT_CREDENTIALS_RECEIVE_0_1 => cred_vault::handle_receive
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_VAULT_CREDENTIALS_QUERY_0_1 => cred_vault::handle_query
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_VAULT_CREDENTIALS_GET_0_1 => cred_vault::handle_get
        [ None Metadata false ],
    // Credential archival lifecycle (openvtc extension; CredentialWrite-gated).
    vta_sdk::trust_tasks::TASK_VAULT_CREDENTIALS_ARCHIVE_0_1 => cred_vault::handle_archive
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_VAULT_CREDENTIALS_UNARCHIVE_0_1 => cred_vault::handle_unarchive
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_VAULT_CREDENTIALS_DELETE_0_1 => cred_vault::handle_delete
        [ Destructive None false ],
    vta_sdk::trust_tasks::TASK_VAULT_CREDENTIALS_RESTORE_0_1 => cred_vault::handle_restore
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_VAULT_CREDENTIALS_PURGE_0_1 => cred_vault::handle_purge
        [ Destructive None false ],
    // ─── Issued-credential lifecycle (spec/vta/credentials/*) ────
    // Mint + revoke VTA-signed VCs; Admin-gated + operator step-up (AAL2).
    vta_sdk::trust_tasks::TASK_VTA_CREDENTIALS_ISSUE_0_2 => credentials::handle_issue
        [ Mutating None true ],
    vta_sdk::trust_tasks::TASK_VTA_CREDENTIALS_REVOKE_0_1 => credentials::handle_revoke
        [ Destructive None false ],
    // A read. `None` side-effect and no step-up: gated on `require_manage`
    // like `acl/list`, because "what has my agent issued" is the same category
    // of question as "who may act at it". What it discloses is the issuer's
    // holder set rather than any one credential's claims — bodies are never
    // returned — so the exposure class stays `None` too.
    vta_sdk::trust_tasks::TASK_VTA_CREDENTIALS_LIST_0_1 => credentials::handle_list
        [ None None false ],
    // ─── Agent-memory slice (spec/vta/memory/*) ──────────────────
    // Per-context key/value store; gated on context access (require_context),
    // NOT operator step-up.
    vta_sdk::trust_tasks::TASK_VTA_MEMORY_PUT_0_1 => memory::handle_put
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_VTA_MEMORY_LIST_0_1 => memory::handle_list
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_VTA_MEMORY_DELETE_0_1 => memory::handle_delete
        [ Mutating None false ],
    // ─── Room oracle (spec/rooms/keys/*) ─────────────────────────
    // An agent asks for a scoped presentation over its principal's room
    // credentials. Gated on the `roomPresent` capability plus context access
    // for the principal's key — NOT on `Sign`, which would grant far more.
    vta_sdk::trust_tasks::TASK_ROOMS_KEYS_PRESENT_0_2 => room_keys::handle_present
        [ None Metadata false ],
    // Group custody: how a group reaches this VTA, and what it does with one.
    // Three inbound (a room's owner reaching us) and one outbound-facing; only
    // `open` is capability-gated, because only it is our own principal asking.
    vta_sdk::trust_tasks::TASK_ROOMS_KEYS_KEY_PACKAGE_0_1 => room_group::handle_key_package
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_ROOMS_KEYS_WELCOME_0_1 => room_group::handle_welcome
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_ROOMS_KEYS_COMMIT_0_1 => room_group::handle_commit
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_ROOMS_KEYS_OPEN_0_1 => room_group::handle_open
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_ROOMS_KEYS_CHAIN_0_1 => room_group::handle_chain
        [ Mutating None false ],
    // `actsAsSubject`, unlike every other `rooms/keys/*`: this one presents the
    // principal's credentials to a third party as them. The response discloses
    // only how far back the agent can now read.
    vta_sdk::trust_tasks::TASK_ROOMS_KEYS_BACKFILL_0_1 => room_group::handle_backfill
        [ Mutating Metadata true ],
    // Returns a record's plaintext — on a sealed tier, material the room
    // withholds from its own host — after presenting the principal's
    // credentials to a party the caller names.
    // Publishes a witnessed log entry in the room's name, which cannot be
    // withdrawn — only superseded.
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_ROOMS_OWNER_ANCHOR_0_1 => room_owner::handle_anchor
        [ Mutating Metadata true ],
    vta_sdk::trust_tasks::TASK_ROOMS_KEYS_READ_0_1 => room_group::handle_read
        [ None Secret true ],
    // Metadata only, and still `actsAsSubject`: the presentation names a member
    // of the room to the host it is shown to.
    vta_sdk::trust_tasks::TASK_ROOMS_KEYS_BROWSE_0_1 => room_group::handle_browse
        [ None Metadata true ],
    vta_sdk::trust_tasks::TASK_ROOMS_KEYS_SEAL_0_1 => room_group::handle_seal
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_ROOMS_KEYS_LIST_0_1 => room_group::handle_list
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_ROOMS_OWNER_INVITE_0_1 => room_owner::handle_invite
        [ Mutating Metadata false ],
    // `actsAsSubject`, unlike the issuance verbs beside it: those sign as the
    // room and return the credential to the caller, while this one speaks to a
    // third party as its principal.
    vta_sdk::trust_tasks::TASK_ROOMS_OWNER_REGISTER_0_1 => room_owner::handle_register
        [ Mutating Metadata true ],
    vta_sdk::trust_tasks::TASK_ROOMS_OWNER_ISSUE_MEMBERSHIP_0_1 => room_owner::handle_issue_membership
        [ Mutating Metadata false ],
    vta_sdk::trust_tasks::TASK_ROOMS_OWNER_ISSUE_AUTHORITY_0_2 => room_owner::handle_issue_authority
        [ Mutating Metadata false ],
    // ─── Application-state slice (spec/vta/app-state/*) ──────────
    // Versioned, namespaced per-context JSON the VTA stores but never
    // interprets. Gated on context access (require_context), NOT operator
    // step-up — same boundary as the memory slice. `discloses: Metadata` on
    // the reads because the values are application data rather than secrets;
    // secret material belongs in the vault, and the published specs say so
    // normatively. `delete` is Destructive: the value goes immediately and,
    // once the tombstone is reaped, nothing records the record ever existed.
    vta_sdk::trust_tasks::TASK_VTA_APP_STATE_GET_1_0 => app_state::handle_get
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_VTA_APP_STATE_PUT_1_0 => app_state::handle_put
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_VTA_APP_STATE_LIST_1_0 => app_state::handle_list
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_VTA_APP_STATE_DELETE_1_0 => app_state::handle_delete
        [ Destructive None false ],
    vta_sdk::trust_tasks::TASK_VTA_APP_STATE_GET_MANY_1_0 => app_state::handle_get_many
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_VTA_APP_STATE_PUT_MANY_1_0 => app_state::handle_put_many
        [ Mutating None false ],
    // ─── Persona slice (spec/persona/*) ──────────────────────────
    // The holder's own identity. Eleven of the family's tasks are gated on an
    // UNSCOPED HOLDER credential rather than context access — see
    // `trust_tasks::persona::authorize`, where the classification lives and a
    // census pins it. `attribute/put` is Mutating and `delete` Destructive;
    // both reads disclose Metadata because they return the holder's own data
    // to the holder.
    vta_sdk::trust_tasks::TASK_PERSONA_ATTRIBUTE_PUT_1_0 => persona::handle_attribute_put
        [ Mutating Metadata false ],
    vta_sdk::trust_tasks::TASK_PERSONA_ATTRIBUTE_LIST_1_0 => persona::handle_attribute_list
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_PERSONA_ATTRIBUTE_DELETE_1_0 => persona::handle_attribute_delete
        [ Destructive None false ],
    vta_sdk::trust_tasks::TASK_PERSONA_PROFILE_PUT_1_0 => persona::handle_profile_put
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_PERSONA_PROFILE_GET_1_0 => persona::handle_profile_get
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_PERSONA_PROFILE_LIST_1_0 => persona::handle_profile_list
        [ None Metadata false ],
    // A facet arranges records; it never touches one. `put` is Mutating because
    // it writes a record of its own, and `delete` Destructive for the same
    // reason — neither reaches a profile or an attribute, which is the property
    // `deleting_a_facet_deletes_nothing_it_named` pins in vta-persona.
    vta_sdk::trust_tasks::TASK_PERSONA_FACET_PUT_1_0 => persona::handle_facet_put
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_PERSONA_FACET_LIST_1_0 => persona::handle_facet_list
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_PERSONA_FACET_DELETE_1_0 => persona::handle_facet_delete
        [ Destructive None false ],
    vta_sdk::trust_tasks::TASK_PERSONA_PROFILE_DELETE_1_0 => persona::handle_profile_delete
        [ Destructive None false ],
    // The critical gate. Holder-only, and Mutating because it materialises a
    // projection into a context — a push across the trust boundary.
    vta_sdk::trust_tasks::TASK_PERSONA_BINDING_SET_1_0 => persona::handle_binding_set
        [ Mutating Metadata false ],
    // Context-callable and deliberately thin: whether bound, the label, a
    // claim count. Never contents.
    vta_sdk::trust_tasks::TASK_PERSONA_BINDING_GET_1_0 => persona::handle_binding_get
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_PERSONA_BINDING_LIST_1_0 => persona::handle_binding_list
        [ None Metadata false ],
    // Contacts are a third party's disclosed data held for the holder.
    vta_sdk::trust_tasks::TASK_PERSONA_CONTACT_PUT_1_0 => persona::handle_contact_put
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_PERSONA_CONTACT_GET_1_0 => persona::handle_contact_get
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_PERSONA_CONTACT_LIST_1_0 => persona::handle_contact_list
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_PERSONA_CONTACT_DELETE_1_0 => persona::handle_contact_delete
        [ Destructive None false ],
    // Holder-only: both span every context, which is the view a context-scoped
    // caller must not have.
    vta_sdk::trust_tasks::TASK_PERSONA_DISCLOSURE_HISTORY_1_0 => persona::handle_disclosure_history
        [ None Metadata false ],
    // Two calls that cannot be collapsed: present consumes a single-use token
    // only preview can mint. preview is Mutating despite looking like a read,
    // because that token is durable state — and it is what makes the summary
    // unskippable.
    vta_sdk::trust_tasks::TASK_PERSONA_DISCLOSURE_PREVIEW_1_0 => persona::handle_disclosure_preview
        [ Mutating Metadata false ],
    // The only task in the family that releases personal data to a third party.
    vta_sdk::trust_tasks::TASK_PERSONA_DISCLOSURE_PRESENT_1_0 => persona::handle_disclosure_present
        [ Mutating Secret true ],
    vta_sdk::trust_tasks::TASK_PERSONA_CORRELATION_ANALYZE_1_0 => persona::handle_correlation_analyze
        [ None Metadata false ],
    // Describes the agent's capabilities, not the holder. Discloses nothing.
    vta_sdk::trust_tasks::TASK_PERSONA_RENDERERS_LIST_1_0 => persona::handle_renderers_list
        [ None None false ],
    // Describes the agent's vocabulary, not the holder. Discloses nothing.
    vta_sdk::trust_tasks::TASK_PERSONA_CLAIM_TYPES_LIST_1_0 => persona::handle_claim_types_list
        [ None None false ],
    // The context-local surface. Context-callable because authoring below the
    // boundary is safe; the rule exists to stop reading across it.
    vta_sdk::trust_tasks::TASK_PERSONA_LOCAL_PROFILE_PUT_1_0 => persona::handle_local_profile_put
        [ Mutating Metadata false ],
    vta_sdk::trust_tasks::TASK_PERSONA_LOCAL_PROFILE_GET_1_0 => persona::handle_local_profile_get
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_PERSONA_LOCAL_PROFILE_LIST_1_0 => persona::handle_local_profile_list
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_PERSONA_LOCAL_PROFILE_DELETE_1_0 => persona::handle_local_profile_delete
        [ Destructive None false ],
    vta_sdk::trust_tasks::TASK_PERSONA_LOCAL_BINDING_SET_1_0 => persona::handle_local_binding_set
        [ Mutating None false ],
    // ─── Config slice ────────────────────────────────────────────
    vta_sdk::trust_tasks::TASK_CONFIG_SHOW_0_1 => config::handle_get
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_CONFIG_PATCH_0_1 => config::handle_update
        [ Mutating None false ],
    // ─── Management slice ────────────────────────────────────────
    vta_sdk::trust_tasks::TASK_MANAGEMENT_RELOAD_SERVICES_1_0 => management::handle_reload_services
        [ Mutating None false ],
    // ─── Backup slice (descriptor pattern) ───────────────────────
    vta_sdk::trust_tasks::TASK_BACKUP_INITIATE_EXPORT_1_0 => backup::handle_initiate_export
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_BACKUP_COMPLETE_EXPORT_1_0 => backup::handle_complete_export
        [ Mutating Secret false ],
    vta_sdk::trust_tasks::TASK_BACKUP_INITIATE_IMPORT_1_0 => backup::handle_initiate_import
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_BACKUP_FINALIZE_IMPORT_1_0 => backup::handle_finalize_import
        [ Destructive None false ],
    vta_sdk::trust_tasks::TASK_BACKUP_ABORT_1_0 => backup::handle_abort
        [ Mutating None false ],
    // The `chunkedTrustTask` algorithm. The 1.1 initiators serve `stream` through
    // the 1.0 path unchanged. `get-chunk` releases part of the encrypted export,
    // so it discloses Secret like `complete-export`; it is Mutating because it
    // records the index as served and slides the bundle's expiry. `put-chunk`
    // stages inert bytes checked against a pre-committed manifest.
    vta_sdk::trust_tasks::TASK_BACKUP_INITIATE_EXPORT_1_1 => backup::handle_initiate_export_1_1
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_BACKUP_INITIATE_IMPORT_1_1 => backup::handle_initiate_import_1_1
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_BACKUP_FINALIZE_IMPORT_1_1 => backup::handle_finalize_import_1_1
        [ Destructive None false ],
    vta_sdk::trust_tasks::TASK_BACKUP_GET_CHUNK_1_0 => backup::handle_get_chunk
        [ Mutating Secret false ],
    vta_sdk::trust_tasks::TASK_BACKUP_PUT_CHUNK_1_0 => backup::handle_put_chunk
        [ Mutating None false ],
    // ─── DID-templates slice (2.0 — optional contextId selects the
    // scope; the twelve retired 1.0 URIs now get UnsupportedType) ──
    vta_sdk::trust_tasks::TASK_DID_TEMPLATES_LIST_2_0 => did_templates::handle_list
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_DID_TEMPLATES_CREATE_2_0 => did_templates::handle_create
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_DID_TEMPLATES_GET_2_0 => did_templates::handle_get
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_DID_TEMPLATES_UPDATE_2_0 => did_templates::handle_update
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_DID_TEMPLATES_DELETE_2_0 => did_templates::handle_delete
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_DID_TEMPLATES_RENDER_2_0 => did_templates::handle_render
        [ None Metadata false ],
    // ─── DID-templates 3.0 — same handlers, wider template schema ──
    //
    // Only the four that carry a template shape. `delete` takes a name and
    // `render` returns a rendered document, so neither is affected by the
    // `keys` block and neither gained a 3.0 spec.
    vta_sdk::trust_tasks::TASK_DID_TEMPLATES_LIST_3_0 => did_templates::handle_list
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_DID_TEMPLATES_CREATE_3_0 => did_templates::handle_create
        [ Mutating None false ],
    vta_sdk::trust_tasks::TASK_DID_TEMPLATES_GET_3_0 => did_templates::handle_get
        [ None Metadata false ],
    vta_sdk::trust_tasks::TASK_DID_TEMPLATES_UPDATE_3_0 => did_templates::handle_update
        [ Mutating None false ],
    // ─── Passkey-VMs slice (feature-gated: webvh + didcomm) ─────
    //
    // Canonical 0.1 only — the pre-spec 1.0 aliases were removed (the browser
    // plugin migrated to 0.1; a 1.0 doc now gets UnsupportedType).
    #[cfg(all(feature = "webvh", feature = "didcomm"))]
    vta_sdk::trust_tasks::TASK_PASSKEY_VMS_ENROLL_CHALLENGE_0_1
        => passkey_vms::handle_enroll_challenge
        [ None None false ],
    #[cfg(all(feature = "webvh", feature = "didcomm"))]
    vta_sdk::trust_tasks::TASK_PASSKEY_VMS_ENROLL_SUBMIT_0_1 => passkey_vms::handle_enroll_submit
        [ Mutating None false ],
    #[cfg(all(feature = "webvh", feature = "didcomm"))]
    vta_sdk::trust_tasks::TASK_PASSKEY_VMS_LIST_0_1 => passkey_vms::handle_list
        [ None Metadata false ],
    #[cfg(all(feature = "webvh", feature = "didcomm"))]
    vta_sdk::trust_tasks::TASK_PASSKEY_VMS_REVOKE_0_1 => passkey_vms::handle_revoke
        [ Destructive None false ],
    // ─── Provision-integration (feature-gated: webvh) ────────────
    // 0.3 only. 0.2 required a bare-hex `digest` and forbade
    // `digestMultibase`; 0.3 is the reverse, and both close their response with
    // `additionalProperties: false` — so no single response satisfies the two,
    // and dual-accepting them would mean a version-aware response shape for one
    // renamed member. Cut over instead.
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_PROVISION_INTEGRATION_0_3
        => provision_integration::handle_request
        [ Mutating Secret false ],
    // ─── WebVH-DID-lifecycle slice (feature-gated: webvh) ────────
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_SERVERS_LIST_1_0 => webvh::handle_servers_list
        [ None Metadata false ],
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_SERVERS_REGISTER_1_0 => webvh::handle_servers_register
        [ Mutating None false ],
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_SERVERS_REMOVE_1_0 => webvh::handle_servers_remove
        [ Mutating None false ],
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_SERVERS_DOMAINS_0_1 => webvh::handle_servers_domains
        [ None Metadata false ],
    // Reads two listings and compares them — no side effects, same class as
    // the domains read beside it.
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_SERVERS_RECONCILE_0_1 => webvh::handle_servers_reconcile
        [ None Metadata false ],
    // Destructive rather than Mutating: it stops a published identifier
    // resolving, with no undo, and every relying party that held the DID sees
    // it go — they cannot distinguish retirement from compromise or an outage.
    // Reconcile above it is the read that finds these; this is the only write
    // in the pair, and the asymmetry in class is the point.
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_SERVERS_RETIRE_ORPHAN_0_1 => webvh::handle_servers_retire_orphan
        [ Destructive None false ],
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_LIST_1_0 => webvh::handle_dids_list
        [ None Metadata false ],
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_CREATE_1_0 => webvh::handle_dids_create
        [ Mutating None false ],
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_GET_1_0 => webvh::handle_dids_get
        [ None Metadata false ],
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_DELETE_1_0 => webvh::handle_dids_delete
        [ Destructive None false ],
    // Destructive, not mutating — and the line below is why. A document update
    // ROTATES the DID's update key: the key that could authorize changes before
    // this entry cannot afterwards. SPEC §7.3 item 13 names exactly that —
    // "rotation of a sole controlling key" — as authority-shifting, and
    // authority-shifting is destructive.
    //
    // `dids/rotate-keys` two lines down has always been Destructive. It rotates
    // the same key. Classing an update as merely `Mutating` said that the same
    // effect was destructive when you asked for it and recoverable when you got
    // it as a side effect, which is precisely backwards: the side effect is the
    // dangerous one, because it is the one nobody asked for.
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_UPDATE_1_0 => webvh::handle_dids_update
        [ Destructive None false ],
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_ROTATE_KEYS_1_0 => webvh::handle_dids_rotate_keys
        [ Destructive None false ],
    // Mutating rather than Destructive, unlike its two neighbours above: a
    // realign renames records, and the key material behind them is untouched.
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_REALIGN_KEYS_1_0 => webvh::handle_dids_realign_keys
        [ Mutating None false ],
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_REGISTER_WITH_SERVER_1_0
        => webvh::handle_dids_register_with_server
        [ Mutating None false ],
    // Agent-name bind/release/park/resume. All four publish a new signed
    // version (and so rotate the update key exactly like any update), and all
    // four change a public name binding — Destructive, like `dids/update`,
    // per the rationale above. Classifying them Destructive is what makes the
    // wallet force a cross-device type-to-confirm, which is the elevation
    // for these ops (the hosting endpoint is deliberately not step-up-gated
    // — the VTA can't hold an aal2 session).
    //
    // `remove` earns the classification most directly: it releases the name
    // for anyone to reclaim, so unlike `disable` it is not recoverable by
    // this DID alone.
    // Read-only: no side effect, metadata-class. A parked name is invisible
    // in the DID document, so `list` is the only way to see one — and `check`
    // is what lets a client report a collision before it signs a new version.
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_AGENT_NAME_LIST_1_0 => webvh::handle_agent_name_list
        [ None Metadata false ],
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_AGENT_NAME_CHECK_1_0 => webvh::handle_agent_name_check
        [ None Metadata false ],
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_AGENT_NAME_SET_1_0 => webvh::handle_agent_name_set
        [ Destructive None false ],
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_AGENT_NAME_REMOVE_1_0 => webvh::handle_agent_name_remove
        [ Destructive None false ],
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_AGENT_NAME_DISABLE_1_0 => webvh::handle_agent_name_disable
        [ Destructive None false ],
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_AGENT_NAME_ENABLE_1_0 => webvh::handle_agent_name_enable
        [ Destructive None false ],
}

#[cfg(test)]
mod tests {
    //! Smoke tests for the dispatcher's wire-shape contracts + the
    //! cross-crate URI parity harness. Each arm's actual handler
    //! logic is tested in its owning operations module (or by the
    //! Phase 5 integration suite once full AppState scaffolding is
    //! in place).

    use trust_tasks_rs::TrustTask;

    use super::*;

    /// **A success response carries this agent'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 agent attached a proof to none
    /// of them until the spine started signing, and nothing caught it because no
    /// consumer verifies one either.
    ///
    /// Tests the cryptographic path rather than the plumbing: a booted agent is
    /// not needed to answer "does this produce a verifiable proof", and the
    /// question that needs answering is that one.
    #[tokio::test]
    async fn a_success_response_is_signed() {
        let secret = test_secret();
        let body =
            br#"{"id":"urn:uuid:x","type":"https://example.org/t#response","payload":{"ok":true}}"#;

        let signed = super::attach_proof(&secret, body)
            .await
            .expect("a well-formed response signs");
        let doc: Value = serde_json::from_slice(&signed).expect("signed document parses");

        let proof = doc
            .get("proof")
            .expect("a success response with no proof is unattributable");
        assert_eq!(
            proof.get("cryptosuite").and_then(Value::as_str),
            Some("eddsa-jcs-2022")
        );
        assert!(proof.get("proofValue").and_then(Value::as_str).is_some());
        assert_eq!(
            proof.get("verificationMethod").and_then(Value::as_str),
            Some(secret.id.as_str()),
            "the proof must name the key that signed it"
        );
        // The payload is untouched — signing attests to the answer, it does not
        // change it.
        assert_eq!(doc["payload"]["ok"], Value::Bool(true));
    }

    /// A proof never covers itself. Re-signing a document that already carries
    /// one must replace it, not sign over it — otherwise the second proof
    /// attests to a document containing the first, and neither verifies against
    /// what a consumer canonicalises.
    #[tokio::test]
    async fn an_existing_proof_is_replaced_not_nested() {
        let secret = test_secret();
        let body = br#"{"id":"urn:uuid:x","type":"https://example.org/t#response","proof":{"stale":true},"payload":{}}"#;

        let signed = super::attach_proof(&secret, body).await.expect("signs");
        let doc: Value = serde_json::from_slice(&signed).expect("parses");
        assert!(
            doc["proof"].get("stale").is_none(),
            "the stale proof survived: {}",
            doc["proof"]
        );
    }

    /// A body that is not a JSON object cannot be signed, and that must degrade
    /// to an unsigned answer rather than a panic — the operation already
    /// succeeded.
    #[tokio::test]
    async fn an_unsignable_body_degrades_rather_than_panicking() {
        assert!(
            super::attach_proof(&test_secret(), b"not json")
                .await
                .is_none()
        );
        assert!(
            super::attach_proof(&test_secret(), b"[1,2,3]")
                .await
                .is_none()
        );
    }

    /// **The spine calls the signer.**
    ///
    /// The behavioural tests above cover the cryptographic path and pass
    /// perfectly well with the call deleted from `dispatch_trust_task_core` —
    /// which is precisely the shape of the bug they exist to prevent, so on its
    /// own that coverage is a comfort rather than a guard. This reads the source
    /// of the spine and asserts the call is there, in the same spirit as
    /// `vta-sdk`'s `connect_with_transport` body check.
    ///
    /// A source assertion rather than a behavioural one because the alternative
    /// needs a booted agent with a resident signing secret, and the property is
    /// one line: does every answer pass through the signer on its way out.
    /// **One inbound path, and it stays one.**
    ///
    /// Every transport this service accepts Trust Tasks on — REST, DIDComm, TSP
    /// — reaches [`dispatch_trust_task_core`], and each does only what its own
    /// binding requires on the way: REST's binding is the request path, DIDComm's
    /// is the message `type`, TSP's is the payload wrapper
    /// (`vta_sdk::tsp_binding`). None of them parses a Trust-Task document
    /// itself.
    ///
    /// That is true today. This is what keeps it true: a fourth transport is
    /// meant to be a binding module plus a thin entry, and the way that goes
    /// wrong is not dramatic — someone deserialises the document in their
    /// handler to read one field, then branches on it, and a second spine grows
    /// with its own idea of validation, replay and signing. By the time it is
    /// visible it is a rewrite.
    ///
    /// Source-level, because the property is about *where* parsing happens, and
    /// a behavioural test cannot see that: a second spine that does all the same
    /// checks passes every round-trip test there is.
    #[test]
    fn only_the_spine_parses_a_trust_task_document() {
        /// Transport modules that legitimately parse a document, with the
        /// reason. May only shrink.
        const ALLOWED: &[(&str, &str)] = &[(
            "routes/auth.rs",
            "Pre-login: `auth/{challenge,authenticate,refresh}` carry no session,              so they cannot pass `AuthClaims` through the dispatcher's extractor              and are served as dedicated REST routes. `vta_sdk`'s              `REST_ROUTED_URIS` is the canonical list and names exactly these.",
        )];

        fn rust_files(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
            let Ok(entries) = std::fs::read_dir(dir) else {
                return;
            };
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_dir() {
                    rust_files(&path, out);
                } else if path.extension().is_some_and(|e| e == "rs") {
                    out.push(path);
                }
            }
        }

        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
        let mut files = Vec::new();
        for area in ["messaging", "routes"] {
            rust_files(&root.join(area), &mut files);
        }
        assert!(
            !files.is_empty(),
            "the sweep found no transport sources — it has stopped checking anything"
        );

        let mut offenders: Vec<String> = Vec::new();
        let mut allowed_seen: Vec<&str> = Vec::new();
        for file in &files {
            let rel = file
                .strip_prefix(&root)
                .unwrap_or(file)
                .to_string_lossy()
                .replace('\\', "/");
            let src = std::fs::read_to_string(file).expect("read a transport source");
            // Test code is exempt: a test constructing a document to feed the
            // spine is the spine being tested, not a second one.
            let production = src.split("#[cfg(test)]").next().unwrap_or(&src);
            for (n, line) in production.lines().enumerate() {
                let parses = line.contains("TrustTask<")
                    && (line.contains("from_slice")
                        || line.contains("from_str")
                        || line.contains("from_value"));
                if !parses {
                    continue;
                }
                if ALLOWED.iter().any(|(f, _)| *f == rel) {
                    if !allowed_seen.contains(&rel.as_str()) {
                        allowed_seen.push(Box::leak(rel.clone().into_boxed_str()));
                    }
                    continue;
                }
                offenders.push(format!("{rel}:{}  {}", n + 1, line.trim()));
            }
        }

        assert!(
            offenders.is_empty(),
            "these transport modules parse a Trust-Task document themselves:\n  {}\n\n\
             A transport opens its own binding and hands the bytes to \
             `dispatch_trust_task_core`; it does not read the document. Parsing one \
             here is how a second dispatch path starts — first to read a field, then \
             to branch on it, and then with its own idea of validation, replay and \
             signing. If this is genuinely a pre-dispatch surface like \
             `routes/auth.rs`, add it to ALLOWED with the reason.",
            offenders.join("\n  ")
        );

        for (file, _) in ALLOWED {
            assert!(
                allowed_seen.contains(file),
                "`{file}` is allow-listed but no longer parses a document — remove \
                 the entry so the list shrinks"
            );
        }
    }

    #[test]
    fn the_spine_signs_every_response_it_returns() {
        let src = include_str!("mod.rs");
        let start = src
            .find("pub(crate) async fn dispatch_trust_task_core(")
            .expect("the spine is still named that");
        let body = &src[start..];
        let end = body.find("\n}\n").expect("the spine has an end");

        assert!(
            body[..end].contains("sign_success_response("),
            "the dispatch spine no longer signs its responses. 265 published \
             specifications require a proof on the response (SPEC §7.3 item 7). \
             `VtaClient` verifies one since #1341, so dropping this would break \
             every round-trip test — but it would break them by blaming the \
             reply, which is a long way from the cause."
        );
    }

    /// The wiring from state to signature: a configured agent signs, and one
    /// with no resident secret answers unsigned rather than failing.
    #[tokio::test]
    async fn the_signer_reads_the_agents_resident_key() {
        use affinidi_secrets_resolver::ThreadedSecretsResolver;
        use affinidi_tdk::secrets_resolver::SecretsResolver as _;

        let (mut state, _dir) = crate::test_support::build_signing_test_app_state().await;
        let outcome = || TrustTaskOutcome {
            status: axum::http::StatusCode::OK,
            body: br#"{"id":"urn:uuid:x","type":"https://example.org/t#response","payload":{}}"#
                .to_vec(),
        };

        // No resident secret: the answer still goes out, unsigned. Cleared
        // explicitly — this fixture ships one, which is worth knowing rather
        // than relying on.
        state.secrets_resolver = None;
        state.signing_vm_id = None;
        let unsigned = super::sign_success_response(&state, outcome()).await;
        let doc: Value = serde_json::from_slice(&unsigned.body).expect("parses");
        assert!(doc.get("proof").is_none());
        assert!(
            unsigned.status.is_success(),
            "an unsigned answer is still an answer"
        );

        // Configured: the same answer, signed by the named key.
        let secret = test_secret();
        let vm_id = secret.id.clone();
        let (resolver, _task) = ThreadedSecretsResolver::new(None).await;
        resolver.insert(secret).await;
        state.secrets_resolver = Some(std::sync::Arc::new(resolver));
        state.signing_vm_id = Some(vm_id.clone());

        let signed = super::sign_success_response(&state, outcome()).await;
        let doc: Value = serde_json::from_slice(&signed.body).expect("parses");
        assert_eq!(
            doc["proof"]["verificationMethod"].as_str(),
            Some(vm_id.as_str()),
            "signed by the wrong key, or not at all: {doc}"
        );
    }

    /// An Ed25519 `did:key` secret, which is what the agent's own signing key is
    /// on a `did:key` deployment and shaped the same everywhere else.
    fn test_secret() -> affinidi_secrets_resolver::secrets::Secret {
        use ed25519_dalek::SigningKey;
        let sk = SigningKey::from_bytes(&[7u8; 32]);
        let mut mc = vec![0xed, 0x01];
        mc.extend_from_slice(sk.verifying_key().as_bytes());
        let did = format!(
            "did:key:{}",
            multibase::encode(multibase::Base::Base58Btc, mc)
        );
        let secrets =
            vta_sdk::did_key::secrets_from_did_key(&did, &sk.to_bytes()).expect("did:key secrets");
        secrets.signing
    }

    /// The macro-generated `class_for` returns the authoritative §7.3
    /// classification declared inline next to each handler — the value the PDP
    /// feeds into PolicyInput, independent of the published registry. An
    /// unknown URI is unclassified so callers apply the fail-safe floor.
    #[test]
    #[allow(deprecated)]
    fn class_for_carries_authoritative_classification() {
        use crate::policy::{Discloses, SideEffectLevel};

        let release = class_for(vta_sdk::trust_tasks::TASK_VAULT_RELEASE_0_1)
            .expect("vault/release is classified");
        assert_eq!(release.side_effects, SideEffectLevel::Mutating);
        assert_eq!(release.exposure.discloses, Discloses::Secret);
        assert!(!release.exposure.acts_as_subject);

        let proxy = class_for(vta_sdk::trust_tasks::TASK_VAULT_PROXY_LOGIN_0_1)
            .expect("proxy-login is classified");
        assert!(
            proxy.exposure.acts_as_subject,
            "proxy-login acts as the subject"
        );

        let export = class_for(vta_sdk::trust_tasks::TASK_KEYS_EXPORT_SECRET_0_1)
            .expect("key export is classified");
        assert_eq!(
            export.exposure.discloses,
            Discloses::Secret,
            "releasing a key's private half discloses a secret"
        );
        assert_eq!(
            export.side_effects,
            SideEffectLevel::None,
            "it reads one key and changes nothing — the act is disclosure, not mutation"
        );

        assert!(
            class_for("https://trusttasks.org/spec/does-not-exist/9.9").is_none(),
            "an unknown URI is unclassified — caller applies the floor"
        );
    }

    #[test]
    fn body_parse_error_wire_shape() {
        let resp = body_parse_error_response("expected `,`");
        // Function returns; full HTTP-shape assertions live in the
        // Phase 5 integration tests once the route is reachable
        // through a real router setup.
        let _ = resp;
    }

    /// Pins the framework's current `TypeUri::from_str` constraint:
    /// the wire-format `type` field MUST use the canonical
    /// `/spec/<slug>/<major.minor>` shape. Flat URIs are rejected.
    ///
    /// If the framework parser relaxes (accepts both), the test fails
    /// on the flat-rejection assert and we know Phase 3 can simplify.
    #[test]
    fn framework_requires_canonical_uri_in_wire_type_field() {
        // Canonical form parses — with HIERARCHICAL slug
        // (`vta/auth/revoke-session`) per SPEC.md slug grammar.
        let canonical = serde_json::json!({
            "id": "urn:uuid:00000000-0000-0000-0000-000000000001",
            "type": "https://trusttasks.org/spec/auth/revoke-session/0.1",
            "issuer": "did:example:alice",
            "recipient": "did:example:vta",
            "issuedAt": chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
            "payload": { "session_id": "sess-1" }
        });
        let bytes = serde_json::to_vec(&canonical).unwrap();
        let parsed: Result<TrustTask<Value>, _> = serde_json::from_slice(&bytes);
        assert!(
            parsed.is_ok(),
            "canonical URI must parse: {:?}",
            parsed.err()
        );

        // Flat form is rejected.
        let flat = serde_json::json!({
            "id": "urn:uuid:00000000-0000-0000-0000-000000000001",
            "type": "https://trusttasks.org/vta/auth/revoke-session/1.0",
            "issuer": "did:example:alice",
            "recipient": "did:example:vta",
            "issuedAt": chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
            "payload": { "session_id": "sess-1" }
        });
        let bytes = serde_json::to_vec(&flat).unwrap();
        let parsed: Result<TrustTask<Value>, _> = serde_json::from_slice(&bytes);
        assert!(
            parsed.is_err(),
            "flat URI must NOT parse — if this changes, the framework \
             relaxed its parser and Phase 3 design can simplify"
        );
    }

    #[test]
    #[allow(deprecated)] // names the dual-accepted passkey-login 0.1 URIs on purpose
    fn phase_2_uri_registry_present() {
        // Compile-time check: every URI we route in `dispatch_typed`
        // is declared in `vta-sdk::trust_tasks`. If a URI gets renamed
        // or removed in vta-sdk, this stops compiling.
        let _ = vta_sdk::trust_tasks::TASK_AUTH_CHALLENGE_0_1;
        let _ = vta_sdk::trust_tasks::TASK_AUTH_AUTHENTICATE_0_1;
        let _ = vta_sdk::trust_tasks::TASK_AUTH_REFRESH_0_1;
        let _ = vta_sdk::trust_tasks::TASK_AUTH_REVOKE_SESSION_0_1;
        let _ = vta_sdk::trust_tasks::TASK_AUTH_WHOAMI_0_1;
        let _ = vta_sdk::trust_tasks::TASK_AUTH_SESSIONS_LIST_0_1;
        let _ = vta_sdk::trust_tasks::TASK_AUTH_PASSKEY_LOGIN_START_0_1;
        let _ = vta_sdk::trust_tasks::TASK_AUTH_PASSKEY_LOGIN_FINISH_0_1;
    }

    /// Cross-crate URI parity harness (mirrors webvh-service's T9
    /// invariant). Every URI declared in `vta-sdk::trust_tasks` must
    /// either:
    ///
    /// 1. Be tracked by `dispatched_uris()` (i.e. have a
    ///    [`dispatch_table!`] entry wiring its handler into `dispatch_typed`), OR
    /// 2. Be on the `REST_ROUTED` allowlist (served by dedicated
    ///    unauth REST handlers — passkey login, legacy challenge/
    ///    authenticate/refresh, TEE attestation), OR
    /// 3. Be on the `KNOWN_FEATURE_GATED_URIS` allowlist (feature-
    ///    flagged in vta-service and not compiled in this build).
    ///
    /// See `docs/05-design-notes/trust-task-feature-gating.md` for
    /// the full convention.
    ///
    /// Adding a new URI to `vta-sdk::trust_tasks::ALL_URIS` without
    /// doing one of these three fails this test loudly with the
    /// offending URI in the message.
    #[test]
    fn dispatcher_handles_every_vta_sdk_uri() {
        let dispatched = dispatched_uris();

        for declared in vta_sdk::trust_tasks::ALL_URIS {
            let in_dispatched = dispatched.contains(declared);
            let in_rest_routed = REST_ROUTED.contains(declared);
            let in_feature_gated = KNOWN_FEATURE_GATED_URIS.contains(declared);
            // 0.2 dual-accept URIs are served via the `wire_v0_2` edge
            // transform (down-convert → 0.1 handler → up-convert), not a
            // dedicated `dispatch_typed` arm, so they're tracked here.
            let in_wire_v0_2 = wire_v0_2::WIRE_V0_2_URIS.contains(declared);

            assert!(
                in_dispatched || in_rest_routed || in_feature_gated || in_wire_v0_2,
                "vta-sdk declares URI `{declared}` but it is not tracked in this dispatcher — \
                 either (a) add a `dispatch_table!` entry (`URI => slice::handler`), \
                 (b) add it to `REST_ROUTED` if it lives on a dedicated REST route, \
                 (c) add it to `KNOWN_FEATURE_GATED_URIS` with a comment explaining the gating, or \
                 (d) register it in `wire_v0_2::WIRE_V0_2_URIS` if it's an edge-transformed 0.2 URI"
            );
        }
    }

    /// Every `SUPERSEDED_TASKS` row must name a URI this spine dispatches.
    ///
    /// The table exists so a task can be retired on an observed zero, and the
    /// counter only moves when the spine sees the URI. A row for something the
    /// spine never routes — a REST-routed URI, a typo, a task already deleted —
    /// reads zero forever, which is precisely the "safe to delete" signal,
    /// produced about something that is already gone. That is the route-table
    /// defect from #1042 in the other half of the mechanism, and it is why the
    /// row and the handler have to be pinned to each other rather than each
    /// maintained by hand.
    ///
    /// Fixing a failure: if the task was retired, drop its row (the whole
    /// point of the row has been served). If the URI is a typo, correct it. If
    /// the operation is served by a dedicated REST route rather than the
    /// dispatcher, it belongs in `deprecation::SUPERSEDED` — the route table —
    /// not here.
    /// The schema index must be a declared dependency, not an inherited one.
    ///
    /// This workspace asks `trust-tasks-rs` for `default-features = false`. It
    /// received every spec family regardless, because a transitive dependency
    /// enables the default feature and cargo unions them — so the index that
    /// `validate_payload` and `spec_policy_for` both read arrived by luck.
    ///
    /// Both of those fail *open* when a spec is unknown: `validate_payload`
    /// dispatches unvalidated unless `require_payload_schema` is set, and
    /// `spec_policy_for` returning `None` skips SPEC §7.2 entirely. So the day
    /// that chain changed, this VTA would have quietly stopped checking
    /// payloads and stopped enforcing proof-REQUIRED, with one `debug!` line
    /// between it and nobody noticing.
    ///
    /// What this test does and does not prove, precisely: it fails when the
    /// index is empty, which is the outcome that matters. It cannot fail when
    /// the *declaration* is removed but the transitive path still supplies the
    /// families — cargo unions features, so the two are indistinguishable from
    /// inside the build. That is the right coverage anyway: an index populated
    /// by either route is a working VTA, and this fires on the day neither
    /// route supplies it.
    #[test]
    fn the_spec_index_is_populated() {
        for uri in [
            "https://trusttasks.org/spec/acl/grant/0.1",
            "https://trusttasks.org/spec/auth/authenticate/0.1",
            "https://trusttasks.org/spec/vault/list/0.3",
        ] {
            assert!(
                trust_tasks_rs::schema_index::schema_for(uri).is_some(),
                "no schema for `{uri}` — this build's `trust-tasks-rs` carries no spec \
                 families, so payload validation and SPEC §7.2 enforcement are both off"
            );
            assert!(
                trust_tasks_rs::schema_index::spec_policy_for(uri).is_some(),
                "no spec policy for `{uri}` — §7.2's recipient/proof/issuedAt checks \
                 cannot fire for it"
            );
        }
    }

    #[test]
    fn superseded_tasks_are_dispatched() {
        let dispatched = dispatched_uris();

        for task in crate::deprecation::superseded_tasks_table() {
            let served = dispatched.contains(&task.uri)
                // Feature-gated arms drop out of `dispatched_uris()` when their
                // cfg is off; the allowlist is where the parity harness tracks
                // them, so it is the right second source here too.
                || KNOWN_FEATURE_GATED_URIS.contains(&task.uri)
                // An edge-transformed URI never reaches the dispatch table —
                // it is rewritten to the canonical form first — but it is
                // served, and its counter does fire: `dispatch_trust_task_core`
                // reads the superseded row from the URI *as it arrived*,
                // before the down-convert. So the premise of this test (a row
                // whose counter can never move) does not apply to it. The
                // successor half of this pair already accepts them.
                || wire_v0_2::WIRE_V0_2_URIS.contains(&task.uri);
            assert!(
                served,
                "`{}` is marked superseded but nothing dispatches it, so its counter \
                 reads zero forever and would report the task as safe to retire when \
                 it has already been retired. Drop the row if the task is gone; fix \
                 the URI if it is a typo; move it to `deprecation::SUPERSEDED` if the \
                 operation is served by a REST route rather than this dispatcher.",
                task.uri
            );
        }
    }

    /// A successor must be something the client can actually send instead.
    ///
    /// A row pointing at a URI this VTA does not serve tells a client to
    /// migrate onto a 404 — worse than saying nothing, because the client acts
    /// on it. `REST_ROUTED` counts: the operation is reachable, just not
    /// through this dispatcher.
    #[test]
    fn superseded_task_successors_are_served() {
        let dispatched = dispatched_uris();

        for task in crate::deprecation::superseded_tasks_table() {
            let served = dispatched.contains(&task.successor)
                || KNOWN_FEATURE_GATED_URIS.contains(&task.successor)
                || REST_ROUTED.contains(&task.successor)
                || wire_v0_2::WIRE_V0_2_URIS.contains(&task.successor);
            assert!(
                served,
                "`{}` is advertised as the successor to `{}`, but this VTA does not \
                 serve it — the notice would send a migrating client onto an \
                 unsupported type",
                task.successor, task.uri
            );
        }
    }

    /// The two tables must agree.
    ///
    /// `wire_v0_2::WIRE_SPECS_V0_2` is where a spec is declared dual-accepted;
    /// `deprecation::SUPERSEDED_TASKS` is where the older form is declared on
    /// its way out. They are separate because only the second carries a reason
    /// and only the first carries the enum paths — but a newer form added
    /// without the matching deprecation row is a task nothing is measuring,
    /// which is the state #1045 exists to end. Adding one entry now requires
    /// the other.
    ///
    /// Checked per hop, not just for 0.1: a spec accepting 0.1, 0.2 and 0.3
    /// needs a row for each superseded version, or the middle one is retired
    /// on no evidence at all.
    #[test]
    fn every_dual_accepted_spec_marks_its_older_forms_superseded() {
        for spec in wire_v0_2::WIRE_SPECS_V0_2 {
            // Oldest first: the canonical form, then each wire form except the
            // newest, which is the one nothing supersedes yet.
            let mut chain = vec![spec.uri_0_1];
            chain.extend(spec.uris_wire.iter().rev());
            let newest = chain.pop().expect("a spec has at least one wire form");

            for superseded in chain {
                let row = crate::deprecation::superseded_task(superseded).unwrap_or_else(|| {
                    panic!(
                        "`{superseded}` is superseded (this spec also accepts \
                             `{newest}`) but it is not in \
                             `deprecation::SUPERSEDED_TASKS`, so nothing counts the \
                             callers still on it and it can never be retired on \
                             evidence"
                    )
                });
                assert!(
                    spec.uris_wire.contains(&row.successor),
                    "`{superseded}`'s deprecation row points at `{}`, which this \
                     spec does not accept on the wire",
                    row.successor
                );
            }
        }
    }

    /// Reverse parity harness (#854) — the opposite direction of
    /// [`dispatcher_handles_every_vta_sdk_uri`]. Every URI this service
    /// *serves* — dispatched, REST-routed, feature-gated, or accepted via the
    /// `wire_v0_2` edge transform — must resolve to a published spec in the
    /// Trust-Tasks registry, as vendored by the generated
    /// `trust_tasks_rs::schema_index` this build validates payloads against.
    ///
    /// A URI with no published spec is a live wire contract with no schema,
    /// no registry page, no generated bindings, and no discovery entry. The
    /// known ones are acknowledged per-URI in [`UNSPECCED_DISPATCHED_URIS`]
    /// with their disposition recorded in
    /// `docs/05-design-notes/registry-drift-triage.md`; anything else fails
    /// here, so NEW drift cannot land silently.
    ///
    /// The allowlist is also checked for staleness in both directions: an
    /// entry whose spec has since been published upstream must be removed
    /// (the debt shrinks monotonically), and an entry no longer served is
    /// dead and must be removed too.
    #[test]
    fn every_served_uri_has_a_published_spec_or_is_tracked_debt() {
        let mut served: std::collections::BTreeSet<&str> = dispatched_uris().into_iter().collect();
        served.extend(REST_ROUTED);
        served.extend(KNOWN_FEATURE_GATED_URIS);
        served.extend(wire_v0_2::WIRE_V0_2_URIS);

        let unspecced: Vec<&&str> = served
            .iter()
            .filter(|uri| {
                trust_tasks_rs::schema_index::schema_for(uri).is_none()
                    && !UNSPECCED_DISPATCHED_URIS.contains(uri)
            })
            .collect();
        assert!(
            unspecced.is_empty(),
            "this service serves URIs the published registry (trust-tasks-rs) \
             has no spec for, and they are not acknowledged in \
             UNSPECCED_DISPATCHED_URIS:\n  {}\n\n\
             Author the spec upstream in trustoverip/dtgwg-trust-tasks-tf and \
             bump trust-tasks-rs — growing the allowlist is the wrong fix \
             (see issue #854 and docs/05-design-notes/registry-drift-triage.md).",
            unspecced
                .iter()
                .map(|u| u.to_string())
                .collect::<Vec<_>>()
                .join("\n  ")
        );

        for uri in UNSPECCED_DISPATCHED_URIS {
            assert!(
                trust_tasks_rs::schema_index::schema_for(uri).is_none(),
                "`{uri}` is now published in the registry — remove it from \
                 UNSPECCED_DISPATCHED_URIS so the debt shrinks monotonically"
            );
            assert!(
                served.contains(uri),
                "`{uri}` is in UNSPECCED_DISPATCHED_URIS but this service no \
                 longer serves it — remove the stale entry"
            );
        }
    }

    /// Passkey-VMs: the canonical `…/0.1` URIs are dispatched. The pre-spec
    /// `…/1.0` aliases were removed (the browser plugin migrated to 0.1), so a
    /// 1.0 document now falls through to `UnsupportedType`.
    #[test]
    fn passkey_vms_0_1_dispatched() {
        let dispatched = dispatched_uris();
        let tracked = |u: &&str| dispatched.contains(u) || KNOWN_FEATURE_GATED_URIS.contains(u);
        for v0_1 in [
            vta_sdk::trust_tasks::TASK_PASSKEY_VMS_ENROLL_CHALLENGE_0_1,
            vta_sdk::trust_tasks::TASK_PASSKEY_VMS_ENROLL_SUBMIT_0_1,
            vta_sdk::trust_tasks::TASK_PASSKEY_VMS_LIST_0_1,
            vta_sdk::trust_tasks::TASK_PASSKEY_VMS_REVOKE_0_1,
        ] {
            assert!(tracked(&v0_1), "canonical 0.1 URI not dispatched: {v0_1}");
            assert!(v0_1.ends_with("/0.1"), "version-label mismatch for {v0_1}");
        }
    }

    /// The provisioning clients dispatch the version this service serves.
    ///
    /// This is the test that was missing when #1147 cut provision-integration
    /// over to 0.3. That change moved the server and the REST runner and left
    /// the TSP runner on 0.2 and the DIDComm runners on 0.1 — versions it had
    /// just *removed*, because 0.2 requires a bare-hex `digest` and forbids the
    /// `digestMultibase` 0.3 requires. Nothing failed in CI: each half was
    /// self-consistent, and the census tests below check that everything this
    /// service serves is specced, never that a client asks for it. Provisioning
    /// over TSP and DIDComm was dead from the release until an operator hit
    /// `unsupportedType` against a VTA that was otherwise healthy.
    ///
    /// `ProvisionSpecVersion::CURRENT` is now the single thing every client
    /// dispatch site reads, so this one assertion covers all of them: move the
    /// server to 0.4 without moving `CURRENT`, or the reverse, and this fails.
    #[test]
    fn provision_clients_dispatch_the_version_this_service_serves() {
        use vta_sdk::protocols::provision_integration_management::ProvisionSpecVersion;

        let uri = ProvisionSpecVersion::CURRENT.request_uri();
        let dispatched = dispatched_uris();
        assert!(
            dispatched.contains(&uri) || KNOWN_FEATURE_GATED_URIS.contains(&uri),
            "vta-sdk's provisioning clients dispatch `{uri}` \
             (`ProvisionSpecVersion::CURRENT`), but this service does not serve \
             it. A provision-integration version cut-over has to move both \
             halves: the `dispatch_table!` entry and `CURRENT`."
        );
    }

    /// Defensive guard against double-tracking. A URI should appear in
    /// exactly one of (`dispatched_uris()`, `REST_ROUTED`,
    /// `KNOWN_FEATURE_GATED_URIS`) — except that `KNOWN_FEATURE_GATED_URIS`
    /// redundantly mirrors a feature-gated `dispatch_table!` entry's URIs when
    /// the feature is on. That redundancy is allowed (the harness tolerates
    /// it); other overlaps would indicate confusion about which transport a URI
    /// uses.
    ///
    /// Specifically: a URI MUST NOT be in BOTH `dispatched_uris()`
    /// AND `REST_ROUTED`. That'd mean two handlers compete for it.
    #[test]
    fn no_uri_is_both_dispatched_and_rest_routed() {
        let dispatched = dispatched_uris();
        for uri in REST_ROUTED {
            assert!(
                !dispatched.contains(uri),
                "URI `{uri}` is in REST_ROUTED but also in a `dispatch_table!` entry — \
                 a URI must live on exactly one transport"
            );
        }
    }
}

#[cfg(all(test, feature = "webvh"))]
mod payload_validation_tests {
    //! Payload schema validation at the gate.
    //!
    //! The defect that put this here: a caller sent `expectedVersionId` — the
    //! optimistic-concurrency precondition — and the handler's type expected
    //! `expected_version_id`. Serde matched no field, nothing rejected the unknown
    //! member, and the precondition never applied. DID updates published with no
    //! lost-update protection, while the caller's own source read as though the
    //! danger were handled.
    //!
    //! The member was not *wrong*. It was **unrecognised**, and nothing was
    //! watching for that.

    use serde_json::{Value, json};
    use trust_tasks_rs::TrustTask;

    const WEBVH_UPDATE: &str = "https://trusttasks.org/spec/vta/webvh/dids/update/1.0";

    fn doc(payload: Value) -> TrustTask<Value> {
        serde_json::from_value(json!({
            "id": "urn:uuid:00000000-0000-0000-0000-000000000042",
            "type": WEBVH_UPDATE,
            "issuer": "did:key:zTestAdmin",
            "recipient": "did:example:vta",
            "issuedAt": chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
            "payload": payload,
        }))
        .expect("valid trust task")
    }

    /// The bug, pinned. A safety precondition in the wrong case is now REFUSED,
    /// where before it was silently dropped.
    #[tokio::test]
    async fn a_precondition_in_the_wrong_case_is_refused_not_ignored() {
        let (state, _dir) = crate::test_support::build_signing_test_app_state().await;
        let d = doc(json!({
            "did": "did:webvh:QmScid:example.com:acme",
            "expected_version_id": "3-QmPrior"
        }));

        let reject = super::validate_payload(&state, WEBVH_UPDATE, &d)
            .await
            .expect("an unrecognised member must be refused");

        let body: Value = serde_json::from_slice(&reject.body).unwrap();
        let msg = body.to_string();
        assert!(
            msg.contains("does not conform"),
            "expected a schema-conformance refusal, got: {msg}"
        );
    }

    /// The correct casing passes — the fix must refuse the typo without breaking
    /// the thing it was a typo of.
    #[tokio::test]
    async fn the_correct_casing_passes() {
        let (state, _dir) = crate::test_support::build_signing_test_app_state().await;
        let d = doc(json!({
            "did": "did:webvh:QmScid:example.com:acme",
            "document": { "id": "did:webvh:QmScid:example.com:acme" },
            "expectedVersionId": "3-QmPrior"
        }));
        assert!(
            super::validate_payload(&state, WEBVH_UPDATE, &d)
                .await
                .is_none()
        );
    }

    /// The relay stamps the browser-attested origin into `payload.ext`. A closed
    /// payload that refused the framework's own extension slot would break it.
    #[tokio::test]
    async fn the_ext_slot_the_relay_stamps_an_origin_into_is_permitted() {
        let (state, _dir) = crate::test_support::build_signing_test_app_state().await;
        let d = doc(json!({
            "did": "did:webvh:QmScid:example.com:acme",
            "ext": { "openvtc.origin": "https://control.example.com" }
        }));
        assert!(
            super::validate_payload(&state, WEBVH_UPDATE, &d)
                .await
                .is_none(),
            "closed payloads must still admit `ext`, or the relay cannot stamp an origin"
        );
    }

    /// The payload the CLI actually sends for a partial edit must validate.
    ///
    /// Built by **serialising the real wire type**, not by hand-writing the
    /// JSON. A literal here would only ever encode what the author believed
    /// the type emits, and the defect this pins was precisely a gap between
    /// those two: `UpdateDidWebvhBody` serialised every unset `Option` as an
    /// explicit `null`, and the schema types each member by what it holds —
    /// object, string, integer, array — with none of them nullable. So
    /// `pnm did-mgmt dids edit --label resync` was refused with one complaint
    /// per unset field, and no combination of flags helped: each one removed a
    /// single null and left the others.
    ///
    /// Every sibling body in `did_management` already skipped its `None`s.
    /// This one did not, which made the whole documented CLI edit path
    /// unusable over the trust-task transport.
    #[tokio::test]
    async fn a_partial_edit_from_the_cli_validates() {
        use vta_sdk::protocols::did_management::update::UpdateDidWebvhBody;

        let (state, _dir) = crate::test_support::build_signing_test_app_state().await;

        // `--label resync --no-confirm`, exactly as the CLI builds it.
        let body = UpdateDidWebvhBody {
            label: Some("resync".into()),
            ..Default::default()
        };
        let mut payload = serde_json::to_value(&body).expect("serialises");
        // `UpdateDidWithDid` flattens the body alongside `did`.
        payload
            .as_object_mut()
            .expect("object")
            .insert("did".into(), json!("did:webvh:QmScid:example.com:acme"));

        assert!(
            !payload.to_string().contains("null"),
            "the CLI's own payload must carry no nulls: {payload}"
        );

        let reject = super::validate_payload(&state, WEBVH_UPDATE, &doc(payload.clone())).await;
        assert!(
            reject.is_none(),
            "a label-only edit must validate, got: {:?}",
            reject.map(|r| String::from_utf8_lossy(&r.body).into_owned())
        );
    }

    /// The same payload with the nulls put back is refused — so the test above
    /// pins the serialisation rather than passing incidentally.
    #[tokio::test]
    async fn the_null_form_that_broke_the_cli_is_still_refused() {
        let (state, _dir) = crate::test_support::build_signing_test_app_state().await;
        let d = doc(json!({
            "did": "did:webvh:QmScid:example.com:acme",
            "document": Value::Null,
            "preRotationCount": Value::Null,
            "witnesses": Value::Null,
            "watchers": Value::Null,
            "ttl": Value::Null,
            "label": "resync",
            "expectedVersionId": Value::Null,
        }));
        assert!(
            super::validate_payload(&state, WEBVH_UPDATE, &d)
                .await
                .is_some(),
            "an explicit null is not a valid member value — if this passes, the \
             schema stopped typing its members and the fix above proves nothing"
        );
    }

    #[tokio::test]
    async fn an_invented_member_is_refused() {
        let (state, _dir) = crate::test_support::build_signing_test_app_state().await;
        let d = doc(json!({ "did": "did:webvh:x", "skipApproval": true }));
        assert!(
            super::validate_payload(&state, WEBVH_UPDATE, &d)
                .await
                .is_some()
        );
    }

    /// A task with no published spec dispatches unvalidated by default — many do —
    /// but an operator can choose to fail closed.
    #[tokio::test]
    async fn an_unspecced_task_proceeds_by_default_and_can_be_refused() {
        let (state, _dir) = crate::test_support::build_signing_test_app_state().await;
        // No published spec — one of the remaining few, and the set keeps
        // shrinking. This fixture named `vta/webvh/dids/create/1.0` until
        // trust-tasks #240 specified it and trust-tasks-rs 0.11 made the schema
        // resolvable, at which point the task validated and the fail-closed
        // half of this test stopped proving anything. That is the growth the
        // comment here has always pointed at, arriving.
        //
        // So the fixture is now *derived* rather than named: whatever is still
        // unspecced at run time. Naming one is what rotted twice, and the fix
        // both times was to name a different one — which only sets the next
        // failure. Deriving it means the test follows the debt down instead of
        // breaking each time a spec lands, and the assertion never weakens.
        let Some(unspecced) = super::UNSPECCED_DISPATCHED_URIS
            .iter()
            .copied()
            .find(|u| trust_tasks_rs::schema_index::schema_for(u).is_none())
        else {
            // Every dispatched task is specced. That is the goal, and when it
            // arrives this test has nothing left to say — delete it, and the
            // `require_payload_schema` escape hatch it exercises with it.
            return;
        };
        // Payload shape is irrelevant: the task is unvalidatable by definition,
        // which is the property under test.
        let d = doc(json!({}));

        assert!(
            super::validate_payload(&state, unspecced, &d)
                .await
                .is_none(),
            "by default an unvalidatable task still dispatches — refusing it would \
             break the many tasks that have no spec yet"
        );

        state.config.write().await.policy.require_payload_schema = true;
        assert!(
            super::validate_payload(&state, unspecced, &d)
                .await
                .is_some(),
            "an operator who would rather fail closed can"
        );
    }
}

#[cfg(test)]
mod superseded_task_dispatch_tests {
    //! The Trust-Task deprecation signal, end to end through the spine.
    //!
    //! `deprecation.rs` covers the table and the annotation in isolation. What
    //! those cannot show is that the spine *reaches* them — and a signal that
    //! is silently not attached reads exactly like "nobody sends this any
    //! more", which is the reading the whole mechanism exists to trust. That is
    //! why the REST half has `superseded_route_advertises_its_trust_task_successor`
    //! against a live router rather than a unit test of `superseded()`.

    use serde_json::{Value, json};

    use crate::deprecation::DEPRECATION_MEMBER;
    use crate::test_support::{build_signing_test_app_state, super_admin_claims};
    use crate::trust_tasks::transport::TransportConfidentiality;

    /// Dispatch `type_uri` with `payload` and return the response document.
    async fn dispatch(type_uri: &str, payload: Value) -> Value {
        let (state, _dir) = build_signing_test_app_state().await;
        let vta_did = state
            .config
            .read()
            .await
            .vta_did
            .clone()
            .expect("the signing test state configures a vta_did");
        let body = serde_json::to_vec(&json!({
            "id": format!("urn:uuid:{}", uuid::Uuid::new_v4()),
            "type": type_uri,
            "issuer": "did:key:zTestAdmin",
            "recipient": vta_did,
            "issuedAt": chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
            "payload": payload,
        }))
        .unwrap();

        let outcome = super::dispatch_trust_task_core(
            &state,
            &super_admin_claims(),
            &body,
            TransportConfidentiality::HopByHop,
        )
        .await;
        serde_json::from_slice(&outcome.body).expect("a response document")
    }

    #[tokio::test]
    #[allow(deprecated)] // sends a deprecated URI on purpose — that is the subject
    async fn a_superseded_task_names_its_successor_in_the_response() {
        let uri = vta_sdk::trust_tasks::TASK_DEVICE_LIST_0_1;
        let doc = dispatch(uri, json!({})).await;

        // Non-vacuity: a rejection document would also carry the notice (that
        // is deliberate — see the spine), but then this test would be
        // asserting nothing about the case that matters, which is a task that
        // still works and is on its way out.
        assert_eq!(
            doc["type"],
            format!("{uri}#response"),
            "expected a success response to annotate, got: {doc}"
        );

        let notice = &doc[DEPRECATION_MEMBER];
        assert_eq!(
            notice["supersededBy"],
            vta_sdk::trust_tasks::TASK_DEVICE_LIST_0_2,
            "the response must name what to send instead, so a client can act \
             rather than guess; got document: {doc}"
        );
        assert!(
            notice["reason"].as_str().is_some_and(|r| !r.is_empty()),
            "the notice must say why, got: {notice}"
        );
    }

    #[tokio::test]
    #[allow(deprecated)] // sends a deprecated URI on purpose — that is the subject
    async fn a_rejected_superseded_task_still_names_its_successor() {
        // A client whose request was refused is the client most in need of the
        // successor: it is about to retry, and it can retry onto the right URI.
        // `device/register/0.1` requires members an empty payload does not
        // carry, so this is a schema rejection, not a handler failure.
        let uri = vta_sdk::trust_tasks::TASK_DEVICE_REGISTER_0_1;
        let doc = dispatch(uri, json!({})).await;

        assert_eq!(
            doc["payload"]["code"], "malformedRequest",
            "expected a rejection to annotate, got: {doc}"
        );
        assert_eq!(
            doc[DEPRECATION_MEMBER]["supersededBy"],
            vta_sdk::trust_tasks::TASK_DEVICE_REGISTER_0_2,
            "a rejection must carry the successor too: {doc}"
        );
    }

    #[tokio::test]
    async fn a_current_task_carries_no_notice() {
        // The counterpart the route table learned to need: a signal attached to
        // everything is a signal about nothing. `auth/whoami/0.1` is current.
        let doc = dispatch(vta_sdk::trust_tasks::TASK_AUTH_WHOAMI_0_1, json!({})).await;
        assert!(
            doc.get(DEPRECATION_MEMBER).is_none(),
            "a task that is not superseded must not be advertised as one: {doc}"
        );
    }

    #[tokio::test]
    async fn the_payload_is_untouched_by_the_notice() {
        // The notice rides the document top level precisely so the payload
        // stays exactly what the spec says it is — every published payload
        // schema is `additionalProperties: false` and the generated `Response`
        // types are `deny_unknown_fields`. Assert it on a real dispatch, not
        // just on the annotation helper.
        #[allow(deprecated)]
        let uri = vta_sdk::trust_tasks::TASK_DEVICE_LIST_0_1;
        let doc = dispatch(uri, json!({})).await;

        let payload = doc.get("payload").expect("a response carries a payload");
        assert!(
            payload.get(DEPRECATION_MEMBER).is_none() && payload.get("ext").is_none(),
            "the notice must not reach the payload: {payload}"
        );
    }
}

/// Framework 0.5.0 Consumer Requirements item 13 — the freshness bounds.
#[cfg(test)]
mod freshness_bounds {
    use super::*;
    use chrono::{TimeDelta, Utc};
    use serde_json::json;

    fn doc(issued_at: Option<&str>, expires_at: Option<&str>) -> TrustTask<Value> {
        let mut v = json!({
            "id": "urn:uuid:11111111-1111-1111-1111-111111111111",
            "type": vta_sdk::trust_tasks::TASK_AUTH_WHOAMI_0_1,
            "issuer": "did:key:zTestAdmin",
            "payload": {},
        });
        // Previously always seeded a fresh default `issuedAt` here regardless
        // of this arg, so `doc(None, None)` never actually built a document
        // without one — see
        // `a_document_with_no_timestamps_is_malformed_not_expired`.
        if let Some(i) = issued_at {
            v["issuedAt"] = json!(i);
        }
        if let Some(e) = expires_at {
            v["expiresAt"] = json!(e);
        }
        serde_json::from_value(v).expect("a document")
    }

    #[test]
    fn a_document_inside_the_skew_window_is_accepted() {
        let now = Utc::now();
        let soon = (now + TimeDelta::seconds(30)).to_rfc3339();
        assert!(
            doc(Some(&soon), None)
                .validate_freshness(now, &freshness_policy())
                .is_ok(),
            "a modestly fast producer clock is the ordinary case, not a defect"
        );
    }

    #[test]
    fn a_future_dated_document_is_malformed_not_expired() {
        let now = Utc::now();
        let far = (now + TimeDelta::seconds(600)).to_rfc3339();
        let err = doc(Some(&far), None)
            .validate_freshness(now, &freshness_policy())
            .expect_err("beyond the skew tolerance must be refused");
        assert!(
            matches!(err, RejectReason::MalformedRequest { .. }),
            "it must be malformed, never expired: `expired` names a document \
             that was once acceptable and tells the producer to wait, when \
             what it must do is reissue. Got {err:?}"
        );
    }

    #[test]
    fn an_expiry_at_or_before_issuance_is_malformed() {
        let now = Utc::now();
        let issued = now.to_rfc3339();
        for expiry in [now, now - TimeDelta::seconds(1)] {
            let err = doc(Some(&issued), Some(&expiry.to_rfc3339()))
                .validate_freshness(now, &freshness_policy())
                .expect_err("a validity interval containing no instant is malformed");
            assert!(
                matches!(err, RejectReason::MalformedRequest { .. }),
                "got {err:?}"
            );
        }
    }

    /// A document carrying **no timestamp at all** is refused as
    /// `malformedRequest`, not `expired`. `doc(None, None)` previously always
    /// seeded a fresh default `issuedAt` regardless of the `None` argument, so
    /// this case went unexercised for as long as the helper existed.
    ///
    /// The code is what matters. `expired` names a document that was once
    /// acceptable and tells the producer to wait; this one was never
    /// acceptable, so waiting and reissuing the same shape loops forever.
    /// Under a bare `with_max_age` the answer here *is* `expired`
    /// (`Stale { Unboundable }`), and it arrives ~250 lines before
    /// `spec_policy_for(..).enforce(..)` could name the missing member — so
    /// the spec's own `issuedAt` rule was unreachable for every spec that
    /// declares it. Same principle as
    /// `a_future_dated_document_is_malformed_not_expired` above.
    #[test]
    fn a_document_with_no_timestamps_is_malformed_not_expired() {
        let err = doc(None, None)
            .validate_freshness(Utc::now(), &freshness_policy())
            .expect_err("an unbounded document cannot sit in a bounded window");
        assert!(
            matches!(
                &err,
                RejectReason::MalformedRequest { reason }
                    if reason == trust_tasks_rs::freshness::ISSUED_AT_REQUIRED
            ),
            "it must be malformed and must name the missing member, never \
             `expired`: a producer told to wait reissues the same unboundable \
             document and loops. Got {err:?}"
        );
    }

    /// An `expiresAt` alone bounds the *record*, which is why the library's
    /// default policy accepts it — but it does not bound this consumer's
    /// **acceptance window**, which is then whatever instant the producer
    /// chose. §7.2 makes the two one bound, so accepting it would let a
    /// producer decide unilaterally how long this VTA must remember its `id`.
    /// The difference between the two policies is the whole point of the test.
    #[test]
    fn an_expiry_alone_bounds_the_record_but_not_this_consumers_window() {
        let expires =
            (Utc::now() + TimeDelta::minutes(5)).to_rfc3339_opts(chrono::SecondsFormat::Secs, true);

        assert!(
            doc(None, Some(&expires))
                .validate_freshness(Utc::now(), &trust_tasks_rs::FreshnessPolicy::default())
                .is_ok(),
            "an `expiresAt` is enough to bound the record, so the library's \
             permissive default takes it"
        );

        let err = doc(None, Some(&expires))
            .validate_freshness(Utc::now(), &freshness_policy())
            .expect_err("this service runs a replay guard, so it needs the window too");
        assert!(
            matches!(err, RejectReason::MalformedRequest { .. }),
            "got {err:?}"
        );
    }

    /// The two properties every assertion above rests on, pinned against the
    /// service's own policy rather than a library default it never uses.
    /// Without this, deleting either from [`freshness_policy`] leaves the
    /// module still passing.
    #[test]
    fn the_services_policy_bounds_both_the_window_and_the_member() {
        let policy = freshness_policy();
        assert_eq!(
            policy.max_age,
            Some(TimeDelta::minutes(10)),
            "the acceptance window is also the replay record's retention \
             (SPEC §7.2); dropping it makes the guard's horizon load-dependent"
        );
        assert!(
            policy.require_issued_at,
            "without it a timestamp-less document is answered `expired`, and \
             the spec's own `issuedAt` rule further down the spine never runs"
        );
    }
}

/// SPEC §7.2 (*Bounding the record*) — the retention derived from the window.
#[cfg(test)]
mod record_retention {
    use super::*;
    use chrono::{SubsecRound, TimeDelta, Utc};
    use serde_json::json;

    /// The document's timestamps round-trip at second precision, so the
    /// instant compared against them has to sit on a second boundary too —
    /// otherwise every assertion here fails by a few hundred microseconds.
    fn now() -> chrono::DateTime<Utc> {
        Utc::now().trunc_subsecs(0)
    }

    fn doc(issued_at: chrono::DateTime<Utc>, expires_at: Option<&str>) -> TrustTask<Value> {
        let mut v = json!({
            "id": "urn:uuid:22222222-2222-2222-2222-222222222222",
            "type": vta_sdk::trust_tasks::TASK_AUTH_WHOAMI_0_1,
            "issuedAt": issued_at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
            "issuer": "did:key:zTestAdmin",
            "payload": {},
        });
        if let Some(e) = expires_at {
            v["expiresAt"] = json!(e);
        }
        serde_json::from_value(v).expect("a document")
    }

    /// A far-future `expiresAt` is the producer's to choose, and
    /// `record_expiry` returns it verbatim. The guard must not hold the record
    /// past the last instant the document could come back.
    #[test]
    fn a_far_future_expiry_does_not_pin_the_record_past_the_window() {
        let now = now();
        let far = (now + TimeDelta::days(3650)).to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
        let d = doc(now, Some(&far));

        let uncapped = freshness_policy()
            .record_expiry(&d, now)
            .expect("a bounded policy always yields one");
        assert!(
            uncapped > now + TimeDelta::days(3000),
            "precondition: the library takes the producer's `expiresAt` verbatim"
        );

        let capped = retain_until(&d, now).expect("a bounded policy always yields one");
        let window = now + TimeDelta::minutes(10) + trust_tasks_rs::DEFAULT_SKEW;
        assert_eq!(
            capped, window,
            "retention past the acceptance window is retention the guard can \
             never draw on, and it evicts records that are still needed"
        );
    }

    /// The cap must never move retention *earlier* than the window: a replay
    /// arriving while the document is still acceptable, with its record already
    /// dropped, executes a second time.
    #[test]
    fn a_near_expiry_is_left_alone() {
        let now = now();
        let soon = now + TimeDelta::minutes(2);
        let d = doc(
            now,
            Some(&soon.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)),
        );
        assert_eq!(
            retain_until(&d, now).expect("a bounded policy always yields one"),
            soon,
            "an expiry inside the window is the tighter bound and stands"
        );
    }

    /// With no `expiresAt` the retention is the window itself, unchanged by
    /// the cap.
    #[test]
    fn without_an_expiry_the_window_is_the_retention() {
        let now = now();
        assert_eq!(
            retain_until(&doc(now, None), now).expect("a bounded policy always yields one"),
            now + TimeDelta::minutes(10),
            "`issuedAt + max_age`, and the cap adds only the skew allowance"
        );
    }
}

/// SPEC §7.2 item 11 — the duplicate-execution record, as the dispatch spine
/// applies it.
#[cfg(test)]
mod replay_guard {
    use super::*;
    use serde_json::json;

    /// Dispatch a document verbatim, twice, and return both outcomes.
    async fn twice(payload: Value, type_uri: &str) -> (TrustTaskOutcome, TrustTaskOutcome) {
        let (state, _dir) = crate::test_support::build_signing_test_app_state().await;
        let vta_did = state.config.read().await.vta_did.clone().expect("vta_did");
        let body = serde_json::to_vec(&json!({
            "id": "urn:uuid:5eaf00d0-0000-4000-8000-00000000dead",
            "type": type_uri,
            "issuer": "did:key:zTestAdmin",
            "recipient": vta_did,
            "issuedAt": chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
            "payload": payload,
        }))
        .expect("envelope");

        let claims = crate::test_support::super_admin_claims();
        let first = super::dispatch_trust_task_core(
            &state,
            &claims,
            &body,
            transport::TransportConfidentiality::HopByHop,
        )
        .await;
        // The *same document*, delivered again. A mediator redelivery looks
        // exactly like this: identical framework document, fresh transport
        // envelope. Nothing about the transport is passed to the guard, which
        // is the point — SPEC §7.2 forbids substituting a transport identifier
        // for the document `id`, and keying on one would let a redelivery
        // straight through and execute twice.
        let second = super::dispatch_trust_task_core(
            &state,
            &claims,
            &body,
            transport::TransportConfidentiality::HopByHop,
        )
        .await;
        (first, second)
    }

    #[tokio::test]
    async fn a_redelivered_document_is_absorbed_not_executed_again() {
        // `contexts/list`: a read that needs no session row, so the test is
        // about the guard rather than about fixture setup.
        let (first, second) = twice(json!({}), vta_sdk::trust_tasks::TASK_CONTEXTS_LIST_1_0).await;
        assert!(
            first.status.is_success(),
            "the first delivery must run: {}",
            String::from_utf8_lossy(&first.body)
        );
        assert!(
            second.status.is_success(),
            "a duplicate is not a failure — §7.2 is explicit that it is never \
             reported as `taskFailed`, because the task did not fail, it \
             already happened"
        );
        // Answered with the first execution's result, not merely absorbed:
        // that is what `record_response` buys, and what a §8.4 retry needs.
        //
        // Compared as documents, not as bytes. `ReplayGuard::record_response`
        // takes an `Option<&Value>`, so a recorded response makes a round trip
        // through `serde_json::Value` and comes back with its object keys in
        // alphabetical order rather than the handler's insertion order. The
        // spine keeps `TrustTaskOutcome.body` as raw bytes precisely to avoid
        // that round trip on the *first* answer; a duplicate is the one path
        // where it is unavoidable, and it is harmless — every proof in this
        // framework is computed over JCS, which is itself key-ordered, so a
        // re-ordered document verifies identically.
        //
        // And compared **without the proof**, which is the part that made this
        // test flaky: `record_response` is called inside
        // `dispatch_trust_task_inner`, while `sign_success_response` runs in the
        // outer `dispatch_trust_task` — so the guard caches the *unsigned*
        // response and every delivery, first or duplicate, is signed afresh on
        // the way out. `proof.created` has one-second resolution, so two
        // signings that straddle a second produce two different proofs over the
        // same document and this assertion failed for a reason that had nothing
        // to do with the guard.
        //
        // Re-signing per delivery is the right behaviour, not a defect to work
        // around here: a replayed proof would carry a `created` drifting further
        // into the past on every retry, and §7.2 item 11 asks for the prior
        // *response*, which is the payload. So the payload is what is compared,
        // and that both answers are signed at all is asserted separately —
        // dropping the proof from the comparison must not quietly become
        // "nobody checks there is one".
        let (mut a, mut b): (Value, Value) = (
            serde_json::from_slice(&first.body).expect("first body"),
            serde_json::from_slice(&second.body).expect("second body"),
        );
        for doc in [&mut a, &mut b] {
            let proof = doc
                .as_object_mut()
                .expect("a response is an object")
                .remove("proof");
            assert!(
                proof.is_some(),
                "every response this spine returns carries a proof, duplicate or not"
            );
        }
        assert_eq!(
            a, b,
            "the duplicate must be answered with the prior response"
        );
    }

    /// A *different* document under an already-spent `id` is a conflict, not a
    /// retry. This is the case the retired `replay::check_and_record` could not
    /// see at all: it kept no digest, so it absorbed this silently — the one
    /// outcome §7.2 item 11 and §8.4 both rule out.
    #[tokio::test]
    async fn a_different_document_under_the_same_id_is_an_id_conflict() {
        let (state, _dir) = crate::test_support::build_signing_test_app_state().await;
        let vta_did = state.config.read().await.vta_did.clone().expect("vta_did");
        let claims = crate::test_support::super_admin_claims();
        let envelope = |issued: &str| {
            serde_json::to_vec(&json!({
                "id": "urn:uuid:5eaf00d0-0000-4000-8000-0000000c0nf1",
                "type": vta_sdk::trust_tasks::TASK_CONTEXTS_LIST_1_0,
                "issuedAt": chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
                "issuer": "did:key:zTestAdmin",
                "recipient": vta_did,
                // Differing only here is deliberate and is exactly §8.4's
                // example: "a producer that 'retries' by re-signing,
                // re-stamping `issuedAt`, or otherwise altering the bytes has
                // not retried — it has issued a different document under a
                // reused `id`".
                "issuedAt": issued,
                "payload": {},
            }))
            .expect("envelope")
        };

        let first = super::dispatch_trust_task_core(
            &state,
            &claims,
            &envelope(&chrono::Utc::now().to_rfc3339()),
            transport::TransportConfidentiality::HopByHop,
        )
        .await;
        assert!(first.status.is_success());

        let second = super::dispatch_trust_task_core(
            &state,
            &claims,
            &envelope(&(chrono::Utc::now() - chrono::TimeDelta::seconds(5)).to_rfc3339()),
            transport::TransportConfidentiality::HopByHop,
        )
        .await;
        let doc: Value = serde_json::from_slice(&second.body).expect("a response document");
        assert_eq!(
            doc["payload"]["code"], "idConflict",
            "a different document under a spent id must be refused, not \
             absorbed as a retry: {doc}"
        );
    }
}

/// Exercise the happy path of tasks the suite otherwise never reaches.
///
/// These are not tests of handler *logic* — every arm has that in its owning
/// operations module. They exist so the response-conformance gate in
/// `test_support::response_conformance` gets to look at each task's real
/// success response at all.
///
/// The gap they close is the one `scripts/trust-task-coverage.sh` measures: the
/// gate was validating 29 of 109 checkable tasks, and the seventy-odd it had
/// never seen included the signing oracle. A gate that has never observed
/// `keys/sign` is not evidence about `keys/sign`.
///
/// Each test asserts a success document came back and lets the layer do the
/// schema work — a violation replaces the response, so the `type` assertion
/// below is what fails when a shape drifts.
#[cfg(test)]
mod response_coverage {
    use super::*;
    use base64::Engine;
    use serde_json::json;
    use vta_sdk::trust_tasks as t;

    use crate::test_support::build_signing_test_app_state;

    /// Serialise a signed super-admin document, ready for
    /// `dispatch_trust_task_core`.
    ///
    /// Every test here needs the same three things the spine now enforces — an
    /// in-band `recipient`, an `issuedAt`, and a `proof` from the same identity
    /// the claims carry — so they are built in one place rather than seven.
    pub(super) fn signed_body(uri: &str, vta_did: &str, payload: Value) -> Vec<u8> {
        let mut doc: TrustTask<Value> = serde_json::from_value(json!({
            "id": format!("urn:uuid:{}", uuid::Uuid::new_v4()),
            "type": uri,
            "issuer": crate::test_support::test_admin_did().0,
            "recipient": vta_did,
            "issuedAt": chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
            "payload": payload,
        }))
        .expect("envelope deserialises");
        crate::test_support::sign_as_test_admin(&mut doc);
        serde_json::to_vec(&doc).expect("envelope serialises")
    }

    /// Dispatch as a super-admin and require a success document back.
    ///
    /// Returns the response `payload` so a test can chain (e.g. take a key id
    /// out of `keys/create` and sign with it).
    async fn ok(state: &crate::server::AppState, uri: &str, payload: Value) -> Value {
        let vta_did = state.config.read().await.vta_did.clone().expect("vta_did");
        let body = signed_body(uri, &vta_did, payload);

        let outcome = super::dispatch_trust_task_core(
            state,
            &crate::test_support::super_admin_claims(),
            &body,
            transport::TransportConfidentiality::HopByHop,
        )
        .await;
        let doc: Value = serde_json::from_slice(&outcome.body).expect("a response document");
        assert_eq!(
            doc["type"],
            format!("{uri}#response"),
            "expected a success response from {uri}, got: {doc}"
        );
        doc["payload"].clone()
    }

    /// [`ok`], but on a transport that is confidential end to end.
    ///
    /// `keys/import` refuses a cleartext `privateKeyMultibase` on anything less
    /// — TLS terminates wherever the operator terminates it, so the key would
    /// exist in plaintext there. DIDComm authcrypt and TSP do not, and this is
    /// how a test says it is one of those.
    async fn ok_e2e(state: &crate::server::AppState, uri: &str, payload: Value) -> Value {
        let vta_did = state.config.read().await.vta_did.clone().expect("vta_did");
        let body = signed_body(uri, &vta_did, payload);
        let outcome = super::dispatch_trust_task_core(
            state,
            &crate::test_support::super_admin_claims(),
            &body,
            transport::TransportConfidentiality::EndToEnd,
        )
        .await;
        let doc: Value = serde_json::from_slice(&outcome.body).expect("a response document");
        assert_eq!(
            doc["type"],
            format!("{uri}#response"),
            "expected a success response from {uri}, got: {doc}"
        );
        doc["payload"].clone()
    }

    /// Mint a key and return its id, so the read/sign/rename paths have a real
    /// subject rather than the VTA's own signing key (which they must not
    /// rename or revoke).
    async fn a_key(state: &crate::server::AppState, label: &str) -> String {
        let p = ok(
            state,
            t::TASK_KEYS_CREATE_0_1,
            json!({ "keyType": "ed25519", "derivationPath": "m/26'/2'/0'/0'", "label": label }),
        )
        .await;
        p["key"]["keyId"]
            .as_str()
            .or_else(|| p["keyId"].as_str())
            .unwrap_or_else(|| panic!("keys/create must name the key it made: {p}"))
            .to_owned()
    }

    /// A context to hang scoped state off. Also covers
    /// `vta/contexts/create/1.0`.
    async fn a_context(state: &crate::server::AppState, id: &str) {
        ok(
            state,
            t::TASK_CONTEXTS_CREATE_1_0,
            json!({ "id": id, "name": id }),
        )
        .await;
    }

    // The `device/*` family is deliberately NOT covered here. It looks cheap —
    // register, heartbeat, set-wake, disable — and it is not: `device/register`
    // refuses a DID that is not already in the ACL ("complete
    // provision-integration + acl/swap-key first"), so every path behind it
    // needs a provisioned integration rather than a seeded row. That belongs
    // with the provision-integration tests.

    /// `all: true` is a legal document, refused as unsupported — not malformed.
    ///
    /// `auth/revoke-session/0.1` is `sessionId` **XOR** `all`. This VTA
    /// implements only the named-session arm, and its request type used to
    /// require `sessionId`, so a conforming client sending `{"all": true}` got
    /// `malformedRequest` — which tells the client its *shape* is wrong when
    /// the shape was fine. An unimplemented option deserves to be named.
    #[tokio::test]
    async fn revoke_all_is_refused_as_unsupported_not_malformed() {
        let (state, _dir) = build_signing_test_app_state().await;
        let vta_did = state.config.read().await.vta_did.clone().expect("vta_did");
        let body = signed_body(
            t::TASK_AUTH_REVOKE_SESSION_0_1,
            &vta_did,
            json!({ "all": true }),
        );
        let outcome = super::dispatch_trust_task_core(
            &state,
            &crate::test_support::super_admin_claims(),
            &body,
            transport::TransportConfidentiality::HopByHop,
        )
        .await;
        let doc: Value = serde_json::from_slice(&outcome.body).expect("a response document");
        assert_eq!(
            doc["payload"]["code"], "taskFailed",
            "a legal document must not be called malformed: {doc}"
        );
        assert!(
            doc["payload"]["message"]
                .as_str()
                .is_some_and(|m| m.contains("revoke_all_unsupported")),
            "the refusal must name the option it cannot honour: {doc}"
        );
    }

    /// Signing paths that derive a key rather than naming a stored one, plus
    /// the two liveness/session tasks that need no fixture at all.
    #[tokio::test]
    async fn derive_and_sign_ping_and_revoke_session() {
        let (state, _dir) = build_signing_test_app_state().await;
        let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(b"coverage");

        // Derive-and-sign never stores the key: it derives, signs and discards,
        // so there is no `keys/create` to pair it with.
        ok(
            &state,
            t::TASK_KEYS_DERIVE_AND_SIGN_0_1,
            json!({
                "keyType": "ed25519",
                "derivationPath": "m/26'/2'/0'/7'",
                "payload": payload,
                "algorithm": "EdDSA",
            }),
        )
        .await;

        ok(&state, t::TASK_MESSAGING_PING_0_1, json!({})).await;
        // `auth/revoke-session` is not covered for a success response: it needs
        // a real session row, and `all: true` is a legal document this VTA
        // refuses by design (it revokes one named session). The refusal path is
        // asserted in `revoke_all_is_refused_as_unsupported_not_malformed`.
    }

    /// Issue then revoke, chained: revoke needs an id only an issue produces.
    #[tokio::test]
    async fn credentials_issue_then_revoke() {
        let (state, _dir) = build_signing_test_app_state().await;
        let issued = ok(
            &state,
            t::TASK_VTA_CREDENTIALS_ISSUE_0_2,
            json!({
                "holder": "did:key:z6MkCoverageHolder",
                "claims": { "role": "coverage" },
                "validitySeconds": 3600,
            }),
        )
        .await;
        let id = issued["credentialId"]
            .as_str()
            .or_else(|| issued["credential"]["id"].as_str())
            .unwrap_or_else(|| panic!("issue must name the credential: {issued}"))
            .to_owned();
        ok(
            &state,
            t::TASK_VTA_CREDENTIALS_REVOKE_0_1,
            json!({ "credentialId": id, "reason": "coverage" }),
        )
        .await;
    }

    /// A context's DID can be repointed after creation.
    #[tokio::test]
    async fn contexts_update_did() {
        let (state, _dir) = build_signing_test_app_state().await;
        a_context(&state, "cov-update-did").await;
        ok(
            &state,
            t::TASK_CONTEXTS_UPDATE_DID_1_0,
            json!({ "id": "cov-update-did", "did": "did:key:z6MkCovContextDid" }),
        )
        .await;
    }

    /// A swap with no `linkProof` names the policy, rather than calling a
    /// well-formed document malformed.
    ///
    /// `acl/swap-key/0.1` makes `linkProof` optional — "required by some
    /// maintainers … Producers omit this when the consumer's policy doesn't
    /// require it." This deployment requires it, which is exactly the split the
    /// specification describes; what was wrong was the answer. A producer that
    /// omitted it got `malformedRequest`, sending it to re-read a schema that
    /// would agree with it.
    ///
    /// The success path is not covered: it needs a real VP-JWT signed by the
    /// new subject, and `currentSubject` must equal the authenticated caller,
    /// so it wants a second keypair and a signing ceremony.
    #[tokio::test]
    async fn swap_key_without_a_link_proof_names_the_policy() {
        let (state, _dir) = build_signing_test_app_state().await;
        let claims = crate::test_support::super_admin_claims();
        let vta_did = state.config.read().await.vta_did.clone().expect("vta_did");
        let body = signed_body(
            t::TASK_ACL_SWAP_KEY_0_1,
            &vta_did,
            json!({
                "currentSubject": claims.did,
                "newSubject": "did:key:z6MkCovNewSubject",
            }),
        );
        let outcome = super::dispatch_trust_task_core(
            &state,
            &claims,
            &body,
            transport::TransportConfidentiality::HopByHop,
        )
        .await;
        let doc: Value = serde_json::from_slice(&outcome.body).expect("a response document");
        assert_eq!(
            doc["payload"]["code"], "taskFailed",
            "a document the schema accepts must not be called malformed: {doc}"
        );
        assert!(
            doc["payload"]["message"]
                .as_str()
                .is_some_and(|m| m.contains("link_proof_required")),
            "the refusal must name what this maintainer wants: {doc}"
        );
    }

    /// The device family.
    ///
    /// `device/register` refuses a DID that holds no ACL entry
    /// ("noPendingEnrolment — complete provision-integration + acl/swap-key
    /// first"), which reads as though the whole family needs a provisioned
    /// integration. It needs one *row*: the entry is the enrolment the device
    /// is completing, and seeding it is what a swapped-in long-term key leaves
    /// behind.
    #[tokio::test]
    async fn device_lifecycle() {
        let (state, _dir) = build_signing_test_app_state().await;
        let claims = crate::test_support::super_admin_claims();
        crate::test_support::seed_acl_entry(
            &state.acl_ks,
            &claims.did,
            crate::acl::Role::Admin,
            vec![],
        )
        .await;

        ok(
            &state,
            t::TASK_DEVICE_REGISTER_0_2,
            json!({
                "consumerKind": { "kind": "companion", "formFactor": "mobile" },
                "displayName": "Coverage Phone",
            }),
        )
        .await;
        ok(&state, t::TASK_DEVICE_HEARTBEAT_0_2, json!({})).await;
        ok(&state, t::TASK_DEVICE_SET_WAKE_0_2, json!({})).await;
    }

    /// SPEC §7.2 item 7, first clause: "If the document carries a `proof`
    /// member, verify it per §4.7 against the in-band `issuer` and reject the
    /// document with `proofInvalid` on verification failure."
    #[tokio::test]
    async fn a_proof_that_does_not_verify_is_refused() {
        let (state, _dir) = build_signing_test_app_state().await;
        let vta_did = state.config.read().await.vta_did.clone().expect("vta_did");

        // Signed by a *different* identity than the one it claims as issuer.
        let mut doc: TrustTask<Value> = serde_json::from_value(json!({
            "id": format!("urn:uuid:{}", uuid::Uuid::new_v4()),
            "type": t::TASK_AUTH_WHOAMI_0_1,
            "issuer": crate::test_support::test_admin_did().0,
            "recipient": vta_did,
            "issuedAt": chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
            "payload": {},
        }))
        .expect("envelope");
        crate::test_support::sign_as(0xEE, &mut doc);

        let outcome = super::dispatch_trust_task_core(
            &state,
            &crate::test_support::super_admin_claims(),
            &serde_json::to_vec(&doc).expect("bytes"),
            transport::TransportConfidentiality::HopByHop,
        )
        .await;
        let v: Value = serde_json::from_slice(&outcome.body).expect("a response");
        assert_eq!(
            v["payload"]["code"], "proofInvalid",
            "a proof from a key the issuer does not control must be refused: {v}"
        );
    }

    /// The same family at its **canonical** 0.1 URIs, plus the two ends of the
    /// lifecycle that have no 0.2 form.
    ///
    /// Not a duplicate of the 0.2 walk above. A 0.2 request is down-converted
    /// to the 0.1 handler and its response up-converted back, so driving 0.2
    /// never produces a `…/0.1#response` and never exercises the branch that
    /// answers a caller who asked in the canonical form. Those are two
    /// different paths through the spine, and only one of them was tested.
    ///
    /// Its own `AppState` because `device/register` refuses a second binding
    /// for the same DID, and both walks register as the super-admin.
    // Names the deprecated 0.1 URIs on purpose: they are what this test exists
    // to cover, and they are still dispatched.
    #[allow(deprecated)]
    #[tokio::test]
    async fn device_lifecycle_canonical() {
        let (state, _dir) = build_signing_test_app_state().await;
        let claims = crate::test_support::super_admin_claims();
        crate::test_support::seed_acl_entry(
            &state.acl_ks,
            &claims.did,
            crate::acl::Role::Admin,
            vec![],
        )
        .await;

        let registered = ok(
            &state,
            t::TASK_DEVICE_REGISTER_0_1,
            json!({
                // `formFactor`, not `form-factor`: the 0.1 → 0.2 difference is
                // in the enum *values*, never the member names, and the edge
                // transform only ever rewrites values at declared enum paths.
                "consumerKind": { "kind": "companion", "formFactor": "mobile" },
                "displayName": "Coverage Phone (canonical)",
            }),
        )
        .await;
        // The id the rest of the lifecycle is addressed by. Read from the
        // response rather than minted here: the VTA assigns it, and a test that
        // guesses would pass against a VTA that had stopped returning one.
        let device_id = registered["binding"]["deviceId"]
            .as_str()
            .expect("register returns the binding's deviceId")
            .to_string();

        ok(&state, t::TASK_DEVICE_HEARTBEAT_0_1, json!({})).await;
        ok(&state, t::TASK_DEVICE_SET_WAKE_0_1, json!({})).await;

        // Wipe before disable: a wipe instruction is issued *to* a device, and
        // a disabled one has nothing to collect it. The operator's order.
        ok(
            &state,
            t::TASK_DEVICE_WIPE_0_1,
            json!({
                "deviceId": device_id,
                "scope": "cache-and-keys",
                "reason": "coverage",
            }),
        )
        .await;
        ok(
            &state,
            t::TASK_DEVICE_DISABLE_0_1,
            json!({ "deviceId": device_id, "reason": "coverage" }),
        )
        .await;
    }

    /// `keys/import` and `keys/derive-and-sign-document`.
    ///
    /// Import needs a transport that is confidential end to end; the cleartext
    /// key carrier is refused on anything less, and that refusal is already
    /// covered in `tests/api_integration.rs`. This is the other side of it.
    #[tokio::test]
    async fn keys_import_and_derive_and_sign() {
        let (state, _dir) = build_signing_test_app_state().await;

        // A real Ed25519 seed, multibase-encoded — the form the handler decodes.
        let seed = [0x5Au8; 32];
        ok_e2e(
            &state,
            t::TASK_KEYS_IMPORT_0_1,
            json!({
                "keyType": "ed25519",
                "privateKeyMultibase": multibase::encode(multibase::Base::Base58Btc, seed),
                "label": "imported",
            }),
        )
        .await;

        // Derive-and-sign takes a document rather than a key id: the key is
        // derived on the spot from the path, signed with, and not persisted.
        ok(
            &state,
            t::TASK_KEYS_DERIVE_AND_SIGN_DOCUMENT_0_1,
            json!({
                "keyType": "ed25519",
                "derivationPath": "m/26'/9'/0'",
                "document": {
                    "type": "https://trusttasks.org/spec/auth/authenticate/0.1",
                    "payload": { "challenge": "abc", "sessionId": "s1" },
                },
            }),
        )
        .await;
    }

    /// Seed a vault entry with its secret already in place.
    ///
    /// `vault/upsert` refuses a *create* with no `sealedSecret` — every
    /// `secretKind` needs one — and sealing takes an HPKE envelope addressed to
    /// this VTA. An *update* does not: it carries the stored secret forward.
    /// Seeding the create is what lets the rest of the family be driven without
    /// standing up the envelope machinery, which `tests/vault_unseal_authcrypt`
    /// already covers on its own terms.
    async fn a_vault_entry(state: &crate::server::AppState, id: &str, context_id: &str) -> String {
        use vti_common::vault::{
            SecretKind, SiteTarget, StoredVaultEntry, VaultEntry, VaultSecret, VaultStatus,
            put_stored_vault_entry,
        };
        let now = "2026-01-01T00:00:00Z".to_string();
        let entry = StoredVaultEntry {
            entry: VaultEntry {
                id: id.to_string(),
                context_id: context_id.to_string(),
                targets: vec![SiteTarget::WebOrigin {
                    origin: "https://example.com".to_string(),
                }],
                label: "Coverage entry".to_string(),
                secret_kind: SecretKind::Password,
                tags: Vec::new(),
                notes: None,
                favicon: None,
                selectors: Vec::new(),
                custom_field_names: Vec::new(),
                attachments: Vec::new(),
                expires_at: None,
                breached_at: None,
                password_changed_at: None,
                created_at: now.clone(),
                created_by: None,
                updated_at: now,
                updated_by: None,
                last_used_at: None,
                version: 1,
                principal_did: None,
                status: VaultStatus::Active,
                archived_at: None,
                deleted_at: None,
                grace_until: None,
            },
            secret: VaultSecret::Password {
                username: Some("alice".to_string()),
                password: "hunter2-very-secret".to_string(),
                totp: None,
                login_config: None,
                secure_notes: None,
                custom_fields: Vec::new(),
            },
        };
        put_stored_vault_entry(&state.vault_ks, &entry)
            .await
            .expect("seed the vault entry");
        id.to_string()
    }

    /// The vault write and release paths.
    // Names the deprecated 0.1 URI on purpose: it is the canonical form this
    // covers, and it is still dispatched.
    #[allow(deprecated)]
    #[tokio::test]
    async fn vault_entry_lifecycle() {
        let (state, _dir) = build_signing_test_app_state().await;
        a_context(&state, "vault-ctx").await;
        let entry_id = a_vault_entry(&state, "vault-cov-1", "vault-ctx").await;

        // An update: `sealedSecret` omitted, so the stored secret carries
        // forward. A create with none is refused, and correctly.
        ok(
            &state,
            t::TASK_VAULT_UPSERT_0_1,
            json!({
                "id": entry_id,
                "contextId": "vault-ctx",
                "targets": [{ "kind": "web-origin", "origin": "https://example.com" }],
                "label": "Coverage entry (renamed)",
                "secretKind": "password",
            }),
        )
        .await;

        // `release`, `proxy-login` and `sign-trust-task` are deliberately not
        // here. Each seals its answer into a DIDComm envelope addressed to the
        // caller, so covering their success path means being a real DIDComm
        // client with keys the mediator knows — `MockVta::start_with_transports`
        // and its embedded mediator, not this in-process fixture. An offline
        // ATM gets as far as packing and no further.
    }

    /// `acl/swap-key` — the self-service key rotation.
    ///
    /// The `linkProof` is a real VP-JWT built by the SDK's own producer, signed
    /// by the *new* DID and audience-bound to this VTA. A transcribed fixture
    /// would prove someone can type a JWT; this proves the two sides agree.
    #[tokio::test]
    async fn acl_swap_key_rotates_the_callers_own_entry() {
        use ed25519_dalek::SigningKey;

        let (state, _dir) = build_signing_test_app_state().await;
        let claims = crate::test_support::super_admin_claims();
        crate::test_support::seed_acl_entry(
            &state.acl_ks,
            &claims.did,
            crate::acl::Role::Admin,
            vec![],
        )
        .await;
        let vta_did = state.config.read().await.vta_did.clone().expect("vta_did");

        // The DID being rotated *to*, and the key that proves control of it.
        let new_sk = SigningKey::from_bytes(&[0xD1; 32]);
        let (new_did, _vm) = crate::test_support::did_for_seed(0xD1);
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        let link_proof = vta_sdk::protocols::acl_management::swap::build_swap_presentation(
            &new_sk, &new_did, &vta_did, now, 300, None,
        );

        ok(
            &state,
            t::TASK_ACL_SWAP_KEY_0_1,
            json!({
                // Must equal the authenticated caller: the operation exists so a
                // holder can rotate *its own* entry, never someone else's.
                "currentSubject": claims.did,
                "newSubject": new_did,
                "linkProof": link_proof,
            }),
        )
        .await;
    }

    /// `services/drain/cancel` — call off a drain before its deadline.
    ///
    /// Needs an active drain to cancel, which is a registry record rather than
    /// a live mediator: `record_drain_persisted` is what the drain path itself
    /// writes, so seeding through it is the same state a real drain leaves.
    #[tokio::test]
    async fn services_drain_cancel() {
        let (state, _dir) = build_signing_test_app_state().await;
        let mediator_did = "did:key:z6MkDrainedMediator";
        state
            .mediator_registry
            .record_drain_persisted(
                &state.drains_ks,
                mediator_did,
                "wss://drained.example".into(),
                chrono::Utc::now() + chrono::Duration::minutes(30),
            )
            .await
            .expect("seed an active drain");

        ok(
            &state,
            t::TASK_SERVICES_DRAIN_CANCEL_1_0,
            json!({ "mediatorDid": mediator_did }),
        )
        .await;
    }

    /// `credential-exchange/pending/approve` — answer a deferral the holder can
    /// satisfy.
    ///
    /// The refusal path (nothing held matches the query) is covered in
    /// `tests/pending_presentation_trust_task.rs`. This is the other side, and
    /// it needs two things that fixture cannot give it: a credential the DCQL
    /// query matches, and a holder key this VTA manages — presenting means
    /// signing as the holder.
    ///
    /// The credential is minted and received rather than written straight into
    /// storage. The DCQL match runs off the index the receive path builds, so a
    /// hand-written row would exercise a different lookup than production does.
    #[tokio::test]
    async fn pending_approve_presents_a_held_credential() {
        use crate::operations::credential_exchange::pending::{
            PendingPresentation, put as put_pending,
        };

        const VCT: &str = "https://openvtc.org/credentials/MembershipCredential";

        let (state, _dir) = build_signing_test_app_state().await;

        // A holder key, not the VTA's signing identity: presenting means
        // signing *as the subject*, and `resolve_holder_keys` looks the subject
        // up in the keys keyspace. Using `vta_did` here is refused with
        // "holder key … is not managed by this VTA", correctly.
        let holder = crate::test_support::seed_holder_key(&state, "m/26'/2'/0'/0'", None).await;
        let credential_id =
            crate::test_support::seed_held_credential(&state.vault_ks, VCT, "givenName", &holder)
                .await;

        let record: PendingPresentation = serde_json::from_value(json!({
            "id": "cov-pending-1",
            "verifier_did": "did:web:stranger.example",
            // The *real* stored id, not a placeholder. The consent is built by
            // mapping the requested claims onto the matched credential, so an
            // id that matches nothing yields an empty reveal set — which the
            // operation refuses as authorizing nothing.
            "requested": [{
                "credential_query_id": "membership",
                "credential_id": credential_id,
                "claims": ["givenName"]
            }],
            "purpose": "coverage",
            "query": {
                "dcql_query": {
                    "credentials": [{
                        "id": "membership",
                        "format": "dc+sd-jwt",
                        "meta": { "vct_values": [VCT] },
                        // The reveal set comes from the *query's* claim paths,
                        // not from `requested` — a query that names no claims
                        // discloses nothing, and the operation refuses an empty
                        // reveal set as authorizing nothing.
                        "claims": [{ "path": ["givenName"] }]
                    }]
                },
                "nonce": "n-1",
                "purpose": "coverage"
            },
            "status": "pending",
            "created_at": "2026-06-12T00:00:00Z",
            "expires_at": "2126-06-12T00:00:00Z"
        }))
        .expect("pending record deserialises");
        put_pending(&state.vault_ks, &record)
            .await
            .expect("seed the deferral");

        ok(
            &state,
            vta_sdk::protocols::credential_exchange::PENDING_APPROVE,
            json!({ "id": "cov-pending-1" }),
        )
        .await;
    }

    /// The runtime service-management read paths.
    ///
    /// Only the reads: `enable`/`update`/`disable`/`rollback` publish a new
    /// WebVH LogEntry and run a live DIDComm handshake against the running
    /// service, so their success path needs the mediator-backed harness rather
    /// than this fixture. Covering the reads is what the gate can see today.
    #[tokio::test]
    async fn services_read_paths() {
        let (state, _dir) = build_signing_test_app_state().await;
        ok(&state, t::TASK_SERVICES_LIST_1_0, json!({})).await;
        ok(
            &state,
            t::TASK_SERVICES_GET_1_0,
            json!({ "service": "rest" }),
        )
        .await;
        // Drain is DIDComm-only and empty here; an empty list is still a
        // response shape, and an empty one is the shape most likely to be got
        // wrong (`[]` against absent).
        ok(&state, t::TASK_SERVICES_DRAIN_LIST_1_0, json!({})).await;
    }

    /// The webvh read paths that need no hosting server.
    ///
    /// `dids/{create,delete,register-with-server,rotate-keys}`, every
    /// `servers/*` task, and — less obviously — every `agent-name/*` task
    /// reach out to or require a hosting server, so their success paths belong
    /// with the stub-host tests rather than here.
    #[tokio::test]
    async fn webvh_read_paths() {
        let (state, _dir) = build_signing_test_app_state().await;

        // Seed a webvh record. Agent names are keyed on one, and the VTA's own
        // `did:key` is not — it is a self-resolving signing identity, not a
        // hosted DID. Seeding also makes `dids/list` answer with content rather
        // than an empty array, which is the more interesting response shape.
        let did = "did:webvh:example.com:coverage";
        let record = vta_sdk::webvh::WebvhDidRecord {
            did: did.to_string(),
            server_id: "serverless".into(),
            mnemonic: "coverage-slot".into(),
            scid: "scid-coverage".into(),
            context_id: "cov-webvh".into(),
            portable: false,
            log_entry_count: 1,
            pre_rotation_count: 0,
            next_fragment_id: 1,
            created_at: chrono::Utc::now(),
            updated_at: chrono::Utc::now(),
        };
        crate::webvh_store::store_did(&state.webvh_ks, &record)
            .await
            .expect("seed the webvh record");

        ok(&state, t::TASK_WEBVH_DIDS_LIST_1_0, json!({})).await;

        // `agent-name/*` is deliberately NOT covered here, and the reason is
        // not obvious: the names are local records, but every one of those
        // tasks refuses a **serverless** DID ("agent names require a hosted
        // DID"). A seeded record is serverless unless a hosting server is
        // registered, so covering them means standing up the stub host — which
        // is where the rest of the webvh write paths already live.
        let _ = did;
    }

    /// The DID-template family: the operator surface that every
    /// provision-integration flow renders from.
    #[tokio::test]
    async fn did_templates_lifecycle() {
        let (state, _dir) = build_signing_test_app_state().await;
        a_context(&state, "cov-templates").await;

        // A minimal template. `document` is the DID-document shape with
        // `{TOKEN}` placeholders the renderer fills; `requiredVars` is what the
        // renderer will insist on, so keeping it to one keeps `render` honest
        // without making the fixture about template authoring.
        let template = json!({
            "schemaVersion": 1,
            "name": "cov-template",
            "kind": "app",
            "requiredVars": ["LABEL"],
            // `document.id` must be the `{DID}` placeholder: the renderer
            // fills it with the DID it mints, and a template that hardcoded an
            // id would mint every integration the same identity.
            "document": {
                "id": "{DID}",
                "service": [{ "id": "#cov", "type": "VTARest", "serviceEndpoint": "{LABEL}" }],
            },
        });

        ok(
            &state,
            t::TASK_DID_TEMPLATES_CREATE_2_0,
            json!({ "contextId": "cov-templates", "template": template }),
        )
        .await;
        ok(
            &state,
            t::TASK_DID_TEMPLATES_LIST_2_0,
            json!({ "contextId": "cov-templates" }),
        )
        .await;
        ok(
            &state,
            t::TASK_DID_TEMPLATES_GET_2_0,
            json!({ "contextId": "cov-templates", "name": "cov-template" }),
        )
        .await;

        let mut updated = template.clone();
        updated["description"] = json!("renamed");
        ok(
            &state,
            t::TASK_DID_TEMPLATES_UPDATE_2_0,
            json!({ "contextId": "cov-templates", "name": "cov-template", "template": updated }),
        )
        .await;
        ok(
            &state,
            t::TASK_DID_TEMPLATES_RENDER_2_0,
            json!({
                "contextId": "cov-templates",
                "name": "cov-template",
                // `DID` is a reserved var, not a template bug: `create`
                // requires `document.id` to be the `{DID}` placeholder, and the
                // caller supplies the minted DID at render time.
                "vars": { "LABEL": "https://cov.example", "DID": "did:key:z6MkCovRender" },
            }),
        )
        .await;
        ok(
            &state,
            t::TASK_DID_TEMPLATES_DELETE_2_0,
            json!({ "contextId": "cov-templates", "name": "cov-template" }),
        )
        .await;
    }

    /// The policy family. `upsert` is `0.2` and `get`/`delete` are `0.1`, which
    /// is why they are covered together rather than by version.
    #[tokio::test]
    async fn policy_lifecycle() {
        let (state, _dir) = build_signing_test_app_state().await;
        a_context(&state, "cov-policy").await;

        let created = ok(
            &state,
            t::TASK_POLICY_UPSERT_0_2,
            json!({
                "name": "cov-policy",
                // The smallest Rego module that loads: a package and one rule.
                "module": "package vta.cov\n\ndefault allow := false\n",
            }),
        )
        .await;
        let id = created["policy"]["id"]
            .as_str()
            .or_else(|| created["id"].as_str())
            .unwrap_or_else(|| panic!("upsert must name the policy it stored: {created}"))
            .to_owned();

        ok(&state, t::TASK_POLICY_LIST_0_2, json!({})).await;
        ok(&state, t::TASK_POLICY_GET_0_1, json!({ "id": id })).await;
        ok(
            &state,
            t::TASK_POLICY_DELETE_0_1,
            json!({ "id": id, "reason": "coverage" }),
        )
        .await;
    }

    /// The context family's read and write paths.
    #[tokio::test]
    async fn contexts_lifecycle() {
        let (state, _dir) = build_signing_test_app_state().await;
        a_context(&state, "cov-contexts").await;
        ok(&state, t::TASK_CONTEXTS_LIST_1_0, json!({})).await;
        ok(
            &state,
            t::TASK_CONTEXTS_GET_1_0,
            json!({ "id": "cov-contexts" }),
        )
        .await;
        ok(
            &state,
            t::TASK_CONTEXTS_UPDATE_1_0,
            json!({ "id": "cov-contexts", "name": "renamed" }),
        )
        .await;
        // A sub-context, so the preview below actually emits `subContexts`.
        //
        // Without one the member is empty, `skip_serializing_if` keeps it off
        // the wire, and the response gate validates a document that never
        // carries the thing this coverage is here to check. A member that is
        // only ever absent is not covered by a test that passes.
        ok(
            &state,
            t::TASK_CONTEXTS_CREATE_1_0,
            json!({ "id": "sub", "name": "sub", "parent": "cov-contexts" }),
        )
        .await;
        // Preview before delete: the pair exists so an operator can see what a
        // delete would take with it, so cover them in that order.
        let preview = ok(
            &state,
            t::TASK_CONTEXTS_PREVIEW_DELETE_1_0,
            json!({ "id": "cov-contexts" }),
        )
        .await;
        // The gate above validated this document against the published
        // schema. That is only evidence about `subContexts` if `subContexts`
        // was in it — an omitted member validates perfectly against a schema
        // that has never heard of it, which is exactly how a response gate
        // reports a route as conforming while telling you nothing.
        assert_eq!(
            preview["subContexts"],
            json!(["cov-contexts/sub"]),
            "the preview must name the subtree on the wire, camelCase: {preview}"
        );
        // `force`, because the subtree is no longer empty — which is the
        // refusal the preview above exists to warn about.
        ok(
            &state,
            t::TASK_CONTEXTS_DELETE_1_0,
            json!({ "id": "cov-contexts", "force": true }),
        )
        .await;
    }

    /// `vta/contexts/delete:notEmpty` reaches the wire.
    ///
    /// The specification requires a conforming consumer to answer this code
    /// when a context still holds something and `force` is absent. It answered
    /// the framework's `malformedRequest` instead — which says the request was
    /// wrong, when it was well-formed, understood, and refused for what the
    /// context holds. A consumer could separate the two only by matching on
    /// English.
    ///
    /// Asserted on the emitted document, not on the operations layer: the
    /// refusal being typed internally is not evidence that anything puts the
    /// declared code on the wire.
    #[tokio::test]
    async fn a_delete_without_force_answers_not_empty_on_the_wire() {
        let (state, _dir) = build_signing_test_app_state().await;
        a_context(&state, "cov-notempty").await;
        ok(
            &state,
            t::TASK_CONTEXTS_CREATE_1_0,
            json!({ "id": "sub", "name": "sub", "parent": "cov-notempty" }),
        )
        .await;

        let vta_did = state.config.read().await.vta_did.clone().expect("vta_did");
        let body = signed_body(
            t::TASK_CONTEXTS_DELETE_1_0,
            &vta_did,
            json!({ "id": "cov-notempty" }),
        );
        let outcome = super::dispatch_trust_task_core(
            &state,
            &crate::test_support::super_admin_claims(),
            &body,
            transport::TransportConfidentiality::HopByHop,
        )
        .await;
        let doc: Value = serde_json::from_slice(&outcome.body).expect("a response document");

        assert_eq!(
            doc["payload"]["code"], "vta/contexts/delete:notEmpty",
            "the specification names this code for this refusal: {doc}"
        );
        // The counts, so a consumer decides without parsing the message.
        assert_eq!(doc["payload"]["details"]["subContexts"], 1, "{doc}");

        // And the refusal left the subtree alone.
        let still = ok(
            &state,
            t::TASK_CONTEXTS_GET_1_0,
            json!({ "id": "cov-notempty/sub" }),
        )
        .await;
        assert_eq!(still["id"], "cov-notempty/sub");
    }

    /// Every id-taking task in the contexts family answers its own
    /// `<task>:notFound`, and says nothing about whether the id exists.
    ///
    /// The family declares eight extended codes and emitted none of them:
    /// an unreachable id rode out as the framework's `taskFailed` (or, for an
    /// id outside the caller's scope, `permissionDenied` — which is the leak,
    /// not merely the wrong code). `vta/contexts/get` states the requirement
    /// plainly: "deliberately does not distinguish 'does not exist' from
    /// 'exists but not yours'".
    ///
    /// Asserted per task, because the code is per task: one handler emitting
    /// the right slug says nothing about the other four.
    #[tokio::test]
    async fn every_contexts_task_answers_its_own_not_found() {
        let (state, _dir) = build_signing_test_app_state().await;
        let vta_did = state.config.read().await.vta_did.clone().expect("vta_did");

        // A real context the caller is not scoped to, and an id that does not
        // exist. Both must come back identical.
        a_context(&state, "cov-real").await;

        let scoped = crate::test_support::admin_claims_for_context("cov-other");

        for (uri, slug, payload) in [
            (
                t::TASK_CONTEXTS_GET_1_0,
                "vta/contexts/get",
                json!({ "id": "PLACEHOLDER" }),
            ),
            (
                t::TASK_CONTEXTS_UPDATE_DID_1_0,
                "vta/contexts/update-did",
                json!({ "id": "PLACEHOLDER", "did": "did:key:z6MkTest" }),
            ),
            (
                t::TASK_CONTEXTS_PREVIEW_DELETE_1_0,
                "vta/contexts/preview-delete",
                json!({ "id": "PLACEHOLDER" }),
            ),
            (
                t::TASK_CONTEXTS_DELETE_1_0,
                "vta/contexts/delete",
                json!({ "id": "PLACEHOLDER", "force": true }),
            ),
        ] {
            let mut codes = Vec::new();
            for id in ["cov-real", "cov-ghost"] {
                let mut p = payload.clone();
                p["id"] = json!(id);
                let body = signed_body(uri, &vta_did, p);
                let outcome = super::dispatch_trust_task_core(
                    &state,
                    &scoped,
                    &body,
                    transport::TransportConfidentiality::HopByHop,
                )
                .await;
                let doc: Value =
                    serde_json::from_slice(&outcome.body).expect("a response document");
                assert_eq!(
                    doc["payload"]["code"],
                    json!(format!("{slug}:notFound")),
                    "{uri} must answer its own notFound for `{id}`: {doc}"
                );
                codes.push(doc["payload"]["message"].clone());
            }
            // The real id and the absent one are answered identically — the
            // property the code exists for, not just the code itself.
            assert_eq!(
                codes[0], codes[1],
                "{uri} distinguishes a real id from an absent one, which is the leak"
            );
        }
    }

    /// The app-state key/value family, single and batch.
    #[tokio::test]
    async fn app_state_lifecycle() {
        let (state, _dir) = build_signing_test_app_state().await;
        a_context(&state, "cov-appstate").await;
        let base = json!({ "contextId": "cov-appstate", "namespace": "cov", "key": "k1" });

        let mut put = base.clone();
        put["value"] = json!({ "hello": "world" });
        ok(&state, t::TASK_VTA_APP_STATE_PUT_1_0, put).await;
        ok(&state, t::TASK_VTA_APP_STATE_GET_1_0, base.clone()).await;
        ok(
            &state,
            t::TASK_VTA_APP_STATE_LIST_1_0,
            json!({ "contextId": "cov-appstate", "includeValues": true }),
        )
        .await;
        ok(
            &state,
            t::TASK_VTA_APP_STATE_PUT_MANY_1_0,
            json!({
                "contextId": "cov-appstate",
                "namespace": "cov",
                // `writes`, not `entries` — and each write is a put payload
                // minus the context and namespace the batch supplies.
                "writes": [{ "key": "k2", "value": {"n": 1} }],
            }),
        )
        .await;
        ok(
            &state,
            t::TASK_VTA_APP_STATE_GET_MANY_1_0,
            json!({ "contextId": "cov-appstate", "namespace": "cov", "keys": ["k1", "k2"] }),
        )
        .await;
        ok(&state, t::TASK_VTA_APP_STATE_DELETE_1_0, base).await;
    }

    /// The agent-memory family.
    #[tokio::test]
    async fn memory_lifecycle() {
        let (state, _dir) = build_signing_test_app_state().await;
        a_context(&state, "cov-memory").await;
        ok(
            &state,
            t::TASK_VTA_MEMORY_PUT_0_1,
            json!({ "contextId": "cov-memory", "key": "m1", "value": "remembered" }),
        )
        .await;
        ok(
            &state,
            t::TASK_VTA_MEMORY_LIST_0_1,
            json!({ "contextId": "cov-memory" }),
        )
        .await;
        ok(
            &state,
            t::TASK_VTA_MEMORY_DELETE_0_1,
            json!({ "contextId": "cov-memory", "key": "m1" }),
        )
        .await;
    }

    #[tokio::test]
    async fn keys_show_and_sign() {
        let (state, _dir) = build_signing_test_app_state().await;
        let key_id = a_key(&state, "coverage-show-sign").await;

        ok(&state, t::TASK_KEYS_SHOW_0_1, json!({ "keyId": key_id })).await;

        // The signing oracle. `payload` is base64url without padding, and the
        // maintainer signs those bytes verbatim.
        let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(b"coverage");
        ok(
            &state,
            t::TASK_KEYS_SIGN_0_1,
            json!({ "keyId": key_id, "payload": payload, "algorithm": "EdDSA" }),
        )
        .await;
    }

    /// An internal key is actually internal.
    ///
    /// This is the assertion whose absence let `pnm keys create --internal`
    /// lie. The CLI prints a non-recoverable-key warning, requires the operator
    /// to type "i understand this key cannot be recovered", and then called a
    /// client that built its wire body with `internal: None` hardcoded — so the
    /// operator was handed an ordinary seed-derived key that *is* in backups
    /// and *is* exportable, believing the opposite.
    ///
    /// It could not have worked even if the client had forwarded the flag:
    /// `keys/create/0.1` was `additionalProperties: false` with no `internal`
    /// member, so the dispatch spine rejected the document. The capability
    /// existed at both ends and was unreachable over the wire, which is what
    /// dtgwg-trust-tasks-tf#269 fixed.
    ///
    /// `origin` is the check that matters, and it is the one the CLI already
    /// makes: a maintainer that ignored the member returns `derived`, and that
    /// difference is the only reliable signal the request was honoured.
    #[tokio::test]
    async fn an_internal_key_is_actually_internal() {
        let (state, _dir) = build_signing_test_app_state().await;
        let p = ok(
            &state,
            t::TASK_KEYS_CREATE_0_1,
            // `keyId` is supplied by the caller now, as `keys/create/0.1`
            // publishes it. An internal key has no derivation path to be named
            // after, so this is the only name it can have.
            json!({
                "keyType": "ed25519",
                "internal": true,
                "keyId": "cov-unexportable",
                "label": "unexportable",
            }),
        )
        .await;
        let record = p.get("key").unwrap_or(&p);
        assert_eq!(
            record["keyId"], "cov-unexportable",
            "the caller's `keyId` must be honoured, not replaced: {p}"
        );
        assert_eq!(
            record["origin"], "internal",
            "the key must come back marked internal — a `derived` here is \
             exactly the silent downgrade the operator was warned about and \
             did not get: {p}"
        );
        // An internal key derives from no seed, and the shared `KeyRecord`
        // component says `derivationPath` is the path "the key was derived at,
        // when `origin` is `derived`", absent otherwise. This service instead
        // records the sentinel string `"internal"`, with a comment saying it
        // "names the origin instead, so a reader cannot mistake it for
        // something re-derivable" — reasoning that predates `origin` gaining
        // an `internal` value (dtgwg-trust-tasks-tf#269), which now carries
        // that fact properly.
        //
        // Asserted as-is rather than fixed here: making `KeyRecord`'s
        // `derivation_path` an `Option` touches 84 construction sites and is
        // its own change. Worth knowing that the response-conformance gate
        // cannot catch this — the schema types the member `string`, so a
        // sentinel validates cleanly. It is a semantic divergence, and only a
        // reader notices.
        assert_eq!(
            record["derivationPath"], "internal",
            "the sentinel is the current behaviour; when `derivationPath` \
             becomes optional this should assert absence instead: {p}"
        );
    }

    /// A create with no `derivationPath` succeeds.
    ///
    /// The spec says "omitting it leaves the choice to the custodian", and the
    /// operation layer has always auto-derived from the context. Only the wire
    /// type disagreed, so a conforming client that omitted it got
    /// `malformedRequest` — and the SDK hid that by sending `""`.
    #[tokio::test]
    async fn a_create_without_a_derivation_path_succeeds() {
        let (state, _dir) = build_signing_test_app_state().await;
        // The context has to exist: with no path *and* no context there is
        // nothing for the custodian to derive from, which the operation layer
        // refuses on its own terms. Creating it also covers
        // `vta/contexts/create/1.0`.
        ok(
            &state,
            t::TASK_CONTEXTS_CREATE_1_0,
            json!({ "id": "coverage-ctx", "name": "Coverage" }),
        )
        .await;
        ok(
            &state,
            t::TASK_KEYS_CREATE_0_1,
            json!({ "keyType": "ed25519", "contextId": "coverage-ctx" }),
        )
        .await;
    }

    #[tokio::test]
    async fn keys_rename_then_revoke() {
        let (state, _dir) = build_signing_test_app_state().await;
        let key_id = a_key(&state, "coverage-rename").await;

        // `newKeyId` is an identifier, not a path — `/` is rejected, and the
        // key id defaults to the derivation path, so it cannot be reused here.
        let renamed = "coverage-renamed-key".to_string();
        ok(
            &state,
            t::TASK_KEYS_RENAME_0_1,
            json!({ "keyId": key_id, "newKeyId": renamed }),
        )
        .await;

        // Revoke last: it is terminal, and revoking under the new id also
        // proves the rename took on the record rather than only in the reply.
        ok(
            &state,
            t::TASK_KEYS_REVOKE_0_1,
            json!({ "keyId": renamed, "reason": "coverage" }),
        )
        .await;
    }
}