openvtc-core 0.5.0

OpenVTC Core Library
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
//! The whole exchange between an applicant and a vetter, message by message,
//! through the same [`super::inbound::handle`] the TUI's dispatch calls.
//!
//! Each party keeps its own book and account; the only thing that passes
//! between them is a DIDComm `Message`, built and signed the way the client
//! sends it. Nothing here touches a network: every DID is a `did:key`.

use affinidi_data_integrity::{DataIntegrityProof, SignOptions};
use affinidi_tdk::didcomm::Message;
use affinidi_tdk::secrets_resolver::secrets::Secret;
use chrono::{Duration, Utc};
use dtg_credentials::DTGCredential;
use serde_json::{Value, json};
use trust_tasks_rs::TrustTask;
use uuid::Uuid;
use vta_sdk::protocols::join_requests::manifest;

/// The `manifest/0.2` `#response` type a pre-0.3 community answers with;
/// `vta-sdk` 0.63 dropped its constant when it moved to `manifest/0.3`.
const JOIN_REQUEST_MANIFEST_0_2_RESPONSE_TYPE: &str =
    <manifest::v0_2::Response as trust_tasks_rs::Payload>::TYPE_URI;
use vta_sdk::protocols::vetting::{
    VETTED_PREDICATE, VETTER_ROLE, VETTING_DECLINE_TYPE, VETTING_REQUEST_ERR_INVALID_TICKET,
    VETTING_REQUEST_ERR_NOT_ELIGIBLE, VETTING_REQUEST_TYPE, VETTING_SESSION_TYPE,
    VETTING_VETTER_PROFILE_ERR_NOT_ELIGIBLE, VETTING_VETTER_RESEND_ERR_NOT_GRANTED, VettingMethod,
    VettingRelationship, VettingRequirements, decline, request, revoke_statement, session, vetters,
};
use vta_sdk::trust_task_proof::TrustTaskVmResolver;
use vta_sdk::vetting::card::sign_card;
use vta_sdk::vetting::statement::sign_statement;
use vta_sdk::vetting::status::StatusCheck;

use super::VettingBook;
use super::applicant::{
    ApplicantError, Application, ChosenFace, GrantStatus, NextStep, RequestDraft, RequestState,
    TicketUriError, VetterEligibility,
};
use super::book::{Knowledge, VetterPolicy};
use super::inbound::{Context, Handled, Notice, Reply, handle};
use super::queries::{CommunityAnswer, CommunityQuery, QueryKind};
use super::registry::{ProfileDraft, ProfileState};
use super::tickets::{DEFAULT_VALIDITY, Ticket};
use super::vetter::{Attestation, DeskState};
use super::wire::{
    self,
    tests::{did, secret},
};
use crate::config::account::{Account, CommunityRecord, PersonaId};
use crate::persona::disclosure::ReleasedClaim;

/// The community is a `did:key` too, so the role credentials it signs verify
/// offline. [`the_community_is_its_key`] holds the two together.
const COMMUNITY: &str = "did:key:z6MkkckEJvRiDoUSv2KFGPFuUoNjJbWTZUvWThqshF7g1u4p";
const COMMUNITY_SEED: u8 = 0xC0;
/// A `requirementsDigest` the published criterion accepts: base58btc, at least
/// 16 characters.
const DIGEST: &str = "zQmbWqxBEKC3P8tqsKc98xmWNzrzDtRLMiMPL8wBuTGsMnR";

/// A listing request with no filters at all.
fn unfiltered_list() -> vetters::list::v0_1::Payload {
    vetters::list::v0_1::Payload::try_from(vetters::list::v0_1::Payload::builder()).unwrap()
}

/// A spoken ticket in the published form — upper-case Crockford base32.
fn code_ticket(code: &str) -> request::v0_1::Ticket {
    request::v0_1::Ticket::ShortCodeTicket(
        request::v0_1::ShortCodeTicket::try_from(
            request::v0_1::ShortCodeTicket::builder().code(code),
        )
        .expect("a Crockford code"),
    )
}

/// A credential-issue's credential, verified as the dispatcher's off-loop job
/// verifies it; `None` for any other message.
async fn verified_delivery(
    message: &Message,
    sender: &str,
    resolver: &affinidi_did_resolver_cache_sdk::DIDCacheClient,
) -> Option<
    Result<
        crate::issued_credential::VerifiedIssuedCredential,
        crate::issued_credential::IssuedCredentialError,
    >,
> {
    if message.typ != vta_sdk::protocols::credential_exchange::ISSUE {
        return None;
    }
    crate::messaging::credential_in_issue(message)?;
    Some(
        crate::issued_credential::verify_issued_delivery(
            &message.body,
            sender,
            resolver,
            Utc::now(),
        )
        .await,
    )
}

/// A DID resolver. Every DID here is a `did:key`, which resolves locally.
async fn did_resolver() -> affinidi_did_resolver_cache_sdk::DIDCacheClient {
    affinidi_did_resolver_cache_sdk::DIDCacheClient::new(
        affinidi_did_resolver_cache_sdk::config::DIDCacheConfigBuilder::default().build(),
    )
    .await
    .expect("a DID resolver")
}

#[test]
fn the_community_is_its_key() {
    assert_eq!(did(&secret(COMMUNITY_SEED)), COMMUNITY);
}

/// A community role credential — a VAC conferring `role:<role>` in
/// `community`'s scope, `issuerScope` public, `maxAttenuation` 0 — signed by
/// `issuer`. `issuer` other than `community` is a forgery: authority in a scope
/// the signer does not govern.
fn role_vac(issuer: &Secret, community: &str, subject: &str, role: &str) -> DTGCredential {
    let now = Utc::now();
    DTGCredential::new_vac(
        did(issuer),
        dtg_credentials::IssuerScope::Public,
        subject.to_string(),
        community.to_string(),
        vec![vta_sdk::protocols::vetting::role_action(role)],
        now - chrono::Duration::minutes(1),
        now + chrono::Duration::days(365),
    )
    .unwrap()
    .with_max_attenuation(0)
    .unwrap()
    .with_id(wire::new_id())
}

/// A community role credential, signed by `issuer`.
async fn role_credential(issuer: &Secret, community: &str, subject: &str, role: &str) -> Value {
    let mut credential = role_vac(issuer, community, subject, role);
    credential.sign(issuer, None).await.unwrap();
    serde_json::to_value(&credential).unwrap()
}

/// `credential-exchange/issue` from `from`, as a community delivers.
/// `credential-exchange/issue` as a community pushes it: a Trust Task document
/// signed by `issuer` under `authentication`.
async fn delivery(credential: &Value, issuer: &Secret) -> Message {
    let document: TrustTask<Value> = serde_json::from_value(json!({
        "id": format!("urn:uuid:{}", wire::new_id()),
        "type": vta_sdk::protocols::credential_exchange::ISSUE,
        "issuer": did(issuer),
        "recipient": "did:key:zTheMember",
        "issuedAt": Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
        "payload": { "credential_response": { "credential": credential } },
    }))
    .expect("an issue document");
    signed(document, issuer).await
}

/// Sign a reply the way `wire::send_reply` does: presentation first.
async fn signed_reply(reply: Reply, signer: &Secret) -> Message {
    let mut document = reply.document;
    if let Some(eligibility) = reply.eligibility {
        wire::attach_eligibility(&mut document, signer, eligibility)
            .await
            .unwrap();
    }
    signed(document, signer).await
}

struct Party {
    secret: Secret,
    did: String,
    persona: PersonaId,
    book: VettingBook,
    account: Account,
    seen: crate::operational::SeenDocuments,
}

impl Party {
    fn new(seed: u8) -> Self {
        let secret = secret(seed);
        Self {
            did: did(&secret),
            secret,
            persona: PersonaId::new(),
            book: VettingBook::default(),
            account: Account::default(),
            seen: crate::operational::SeenDocuments::default(),
        }
    }

    fn member_of(mut self, community: &str) -> Self {
        let mut record = CommunityRecord::new_pending(
            community.to_string(),
            None,
            "openvtc/test".to_string(),
            self.persona,
            Uuid::new_v4(),
            Utc::now(),
        );
        record.activate(Utc::now());
        self.account.add_membership(record);
        self
    }

    /// The community names this party a vetter, and delivers the credential.
    async fn named_vetter(&mut self) {
        let credential = role_credential(
            &secret(COMMUNITY_SEED),
            COMMUNITY,
            &self.did.clone(),
            VETTER_ROLE,
        )
        .await;
        let handled = self
            .receive(
                &delivery(&credential, &secret(COMMUNITY_SEED)).await,
                COMMUNITY,
            )
            .await;
        assert!(matches!(handled.notice, Some(Notice::VetterGranted { .. })));
    }

    async fn receive(&mut self, message: &Message, sender: &str) -> Handled {
        self.try_receive(message, sender)
            .await
            .expect("a vetting message is claimed")
    }

    /// [`Self::receive`] for a message the vetting handler may not claim at all.
    async fn try_receive(&mut self, message: &Message, sender: &str) -> Option<Handled> {
        let resolver = TrustTaskVmResolver::did_key_only();
        let did_resolver = did_resolver().await;
        // As the dispatcher does off the loop: a delivered credential is
        // verified before the handler sees it.
        let issued = verified_delivery(message, sender, &did_resolver).await;
        let ctx = Context {
            account: &self.account,
            resolver: &resolver,
            did_resolver: &did_resolver,
            issued_credential: issued.as_ref(),
            community_answer: None,
            recipient: Some((self.persona, &self.did)),
            now: Utc::now(),
        };
        handle(&mut self.book, &ctx, &mut self.seen, message, sender).await
    }

    /// [`Self::receive`], with the community answer already checked off the
    /// loop, as the dispatcher passes it.
    async fn receive_checked(
        &mut self,
        message: &Message,
        sender: &str,
        answer: &Result<
            crate::operational::VerifiedOperational,
            crate::operational::OperationalError,
        >,
    ) -> Handled {
        let resolver = TrustTaskVmResolver::did_key_only();
        let did_resolver = did_resolver().await;
        let ctx = Context {
            account: &self.account,
            resolver: &resolver,
            did_resolver: &did_resolver,
            issued_credential: None,
            community_answer: Some(answer),
            recipient: Some((self.persona, &self.did)),
            now: Utc::now(),
        };
        handle(&mut self.book, &ctx, &mut self.seen, message, sender)
            .await
            .expect("a vetting message is claimed")
    }

    fn application(&mut self) -> &mut super::applicant::Application {
        self.book
            .application_mut(COMMUNITY, self.persona)
            .expect("application started")
    }
}

async fn signed(mut document: TrustTask<Value>, signer: &Secret) -> Message {
    wire::sign(&mut document, signer).await.unwrap();
    wire::to_message(&document).unwrap()
}

fn requirements() -> VettingRequirements {
    serde_json::from_value(json!({
        "version": "0.1",
        "statementType": VETTED_PREDICATE,
        "minStatements": 1,
        "minByMethod": { "inPerson": 1 },
        "acceptedMethods": ["inPerson", "video"],
        "requiredClaims": ["name.legal"],
        "eligibleVetters": { "role": "vetter" }
    }))
    .unwrap()
}

/// The community's manifest 0.2 body.
fn manifest_body() -> manifest::v0_2::Response {
    manifest_with(Some(requirements()), None)
}

/// A manifest 0.2 body carrying `vetting` and `branding`.
fn manifest_with(
    vetting: Option<VettingRequirements>,
    branding: Option<manifest::v0_2::CommunityBranding>,
) -> manifest::v0_2::Response {
    let criterion = manifest::v0_2::Criterion::try_from(
        manifest::v0_2::Criterion::builder()
            .id("vetted")
            .presentation_definition(serde_json::Map::new())
            .vetting(vetting)
            .requirements_digest(Some(
                manifest::v0_2::DigestMultibase::try_from(DIGEST).unwrap(),
            )),
    )
    .unwrap();
    manifest::v0_2::Response::try_from(
        manifest::v0_2::Response::builder()
            .community_did(COMMUNITY)
            .criteria(vec![criterion])
            .branding(branding),
    )
    .unwrap()
}

/// A manifest payload as the wire carries it, with `vetting.ext` / `vetting.extCritical`
/// added to the criterion — the members a generated type drops, so the test has to build them
/// on the raw JSON exactly as a community would send them.
fn manifest_raw_with_ext(ext: Value, critical: Option<Value>) -> Value {
    let mut raw = serde_json::to_value(manifest_body()).unwrap();
    let vetting = raw["criteria"][0]["vetting"].as_object_mut().unwrap();
    vetting.insert("ext".into(), ext);
    if let Some(c) = critical {
        vetting.insert("extCritical".into(), c);
    }
    raw
}

/// Real published parameters: the keys have to decode, because adopting the criterion starts
/// the applicant's engine against them.
fn hidden_params() -> Value {
    use openvtc_vetting_pcs::{scheme::key_text, vtc::Vtc};
    use rand::SeedableRng;
    let mut rng = rand::rngs::StdRng::seed_from_u64(0x0BED);
    let vtc = Vtc::new(
        COMMUNITY,
        "2026-10",
        serde_json::to_value(requirements()).unwrap(),
        &mut rng,
    )
    .expect("a community");
    json!({
        "suite": super::hidden::SUITE,
        "helperKey": key_text(vtc.hvk()).unwrap(),
        "tokenKey": key_text(vtc.tvk()).unwrap(),
        "vetterLabels": ["vetter/2026-10"],
        "tokenLabels": [vtc.current_token_label()],
        "tickLength": "P3D"
    })
}

#[tokio::test]
async fn an_application_adopts_the_hidden_vetting_parameters_a_community_publishes() {
    let mut party = Party::new(1);
    party
        .book
        .start_application(COMMUNITY, party.persona, &party.did, Utc::now())
        .expect("an application starts");
    let raw = manifest_raw_with_ext(
        json!({ super::hidden::HIDDEN_VETTING_NS: hidden_params() }),
        Some(json!([super::hidden::HIDDEN_VETTING_NS])),
    );
    let changed = party
        .application()
        .adopt_manifest(&manifest_body(), &raw)
        .expect("the criterion is one this build implements");
    assert!(changed);
    let hidden = party
        .application()
        .hidden
        .clone()
        .expect("the parameters were adopted");
    let published = hidden_params();
    assert_eq!(hidden.helper_key, published["helperKey"].as_str().unwrap());
    assert_eq!(hidden.token_key, published["tokenKey"].as_str().unwrap());
    assert_eq!(hidden.vetter_labels, vec!["vetter/2026-10".to_string()]);
    // Adopting a hidden criterion mints this application's own key, which is what a vetter
    // attests and what the proof is built from.
    assert!(party.application().hidden_id().is_some());
    // The named members are adopted exactly as before.
    assert!(party.application().requirements.is_some());
}

/// The challenge a community issues reaches the application and is answered to whoever asked —
/// by the question's own id, so a join waiting on it resumes on its answer and no other. And it
/// binds one submission only: once a proof bound to it has gone out, the community has spent it,
/// so it is not kept for the next attempt.
#[tokio::test]
async fn a_challenge_is_answered_to_its_question_and_spent_by_the_submit_it_binds() {
    let mut applicant = Party::new(1);
    applicant
        .book
        .start_application(COMMUNITY, applicant.persona, &applicant.did, Utc::now())
        .expect("an application starts");
    let raw = manifest_raw_with_ext(
        json!({ super::hidden::HIDDEN_VETTING_NS: hidden_params() }),
        Some(json!([super::hidden::HIDDEN_VETTING_NS])),
    );
    applicant
        .application()
        .adopt_manifest(&manifest_body(), &raw)
        .expect("a hidden criterion");

    let request = wire::pcs_challenge_request(&applicant.did, COMMUNITY, None).unwrap();
    applicant
        .book
        .ask(asked(&request, applicant.persona, QueryKind::PcsChallenge));
    let issued = wire::pcs::ChallengeResponse {
        challenge: "c0ffee".into(),
        expires_at: Utc::now() + Duration::minutes(15),
        ext: None,
    };
    let handled = applicant
        .receive(&community_answer(&request, &issued).await, COMMUNITY)
        .await;
    assert!(matches!(
        handled.answer,
        Some(CommunityAnswer::Challenge { ref query, ref community })
            if *query == request.id && community == COMMUNITY
    ));
    assert!(matches!(
        handled.notice,
        Some(Notice::ChallengeIssued { .. })
    ));
    assert_eq!(
        applicant.application().hidden_challenge.as_deref(),
        Some("c0ffee")
    );

    // A submit that carried no proof spends nothing.
    assert!(!applicant.application().hidden_submission_sent());
    assert_eq!(
        applicant.application().hidden_challenge.as_deref(),
        Some("c0ffee")
    );
    // One that did spends the challenge with it.
    applicant
        .application()
        .set_hidden_submission(json!({ "challenge": "c0ffee" }));
    assert!(applicant.application().hidden_submission_sent());
    assert_eq!(applicant.application().hidden_challenge, None);
    assert_eq!(applicant.application().hidden_submission, None);
}

#[tokio::test]
async fn a_critical_namespace_this_build_cannot_honour_stops_the_application() {
    let mut party = Party::new(1);
    party
        .book
        .start_application(COMMUNITY, party.persona, &party.did, Utc::now())
        .expect("an application starts");
    let raw = manifest_raw_with_ext(
        json!({ "com.example.some-scheme": { "a": 1 } }),
        Some(json!(["com.example.some-scheme"])),
    );
    let err = party
        .application()
        .adopt_manifest(&manifest_body(), &raw)
        .expect_err("a marked namespace we do not implement must refuse");
    assert!(matches!(
        err,
        super::applicant::ApplicantError::Hidden(super::hidden::HiddenError::UnsupportedExtension(
            _
        ))
    ));
    // Nothing was adopted: the application does not carry on against requirements whose
    // meaning it could not honour.
    assert!(party.application().hidden.is_none());
    assert!(party.application().requirements.is_none());
}

#[tokio::test]
async fn an_unmarked_namespace_this_build_does_not_implement_is_ignored() {
    let mut party = Party::new(1);
    party
        .book
        .start_application(COMMUNITY, party.persona, &party.did, Utc::now())
        .expect("an application starts");
    let raw = manifest_raw_with_ext(json!({ "com.example.hint": { "a": 1 } }), None);
    party
        .application()
        .adopt_manifest(&manifest_body(), &raw)
        .expect("an unmarked namespace is advisory");
    assert!(party.application().hidden.is_none());
    assert!(party.application().requirements.is_some());
}

/// The community's manifest answer to `to`, as a VTC sends an operational
/// document: signed with its authentication key, addressed, dated.
async fn manifest_reply(to: &str) -> Message {
    signed_manifest(to, manifest_body()).await
}

/// `body` as the community's signed manifest answer to `to`.
async fn signed_manifest(to: &str, body: impl serde::Serialize) -> Message {
    let document = crate::operational::test_support::sign(
        json!({
            "id": wire::new_id(),
            "type": JOIN_REQUEST_MANIFEST_0_2_RESPONSE_TYPE,
            "issuer": COMMUNITY,
            "recipient": to,
            "issuedAt": Utc::now().to_rfc3339(),
            "payload": body,
        }),
        &secret(COMMUNITY_SEED),
    )
    .await;
    Message::build(
        wire::new_id(),
        JOIN_REQUEST_MANIFEST_0_2_RESPONSE_TYPE.to_string(),
        document,
    )
    .from(COMMUNITY.to_string())
    .thid(wire::new_id())
    .finalize()
}

/// An applicant with requirements in hand, and a vetter with a ticket for them.
async fn ready() -> (Party, Party, request::v0_1::Ticket) {
    let mut applicant = Party::new(1);
    let mut vetter = Party::new(2).member_of(COMMUNITY);
    vetter.named_vetter().await;
    let now = Utc::now();
    applicant
        .book
        .start_application(COMMUNITY, applicant.persona, &applicant.did, now)
        .unwrap();
    let handled = applicant
        .receive(&manifest_reply(&applicant.did.clone()).await, COMMUNITY)
        .await;
    assert!(matches!(
        handled.notice,
        Some(Notice::RequirementsUpdated { .. })
    ));
    let ticket = Ticket::issue(COMMUNITY, vetter.persona, vec![], 1, DEFAULT_VALIDITY, now);
    let presented = ticket.code_presentation().unwrap();
    vetter.book.tickets.push(ticket);
    (applicant, vetter, presented)
}

async fn request(applicant: &mut Party, vetter: &Party, ticket: request::v0_1::Ticket) -> Message {
    let id = wire::new_id();
    let vetter_did = vetter.did.clone();
    let body = applicant
        .application()
        .prepare_request(
            &id,
            &vetter_did,
            ticket,
            RequestDraft::default(),
            Utc::now(),
        )
        .unwrap();
    let doc = wire::document(VETTING_REQUEST_TYPE, &applicant.did, &vetter.did, id, &body).unwrap();
    signed(doc, &applicant.secret).await
}

/// Request, accept and open a session. Returns the vetter's request id and the
/// session document.
async fn in_session(applicant: &mut Party, vetter: &mut Party) -> (String, TrustTask<Value>) {
    let ticket = vetter.book.tickets[0].code_presentation().unwrap();
    let message = request(applicant, vetter, ticket).await;
    let handled = vetter.receive(&message, &applicant.did).await;
    let Some(Notice::RequestAccepted { request_id, .. }) = handled.notice.clone() else {
        panic!("the request is accepted");
    };
    let reply = handled.reply.expect("an accepted request is answered");
    assert!(
        reply.eligibility.is_some(),
        "a named vetter presents the grant"
    );
    let message = signed_reply(reply, &vetter.secret).await;
    let handled = applicant.receive(&message, &vetter.did).await;
    assert!(matches!(
        handled.notice,
        Some(Notice::VetterAccepted {
            shown_eligible: true,
            ..
        })
    ));
    let accepted = applicant.application().requests.last().unwrap().clone();
    assert!(matches!(
        accepted.eligibility,
        Some(VetterEligibility::Shown { .. })
    ));

    let session_id = wire::new_id();
    let body = vetter
        .book
        .open_session(
            &request_id,
            VettingMethod::InPerson,
            vec!["name.legal".into()],
            vec![],
            &session_id,
            Utc::now(),
        )
        .unwrap();
    let doc = wire::document(
        VETTING_SESSION_TYPE,
        &vetter.did,
        &applicant.did,
        session_id,
        &body,
    )
    .unwrap();
    // The statement cites this document by task digest, which leaves out the
    // proof — so the unsigned document digests the same as the signed one the
    // applicant receives.
    vetter
        .book
        .record_session_document(&request_id, serde_json::to_value(&doc).unwrap())
        .unwrap();
    (request_id, doc)
}

#[tokio::test]
async fn an_applicant_is_vetted_end_to_end() {
    let (mut applicant, mut vetter, _) = ready().await;
    let resolver = TrustTaskVmResolver::did_key_only();
    let (request_id, session_doc) = in_session(&mut applicant, &mut vetter).await;

    // The session reaches the applicant; both screens show the same code.
    let message = signed(session_doc.clone(), &vetter.secret).await;
    let handled = applicant.receive(&message, &vetter.did).await;
    let Some(Notice::SessionOpened {
        session_id,
        match_code,
        ..
    }) = handled.notice.clone()
    else {
        panic!("the session opens");
    };
    assert_eq!(
        Some(match_code.as_str()),
        vetter.book.desk_entry(&request_id).unwrap().match_code()
    );
    assert!(
        handled.notice.unwrap().task().is_some(),
        "the applicant must act"
    );

    // The applicant signs a card and sends it back.
    let draft = applicant
        .application()
        .card_draft(
            &session_id,
            vec![
                session::v0_1::VettingCardClaim::try_from(
                    session::v0_1::VettingCardClaim::builder()
                        .type_("name.legal")
                        .value(json!("Alice Example"))
                        .provenance("selfAsserted"),
                )
                .unwrap(),
            ],
            Utc::now(),
        )
        .unwrap();
    let card = sign_card(draft, &applicant.secret).await.unwrap();
    applicant
        .application()
        .record_card(&session_id, &card, &resolver, Utc::now())
        .await
        .unwrap();
    // The card travels as it was signed: its digest is what the statement names.
    let doc = wire::response(&session_doc, &json!({ "card": card })).unwrap();
    let message = signed(doc, &applicant.secret).await;
    let handled = vetter.receive(&message, &applicant.did).await;
    assert!(matches!(handled.notice, Some(Notice::CardReceived { .. })));

    // The vetter checks the person and attests.
    let draft = vetter
        .book
        .statement_draft(
            &request_id,
            &vetter.did,
            Attestation {
                method: VettingMethod::InPerson,
                document_classes: vec!["passport".into()],
                claims_verified: vec!["name.legal".into()],
                liveness_confirmed: true,
                declared_relationship: VettingRelationship::None,
                attestation_text_digest: None,
            },
            Utc::now(),
        )
        .unwrap();
    let statement = sign_statement(draft, &vetter.secret).await.unwrap();
    let issued = vetter
        .book
        .record_statement(&request_id, &statement, &resolver, Utc::now())
        .await
        .unwrap();
    assert!(matches!(
        vetter.book.desk_entry(&request_id).unwrap().state,
        DeskState::Attested { .. }
    ));

    // The statement reaches the applicant, who now meets the requirements.
    let message = wire::credential_delivery(
        &vetter.did,
        &applicant.did,
        &statement,
        &session_id,
        &vetter.secret,
    )
    .await
    .unwrap();
    let handled = applicant.receive(&message, &vetter.did).await;
    assert!(matches!(
        handled.notice,
        Some(Notice::StatementReceived { .. })
    ));
    let application = applicant.application();
    assert!(application.checklist(Utc::now()).unwrap().satisfied());
    assert_eq!(application.presentable_statements(Utc::now()).len(), 1);
    assert_eq!(
        application.join_extensions(super::protocol::JoinProtocol::V0_2)["requirementsDigest"],
        DIGEST
    );
    assert!(
        application
            .join_extensions(super::protocol::JoinProtocol::V0_3)
            .get("requirementsDigest")
            .is_none(),
        "0.3 names the criterion in the submit, not in extensions"
    );

    // Later, the vetter withdraws it.
    let notice_id = wire::new_id();
    let (body, _) = vetter
        .book
        .withdrawal(
            &issued.id,
            Some(revoke_statement::v0_1::PayloadReason::Mistake),
            &notice_id,
            Utc::now(),
        )
        .unwrap();
    assert_eq!(
        body.statement_digest_multibase.as_str(),
        issued.digest_multibase
    );
    assert!(
        vetter
            .book
            .on_withdrawal_recorded(COMMUNITY, &notice_id, Utc::now())
            .is_some()
    );
}

/// What the face released, as the disclosure reports it.
fn released(name: Option<&str>) -> Vec<ReleasedClaim> {
    vec![
        ReleasedClaim {
            claim_type: "name.legal".into(),
            value: name.map(|n| json!(n)),
            provenance: Some("selfAsserted".into()),
            stale: false,
        },
        ReleasedClaim {
            claim_type: "email.work".into(),
            value: Some(json!("alice@example.com")),
            provenance: Some("selfAsserted".into()),
            stale: false,
        },
    ]
}

/// A card's identity comes from the persona's face, and every later card has
/// to show what the first one did.
#[tokio::test]
async fn cards_come_from_the_face_and_keep_showing_the_same_identity() {
    let (mut applicant, mut vetter, _) = ready().await;
    let resolver = TrustTaskVmResolver::did_key_only();
    let (_, session_doc) = in_session(&mut applicant, &mut vetter).await;
    let message = signed(session_doc, &vetter.secret).await;
    let handled = applicant.receive(&message, &vetter.did).await;
    let Some(Notice::SessionOpened { session_id, .. }) = handled.notice else {
        panic!("the session opens");
    };
    let signer = applicant.secret.clone();
    let app = applicant.application();
    assert_eq!(app.requested_claims(&session_id), vec!["name.legal"]);

    // Only the session's claim types go on the card, and each needs a value a
    // vetter can read.
    let claims = app
        .card_claims(&session_id, &released(Some("Alice Example")))
        .unwrap();
    assert_eq!(claims.len(), 1);
    assert_eq!(claims[0].value, json!("Alice Example"));
    assert!(matches!(
        app.card_claims(&session_id, &released(None)),
        Err(ApplicantError::ValueWithheld(t)) if t == "name.legal"
    ));
    assert!(matches!(
        app.card_claims(&session_id, &[]),
        Err(ApplicantError::MissingClaim(_))
    ));

    let draft = app
        .card_draft(&session_id, claims.clone(), Utc::now())
        .unwrap();
    let card = sign_card(draft, &signer).await.unwrap();
    let sent = app
        .record_card(&session_id, &card, &resolver, Utc::now())
        .await
        .unwrap();
    app.record_sent_card(&session_id, sent, &claims, Utc::now())
        .unwrap();
    // The generated card claim has no `PartialEq`; what was kept is compared as
    // what it serialises to.
    assert_eq!(
        serde_json::to_value(&app.identity_claims).unwrap(),
        serde_json::to_value(&claims).unwrap()
    );

    // The face has changed since: the next card is refused before it is signed.
    assert!(matches!(
        app.card_claims(&session_id, &released(Some("Alicia Example"))),
        Err(ApplicantError::IdentityChanged(t)) if t == "name.legal"
    ));
}

#[tokio::test]
async fn without_a_ticket_there_is_no_answer_at_all() {
    let (mut applicant, mut vetter, _) = ready().await;
    let message = request(&mut applicant, &vetter, code_ticket("0000-0000")).await;
    let handled = vetter.receive(&message, &applicant.did).await;
    assert!(handled.reply.is_none() && handled.notice.is_none());
    assert!(vetter.book.desk.is_empty());
}

#[tokio::test]
async fn a_bad_scanned_ticket_is_refused_and_the_applicant_hears_why() {
    let (mut applicant, mut vetter, _) = ready().await;
    let ticket_id = vetter.book.tickets[0].id.clone();
    let scanned = request::v0_1::Ticket::QrTicket(
        request::v0_1::QrTicket::try_from(
            request::v0_1::QrTicket::builder()
                .ticket_id(ticket_id)
                .secret("A".repeat(43)),
        )
        .unwrap(),
    );
    let message = request(&mut applicant, &vetter, scanned).await;
    let handled = vetter.receive(&message, &applicant.did).await;
    let reply = handled.reply.expect("a scanned ticket is answered");
    assert_eq!(
        reply.document.payload["code"],
        VETTING_REQUEST_ERR_INVALID_TICKET
    );
    // The vetter hears about it too. A refusal used to leave nothing at all on
    // their side, so the one person who can issue a fresh ticket saw an empty
    // desk and no way to find out that anybody had tried.
    let Some(Notice::RequestRefused {
        applicant: who,
        code,
    }) = handled.notice
    else {
        panic!("the vetter is told a request was turned away");
    };
    assert_eq!(who, applicant.did);
    assert_eq!(code, VETTING_REQUEST_ERR_INVALID_TICKET);

    let message = signed(reply.document, &vetter.secret).await;
    let handled = applicant.receive(&message, &vetter.did).await;
    let refused = handled.notice.expect("the applicant is told");
    assert!(matches!(refused, Notice::VetterRefused { .. }));
    // In words, not just the wire code: "vetting/request:invalidTicket" under
    // a vetter's name reads as a fault in the software rather than as a ticket
    // that needs replacing.
    let said = refused.describe();
    assert!(said.contains(VETTING_REQUEST_ERR_INVALID_TICKET), "{said}");
    assert!(said.contains("Ask them for a fresh one"), "{said}");
    assert!(matches!(
        applicant.application().requests[0].state,
        RequestState::Refused { .. }
    ));
}

#[tokio::test]
async fn someone_who_is_not_a_member_cannot_vet() {
    let (mut applicant, _, _) = ready().await;
    let mut outsider = Party::new(3);
    let ticket = Ticket::issue(
        COMMUNITY,
        outsider.persona,
        vec![],
        1,
        DEFAULT_VALIDITY,
        Utc::now(),
    );
    let presented = ticket.code_presentation().unwrap();
    outsider.book.tickets.push(ticket);
    let message = request(&mut applicant, &outsider, presented).await;
    let handled = outsider.receive(&message, &applicant.did).await;
    assert_eq!(
        handled.reply.unwrap().document.payload["code"],
        VETTING_REQUEST_ERR_NOT_ELIGIBLE
    );
}

/// A vetter grant is taken only from the community's signed delivery. The
/// same grant, correctly signed by the community, in a bare `issue` body —
/// the shape a VTC sent before every `issue` was a document — makes nobody a
/// vetter.
#[tokio::test]
async fn a_bare_vetter_grant_delivery_is_refused() {
    let mut member = Party::new(6).member_of(COMMUNITY);
    let credential = role_credential(
        &secret(COMMUNITY_SEED),
        COMMUNITY,
        &member.did.clone(),
        VETTER_ROLE,
    )
    .await;
    let bare = Message::build(
        wire::new_id(),
        vta_sdk::protocols::credential_exchange::ISSUE.to_string(),
        json!({ "credential_response": { "credential": credential } }),
    )
    .from(COMMUNITY.to_string())
    .finalize();
    let resolver = TrustTaskVmResolver::did_key_only();
    let did_resolver = did_resolver().await;
    let ctx = Context {
        account: &member.account,
        resolver: &resolver,
        did_resolver: &did_resolver,
        issued_credential: None,
        community_answer: None,
        recipient: Some((member.persona, &member.did)),
        now: Utc::now(),
    };
    let handled = handle(
        &mut member.book,
        &ctx,
        &mut crate::operational::SeenDocuments::default(),
        &bare,
        COMMUNITY,
    )
    .await;
    assert!(
        handled.is_none_or(|h| h.notice.is_none()),
        "a bare delivery grants nothing"
    );
    assert!(member.book.vetter_grants.is_empty());
}

/// And a signed delivery by anyone but the community is refused before the
/// grant inside is looked at, even when the grant itself is the community's.
#[tokio::test]
async fn a_vetter_grant_relayed_by_another_party_is_refused() {
    let mut member = Party::new(7).member_of(COMMUNITY);
    let credential = role_credential(
        &secret(COMMUNITY_SEED),
        COMMUNITY,
        &member.did.clone(),
        VETTER_ROLE,
    )
    .await;
    let relay = secret(0xD7);
    let handled = member
        .receive(&delivery(&credential, &relay).await, &did(&relay))
        .await;
    assert!(handled.notice.is_none() && member.book.vetter_grants.is_empty());
}

/// Membership is not enough: the community has to have named the member a
/// vetter, or requests are refused before anything is recorded.
#[tokio::test]
async fn a_member_the_community_has_not_named_cannot_vet() {
    let (mut applicant, _, _) = ready().await;
    let mut member = Party::new(4).member_of(COMMUNITY);
    let ticket = Ticket::issue(
        COMMUNITY,
        member.persona,
        vec![],
        1,
        DEFAULT_VALIDITY,
        Utc::now(),
    );
    let presented = ticket.code_presentation().unwrap();
    member.book.tickets.push(ticket);
    let message = request(&mut applicant, &member, presented).await;
    let handled = member.receive(&message, &applicant.did).await;
    assert_eq!(
        handled.reply.unwrap().document.payload["code"],
        VETTING_REQUEST_ERR_NOT_ELIGIBLE
    );
    assert!(member.book.desk.is_empty());
}

/// Only the community a grant names can deliver it, and only to the persona
/// it names. A member's ordinary role credential is left for the join handler,
/// so it keeps its place.
#[tokio::test]
async fn a_vetter_grant_is_kept_only_from_its_community() {
    let mut member = Party::new(5).member_of(COMMUNITY);
    let impostor = secret(0xC1);
    // Authority in a scope the signer does not govern is not a community role
    // credential at all, so the vetting handler does not even claim it.
    let forged = role_credential(&impostor, COMMUNITY, &member.did.clone(), VETTER_ROLE).await;
    let handled = member
        .try_receive(&delivery(&forged, &impostor).await, &did(&impostor))
        .await;
    assert!(handled.is_none_or(|h| h.notice.is_none()) && member.book.vetter_grants.is_empty());

    let for_someone_else = role_credential(
        &secret(COMMUNITY_SEED),
        COMMUNITY,
        "did:key:zSomeoneElse",
        VETTER_ROLE,
    )
    .await;
    let handled = member
        .receive(
            &delivery(&for_someone_else, &secret(COMMUNITY_SEED)).await,
            COMMUNITY,
        )
        .await;
    assert!(handled.notice.is_none() && member.book.vetter_grants.is_empty());

    let ordinary = role_credential(
        &secret(COMMUNITY_SEED),
        COMMUNITY,
        &member.did.clone(),
        "member",
    )
    .await;
    let resolver = TrustTaskVmResolver::did_key_only();
    let did_resolver = did_resolver().await;
    let issued: Option<
        Result<
            crate::issued_credential::VerifiedIssuedCredential,
            crate::issued_credential::IssuedCredentialError,
        >,
    > = None;
    let ctx = Context {
        account: &member.account,
        resolver: &resolver,
        did_resolver: &did_resolver,
        issued_credential: issued.as_ref(),
        community_answer: None,
        recipient: Some((member.persona, &member.did)),
        now: Utc::now(),
    };
    assert!(
        handle(
            &mut member.book,
            &ctx,
            &mut crate::operational::SeenDocuments::default(),
            &delivery(&ordinary, &secret(COMMUNITY_SEED)).await,
            COMMUNITY
        )
        .await
        .is_none(),
        "an ordinary role credential is not vetting's"
    );

    member.named_vetter().await;
    assert!(
        member
            .book
            .vetter_grant(COMMUNITY, member.persona, Utc::now())
            .is_some()
    );
}

/// An acceptance that shows nothing is still an acceptance — the check is
/// advisory — but the applicant is told.
#[tokio::test]
async fn an_acceptance_without_a_grant_shown_is_recorded_as_such() {
    let (mut applicant, mut vetter, ticket) = ready().await;
    let message = request(&mut applicant, &vetter, ticket).await;
    let handled = vetter.receive(&message, &applicant.did).await;
    let mut reply = handled.reply.unwrap();
    reply.eligibility = None;
    let message = signed_reply(reply, &vetter.secret).await;
    let handled = applicant.receive(&message, &vetter.did).await;
    assert!(matches!(
        handled.notice,
        Some(Notice::VetterAccepted {
            shown_eligible: false,
            ..
        })
    ));
    assert_eq!(
        applicant.application().requests[0].eligibility,
        Some(VetterEligibility::NotShown)
    );
}

#[tokio::test]
async fn a_vetter_can_decline_without_a_reason() {
    let (mut applicant, mut vetter, _) = ready().await;
    let (request_id, _) = in_session(&mut applicant, &mut vetter).await;
    let body = vetter
        .book
        .decline(
            &request_id,
            Some(decline::v0_1::PayloadCode::NotComfortable),
            None,
            Utc::now(),
        )
        .unwrap();
    let doc = wire::document(
        VETTING_DECLINE_TYPE,
        &vetter.did,
        &applicant.did,
        wire::new_id(),
        &body,
    )
    .unwrap();
    let message = signed(doc, &vetter.secret).await;
    let handled = applicant.receive(&message, &vetter.did).await;
    assert!(matches!(handled.notice, Some(Notice::Declined { .. })));
    assert!(applicant.application().checklist(Utc::now()).is_some());
}

#[tokio::test]
async fn a_membership_credential_is_left_for_the_join_handler() {
    let mut applicant = Party::new(1);
    let vmc = json!({ "credential_response": { "credential": {
        "type": ["VerifiableCredential", "MembershipCredential"],
        "issuer": COMMUNITY
    } } });
    let message = Message::build(
        wire::new_id(),
        vta_sdk::protocols::credential_exchange::ISSUE.to_string(),
        vmc,
    )
    .from(COMMUNITY.to_string())
    .finalize();
    let resolver = TrustTaskVmResolver::did_key_only();
    let did_resolver = did_resolver().await;
    let issued: Option<
        Result<
            crate::issued_credential::VerifiedIssuedCredential,
            crate::issued_credential::IssuedCredentialError,
        >,
    > = None;
    let ctx = Context {
        account: &applicant.account,
        resolver: &resolver,
        did_resolver: &did_resolver,
        issued_credential: issued.as_ref(),
        community_answer: None,
        recipient: Some((applicant.persona, &applicant.did)),
        now: Utc::now(),
    };
    assert!(
        handle(
            &mut applicant.book,
            &ctx,
            &mut crate::operational::SeenDocuments::default(),
            &message,
            COMMUNITY
        )
        .await
        .is_none()
    );
}

#[tokio::test]
async fn a_vetter_asks_for_the_claims_the_community_requires() {
    let mut vetter = Party::new(2).member_of(COMMUNITY);
    assert_eq!(
        vetter.book.required_claims_for(COMMUNITY, None),
        (vec!["name.legal".to_string()], false),
        "without the manifest, the fallback — and it says so"
    );
    let handled = vetter
        .receive(&manifest_reply(&vetter.did.clone()).await, COMMUNITY)
        .await;
    assert!(handled.changed, "the criteria are remembered");
    let (claims, known) = vetter.book.required_claims_for(COMMUNITY, Some(DIGEST));
    assert!(known);
    assert_eq!(
        claims,
        requirements()
            .required_claims
            .iter()
            .flatten()
            .map(|c| c.as_str().to_string())
            .collect::<Vec<_>>()
    );
    assert!(
        !vetter
            .receive(&manifest_reply(&vetter.did.clone()).await, COMMUNITY)
            .await
            .changed,
        "the same manifest again changes nothing"
    );
}

#[tokio::test]
async fn the_communitys_decision_sla_is_known_once_its_manifest_is() {
    let (applicant, _, _) = ready().await;
    let persona = applicant.persona;
    assert_eq!(applicant.book.decision_sla(COMMUNITY, persona), None);

    let mut with_sla = Party::new(4);
    with_sla
        .book
        .start_application(COMMUNITY, with_sla.persona, &with_sla.did, Utc::now())
        .unwrap();
    let mut requirements = requirements();
    requirements.decision_sla = Some("P21D".try_into().unwrap());
    let body = manifest_with(Some(requirements), None);
    let reply = signed_manifest(&with_sla.did.clone(), body).await;
    with_sla.receive(&reply, COMMUNITY).await;
    assert_eq!(
        with_sla.book.decision_sla(COMMUNITY, with_sla.persona),
        chrono::Duration::try_days(21)
    );
}

// ----------------------------------------------------------------------------
// Questions put to the community: the vetter registry, resends, the manifest
// ----------------------------------------------------------------------------

/// The community's answer to `request`, as its dispatcher sends it: unsigned
/// (transport authenticates it) and threaded on the request.
/// The community answering `request`, signed as a VTC signs its success
/// responses.
async fn community_answer<P: serde::Serialize>(request: &TrustTask<Value>, payload: &P) -> Message {
    let document = wire::response(request, payload).unwrap();
    let mut message = wire::to_message(&document).unwrap();
    message.body = crate::operational::test_support::sign(
        serde_json::to_value(&document).unwrap(),
        &secret(COMMUNITY_SEED),
    )
    .await;
    message
}

/// The community refusing `request` with `code`.
fn community_refusal(request: &TrustTask<Value>, code: &str) -> Message {
    wire::to_message(&wire::refusal(request, code, Some("because")).unwrap()).unwrap()
}

fn asked(request: &TrustTask<Value>, persona: PersonaId, kind: QueryKind) -> CommunityQuery {
    CommunityQuery {
        document_id: request.id.clone(),
        community: COMMUNITY.into(),
        persona,
        kind,
        sent_at: Utc::now(),
    }
}

fn listed_vetter() -> vetters::list::v0_1::ListedVetter {
    serde_json::from_value(json!({
        "vetterDid": "did:key:zCarol",
        "displayName": "Carol",
        "languages": ["en", "cs"],
        "location": { "country": "CZ", "city": "Prague" },
        "methods": ["inPerson", "video"],
        "acceptsDocumentation": ["passport"],
        "contactHint": "find me at the LPC vetting desk",
        "events": [{ "name": "LPC", "startDate": "2026-10-05", "endDate": "2026-10-07" }],
        "grantValidUntil": "2027-09-01T00:00:00Z",
        "updatedAt": "2026-09-01T00:00:00Z"
    }))
    .unwrap()
}

#[tokio::test]
async fn a_vetter_publishes_a_profile_and_hears_the_communitys_answer() {
    let mut vetter = Party::new(2).member_of(COMMUNITY);
    vetter.named_vetter().await;
    let now = Utc::now();
    let mut draft = ProfileDraft::new(&VetterPolicy::default());
    draft.listed = true;
    draft.languages = "en, cs".into();
    let body = draft.to_body().unwrap();

    // What the community receives is signed by the vetter, with the
    // authentication key and proofPurpose (trust-tasks 0.23: `proof`
    // REQUIRED, and this is the vetter acting on their own standing, not a
    // claim to be held to later — the same purpose a personhood challenge or
    // assertion is signed with), and opens as a profile.
    let mut request = wire::vetter_profile_request(&vetter.did, COMMUNITY, &body).unwrap();
    wire::sign(&mut request, &vetter.secret).await.unwrap();
    assert_eq!(
        request.proof.as_ref().unwrap().proof_purpose,
        "authentication"
    );
    // It travels in the binding envelope; the community takes that off first.
    let sent = wire::to_message(&request).unwrap();
    assert_eq!(sent.typ, crate::capabilities::TRUST_TASK_ENVELOPE_TYPE);
    let opened: wire::Opened<vetters::profile::v0_1::Payload> = wire::open(
        &crate::didcomm::open_didcomm_envelope(&sent).unwrap(),
        &vetter.did,
        &TrustTaskVmResolver::did_key_only(),
    )
    .await
    .unwrap();
    // The generated payload has no `PartialEq`; what was sent is compared as
    // what it serialises to.
    assert_eq!(
        serde_json::to_value(&opened.payload).unwrap(),
        serde_json::to_value(&body).unwrap()
    );

    vetter
        .book
        .record_profile_sent(COMMUNITY, vetter.persona, &body, now);
    vetter
        .book
        .ask(asked(&request, vetter.persona, QueryKind::VetterProfile));
    let stored = vetters::profile::v0_1::Response::try_from(
        vetters::profile::v0_1::Response::builder()
            .listed(true)
            .updated_at(now),
    )
    .unwrap();
    let handled = vetter
        .receive(&community_answer(&request, &stored).await, COMMUNITY)
        .await;
    assert!(handled.changed, "the stored state is kept");
    assert!(matches!(
        handled.notice,
        Some(Notice::ProfilePublished { listed: true, .. })
    ));
    assert!(matches!(
        handled.answer,
        Some(CommunityAnswer::ProfileStored { listed: true, .. })
    ));
    assert!(matches!(
        vetter
            .book
            .vetter_profile(COMMUNITY, vetter.persona)
            .unwrap()
            .state,
        ProfileState::Stored { listed: true, .. }
    ));

    // Published again, and refused: the community no longer counts the grant.
    let request = wire::vetter_profile_request(&vetter.did, COMMUNITY, &body).unwrap();
    vetter
        .book
        .record_profile_sent(COMMUNITY, vetter.persona, &body, now);
    vetter
        .book
        .ask(asked(&request, vetter.persona, QueryKind::VetterProfile));
    let handled = vetter
        .receive(
            &community_refusal(&request, VETTING_VETTER_PROFILE_ERR_NOT_ELIGIBLE),
            COMMUNITY,
        )
        .await;
    assert!(matches!(
        &handled.answer,
        Some(CommunityAnswer::Refused { kind: QueryKind::VetterProfile, code, .. })
            if code == VETTING_VETTER_PROFILE_ERR_NOT_ELIGIBLE
    ));
    let notice = handled.notice.expect("a refusal is explained");
    assert!(notice.describe().contains("live vetter credential"));
    assert!(matches!(
        vetter
            .book
            .vetter_profile(COMMUNITY, vetter.persona)
            .unwrap()
            .state,
        ProfileState::Refused { .. }
    ));
}

#[tokio::test]
async fn the_directory_answers_only_what_was_asked() {
    let mut applicant = Party::new(1);
    let page = vetters::list::v0_1::Response::try_from(
        vetters::list::v0_1::Response::builder()
            .vetters(vec![listed_vetter()])
            .next_cursor(Some(
                vetters::list::v0_1::ResponseNextCursor::try_from("page-2").unwrap(),
            )),
    )
    .unwrap();
    let request = wire::vetter_list_request(&applicant.did, COMMUNITY, &unfiltered_list()).unwrap();

    // Nobody asked: the page answers nothing.
    let handled = applicant
        .receive(&community_answer(&request, &page).await, COMMUNITY)
        .await;
    assert!(handled.answer.is_none());

    applicant
        .book
        .ask(asked(&request, applicant.persona, QueryKind::VetterList));
    // Another community cannot answer our question.
    let handled = applicant
        .receive(
            &community_answer(&request, &page).await,
            "did:key:zElsewhere",
        )
        .await;
    assert!(handled.answer.is_none());

    let handled = applicant
        .receive(&community_answer(&request, &page).await, COMMUNITY)
        .await;
    let Some(CommunityAnswer::Vetters {
        query, page: got, ..
    }) = handled.answer
    else {
        panic!("the page is handed to whoever asked");
    };
    assert_eq!(query, request.id);
    assert_eq!(
        serde_json::to_value(&got).unwrap(),
        serde_json::to_value(&page).unwrap()
    );
    assert!(!handled.changed, "a directory page is never saved");

    // Refused: the community would not answer this caller.
    let request = wire::vetter_list_request(&applicant.did, COMMUNITY, &unfiltered_list()).unwrap();
    applicant
        .book
        .ask(asked(&request, applicant.persona, QueryKind::VetterList));
    let handled = applicant
        .receive(&community_refusal(&request, "permissionDenied"), COMMUNITY)
        .await;
    assert!(matches!(
        &handled.answer,
        Some(CommunityAnswer::Refused { kind: QueryKind::VetterList, code, .. })
            if code == "permissionDenied"
    ));

    // An error that answers nothing we asked is left for the join handler.
    let stray = wire::vetter_list_request(&applicant.did, COMMUNITY, &unfiltered_list()).unwrap();
    let resolver = TrustTaskVmResolver::did_key_only();
    let did_resolver = did_resolver().await;
    let issued: Option<
        Result<
            crate::issued_credential::VerifiedIssuedCredential,
            crate::issued_credential::IssuedCredentialError,
        >,
    > = None;
    let ctx = Context {
        account: &applicant.account,
        resolver: &resolver,
        did_resolver: &did_resolver,
        issued_credential: issued.as_ref(),
        community_answer: None,
        recipient: Some((applicant.persona, &applicant.did)),
        now: Utc::now(),
    };
    assert!(
        handle(
            &mut applicant.book,
            &ctx,
            &mut crate::operational::SeenDocuments::default(),
            &community_refusal(&stray, "permissionDenied"),
            COMMUNITY
        )
        .await
        .is_none()
    );

    // An answer this client cannot read says so, rather than timing out.
    let request = wire::vetter_list_request(&applicant.did, COMMUNITY, &unfiltered_list()).unwrap();
    applicant
        .book
        .ask(asked(&request, applicant.persona, QueryKind::VetterList));
    let handled = applicant
        .receive(
            &community_answer(&request, &json!({ "vetters": "not a list" })).await,
            COMMUNITY,
        )
        .await;
    assert!(matches!(
        handled.answer,
        Some(CommunityAnswer::Unreadable {
            kind: QueryKind::VetterList,
            ..
        })
    ));
    assert!(applicant.book.queries.is_empty());
}

/// `message` as a community that follows the DIDComm binding (§5) sends it:
/// typed as the envelope, with the same document as the body.
fn enveloped(message: &Message) -> Message {
    let mut enveloped = message.clone();
    enveloped.typ = crate::capabilities::TRUST_TASK_ENVELOPE_TYPE.to_string();
    enveloped
}

/// A community answers in the response document's own type today and in the
/// binding envelope once it follows §5 fully (the follow-up to VTI #1687). Both
/// must reach the same handler, or the switch silently drops every answer.
#[tokio::test]
async fn a_community_answer_is_read_in_either_carriage() {
    let mut applicant = Party::new(1);
    let page = vetters::list::v0_1::Response::try_from(
        vetters::list::v0_1::Response::builder().vetters(vec![listed_vetter()]),
    )
    .unwrap();
    for in_envelope in [false, true] {
        let request =
            wire::vetter_list_request(&applicant.did, COMMUNITY, &unfiltered_list()).unwrap();
        applicant
            .book
            .ask(asked(&request, applicant.persona, QueryKind::VetterList));
        let reply = community_answer(&request, &page).await;
        let reply = if in_envelope {
            crate::didcomm::open_didcomm_envelope(&enveloped(&reply))
                .expect("an enveloped document opens")
        } else {
            assert!(
                crate::didcomm::open_didcomm_envelope(&reply).is_none(),
                "a document-typed reply needs no opening"
            );
            reply
        };
        let handled = applicant.receive(&reply, COMMUNITY).await;
        assert!(
            matches!(&handled.answer, Some(CommunityAnswer::Vetters { query, .. }) if *query == request.id),
            "answered in the envelope: {in_envelope}"
        );

        // And a refusal, in the same carriage.
        let request =
            wire::vetter_list_request(&applicant.did, COMMUNITY, &unfiltered_list()).unwrap();
        applicant
            .book
            .ask(asked(&request, applicant.persona, QueryKind::VetterList));
        let refusal = community_refusal(&request, "permissionDenied");
        let refusal = if in_envelope {
            crate::didcomm::open_didcomm_envelope(&enveloped(&refusal)).unwrap()
        } else {
            refusal
        };
        let handled = applicant.receive(&refusal, COMMUNITY).await;
        assert!(matches!(
            &handled.answer,
            Some(CommunityAnswer::Refused { kind: QueryKind::VetterList, code, .. })
                if code == "permissionDenied"
        ));
    }
    assert!(applicant.book.queries.is_empty());
}

/// A community refusing at the DIDComm layer — a problem-report, as a VTC sends
/// for a Trust Task typed as its task URI (VTI #1687) — refuses the question it
/// threads on at once, instead of leaving it to time out.
#[tokio::test]
async fn a_problem_report_refuses_the_question_it_threads_on() {
    let mut applicant = Party::new(1);
    let request = wire::vetter_list_request(&applicant.did, COMMUNITY, &unfiltered_list()).unwrap();
    applicant
        .book
        .ask(asked(&request, applicant.persona, QueryKind::VetterList));
    let report = |thid: &str| {
        Message::build(
            wire::new_id(),
            vta_sdk::protocols::PROBLEM_REPORT_TYPE.to_string(),
            json!({
                "code": "e.p.msg.bad-request",
                "comment": "unsupported message type: … — Trust Tasks must be carried in the \
                            DIDComm binding envelope",
            }),
        )
        .from(COMMUNITY.to_string())
        .thid(thid.to_string())
        .finalize()
    };

    let handled = applicant.receive(&report(&request.id), COMMUNITY).await;
    let Some(CommunityAnswer::Refused {
        query,
        kind: QueryKind::VetterList,
        code,
        message,
        ..
    }) = handled.answer
    else {
        panic!("the question is refused");
    };
    assert_eq!(query, request.id);
    assert_eq!(code, "e.p.msg.bad-request");
    assert!(message.unwrap().contains("binding envelope"));
    assert!(applicant.book.queries.is_empty());

    // One threading on nothing of vetting's is left for the join handler.
    let resolver = TrustTaskVmResolver::did_key_only();
    let did_resolver = did_resolver().await;
    let issued: Option<
        Result<
            crate::issued_credential::VerifiedIssuedCredential,
            crate::issued_credential::IssuedCredentialError,
        >,
    > = None;
    let ctx = Context {
        account: &applicant.account,
        resolver: &resolver,
        did_resolver: &did_resolver,
        issued_credential: issued.as_ref(),
        community_answer: None,
        recipient: Some((applicant.persona, &applicant.did)),
        now: Utc::now(),
    };
    assert!(
        handle(
            &mut applicant.book,
            &ctx,
            &mut crate::operational::SeenDocuments::default(),
            &report("urn:uuid:not-ours"),
            COMMUNITY
        )
        .await
        .is_none()
    );
}

#[tokio::test]
async fn a_resend_is_answered_or_refused_in_plain_words() {
    let mut member = Party::new(5).member_of(COMMUNITY);
    let request = wire::vetter_resend_request(&member.did, COMMUNITY).unwrap();
    member
        .book
        .ask(asked(&request, member.persona, QueryKind::VetterResend));
    let resent = vetters::resend::v0_1::Response::try_from(
        vetters::resend::v0_1::Response::builder()
            .credential_id("urn:uuid:grant")
            .valid_until(Utc::now() + Duration::days(300)),
    )
    .unwrap();
    let handled = member
        .receive(&community_answer(&request, &resent).await, COMMUNITY)
        .await;
    assert!(matches!(
        handled.answer,
        Some(CommunityAnswer::Resent { .. })
    ));
    assert!(matches!(handled.notice, Some(Notice::GrantResent { .. })));

    let request = wire::vetter_resend_request(&member.did, COMMUNITY).unwrap();
    member
        .book
        .ask(asked(&request, member.persona, QueryKind::VetterResend));
    let handled = member
        .receive(
            &community_refusal(&request, VETTING_VETTER_RESEND_ERR_NOT_GRANTED),
            COMMUNITY,
        )
        .await;
    assert!(matches!(
        handled.answer,
        Some(CommunityAnswer::Refused {
            kind: QueryKind::VetterResend,
            ..
        })
    ));
    let notice = handled.notice.expect("a refusal is explained");
    assert!(notice.describe().contains("has not named you a vetter"));
}

#[tokio::test]
async fn a_manifest_answers_whoever_asked_and_brings_the_communitys_branding() {
    let mut applicant = Party::new(1);
    let request = wire::manifest_request(
        &applicant.did,
        COMMUNITY,
        super::protocol::JoinProtocol::V0_2,
    )
    .unwrap();
    applicant
        .book
        .ask(asked(&request, applicant.persona, QueryKind::Manifest));
    let branding = manifest::v0_2::CommunityBranding::try_from(
        manifest::v0_2::CommunityBranding::builder()
            .display_name(Some(
                manifest::v0_2::CommunityBrandingDisplayName::try_from("Kernel Developers")
                    .unwrap(),
            ))
            .accent_color(Some(
                manifest::v0_2::CommunityBrandingAccentColor::try_from("#336699").unwrap(),
            )),
    )
    .unwrap();
    let body = manifest_with(Some(requirements()), Some(branding));
    let handled = applicant
        .receive(&community_answer(&request, &body).await, COMMUNITY)
        .await;
    assert!(matches!(
        handled.answer,
        Some(CommunityAnswer::Manifest { .. })
    ));
    assert!(matches!(
        applicant.book.knowledge(COMMUNITY),
        Knowledge::Vetting(_)
    ));
    let branding = applicant.book.branding(COMMUNITY).unwrap();
    assert_eq!(branding.display_name.as_deref(), Some("Kernel Developers"));
    assert_eq!(branding.accent_rgb(), Some((0x33, 0x66, 0x99)));
    assert!(applicant.book.queries.is_empty());
}

/// A community role credential carrying a status list entry, signed by
/// `issuer`. Signed as JSON, as a community's own signer does.
async fn role_credential_with_status(issuer: &Secret, subject: &str) -> Value {
    let credential = role_vac(issuer, COMMUNITY, subject, VETTER_ROLE);
    let mut value = serde_json::to_value(&credential).unwrap();
    value.as_object_mut().unwrap().remove("proof");
    value["credentialStatus"] = json!({
        "id": "https://vtc.example.com/v1/status-lists/revocation#7",
        "type": "BitstringStatusListEntry",
        "statusPurpose": "revocation",
        "statusListIndex": "7",
        "statusListCredential": "https://vtc.example.com/v1/status-lists/revocation"
    });
    let proof = DataIntegrityProof::sign(
        &value,
        issuer,
        SignOptions::new().with_proof_purpose("assertionMethod"),
    )
    .await
    .unwrap();
    value["proof"] = serde_json::to_value(proof).unwrap();
    value
}

#[tokio::test]
async fn a_verified_grant_is_handed_on_for_a_revocation_check() {
    let (mut applicant, mut vetter, ticket) = ready().await;
    let credential =
        role_credential_with_status(&secret(COMMUNITY_SEED), &vetter.did.clone()).await;
    // Receiving this grant would read its status list, which fails closed
    // with no list to fetch (see `a_grant_whose_status_cannot_be_read_is_not_kept`);
    // this test is about the applicant's side, so the vetter is handed the grant.
    vetter.book.keep_vetter_grant(super::book::VetterGrant {
        community: COMMUNITY.to_string(),
        persona: vetter.persona,
        credential_id: credential["id"].as_str().map(str::to_string),
        valid_until: credential["validUntil"]
            .as_str()
            .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok())
            .map(|d| d.with_timezone(&Utc)),
        received_at: Utc::now(),
        credential: credential.clone(),
    });

    let message = request(&mut applicant, &vetter, ticket).await;
    let reply = vetter
        .receive(&message, &applicant.did)
        .await
        .reply
        .expect("accepted");
    let handled = applicant
        .receive(&signed_reply(reply, &vetter.secret).await, &vetter.did)
        .await;
    let check = handled
        .grant_check
        .expect("a verified grant with a status entry is checked");
    assert_eq!(check.issuer, COMMUNITY);
    assert_eq!(check.vetter, vetter.did);
    assert_eq!(check.credential_status["statusListIndex"], "7");
    let app = applicant.application();
    assert!(matches!(
        app.requests[0].grant_status,
        Some(GrantStatus::Checking { .. })
    ));

    app.record_grant_status(
        &check.request_document_id,
        &check.vetter,
        GrantStatus::from_check(StatusCheck::Revoked, Utc::now()),
    )
    .unwrap();
    assert!(matches!(
        app.requests[0].grant_status,
        Some(GrantStatus::Revoked { .. })
    ));
}

#[tokio::test]
async fn a_grant_that_names_no_status_list_is_not_called_unrevoked() {
    let (mut applicant, mut vetter, ticket) = ready().await;
    let message = request(&mut applicant, &vetter, ticket).await;
    let reply = vetter
        .receive(&message, &applicant.did)
        .await
        .reply
        .unwrap();
    let handled = applicant
        .receive(&signed_reply(reply, &vetter.secret).await, &vetter.did)
        .await;
    assert!(handled.grant_check.is_none());
    assert!(matches!(
        applicant.application().requests[0].grant_status,
        Some(GrantStatus::Unknown { .. })
    ));
}

#[tokio::test]
async fn a_scanned_ticket_link_is_enough_to_ask_and_another_communitys_is_refused() {
    let (mut applicant, mut vetter, _) = ready().await;
    let link = vetter.book.tickets[0].uri(&vetter.did).unwrap();
    let ticket = applicant.application().ticket_from_uri(&link).unwrap();
    assert_eq!(ticket.vetter, vetter.did);
    let message = request(&mut applicant, &vetter, ticket.presentation).await;
    let handled = vetter.receive(&message, &applicant.did).await;
    assert!(matches!(
        handled.notice,
        Some(Notice::RequestAccepted { .. })
    ));

    let elsewhere = Ticket::issue(
        "did:key:zOtherCommunity",
        vetter.persona,
        vec![],
        1,
        DEFAULT_VALIDITY,
        Utc::now(),
    );
    assert!(matches!(
        applicant
            .application()
            .ticket_from_uri(&elsewhere.uri(&vetter.did).unwrap()),
        Err(TicketUriError::OtherCommunity(c)) if c == "did:key:zOtherCommunity"
    ));
    assert!(matches!(
        applicant.application().ticket_from_uri("K7QF-2M9X"),
        Err(TicketUriError::Unreadable(_))
    ));
}

#[tokio::test]
async fn the_next_step_follows_the_application() {
    let fresh = Application::new(COMMUNITY, PersonaId::new(), "did:key:zA", Utc::now()).unwrap();
    assert_eq!(fresh.next_step(Utc::now()), NextStep::LearnRequirements);

    let (mut applicant, mut vetter, _) = ready().await;
    assert_eq!(
        applicant.application().next_step(Utc::now()),
        NextStep::ChooseFace
    );
    // Choosing one advances the step. The claims are only read from the face
    // when the first card goes out, so without `face` being recorded in its own
    // right the step still said "choose a face" right after one was chosen —
    // the screen told you to do the thing you had just done.
    applicant.application().face = Some(ChosenFace {
        profile_id: "p1".into(),
        name: "Work".into(),
    });
    assert_eq!(
        applicant.application().next_step(Utc::now()),
        NextStep::AskVetter
    );
    let (_, session_doc) = in_session(&mut applicant, &mut vetter).await;
    assert_eq!(
        applicant.application().next_step(Utc::now()),
        NextStep::WaitForVetters
    );
    let message = signed(session_doc.clone(), &vetter.secret).await;
    applicant.receive(&message, &vetter.did).await;
    assert_eq!(
        applicant.application().next_step(Utc::now()),
        NextStep::SendCard {
            session_id: session_doc.id.clone()
        }
    );
}

/// A community's answer is acted on only when the community signed it: an
/// unsigned manifest, or one whose content was changed after signing, is not
/// adopted — whoever the transport says sent it.
#[tokio::test]
async fn an_unsigned_or_altered_community_answer_is_not_acted_on() {
    let mut applicant = Party::new(1);
    applicant
        .book
        .start_application(COMMUNITY, applicant.persona, &applicant.did, Utc::now())
        .unwrap();

    let unsigned = Message::build(
        wire::new_id(),
        JOIN_REQUEST_MANIFEST_0_2_RESPONSE_TYPE.to_string(),
        json!({
            "type": JOIN_REQUEST_MANIFEST_0_2_RESPONSE_TYPE,
            "issuer": COMMUNITY,
            "payload": manifest_body(),
        }),
    )
    .from(COMMUNITY.to_string())
    .finalize();
    let handled = applicant.receive(&unsigned, COMMUNITY).await;
    assert!(!handled.changed && handled.notice.is_none());

    let mut altered = manifest_reply(&applicant.did.clone()).await;
    altered.body["payload"]["tampered"] = json!(true);
    let handled = applicant.receive(&altered, COMMUNITY).await;
    assert!(!handled.changed && handled.notice.is_none());

    // Signed by the community, but arriving as another sender's answer.
    let handled = applicant
        .receive(
            &manifest_reply(&applicant.did.clone()).await,
            "did:key:zElsewhere",
        )
        .await;
    assert!(!handled.changed && handled.notice.is_none());

    // The genuine answer is adopted.
    let handled = applicant
        .receive(&manifest_reply(&applicant.did.clone()).await, COMMUNITY)
        .await;
    assert!(matches!(
        handled.notice,
        Some(Notice::RequirementsUpdated { .. })
    ));
}

/// A community answer checked off the loop is taken from that check — not
/// resolved again — and one whose check failed or never ran is refused.
#[tokio::test]
async fn a_community_answer_is_taken_from_its_off_loop_check() {
    let mut applicant = Party::new(1);
    applicant
        .book
        .start_application(COMMUNITY, applicant.persona, &applicant.did, Utc::now())
        .unwrap();
    let reply = manifest_reply(&applicant.did.clone()).await;

    let refused = Err(crate::operational::OperationalError::NotChecked);
    let handled = applicant.receive_checked(&reply, COMMUNITY, &refused).await;
    assert!(!handled.changed && handled.notice.is_none());

    let checked = crate::operational::verify_operational(
        &reply.body,
        COMMUNITY,
        &[applicant.did.as_str()],
        &reply.typ,
        &did_resolver().await,
        &applicant.seen,
        Utc::now(),
    )
    .await;
    let handled = applicant.receive_checked(&reply, COMMUNITY, &checked).await;
    assert!(matches!(
        handled.notice,
        Some(Notice::RequirementsUpdated { .. })
    ));
}

/// A vetter role credential whose proof does not verify is not kept — here, a
/// genuine grant with its role claim changed after the community signed it.
#[tokio::test]
async fn a_tampered_vetter_grant_is_not_kept() {
    let mut member = Party::new(2).member_of(COMMUNITY);
    let mut credential = role_credential(
        &secret(COMMUNITY_SEED),
        COMMUNITY,
        &member.did.clone(),
        VETTER_ROLE,
    )
    .await;
    credential["validUntil"] = json!("2999-01-01T00:00:00Z");
    let handled = member
        .receive(
            &delivery(&credential, &secret(COMMUNITY_SEED)).await,
            COMMUNITY,
        )
        .await;
    assert!(handled.notice.is_none() && member.book.vetter_grants.is_empty());
}

/// A vetter grant naming a status list that cannot be read is not kept:
/// revocation fails closed.
#[tokio::test]
async fn a_grant_whose_status_cannot_be_read_is_not_kept() {
    let mut vetter = Party::new(2).member_of(COMMUNITY);
    let credential =
        role_credential_with_status(&secret(COMMUNITY_SEED), &vetter.did.clone()).await;
    let handled = vetter
        .receive(
            &delivery(&credential, &secret(COMMUNITY_SEED)).await,
            COMMUNITY,
        )
        .await;
    assert!(handled.notice.is_none() && vetter.book.vetter_grants.is_empty());
}

/// A community answer is operational: signed with the community's
/// authentication key, not its credential key, and taken once.
#[tokio::test]
async fn a_community_answer_is_taken_once_and_only_from_the_operational_key() {
    let mut applicant = Party::new(1);
    applicant
        .book
        .start_application(COMMUNITY, applicant.persona, &applicant.did, Utc::now())
        .unwrap();
    // `did:key` lists its one key under both relationships, so an
    // assertionMethod proof is refused for its purpose.
    let asserted = crate::proof_check::test_support::sign(
        json!({
            "id": wire::new_id(),
            "type": JOIN_REQUEST_MANIFEST_0_2_RESPONSE_TYPE,
            "issuer": COMMUNITY,
            "recipient": applicant.did,
            "issuedAt": Utc::now().to_rfc3339(),
            "payload": manifest_body(),
        }),
        &[&secret(COMMUNITY_SEED)],
    )
    .await;
    let message = Message::build(
        wire::new_id(),
        JOIN_REQUEST_MANIFEST_0_2_RESPONSE_TYPE.to_string(),
        asserted,
    )
    .from(COMMUNITY.to_string())
    .finalize();
    let handled = applicant.receive(&message, COMMUNITY).await;
    assert!(handled.notice.is_none());

    let reply = manifest_reply(&applicant.did.clone()).await;
    let handled = applicant.receive(&reply, COMMUNITY).await;
    assert!(matches!(
        handled.notice,
        Some(Notice::RequirementsUpdated { .. })
    ));
    let mut again = reply.clone();
    again.id = wire::new_id();
    let handled = applicant.receive(&again, COMMUNITY).await;
    assert!(
        !handled.changed && handled.notice.is_none(),
        "a replayed answer is refused"
    );

    // Addressed to somebody else.
    let other = manifest_reply("did:key:zSomeoneElse").await;
    let handled = applicant.receive(&other, COMMUNITY).await;
    assert!(!handled.changed && handled.notice.is_none());
}

/// A signed manifest nobody asked for — no query, no application, no
/// membership — is not learned, and nothing is written to the replay set.
#[tokio::test]
async fn an_unsolicited_manifest_writes_nothing() {
    let mut stranger = Party::new(7);
    let reply = manifest_reply(&stranger.did.clone()).await;
    let handled = stranger.receive(&reply, COMMUNITY).await;
    assert!(!handled.changed && handled.notice.is_none() && handled.answer.is_none());
    assert!(stranger.seen.is_empty(), "the replay set is untouched");
    assert!(matches!(
        stranger.book.knowledge(COMMUNITY),
        Knowledge::Unknown
    ));
}

impl Party {
    /// The account knows this party's persona, as a real account does — what
    /// a reply needs to sign as it.
    fn with_persona_record(mut self) -> Self {
        self.account.personas.insert(
            self.persona,
            crate::config::account::PersonaRecord {
                extra: serde_json::Map::new(),
                persona_id: self.persona,
                did: self.did.clone(),
                did_document: None,
                key_refs: Vec::new(),
                mediator_did: None,
                origin_context_id: String::new(),
                created_at: Utc::now(),
                label: None,
            },
        );
        self
    }
}

/// A 0.3 manifest answer is read into the book with its version and what each
/// criterion's admission is; a vetting criterion is still known as vetting.
#[tokio::test]
async fn a_v0_3_manifest_is_learned_with_its_version_and_admission() {
    use super::protocol::{Admission, JoinProtocol};
    let mut applicant = Party::new(1);
    let request = wire::manifest_request(&applicant.did, COMMUNITY, JoinProtocol::V0_3).unwrap();
    applicant
        .book
        .ask(asked(&request, applicant.persona, QueryKind::Manifest));
    let body = json!({
        "communityDid": COMMUNITY,
        "criteria": [
            { "id": "invited", "admission": "automatic", "invitationRequired": true,
              "requirementsDigest": DIGEST },
            { "id": "vetted", "admission": "review", "requirementsDigest": DIGEST,
              "vetting": serde_json::to_value(requirements()).unwrap() },
        ],
    });
    let handled = applicant
        .receive(&community_answer(&request, &body).await, COMMUNITY)
        .await;
    assert!(
        matches!(handled.answer, Some(CommunityAnswer::Manifest { .. })),
        "{:?}",
        handled.answer
    );
    assert_eq!(applicant.book.protocol_for(COMMUNITY), JoinProtocol::V0_3);
    let routes = applicant.book.routes(COMMUNITY);
    assert_eq!(routes.len(), 2);
    assert_eq!(routes[0].admission, Some(Admission::Automatic));
    assert_eq!(routes[0].invitation_required, Some(true));
    assert!(routes[1].vetting && routes[1].admission == Some(Admission::Review));
    assert!(matches!(
        applicant.book.knowledge(COMMUNITY),
        Knowledge::Vetting(_)
    ));
}

/// A community that does not serve 0.3 — answering `unsupportedVersion`, as a
/// 0.2 VTC does — is asked again in 0.2, and the person waiting keeps waiting
/// instead of hearing a refusal. A refusal of 0.2 too is reported as one.
#[tokio::test]
async fn a_manifest_refused_as_an_unsupported_version_is_asked_again_in_0_2() {
    use super::protocol::JoinProtocol;
    let mut applicant = Party::new(1).with_persona_record();
    let request = wire::manifest_request(&applicant.did, COMMUNITY, JoinProtocol::V0_3).unwrap();
    applicant
        .book
        .ask(asked(&request, applicant.persona, QueryKind::Manifest));

    let handled = applicant
        .receive(
            &community_refusal(&request, "unsupportedVersion"),
            COMMUNITY,
        )
        .await;
    assert!(
        handled.answer.is_none(),
        "not an answer: {:?}",
        handled.answer
    );
    let reply = handled.reply.expect("asked again");
    assert_eq!(
        reply.document.type_uri.to_string(),
        JoinProtocol::V0_2.manifest_type()
    );
    assert_eq!(reply.persona, applicant.persona);
    assert_eq!(applicant.book.protocol_for(COMMUNITY), JoinProtocol::V0_2);
    assert!(
        applicant
            .book
            .waiting_on(COMMUNITY, QueryKind::Manifest)
            .is_some_and(|q| q.document_id == reply.document.id),
        "the new question is the one waited on"
    );

    let handled = applicant
        .receive(
            &community_refusal(&reply.document, "unsupportedVersion"),
            COMMUNITY,
        )
        .await;
    assert!(handled.reply.is_none(), "nothing older to ask in");
    assert!(matches!(
        handled.answer,
        Some(CommunityAnswer::Refused {
            kind: QueryKind::Manifest,
            ..
        })
    ));
}

/// Both journeys follow the real exchange: the applicant's moves on to the
/// session once a vetter opens one, and the vetter's waits on the card while
/// the code is read, then puts the person check in front of them.
#[tokio::test]
async fn the_journeys_follow_the_exchange() {
    use super::journey::{
        ApplicantStep, StepState, VetterStep, applicant_journey, current, vetter_journey,
    };
    let (mut applicant, mut vetter, _) = ready().await;
    let (request_id, _session) = in_session(&mut applicant, &mut vetter).await;

    let entry = vetter.book.desk_entry(&request_id).expect("on the desk");
    let (steps, ending) = vetter_journey(entry);
    assert_eq!(ending, None);
    assert_eq!(current(&steps), Some(VetterStep::Code));
    let card = steps.iter().find(|s| s.step == VetterStep::Card).unwrap();
    assert_eq!(card.state, StepState::Waiting, "the card is theirs to send");
    let code = steps.iter().find(|s| s.step == VetterStep::Code).unwrap();
    assert!(code.detail.is_some(), "the code is on the step");

    // The applicant's session arrives once the vetter's document is received;
    // before that it is waiting on the vetter, never the holder's to act on.
    let journey = applicant_journey(applicant.application(), Utc::now());
    let sessions = journey
        .iter()
        .find(|s| s.step == ApplicantStep::Sessions)
        .unwrap();
    assert_ne!(sessions.state, StepState::Todo, "{journey:?}");
}

/// A reason and a note sent with a decline reach the applicant's own record
/// of the request — which is what its page shows them — and go nowhere else.
#[tokio::test]
async fn a_declines_reason_and_note_reach_the_applicant() {
    let (mut applicant, mut vetter, _) = ready().await;
    let (request_id, _) = in_session(&mut applicant, &mut vetter).await;
    let body = vetter
        .book
        .decline(
            &request_id,
            Some(decline::v0_1::PayloadCode::DocumentMismatch),
            Some("The name on your passport was spelled differently.".into()),
            Utc::now(),
        )
        .unwrap();
    let doc = wire::document(
        VETTING_DECLINE_TYPE,
        &vetter.did,
        &applicant.did,
        wire::new_id(),
        &body,
    )
    .unwrap();
    let message = signed(doc, &vetter.secret).await;
    applicant.receive(&message, &vetter.did).await;
    let request = applicant.application().requests.last().unwrap().clone();
    match request.state {
        RequestState::Declined { code, message } => {
            assert_eq!(code, Some(decline::v0_1::PayloadCode::DocumentMismatch));
            assert_eq!(
                message.as_deref(),
                Some("The name on your passport was spelled differently.")
            );
        }
        other => panic!("declined, with its reason: {other:?}"),
    }
}

/// A finished request keeps nothing about the person: the card's values go at
/// the first prune after it closes, the request stays on the desk only through
/// the grace a failed send needs, and then it is a record of the community,
/// the date and the outcome — no card, no claims, no DID.
#[tokio::test]
async fn a_finished_request_forgets_the_person_and_leaves_the_desk() {
    use super::book::{CLOSED_GRACE, VettedOutcome};
    let (mut applicant, mut vetter, _) = ready().await;
    let resolver = TrustTaskVmResolver::did_key_only();
    let (request_id, session_doc) = in_session(&mut applicant, &mut vetter).await;
    let message = signed(session_doc.clone(), &vetter.secret).await;
    let handled = applicant.receive(&message, &vetter.did).await;
    let Some(Notice::SessionOpened { session_id, .. }) = handled.notice else {
        panic!("the session opens");
    };
    let draft = applicant
        .application()
        .card_draft(
            &session_id,
            vec![
                session::v0_1::VettingCardClaim::try_from(
                    session::v0_1::VettingCardClaim::builder()
                        .type_("name.legal")
                        .value(json!("Alice Example"))
                        .provenance("selfAsserted"),
                )
                .unwrap(),
            ],
            Utc::now(),
        )
        .unwrap();
    let card = sign_card(draft, &applicant.secret).await.unwrap();
    applicant
        .application()
        .record_card(&session_id, &card, &resolver, Utc::now())
        .await
        .unwrap();
    let doc = wire::response(&session_doc, &json!({ "card": card })).unwrap();
    vetter
        .receive(&signed(doc, &applicant.secret).await, &applicant.did)
        .await;

    let closed = Utc::now();
    vetter
        .book
        .decline(&request_id, None, None, closed)
        .unwrap();
    let held = |book: &VettingBook| {
        serde_json::to_string(book)
            .unwrap()
            .contains("Alice Example")
    };
    assert!(
        held(&vetter.book),
        "the card is there until the first prune"
    );

    // The first prune forgets the card; the request waits out the grace.
    assert!(vetter.book.prune(closed));
    assert!(!held(&vetter.book), "the legal name is gone at once");
    assert!(
        vetter.book.desk_entry(&request_id).is_some(),
        "a failed send must find it"
    );

    // After the grace, it is a record with nothing about the person.
    assert!(vetter.book.prune(closed + CLOSED_GRACE));
    assert!(vetter.book.desk_entry(&request_id).is_none());
    let record = vetter
        .book
        .vetted
        .last()
        .expect("a record that we vetted someone");
    assert_eq!(record.outcome, VettedOutcome::Declined);
    assert_eq!(record.community, COMMUNITY);
    let stored = serde_json::to_string(&vetter.book.vetted).unwrap();
    assert!(!stored.contains(&applicant.did), "no identifier: {stored}");
}

/// A vetter whose engine is enrolled with `COMMUNITY`, and one draw of the drip asked for and
/// in flight — what `hidden_vetting_send` leaves behind.
fn vetter_with_a_draw_in_flight(label: &str, tick: u32) -> (Party, TrustTask<Value>) {
    use rand::SeedableRng;
    let mut vetter = Party::new(7).member_of(COMMUNITY);
    let params: super::hidden::HiddenParams = serde_json::from_value(hidden_params()).unwrap();
    let mut rng = rand::rngs::StdRng::seed_from_u64(0x71C);
    let mut snapshot =
        super::hidden::vetter_start(COMMUNITY, &params, &vetter.did, &mut rng).unwrap();
    let body =
        super::hidden::drip_request(COMMUNITY, &params, &mut snapshot, tick, label, 3, &mut rng)
            .unwrap();
    assert_eq!(
        snapshot.pending.len(),
        3,
        "the serials are kept for the answer"
    );
    vetter
        .book
        .hidden_vetter
        .push(super::book::HiddenVetterState::new(
            COMMUNITY,
            vetter.persona,
            params,
            snapshot,
        ));
    let request = wire::pcs_tokens_request(&vetter.did, COMMUNITY, &body).unwrap();
    vetter
        .book
        .ask(asked(&request, vetter.persona, QueryKind::PcsTokens));
    vetter
        .book
        .draws_in_flight
        .insert(request.id.clone(), (label.to_string(), tick));
    (vetter, request)
}

/// `tickNotYet` is "not yet": no notice, nothing recorded as served, the serials dropped and the
/// next pass held back until the community's clock has caught up. `alreadyServed` is "done":
/// recorded as served, so the tick is never asked for again. Neither is news.
#[tokio::test]
async fn a_tick_not_begun_is_waited_for_and_a_served_one_is_done() {
    let label = "token/2026-10";
    let (mut vetter, request) = vetter_with_a_draw_in_flight(label, 4);
    let handled = vetter
        .receive(
            &community_refusal(&request, super::hidden::TOKENS_TICK_NOT_YET),
            COMMUNITY,
        )
        .await;
    assert!(handled.notice.is_none(), "{:?}", handled.notice);
    assert!(matches!(
        &handled.answer,
        Some(CommunityAnswer::Refused { kind, code, .. }) if !kind.refusal_is_news(code)
    ));
    let state = &vetter.book.hidden_vetter[0];
    assert!(state.retry_at.is_some_and(|t| t > Utc::now()));
    assert!(state.last_ticks.is_empty(), "not served");
    assert!(state.last_refusal.is_none(), "not a failure");
    assert!(
        state.snapshot.pending.is_empty(),
        "the refused draw's serials are dropped"
    );
    assert!(vetter.book.draws_in_flight.is_empty());

    let (mut vetter, request) = vetter_with_a_draw_in_flight(label, 4);
    let handled = vetter
        .receive(
            &community_refusal(&request, super::hidden::TOKENS_ALREADY_SERVED),
            COMMUNITY,
        )
        .await;
    assert!(handled.notice.is_none());
    assert_eq!(vetter.book.hidden_vetter[0].last_ticks.get(label), Some(&4));
}

/// Every other refusal is said in words and kept for the desk to show.
#[tokio::test]
async fn any_other_drip_refusal_is_said_in_words_and_kept() {
    let (mut vetter, request) = vetter_with_a_draw_in_flight("token/2026-10", 4);
    let handled = vetter
        .receive(
            &community_refusal(&request, "vtc/vetting/vetters/pcs-tokens:labelNotLive"),
            COMMUNITY,
        )
        .await;
    let notice = handled.notice.expect("a refusal that is news");
    assert!(
        notice
            .describe()
            .contains("not issuing tokens under that label"),
        "{}",
        notice.describe()
    );
    let refusal = vetter.book.hidden_vetter[0]
        .last_refusal
        .clone()
        .expect("kept for the desk");
    assert_eq!(refusal.code, "vtc/vetting/vetters/pcs-tokens:labelNotLive");
    assert!(vetter.book.hidden_vetter[0].last_ticks.is_empty());
}

/// The rollover and the re-key, on the engine's own state. A new month is new labels under the
/// same keys, and they are taken; new keys are not, and the drip stops until the vetter decides.
#[test]
fn the_engine_follows_the_published_labels_and_stops_at_new_keys() {
    use super::book::{Adopted, HiddenVetterState};
    use super::hidden::{Due, HiddenParams, due};
    let enrolled: HiddenParams = serde_json::from_value(hidden_params()).unwrap();
    let mut snapshot = openvtc_vetting_pcs::snapshot::VetterSnapshot::without_keys("member-1");
    snapshot
        .credentials
        .insert("2026-10".into(), "zOctober".into());
    snapshot
        .credentials
        .insert("2026-11".into(), "zNovember".into());
    let mut state = HiddenVetterState::new(COMMUNITY, PersonaId::new(), enrolled.clone(), snapshot);
    let november = chrono::TimeZone::with_ymd_and_hms(&Utc, 2026, 11, 2, 9, 0, 0).unwrap();

    // What the community publishes in November: the same keys, the next month's labels.
    let live = HiddenParams {
        vetter_labels: vec!["vetter/2026-11".into(), "vetter/2026-10".into()],
        token_labels: vec!["token/2026-11".into(), "token/2026-10".into()],
        tick_length: Some("P1D".into()),
        ..enrolled.clone()
    };
    assert_eq!(state.adopt_published(&live, november), Adopted::Updated);
    assert_eq!(state.adopt_published(&live, november), Adopted::Unchanged);
    assert_eq!(
        due(
            &state.params,
            Some(&state.snapshot),
            &state.last_ticks,
            &[],
            november
        ),
        Due::Draw {
            label: "token/2026-11".into(),
            tick: 0,
            rate: state.params.drip_per_tick,
        },
        "drawn under the live label, oldest tick first"
    );

    // The community re-keys: nothing is taken, and it is noticed once.
    let rekeyed = HiddenParams {
        token_key: "zSomeOtherTokenKey".into(),
        ..live.clone()
    };
    assert_eq!(
        state.adopt_published(&rekeyed, november),
        Adopted::Rekeyed { first: true }
    );
    assert_eq!(
        state.adopt_published(&rekeyed, november),
        Adopted::Rekeyed { first: false }
    );
    assert_eq!(state.params, live, "the keys we enrolled under stay");
    assert!(state.rekeyed_at.is_some());
    let plan = state.plan(Some(&rekeyed), &[], november);
    assert!(plan.owed.is_empty(), "the drip stops: {:?}", plan.owed);
    // Back to our keys, and the drip resumes.
    let plan = state.plan(Some(&live), &[], november);
    assert_eq!(plan.adopted, Adopted::Updated);
    assert!(state.rekeyed_at.is_none());
    assert_eq!(
        plan.owed.len(),
        2,
        "ticks 0 and 1 of November: {:?}",
        plan.owed
    );
    // A draw already on its way is not asked for again.
    let plan = state.plan(Some(&live), &[("token/2026-11".into(), 0)], november);
    assert_eq!(
        plan.owed,
        [Due::Draw {
            label: "token/2026-11".into(),
            tick: 1,
            rate: state.params.drip_per_tick,
        }]
    );
    // And a `tickNotYet` wait holds the whole pass back.
    state.retry_at = Some(november + Duration::minutes(5));
    assert!(state.plan(Some(&live), &[], november).owed.is_empty());
}

/// A manifest carrying `params` on its one criterion, as a community serves it.
fn manifest_publishing(params: &Value) -> Value {
    json!({
        "criteria": [{
            "id": "c1",
            "vetting": {
                "minStatements": 1,
                "ext": { super::hidden::HIDDEN_VETTING_NS: params }
            }
        }]
    })
}

/// A vetter enrolled under October at `COMMUNITY`, holding `rate` tokens a tick as the rate.
fn vetter_drawing_at(rate: usize) -> (VettingBook, Value) {
    let mut published = hidden_params();
    published["dripPerTick"] = json!(rate);
    let params: super::hidden::HiddenParams = serde_json::from_value(published.clone()).unwrap();
    let mut snapshot = openvtc_vetting_pcs::snapshot::VetterSnapshot::without_keys("member-1");
    snapshot
        .credentials
        .insert("2026-10".into(), "zOctober".into());
    let mut book = VettingBook::default();
    book.hidden_vetter.push(super::book::HiddenVetterState::new(
        COMMUNITY,
        PersonaId::new(),
        params,
        snapshot,
    ));
    (book, published)
}

/// Every manifest read moves the rate a vetter's engine draws at — at the read, not at its next
/// pass — and dates it. The community went from 100 tokens a tick to 20; the next draw asks
/// for 20.
#[test]
fn a_manifest_read_moves_the_rate_the_next_draw_asks_for() {
    use super::hidden::Due;
    let (mut book, mut published) = vetter_drawing_at(100);
    let october = chrono::TimeZone::with_ymd_and_hms(&Utc, 2026, 10, 5, 21, 16, 0).unwrap();
    assert!(
        book.hidden_vetter[0].draw_hold(false, october).is_some(),
        "never read from the community: no draw yet"
    );

    published["dripPerTick"] = json!(20);
    book.learn_mode(COMMUNITY, &manifest_publishing(&published), None, october);
    let held = &mut book.hidden_vetter[0];
    assert_eq!(held.params.drip_per_tick, 20, "taken at the read");
    assert_eq!(held.params_read_at, Some(october));
    assert_eq!(held.draw_hold(false, october), None);
    let plan = held.plan(book.hidden_published.get(COMMUNITY), &[], october);
    assert!(!plan.owed.is_empty());
    for owed in &plan.owed {
        assert!(
            matches!(owed, Due::Draw { rate: 20, .. }),
            "drawn at the rate read: {owed:?}"
        );
    }
    // A read that is open holds the draw, and one older than the TTL is not enough.
    assert_eq!(
        held.draw_hold(true, october),
        Some(super::book::DrawHold::Reading)
    );
    assert_eq!(
        held.draw_hold(
            false,
            october + super::book::PARAMS_FRESH_FOR + Duration::seconds(1)
        ),
        Some(super::book::DrawHold::Unread)
    );
}

/// A pass that held its draws for a read is run again when the read lands.
#[test]
fn a_read_a_pass_waited_for_runs_the_schedule_again() {
    let (mut book, published) = vetter_drawing_at(20);
    book.hidden_vetter[0].awaiting_read = true;
    book.vetter_refresh_due = false;
    book.learn_mode(
        COMMUNITY,
        &manifest_publishing(&published),
        None,
        Utc::now(),
    );
    assert!(book.vetter_refresh_due);
    assert!(!book.hidden_vetter[0].awaiting_read);
}

/// `overQuota` is the community saying the rate this client holds is not the one it serves.
/// Nothing is drawn until its manifest has been read again — asked for at once — and then at
/// the rate it says: the published one if it moved, or the one the refusal named.
#[tokio::test]
async fn an_over_quota_refusal_rereads_the_rate_before_drawing_again() {
    use super::book::DrawHold;
    use super::hidden::Due;
    let label = "token/2026-10";
    let october = chrono::TimeZone::with_ymd_and_hms(&Utc, 2026, 10, 5, 21, 16, 0).unwrap();
    let refusal = |request: &TrustTask<Value>, detail: &str| {
        wire::to_message(
            &wire::refusal(request, super::hidden::TOKENS_OVER_QUOTA, Some(detail)).unwrap(),
        )
        .unwrap()
    };
    let setup = || {
        let (mut vetter, request) = vetter_with_a_draw_in_flight(label, 1);
        let held = &mut vetter.book.hidden_vetter[0];
        held.params.drip_per_tick = 100;
        held.params_read_at = Some(Utc::now() - Duration::minutes(1));
        held.snapshot
            .credentials
            .insert("2026-10".into(), "zOctober".into());
        vetter.book.vetter_refresh_due = false;
        vetter
            .book
            .mode_asked(COMMUNITY, Utc::now() - Duration::minutes(1));
        (vetter, request)
    };

    // The refusal names the rate: held, re-read at once, and then drawn at 20.
    let (mut vetter, request) = setup();
    let handled = vetter
        .receive(
            &refusal(
                &request,
                "drip refused: asked for 100 tokens; this community drips 20 a tick",
            ),
            COMMUNITY,
        )
        .await;
    let said = handled.notice.expect("news").describe();
    assert!(said.contains("being read again"), "{said}");
    assert!(
        !said.contains("next pass asks for the published rate"),
        "{said}"
    );
    assert!(vetter.book.vetter_refresh_due, "the re-read is asked now");
    assert!(
        vetter.book.params_reread_owed(COMMUNITY),
        "owed despite a read a minute ago"
    );
    let now = Utc::now();
    let held = &vetter.book.hidden_vetter[0];
    assert_eq!(held.draw_hold(false, now), Some(DrawHold::Unread));
    let q = held.over_quota.clone().expect("kept");
    assert_eq!((q.asked, q.allowed), (100, Some(20)));
    // Asked: no second ask is owed for the same refusal.
    vetter.book.mode_asked(COMMUNITY, now);
    assert!(!vetter.book.params_reread_owed(COMMUNITY));
    // The community still publishes 100: drawn at the 20 it serves.
    let published = serde_json::to_value(&vetter.book.hidden_vetter[0].params).unwrap();
    let later = now + Duration::seconds(2);
    vetter
        .book
        .learn_mode(COMMUNITY, &manifest_publishing(&published), None, later);
    let held = &mut vetter.book.hidden_vetter[0];
    assert_eq!(held.draw_hold(false, later), None);
    let plan = held.plan(None, &[], october);
    assert!(!plan.owed.is_empty());
    assert!(
        plan.owed
            .iter()
            .all(|d| matches!(d, Due::Draw { rate: 20, .. })),
        "{:?}",
        plan.owed
    );

    // The refusal does not name the rate, and the community still publishes 100: nothing is
    // drawn again — it would only be refused — until it publishes another.
    let (mut vetter, request) = setup();
    vetter
        .receive(&refusal(&request, "because"), COMMUNITY)
        .await;
    let mut published = serde_json::to_value(&vetter.book.hidden_vetter[0].params).unwrap();
    let later = Utc::now() + Duration::seconds(2);
    vetter
        .book
        .learn_mode(COMMUNITY, &manifest_publishing(&published), None, later);
    assert!(matches!(
        vetter.book.hidden_vetter[0].draw_hold(false, later),
        Some(DrawHold::Disagrees {
            asked: 100,
            published: 100,
            ..
        })
    ));
    // It publishes 20: the hold ends, and the next draw asks for 20.
    published["dripPerTick"] = json!(20);
    let later = later + Duration::seconds(1);
    vetter
        .book
        .learn_mode(COMMUNITY, &manifest_publishing(&published), None, later);
    let held = &mut vetter.book.hidden_vetter[0];
    assert_eq!(held.draw_hold(false, later), None);
    assert!(held.over_quota.is_none());
    assert!(
        held.plan(None, &[], october)
            .owed
            .iter()
            .all(|d| matches!(d, Due::Draw { rate: 20, .. }))
    );
}

/// The numbers an `overQuota` refusal gives, when it gives them.
#[test]
fn an_over_quota_refusal_is_read_for_its_numbers() {
    use super::book::{over_quota_allowed, over_quota_asked};
    let text = "drip refused: asked for 100 tokens; this community drips 20 a tick";
    assert_eq!(over_quota_asked(text), Some(100));
    assert_eq!(over_quota_allowed(text), Some(20));
    assert_eq!(over_quota_allowed("because"), None);
}

/// A pass over a community fed only what we enrolled under — the bug this replaced — never
/// moves to the new month; fed what the community publishes now, it re-enrols.
#[test]
fn a_pass_reenrols_when_a_new_vetter_label_is_live() {
    use super::book::HiddenVetterState;
    use super::hidden::{Due, HiddenParams};
    let enrolled: HiddenParams = serde_json::from_value(hidden_params()).unwrap();
    let mut snapshot = openvtc_vetting_pcs::snapshot::VetterSnapshot::without_keys("member-1");
    snapshot
        .credentials
        .insert("2026-10".into(), "zOctober".into());
    let mut state = HiddenVetterState::new(COMMUNITY, PersonaId::new(), enrolled.clone(), snapshot);
    let november = chrono::TimeZone::with_ymd_and_hms(&Utc, 2026, 11, 2, 9, 0, 0).unwrap();
    assert!(
        state.plan(None, &[], november).owed.is_empty(),
        "October's labels in November owe nothing"
    );
    let live = HiddenParams {
        vetter_labels: vec!["vetter/2026-11".into(), "vetter/2026-10".into()],
        token_labels: vec!["token/2026-11".into(), "token/2026-10".into()],
        ..enrolled
    };
    assert_eq!(
        state.plan(Some(&live), &[], november).owed,
        [Due::Enrol {
            period: "2026-11".into()
        }]
    );
}

/// A request reaching the desk marks the vetter side due a re-read of what
/// its community requires — the loop takes the flag and asks, so a community
/// that turned on PCS ZKP vetting is known before a session opens.
#[tokio::test]
async fn a_request_on_the_desk_makes_the_vetter_side_due_a_refresh() {
    let (mut applicant, mut vetter, _) = ready().await;
    // Becoming a vetter asked for one already (`a_new_vetter_enrols_now…`); the loop took it.
    vetter.book.vetter_refresh_due = false;
    in_session(&mut applicant, &mut vetter).await;
    assert!(
        vetter.book.vetter_refresh_due,
        "the accepted request asks for a re-read"
    );
    assert!(
        !serde_json::to_string(&vetter.book)
            .unwrap()
            .contains("vetter_refresh_due"),
        "a run-only flag is never saved"
    );
}

// ---------------------------------------------------------------------------------------------
// Enrolment answers that arrive late, or cannot be opened
// ---------------------------------------------------------------------------------------------

/// A community that can actually sign: an issuer, and the parameters it publishes.
fn issuing_community() -> (
    openvtc_vetting_pcs::issuer::Issuer,
    super::hidden::HiddenParams,
) {
    let issuer = openvtc_vetting_pcs::issuer::Issuer::derive(COMMUNITY, &[0x5E; 32]).unwrap();
    let (helper_key, token_key) = issuer.public_text().unwrap();
    let params = super::hidden::HiddenParams {
        suite: super::hidden::SUITE.into(),
        helper_key,
        token_key,
        vetter_labels: vec!["vetter/2026-10".into()],
        token_labels: vec!["token/2026-10".into()],
        drip_per_tick: 10,
        events: Vec::new(),
        tick_length: None,
    };
    (issuer, params)
}

/// A vetter with a fresh engine at `COMMUNITY` that has asked to enrol: the request, and the
/// community's answer to it, signed as the community signs.
async fn vetter_asking_to_enrol() -> (Party, TrustTask<Value>, Message) {
    use rand::SeedableRng;
    let (issuer, params) = issuing_community();
    let mut vetter = Party::new(7).member_of(COMMUNITY);
    let mut rng = rand::rngs::StdRng::seed_from_u64(0xE1);
    let snapshot = super::hidden::vetter_start(COMMUNITY, &params, &vetter.did, &mut rng).unwrap();
    let (body, blinding) =
        super::hidden::enrolment_request(COMMUNITY, &params, &snapshot, "2026-10", &mut rng)
            .unwrap();
    vetter
        .book
        .hidden_vetter
        .push(super::book::HiddenVetterState::new(
            COMMUNITY,
            vetter.persona,
            params,
            snapshot,
        ));
    let request = wire::pcs_root_request(&vetter.did, COMMUNITY, &body).unwrap();
    vetter
        .book
        .ask(asked(&request, vetter.persona, QueryKind::PcsRoot));
    vetter
        .book
        .remember_enrolment(super::book::PendingEnrolment {
            document_id: request.id.clone(),
            community: COMMUNITY.into(),
            persona: vetter.persona,
            blinding: std::sync::Arc::new(blinding),
        });

    // The community's half, as `vtc-service`'s `pcs_issue::enrol` does it.
    let id = openvtc_vetting_pcs::scheme::point_from_text(&body.id).unwrap();
    let pre = issuer
        .issue_root(
            "2026-10",
            &id,
            &serde_json::from_value(body.request.clone()).unwrap(),
            &mut rng,
        )
        .unwrap();
    let answer = wire::pcs::RootResponse {
        label: "vetter/2026-10".into(),
        pre_credential: openvtc_vetting_pcs::scheme::enc(&pre).unwrap(),
        ext: None,
    };
    let message = community_answer(&request, &answer).await;
    (vetter, request, message)
}

/// The live failure: the community enrolled the vetter, its answer arrived after the question
/// had timed out, and was dropped — after which the community refuses every second request
/// under the label (`alreadyEnrolled`), so the vetter could not attest for the rest of the
/// month. A late answer is now taken, and the drip follows at once.
#[tokio::test]
async fn an_enrolment_answered_after_its_question_timed_out_is_still_taken() {
    let (mut vetter, _request, answer) = vetter_asking_to_enrol().await;
    let now = Utc::now();
    let expired = vetter
        .book
        .expire_queries(now + Duration::seconds(31), super::queries::QUERY_TIMEOUT);
    assert_eq!(expired.len(), 1, "the question timed out");
    let retry = vetter.book.hidden_vetter[0].unanswered_at(now);
    assert_eq!(
        retry,
        now + Duration::minutes(1),
        "and is asked again, backed off"
    );

    let handled = vetter.receive(&answer, COMMUNITY).await;
    assert!(
        matches!(handled.notice, Some(Notice::HiddenVetterEnrolled { ref label, .. }) if label == "vetter/2026-10"),
        "{:?}",
        handled.notice
    );
    let held = &vetter.book.hidden_vetter[0];
    assert!(
        held.snapshot.credentials.contains_key("2026-10"),
        "the credential is ours"
    );
    assert_eq!(held.unanswered, 0, "an answer resets the backoff");
    assert!(held.retry_at.is_none());
    assert!(held.lost_enrolment.is_none());
    assert!(
        vetter.book.pending_enrolments.is_empty(),
        "the blinding state is spent"
    );
    assert!(
        vetter.book.vetter_refresh_due,
        "the ticks already owed are drawn now, not at the next hourly pass"
    );
    let outlook = vetter
        .book
        .hidden_outlook(COMMUNITY, vetter.persona, now)
        .unwrap();
    assert!(outlook.enrolled);
}

/// An answer this client cannot open (a restart between the ask and the answer drops the
/// blinding state) is the same lock-out. It is recorded, said, and the schedule stops asking
/// for a credential the community will not issue twice — until its next label.
#[tokio::test]
async fn an_enrolment_answer_that_cannot_be_opened_stops_the_asking_until_the_next_label() {
    let (mut vetter, _request, answer) = vetter_asking_to_enrol().await;
    vetter.book.pending_enrolments.clear();
    let handled = vetter.receive(&answer, COMMUNITY).await;
    let notice = handled.notice.expect("said");
    assert!(matches!(notice, Notice::HiddenEnrolmentLost { .. }));
    assert!(
        notice.describe().contains("one credential per label"),
        "{}",
        notice.describe()
    );
    let october = chrono::TimeZone::with_ymd_and_hms(&Utc, 2026, 10, 5, 15, 0, 0).unwrap();
    let held = &mut vetter.book.hidden_vetter[0];
    assert_eq!(held.lost_enrolment.as_deref(), Some("2026-10"));
    assert_eq!(
        held.plan(None, &[], october).owed,
        [super::hidden::Due::Enrol {
            period: "2026-10".into()
        }],
        "asked once more: the community may re-issue to the same identifier"
    );
    assert!(
        held.plan(None, &[], october).owed.is_empty(),
        "and only once"
    );
    // The next label is a new enrolment.
    let november = chrono::TimeZone::with_ymd_and_hms(&Utc, 2026, 11, 1, 9, 0, 0).unwrap();
    let live = super::hidden::HiddenParams {
        vetter_labels: vec!["vetter/2026-11".into(), "vetter/2026-10".into()],
        token_labels: vec!["token/2026-11".into(), "token/2026-10".into()],
        ..held.params.clone()
    };
    assert_eq!(
        held.plan(Some(&live), &[], november).owed,
        [super::hidden::Due::Enrol {
            period: "2026-11".into()
        }]
    );
}

/// `alreadyEnrolled` for a label we hold no credential under means the answer to an earlier
/// request was lost. The schedule asks once more — a community may re-issue it to the same
/// identifier (VTI #1972) — and, refused that too, stops asking under the label rather than
/// collecting the same refusal every pass.
#[tokio::test]
async fn already_enrolled_without_a_credential_asks_once_more_then_stops() {
    let (mut vetter, request, _) = vetter_asking_to_enrol().await;
    let refusal = community_refusal(&request, "vtc/vetting/vetters/pcs-root:alreadyEnrolled");
    vetter.receive(&refusal, COMMUNITY).await;
    let october = chrono::TimeZone::with_ymd_and_hms(&Utc, 2026, 10, 5, 15, 0, 0).unwrap();
    let outlook = vetter
        .book
        .hidden_outlook(COMMUNITY, vetter.persona, october)
        .unwrap();
    assert!(
        !outlook.enrolment_lost,
        "one more ask to come, so not given up on"
    );
    let held = &mut vetter.book.hidden_vetter[0];
    assert_eq!(held.lost_enrolment.as_deref(), Some("2026-10"));
    assert_eq!(held.plan(None, &[], october).owed.len(), 1, "one more ask");
    // Asked: not asked again, whatever the answer — a refusal leaves it spent, and an opened
    // re-issue clears the lost label altogether.
    assert!(held.lost_reasked);
    assert!(held.plan(None, &[], october).owed.is_empty());
    assert!(
        vetter.book.pending_enrolments.is_empty(),
        "a refused request issued nothing to open"
    );
    let outlook = vetter
        .book
        .hidden_outlook(COMMUNITY, vetter.persona, october)
        .unwrap();
    assert!(outlook.enrolment_lost);
}

/// No credential and no token are states a vetter waits out — not "parameters could not be
/// read", which is what both used to say.
#[tokio::test]
async fn attesting_without_a_credential_or_a_token_says_which() {
    use super::hidden::HiddenError;
    use rand::SeedableRng;
    let (mut vetter, _request, answer) = vetter_asking_to_enrol().await;
    let mut rng = rand::rngs::StdRng::seed_from_u64(0xA7);
    let params = vetter.book.hidden_vetter[0].params.clone();
    // Somebody to attest to: any point of the group will do.
    let applicant =
        super::hidden::start(COMMUNITY, &params, "did:example:applicant", &mut rng).unwrap();
    let applicant_id = applicant.id.clone();
    let meta = || openvtc_vetting_pcs::meta::StatementMeta {
        community: COMMUNITY.into(),
        requirements_digest: "zDigest".into(),
        method: vta_sdk::protocols::vetting::VettingMethod::Video,
        claims_verified: Vec::new(),
        liveness_confirmed: true,
        declared_relationship: vta_sdk::protocols::vetting::VettingRelationship::None,
        identity_commitment: "zCommit".into(),
        card_digest_multibase: "zCard".into(),
        valid_from: Utc::now().date_naive(),
        valid_until: Utc::now().date_naive(),
        token_label: String::new(),
        token_serial: String::new(),
    };

    let mut snapshot = vetter.book.hidden_vetter[0].snapshot.clone();
    let err = super::hidden::attest(
        COMMUNITY,
        &params,
        &mut snapshot,
        &applicant_id,
        meta(),
        &mut rng,
    )
    .unwrap_err();
    assert_eq!(err, HiddenError::NotEnrolled);
    assert!(!err.to_string().contains("could not be read"), "{err}");

    vetter.receive(&answer, COMMUNITY).await;
    let mut snapshot = vetter.book.hidden_vetter[0].snapshot.clone();
    let err = super::hidden::attest(
        COMMUNITY,
        &params,
        &mut snapshot,
        &applicant_id,
        meta(),
        &mut rng,
    )
    .unwrap_err();
    assert_eq!(err, HiddenError::NoToken);
    assert!(err.to_string().contains("no vetting token"), "{err}");
    assert!(!err.to_string().contains("could not be read"), "{err}");
}

/// The backoff after a silence: 1, 2, 4 … minutes, never more than an hour.
#[test]
fn an_unanswered_question_is_asked_again_backed_off_and_bounded() {
    use super::book::{HIDDEN_RETRY_CAP, hidden_retry_after};
    assert_eq!(hidden_retry_after(1), Duration::minutes(1));
    assert_eq!(hidden_retry_after(2), Duration::minutes(2));
    assert_eq!(hidden_retry_after(3), Duration::minutes(4));
    assert_eq!(hidden_retry_after(7), HIDDEN_RETRY_CAP);
    assert_eq!(hidden_retry_after(u32::MAX), HIDDEN_RETRY_CAP);
}

/// A draw answered after its question timed out is still taken while the wallet holds the
/// serials it was asked for: the community served that tick and will not serve it again.
#[tokio::test]
async fn a_draw_answered_after_its_question_timed_out_is_still_taken() {
    use openvtc_vetting_pcs::vtc::Vtc;
    use rand::SeedableRng;
    let label = "token/2026-10";
    let (mut vetter, request) = vetter_with_a_draw_in_flight(label, 1);
    vetter.book.expire_queries(
        Utc::now() + Duration::seconds(31),
        super::queries::QUERY_TIMEOUT,
    );
    assert!(vetter.book.queries.is_empty(), "the question timed out");

    // The community that published `hidden_params()`, serving the draw.
    let mut rng = rand::rngs::StdRng::seed_from_u64(0x0BED);
    let mut vtc = Vtc::new(
        COMMUNITY,
        "2026-10",
        serde_json::to_value(requirements()).unwrap(),
        &mut rng,
    )
    .unwrap();
    assert_eq!(vtc.current_token_label(), label);
    vtc.grant(&vetter.did);
    let asked: wire::pcs::TokensRequest = serde_json::from_value(request.payload.clone()).unwrap();
    let requests = asked
        .requests
        .iter()
        .map(|r| {
            openvtc_vetting_pcs::issuer::TokenRequestWire {
                commitment: r.commitment.clone(),
                opening_proof: r.opening_proof.clone(),
            }
            .to_request()
            .unwrap()
        })
        .collect::<Vec<_>>();
    let pres = vtc
        .drip(&vetter.did, 1, label, &requests, &mut rng)
        .unwrap();
    let served = wire::pcs::TokensResponse {
        label: label.into(),
        tick: 1,
        pre_credentials: pres
            .iter()
            .map(|p| openvtc_vetting_pcs::scheme::enc(p).unwrap())
            .collect(),
        ext: None,
    };
    let handled = vetter
        .receive(&community_answer(&request, &served).await, COMMUNITY)
        .await;
    assert!(
        matches!(
            handled.notice,
            Some(Notice::HiddenTokensDrawn { taken: 3, .. })
        ),
        "{:?}",
        handled.notice
    );
    let held = &vetter.book.hidden_vetter[0];
    assert_eq!(held.tokens().1, 3);
    assert_eq!(held.last_ticks.get(label), Some(&1));
}

/// A new vetter does not wait for the schedule's next pass, which can be an hour away: the
/// grant arriving asks the loop to read the community and enrol now — and the enrolment's answer
/// asks it to draw the first tokens straight after.
#[tokio::test]
async fn a_new_vetter_enrols_now_rather_than_at_the_next_pass() {
    let mut vetter = Party::new(2).member_of(COMMUNITY);
    assert!(!vetter.book.vetter_refresh_due);
    vetter.named_vetter().await;
    assert!(
        vetter.book.vetter_refresh_due,
        "the grant asks for the vetter side to run at once"
    );
}

/// The blinding of an enrolment is stored with the engine before the request goes, so an answer
/// that arrives after a restart — the in-memory copy gone — is still opened, rather than locking
/// the vetter out until the community publishes a new label.
#[tokio::test]
async fn an_enrolment_answer_after_a_restart_is_opened_with_the_stored_blinding() {
    let (mut vetter, request, answer) = vetter_asking_to_enrol().await;
    let pending = vetter.book.pending_enrolments.remove(0);
    let stored = super::hidden::blinding_text(&pending.blinding).unwrap();
    vetter.book.hidden_vetter[0].remember_asked(super::book::AskedEnrolment {
        document_id: request.id.clone(),
        period: "2026-10".into(),
        blinding: stored,
        asked_at: Utc::now(),
    });
    // The restart: the book as saved and loaded again, and every question forgotten.
    let saved = serde_json::to_value(&vetter.book).unwrap();
    vetter.book = serde_json::from_value(saved).unwrap();
    assert!(vetter.book.pending_enrolments.is_empty());
    assert!(vetter.book.queries.is_empty());

    let handled = vetter.receive(&answer, COMMUNITY).await;
    assert!(
        matches!(handled.notice, Some(Notice::HiddenVetterEnrolled { .. })),
        "{:?}",
        handled.notice
    );
    let held = &vetter.book.hidden_vetter[0];
    assert!(held.snapshot.credentials.contains_key("2026-10"));
    assert!(held.lost_enrolment.is_none());
    assert!(held.enrolments_asked.is_empty(), "spent once opened");
    assert!(vetter.book.vetter_refresh_due, "and the first draw follows");
}

/// A refused enrolment drops its stored blinding: nothing will ever need it.
#[tokio::test]
async fn a_refused_enrolment_drops_its_stored_blinding() {
    let (mut vetter, request, _) = vetter_asking_to_enrol().await;
    let stored = super::hidden::blinding_text(&vetter.book.pending_enrolments[0].blinding).unwrap();
    vetter.book.hidden_vetter[0].remember_asked(super::book::AskedEnrolment {
        document_id: request.id.clone(),
        period: "2026-10".into(),
        blinding: stored,
        asked_at: Utc::now(),
    });
    vetter
        .receive(
            &community_refusal(&request, "vtc/vetting/vetters/pcs-root:notAVetter"),
            COMMUNITY,
        )
        .await;
    assert!(vetter.book.hidden_vetter[0].enrolments_asked.is_empty());
}

/// A manifest is not fetched again within seconds of the last ask or answer, nor while a
/// question for it is open — `d` pressed three times fetched it three times (R1.4).
#[test]
fn a_manifest_is_not_asked_for_again_within_seconds() {
    let now = Utc::now();
    let mut book = VettingBook::default();
    assert!(!book.manifest_recently_asked(COMMUNITY, now));
    book.mode_asked(COMMUNITY, now);
    assert!(book.manifest_recently_asked(COMMUNITY, now + Duration::seconds(5)));
    assert!(!book.manifest_recently_asked(COMMUNITY, now + super::mode::MANIFEST_MIN_GAP));
    book.ask(super::queries::CommunityQuery {
        document_id: "m1".into(),
        community: COMMUNITY.into(),
        persona: PersonaId::new(),
        kind: QueryKind::Manifest,
        sent_at: now,
    });
    assert!(
        book.manifest_recently_asked(COMMUNITY, now + Duration::minutes(5)),
        "an open question is answered once, for everyone"
    );
}

/// first-vtc's live manifest (`manifest/0.3`), as its REST route served it: three criteria
/// without vetting and one, `vetted-member`, that publishes hidden vetting in `ext` — alongside
/// named vetters, never `extCritical`.
const FIRST_VTC_MANIFEST: &str = include_str!("../../tests/fixtures/first-vtc-manifest-0.3.json");

fn first_vtc() -> (
    String,
    manifest::v0_2::Response,
    Vec<super::protocol::CriterionMeta>,
    Value,
) {
    let document: Value = serde_json::from_str(FIRST_VTC_MANIFEST).unwrap();
    let payload = document["payload"].clone();
    let community = payload["communityDid"].as_str().unwrap().to_string();
    let (parsed, meta) =
        super::protocol::read_manifest(super::protocol::JoinProtocol::V0_3, &payload)
            .expect("the live manifest parses");
    (community, parsed, meta, payload)
}

/// The live failure: an application started from what the book already knew of first-vtc —
/// the join page's route — took the criterion's requirements and dropped its hidden-vetting
/// parameters, so it stayed on named vetting under a criterion that hides its vetters. Both
/// routes now decide the path the same way: hidden, since `vetted-member` offers it alongside
/// named vetters and nothing is under way.
#[tokio::test]
async fn an_application_started_from_the_book_takes_up_first_vtcs_hidden_vetting() {
    let (community, parsed, meta, raw) = first_vtc();
    let mut party = Party::new(1);
    let now = Utc::now();
    party.book.learn_manifest_in(
        &community,
        &parsed,
        Some(super::protocol::JoinProtocol::V0_3),
        &meta,
        now,
    );
    party.book.learn_mode(&community, &raw, None, now);
    let id = party
        .book
        .start_application(&community, party.persona, &party.did, now)
        .unwrap()
        .id
        .clone();
    assert!(party.book.adopt_known_requirements(&id).unwrap());
    let app = party
        .book
        .application_mut(&community, party.persona)
        .unwrap();
    assert_eq!(app.criterion_id.as_deref(), Some("vetted-member"));
    assert!(app.hidden.is_some(), "the hidden path, from the book");
    assert!(app.hidden_id().is_some(), "with its own key minted");

    // The manifest read again agrees, and changes nothing.
    assert!(!app.adopt_manifest(&parsed, &raw).unwrap());
    assert!(app.hidden.is_some());

    let shown = party.book.application_vetting(&id).unwrap();
    assert_eq!(shown.path, super::applicant::VettingPath::Hidden);
    assert_eq!(shown.paths, super::book::CriterionPaths::Either);
    assert_eq!(
        shown.description.as_deref(),
        Some("One vetter must confirm who you are")
    );
}

/// The second criterion's digest in a community offering two ways to be vetted.
const NAMED_DIGEST: &str = "zQmNamedCriterionDigestAbcdefgh";

/// A community publishing two vetting criteria: `named` (named statements only) first, then
/// `vetted`, which runs hidden vetting — alongside named vetters, or (`critical`) alone.
fn mixed_manifest(critical: bool) -> (manifest::v0_2::Response, Value) {
    let hidden = manifest_raw_with_ext(
        json!({ super::hidden::HIDDEN_VETTING_NS: hidden_params() }),
        critical.then(|| json!([super::hidden::HIDDEN_VETTING_NS])),
    );
    let mut named = hidden["criteria"][0].clone();
    named["id"] = json!("named");
    named["requirementsDigest"] = json!(NAMED_DIGEST);
    named["description"] = json!("Two people who know you");
    let vetting = named["vetting"].as_object_mut().unwrap();
    vetting.remove("ext");
    vetting.remove("extCritical");
    let mut raw = hidden.clone();
    raw["criteria"] = json!([named, hidden["criteria"][0].clone()]);
    (serde_json::from_value(raw.clone()).unwrap(), raw)
}

/// One criterion, `vetted`, running hidden vetting — alongside named vetters, or (`critical`)
/// alone.
fn hidden_manifest(critical: bool) -> (manifest::v0_2::Response, Value) {
    let raw = manifest_raw_with_ext(
        json!({ super::hidden::HIDDEN_VETTING_NS: hidden_params() }),
        critical.then(|| json!([super::hidden::HIDDEN_VETTING_NS])),
    );
    (serde_json::from_value(raw.clone()).unwrap(), raw)
}

/// A book that has read `manifest` for [`COMMUNITY`].
fn learn(book: &mut VettingBook, manifest: &(manifest::v0_2::Response, Value)) {
    let now = Utc::now();
    book.learn_manifest_in(COMMUNITY, &manifest.0, None, &[], now);
    book.learn_mode(COMMUNITY, &manifest.1, None, now);
}

/// A request that went out, as far as an application's progress goes.
fn sent_request() -> super::applicant::OutboundRequest {
    let now = Utc::now();
    super::applicant::OutboundRequest {
        document_id: "urn:uuid:sent".into(),
        vetter: "did:key:zVetter".into(),
        state: RequestState::Sent,
        eligibility: None,
        grant_status: None,
        sent_at: now,
        updated_at: now,
    }
}

/// A named statement, as far as an application's evidence goes.
fn held_statement() -> super::applicant::HeldStatement {
    let now = Utc::now();
    super::applicant::HeldStatement {
        id: "urn:uuid:held".into(),
        vetter: "did:key:zVetter".into(),
        method: VettingMethod::InPerson,
        declared_relationship: VettingRelationship::None,
        document_classes: vec![],
        claims_verified: vec!["name.legal".into()],
        identity_commitment: "z".into(),
        valid_from: now,
        valid_until: now + Duration::days(30),
        received_at: now,
        credential: Value::Null,
    }
}

/// Named and hidden criteria side by side: a new application takes the hidden one — it names
/// no vetter — by either route, while one with a request already out keeps its own.
#[tokio::test]
async fn in_a_mixed_community_a_new_application_picks_the_hidden_criterion() {
    let manifest = mixed_manifest(false);
    let mut party = Party::new(1);
    learn(&mut party.book, &manifest);
    let now = Utc::now();
    let id = party
        .book
        .start_application(COMMUNITY, party.persona, &party.did, now)
        .unwrap()
        .id
        .clone();
    party.book.adopt_known_requirements(&id).unwrap();
    let app = party.application();
    assert_eq!(app.criterion_id.as_deref(), Some("vetted"));
    assert!(app.hidden.is_some());

    // The manifest route picks the same for a fresh application.
    let mut fresh = Application::new(COMMUNITY, party.persona, &party.did, now).unwrap();
    fresh.adopt_manifest(&manifest.0, &manifest.1).unwrap();
    assert_eq!(fresh.criterion_id.as_deref(), Some("vetted"));
    assert!(fresh.hidden.is_some());

    // One whose request already went out under `named` is not moved.
    let mut under_way = Application::new(COMMUNITY, party.persona, &party.did, now).unwrap();
    under_way.criterion_id = Some("named".into());
    under_way.requests.push(sent_request());
    under_way.adopt_manifest(&manifest.0, &manifest.1).unwrap();
    assert_eq!(under_way.criterion_id.as_deref(), Some("named"));
    assert!(under_way.hidden.is_none());
}

/// Under a criterion that offers both paths, an application that already sent a named request
/// stays named — its request carries no identifier a proof could be made to. A criterion that
/// takes the proof alone leaves no choice.
#[tokio::test]
async fn an_application_under_way_keeps_its_named_path_under_a_criterion_offering_both() {
    let now = Utc::now();
    let mut app = Application::new(COMMUNITY, PersonaId::new(), "did:key:zA", now).unwrap();
    app.requests.push(sent_request());
    let alongside = hidden_manifest(false);
    app.adopt_manifest(&alongside.0, &alongside.1).unwrap();
    assert!(app.hidden.is_none(), "kept named");

    let critical = hidden_manifest(true);
    app.adopt_manifest(&critical.0, &critical.1).unwrap();
    assert!(app.hidden.is_some(), "the proof is the only path");
}

/// Before any evidence, `p` walks the ways a community offers — the other path of the same
/// criterion, then the next criterion — and once a statement is held, it refuses.
#[tokio::test]
async fn an_application_switches_criterion_and_path_before_evidence_only() {
    use super::applicant::VettingPath;
    use super::book::CriterionPaths;

    let manifest = mixed_manifest(false);
    let mut party = Party::new(1);
    learn(&mut party.book, &manifest);
    let id = party
        .book
        .start_application(COMMUNITY, party.persona, &party.did, Utc::now())
        .unwrap()
        .id
        .clone();
    party.book.adopt_known_requirements(&id).unwrap();

    let options = party.book.vetting_options(COMMUNITY);
    let ways: Vec<(&str, VettingPath)> = options
        .iter()
        .map(|o| (o.criterion_id.as_str(), o.path))
        .collect();
    assert_eq!(
        ways,
        vec![
            ("named", VettingPath::Named),
            ("vetted", VettingPath::Hidden),
            ("vetted", VettingPath::Named),
        ]
    );

    let now = party.book.switch_vetting(&id).unwrap();
    assert_eq!(
        (now.criterion_id.as_str(), now.path, now.paths),
        ("vetted", VettingPath::Named, CriterionPaths::Either)
    );
    assert!(party.application().hidden.is_none());
    assert!(
        party.application().hidden_state.is_some(),
        "its key is kept for a switch back"
    );

    let now = party.book.switch_vetting(&id).unwrap();
    assert_eq!(now.criterion_id, "named");
    assert_eq!(
        party.application().requirements_digest.as_deref(),
        Some(NAMED_DIGEST)
    );
    assert_eq!(now.description.as_deref(), Some("Two people who know you"));
    assert!(
        party.application().criterion_repicked.is_none(),
        "a switch is not a re-pick"
    );

    let now = party.book.switch_vetting(&id).unwrap();
    assert_eq!(
        (now.criterion_id.as_str(), now.path),
        ("vetted", VettingPath::Hidden)
    );
    assert!(party.application().hidden.is_some());
    assert!(party.application().hidden_id().is_some());

    // Evidence fixes it.
    party.application().statements.push(held_statement());
    let refused = party.book.switch_vetting(&id).unwrap_err();
    assert!(refused.contains("already holds vetting"), "{refused}");
}

/// A criterion the community no longer publishes is re-picked, and the application says which
/// it was.
#[tokio::test]
async fn a_stale_criterion_is_repicked_and_said() {
    let manifest = mixed_manifest(false);
    let now = Utc::now();
    let mut app = Application::new(COMMUNITY, PersonaId::new(), "did:key:zA", now).unwrap();
    app.criterion_id = Some("retired".into());
    assert!(app.adopt_manifest(&manifest.0, &manifest.1).unwrap());
    assert_eq!(app.criterion_id.as_deref(), Some("vetted"), "hidden first");
    assert_eq!(app.criterion_repicked.as_deref(), Some("retired"));
}

/// The vetter follows the request, not the community: under a criterion running hidden vetting
/// alongside named vetters, a request without a PCS identifier is a named request.
#[tokio::test]
async fn the_vetter_attests_named_for_a_named_request_and_pcs_for_a_hidden_one() {
    use super::book::RequestVetting;
    let alongside = hidden_manifest(false);

    // A named request, under a criterion that also accepts PCS ZKP.
    let (mut applicant, mut vetter, _) = ready().await;
    learn(&mut vetter.book, &alongside);
    assert!(vetter.book.pcs_zkp(COMMUNITY), "the community runs PCS ZKP");
    assert!(
        applicant.application().hidden.is_none(),
        "this one is named"
    );
    let (request_id, _) = in_session(&mut applicant, &mut vetter).await;
    assert_eq!(
        vetter.book.request_vetting(&request_id),
        RequestVetting::Named {
            criterion: Some("vetted".into())
        }
    );

    // A hidden request carries the identifier.
    let (mut applicant, mut vetter, _) = ready().await;
    learn(&mut vetter.book, &alongside);
    applicant
        .application()
        .adopt_manifest(&alongside.0, &alongside.1)
        .unwrap();
    assert!(applicant.application().hidden.is_some());
    let (request_id, _) = in_session(&mut applicant, &mut vetter).await;
    assert_eq!(
        vetter.book.request_vetting(&request_id),
        RequestVetting::Hidden
    );

    // A named request under a criterion that takes the proof alone has nothing to attest to.
    let (mut applicant, mut vetter, _) = ready().await;
    learn(&mut vetter.book, &hidden_manifest(true));
    let (request_id, _) = in_session(&mut applicant, &mut vetter).await;
    assert_eq!(
        vetter.book.request_vetting(&request_id),
        RequestVetting::HiddenWithoutId {
            criterion: "vetted".into()
        }
    );
}