vta-service 0.14.34

Service for Verifiable Trust Agents operating in Verifiable Trust Communities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
//! Non-interactive setup (`vta setup --from <file>`).
//!
//! [`WizardInputs`] is the canonical TOML schema. Field-level doc
//! comments are the source of truth for the schema — there is no
//! separate spec doc, by design. [`run_setup_from_file`] reads a TOML
//! file into `WizardInputs` and hands off to [`apply_inputs`], which
//! mirrors [`super::interactive::run_setup_wizard`] step-for-step but
//! with no prompts and no display of generated key material.
//!
//! Design choices (stable; change with care):
//! - Mnemonic input is intentionally absent. Setup always generates
//!   fresh. Operators who need a known seed should run
//!   `vta keys rotate-seed --mnemonic <phrase>` post-setup.
//! - VTA DID and mediator DID creation only support "simple mode"
//!   (operations layer with VTA-managed keys). The interactive
//!   wizard's advanced options (template-from-file, pre-signed log
//!   import, user-specified key IDs) are out of scope here —
//!   operators who need those should use interactive setup.
//! - `admin_did`, when set, runs the same logic as `vta
//!   bootstrap-admin` at the end of apply: writes a super-admin ACL
//!   row and seals the VTA atomically with the rest of setup.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD as BASE64;
use chrono::Utc;
use didwebvh_rs::url::WebVHURL;
use rand::Rng;
use serde::{Deserialize, Serialize};
use serde_json::json;
use url::Url;

use affinidi_did_resolver_cache_sdk::{DIDCacheClient, config::DIDCacheConfigBuilder};
use vta_sdk::protocol::matching::Protocol;

use crate::config::{
    AppConfig, AuditConfig, AuthConfig, LogConfig, MessagingConfig, SecretBackend, SecretsConfig,
    ServerConfig, ServicesConfig, StoreConfig,
};
use crate::contexts::store_context;
use crate::keys::seed_store::{SeedStore, create_seed_store};
use crate::keys::seeds::{SeedRecord, get_seed_record, save_seed_record, set_active_seed_id};
use crate::operations;
use crate::operations::did_webvh::CreateDidWebvhParams;
use crate::store::{KeyspaceHandle, Store};
use crate::webvh_cli::cli_super_admin;

use super::{SetupUi, SilentUi, create_seed_context, generate_mnemonic_silent};

/// TOML schema for `vta setup --from <file>`.
///
/// `Serialize` is derived (alongside `Deserialize`) so the interactive wizard's
/// golden test can assert that prompt-gathered inputs and the equivalent TOML
/// deserialize to structurally-identical `WizardInputs` (compared via
/// `serde_json::to_value`). Production never serializes this type.
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct WizardInputs {
    /// Output path for the generated `config.toml`. The setup wizard refuses
    /// to overwrite an existing file unless `overwrite_config` is set.
    pub config_path: PathBuf,

    /// Permit overwriting an existing `config_path`.
    ///
    /// The file is not touched until the engine writes the finished config at
    /// the very end, so a setup run that fails — or that the operator
    /// cancels — leaves the existing config intact.
    #[serde(default)]
    pub overwrite_config: bool,

    /// Optional human-readable name for this VTA. Surfaced in `vta config
    /// show` and `pnm setup`.
    #[serde(default)]
    pub vta_name: Option<String>,

    /// Public URL the VTA will advertise (e.g. `https://trust.example.com`).
    /// Used as the `VTARest` service endpoint when minting the VTA's DID.
    /// Optional — omit if this VTA is DIDComm-only or behind a private
    /// network.
    #[serde(default)]
    pub public_url: Option<String>,

    /// Where the on-disk fjall store lives.
    pub data_dir: PathBuf,

    /// What to do if `data_dir` already exists. Defaults to `error` (fail
    /// fast); set to `delete` for CI re-run patterns.
    #[serde(default)]
    pub data_dir_exists: ExistingDataDirPolicy,

    /// Which services to enable. Defaults to both REST and DIDComm.
    #[serde(default = "default_services")]
    pub services: ServicesConfig,

    /// HTTP server bind. Defaults to `0.0.0.0:8100`.
    #[serde(default)]
    pub server: ServerConfig,

    /// Logging. Defaults to text format at info level.
    #[serde(default)]
    pub log: LogConfig,

    /// Seed-store backend. Required — there is no implicit default because
    /// the choice is security-sensitive (each backend has different threat
    /// model and durability guarantees).
    pub secrets: SecretsBackendInput,

    /// DIDComm mediator configuration. Defaults to `skip`. Only meaningful
    /// when `services.didcomm = true`.
    #[serde(default)]
    pub messaging: MessagingInput,

    /// VTA DID configuration. Defaults to `skip`. A VTA without a DID can
    /// still serve REST traffic but cannot participate in DIDComm or sign
    /// VCs.
    #[serde(default)]
    pub vta_did: VtaDidInput,

    /// If set, after base setup completes the wizard runs the equivalent of
    /// `vta bootstrap-admin --did <X>` — writes a super-admin ACL row and
    /// seals the VTA atomically. Failure here aborts setup before declaring
    /// success.
    #[serde(default)]
    pub admin_did: Option<String>,

    /// Optional label attached to the seeded admin's ACL row.
    #[serde(default)]
    pub admin_label: Option<String>,

    /// WebSocket URL of a remote DID resolver (e.g.
    /// `ws://resolver.example.com/did/v1/ws`). When set, the VTA uses
    /// the remote resolver instead of resolving DIDs locally. Required
    /// for TEE network mode where DID resolution is bridged to a parent-
    /// side `affinidi-did-resolver-cache-server` over vsock; useful for
    /// any deployment that wants to share a resolver-cache across VTAs.
    #[serde(default)]
    pub resolver_url: Option<String>,

    /// Audit-log retention. Defaults to 28 days; compliance-driven
    /// deployments often want 90 or 365.
    #[serde(default)]
    pub audit: AuditConfig,

    /// Enterprise staff provisioning. For each entry the wizard creates a
    /// context, applies its initial `ContextPolicy`, and seeds a
    /// context-scoped ACL row — the VTA *user*, bounded by the policy. The
    /// *owner* is the super-admin `admin_did` above. Empty by default (a
    /// personal VTA where owner and user are the same DID).
    #[serde(default)]
    pub staff: Vec<StaffProvision>,

    /// Hardened-mode configuration. When `enabled = true`:
    /// - The setup wizard skips generating `jwt_signing_key` and does **not**
    ///   write it to `config.toml`.
    /// - A `[hardened]` section is written to `config.toml` with
    ///   `enabled = true` and `storage_key_salt`.
    /// - At every daemon boot, the JWT signing key is derived/sealed from the
    ///   master seed (never stored on disk).
    /// - All fjall keyspaces are encrypted with a key derived from the seed.
    ///
    /// Requires the `[secrets]` backend to be a real secret store (OS keyring,
    /// AWS SM, GCP SM, …) — the plaintext file fallback defeats the protection.
    #[serde(default)]
    pub hardened: crate::config::HardenedConfig,
}

/// One enterprise staff member to provision at setup: a context, its initial
/// policy, and a context-scoped ACL entry scoped to it (separation of duty —
/// the owner sets the guardrail, the staff member works within it).
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct StaffProvision {
    /// The staff member's DID (the VTA *user*) — gets a context-scoped ACL row.
    pub did: String,
    /// Context to create and scope the staff member to (a kebab-case slug,
    /// e.g. `staff` or `sales`).
    pub context: String,
    /// Human label for the context and the ACL row.
    #[serde(default)]
    pub label: Option<String>,
    /// Role for the staff entry (admin / initiator / application / reader /
    /// monitor). Defaults to `application` — use keys, present, and vault
    /// within the context, but never manage it.
    #[serde(default)]
    pub role: Option<String>,
    /// Initial `ContextPolicy` guardrail for the context (trusted verifiers,
    /// presentable types, signable keys, export, quotas). Omit for an
    /// unrestricted context the owner tightens later.
    #[serde(default)]
    pub context_policy: Option<vta_sdk::context_policy::ContextPolicy>,
}

fn default_services() -> ServicesConfig {
    ServicesConfig {
        rest: true,
        didcomm: true,
        // WebAuthn defaults off — operators flip this on via
        // `services webauthn enable`, and the existing `services.rest`
        // continues to be the discoverable HTTP surface until they do.
        webauthn: false,
        // TSP defaults off — operators enable it via `services tsp enable`
        // (or the setup wizard once it learns TSP). DIDComm stays default.
        tsp: false,
    }
}

/// What to do when `data_dir` already holds a store.
///
/// Only consulted when [`vti_common::store::local_store_exists`] reports a
/// store — an existing-but-storeless directory (a mounted volume, a PVC, an
/// operator's `mkdir`) is initialized into without asking, because it carries
/// nothing to lose.
#[derive(Debug, Deserialize, Serialize, Default, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ExistingDataDirPolicy {
    /// Refuse to proceed if `data_dir` already holds a store.
    #[default]
    Error,
    /// Delete the *contents* of `data_dir` before initializing the store.
    ///
    /// The directory itself is kept: `data_dir` is routinely a mount point
    /// (Docker volume, K8s PVC), and `rmdir` on a mount point fails with
    /// `EBUSY` no matter how empty it is.
    Delete,
    /// Initialize into `data_dir` as-is, keeping whatever is already there.
    ///
    /// Setup still refuses to run over a store that already holds an
    /// initialized VTA — that would mint a fresh master seed on top of the
    /// existing one and orphan every key derived from it.
    Reuse,
}

/// Delete everything *inside* `dir`, leaving `dir` itself in place.
///
/// `remove_dir_all` is wrong here: it removes the directory too, and
/// `data_dir` is commonly a mount point, where the final `rmdir` fails with
/// `EBUSY` (Linux) or a sharing violation (Windows) — after the contents are
/// already gone. Clearing entry-by-entry is destructive in exactly the same
/// way but succeeds on a mounted target.
fn clear_dir_contents(dir: &Path) -> std::io::Result<()> {
    for entry in std::fs::read_dir(dir)? {
        let entry = entry?;
        // `DirEntry::file_type` does not follow symlinks, so a symlinked
        // directory is unlinked (remove_file) rather than recursed into.
        if entry.file_type()?.is_dir() {
            std::fs::remove_dir_all(entry.path())?;
        } else {
            std::fs::remove_file(entry.path())?;
        }
    }
    Ok(())
}

/// Per-backend seed-store config. The `backend` discriminator selects the
/// variant; required fields per variant are validated at deserialization
/// time via `serde(deny_unknown_fields)`.
///
/// `large_enum_variant` is suppressed deliberately: the `Vault` arm
/// carries ~14 KV-v2 + auth-method fields, which dominates the
/// stack size of an `Option<SecretsBackendInput>`. The enum is
/// parsed exactly once at setup time from a TOML file and never
/// stored on a hot path, so the per-variant size footprint isn't
/// load-bearing — boxing just to mollify the lint would add
/// indirection for no operational benefit.
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Deserialize, Serialize)]
#[serde(tag = "backend", rename_all = "snake_case", deny_unknown_fields)]
pub enum SecretsBackendInput {
    /// OS keyring (libsecret / Keychain / Credential Vault). The
    /// `service` field defaults to `"vta"` but should be unique per VTA
    /// instance running on the same host.
    Keyring {
        #[serde(default = "default_keyring_service")]
        service: String,
    },
    /// Hex-encoded seed embedded in `config.toml`. **Not recommended** —
    /// the config file becomes a secret. Compiled in only when the
    /// `config-seed` feature is enabled.
    ConfigSeed,
    /// AWS Secrets Manager. `region` defaults to the SDK's default
    /// resolution chain.
    Aws {
        #[serde(default)]
        region: Option<String>,
        secret_name: String,
    },
    /// GCP Secret Manager.
    Gcp {
        project: String,
        secret_name: String,
    },
    /// Azure Key Vault.
    Azure {
        vault_url: String,
        secret_name: String,
    },
    /// HashiCorp Vault (KV v2). Authenticates via Kubernetes (default),
    /// AppRole, or a static token. The seed is stored at
    /// `<kv_mount>/<secret_path>` in the configured field (default
    /// `seed`). See `docs/02-vta/secret-backends.md` for the
    /// auth-method matrix.
    Vault {
        /// Vault server URL (e.g. `https://vault.example.com:8200`).
        addr: String,
        /// KV v2 secret path under the mount, e.g. `vta/master-seed`.
        secret_path: String,
        /// KV v2 mount path. Defaults to `secret`.
        #[serde(default = "default_vault_kv_mount")]
        kv_mount: String,
        /// Field name within the KV v2 secret holding the hex-encoded
        /// seed. Defaults to `seed`.
        #[serde(default = "default_vault_secret_key")]
        secret_key: String,
        /// Vault Enterprise namespace, if any.
        #[serde(default)]
        namespace: Option<String>,
        /// Auth method: `kubernetes` (default), `token`, or `approle`.
        #[serde(default = "default_vault_auth_method")]
        auth_method: String,
        /// Kubernetes auth role name (when `auth_method = "kubernetes"`).
        #[serde(default)]
        k8s_role: Option<String>,
        /// Kubernetes auth mount path. Defaults to `kubernetes`.
        #[serde(default = "default_vault_k8s_mount")]
        k8s_mount: String,
        /// File holding the ServiceAccount JWT presented to Vault.
        /// Defaults to the kubelet-mounted projected volume path.
        #[serde(default = "default_vault_k8s_jwt_path")]
        k8s_jwt_path: String,
        /// Static token (when `auth_method = "token"`). Prefer the
        /// `VAULT_TOKEN` env var over hard-coding here.
        #[serde(default)]
        token: Option<String>,
        /// AppRole role_id (when `auth_method = "approle"`).
        #[serde(default)]
        approle_role_id: Option<String>,
        /// AppRole secret_id (when `auth_method = "approle"`).
        #[serde(default)]
        approle_secret_id: Option<String>,
        /// AppRole mount path. Defaults to `approle`.
        #[serde(default = "default_vault_approle_mount")]
        approle_mount: String,
        /// Skip TLS certificate verification — dev/test only.
        #[serde(default)]
        skip_verify: bool,
    },
    /// Kubernetes `Secret`. The seed is stored hex-encoded under
    /// `secret_key` (default `seed`) in a namespaced `Secret`.
    /// Credentials come from the in-cluster ServiceAccount or a local
    /// kubeconfig. Compiled in only when the `k8s-secrets` feature is
    /// enabled.
    Kubernetes {
        /// Name of the `Secret` resource.
        secret_name: String,
        /// Namespace the `Secret` lives in. When omitted, the
        /// in-cluster ServiceAccount namespace (or kubeconfig context
        /// namespace) is used, falling back to `default`.
        #[serde(default)]
        namespace: Option<String>,
        /// Key within the `Secret`'s `data` map. Defaults to `seed`.
        #[serde(default = "default_k8s_secret_key")]
        secret_key: String,
    },
    /// Plaintext file under `data_dir`. **Not recommended** — for dev only.
    Plaintext,
}

fn default_keyring_service() -> String {
    "vta".into()
}

pub(crate) fn default_vault_kv_mount() -> String {
    "secret".into()
}

pub(crate) fn default_vault_secret_key() -> String {
    "seed".into()
}

pub(crate) fn default_vault_auth_method() -> String {
    "kubernetes".into()
}

pub(crate) fn default_vault_k8s_mount() -> String {
    "kubernetes".into()
}

pub(crate) fn default_vault_k8s_jwt_path() -> String {
    "/var/run/secrets/kubernetes.io/serviceaccount/token".into()
}

pub(crate) fn default_k8s_secret_key() -> String {
    "seed".into()
}

pub(crate) fn default_vault_approle_mount() -> String {
    "approle".into()
}

#[derive(Debug, Deserialize, Serialize, Default)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum MessagingInput {
    /// No DIDComm mediator. The VTA will not participate in DIDComm flows.
    #[default]
    Skip,
    /// Point at a mediator DID that already exists. ATM resolves the
    /// endpoint from the DID document.
    ///
    /// `mediator_host` is the *external* hostname the VTA should resolve
    /// to when dialling the mediator's DIDComm endpoint. Used in TEE
    /// network mode where outbound traffic is bridged via a vsock proxy
    /// on the parent EC2 instance and the proxy needs the real upstream
    /// hostname for SNI / TLS validation. Leave unset for the standard
    /// case where the URL in the resolved DID document is reachable
    /// directly.
    Existing {
        did: String,
        #[serde(default)]
        mediator_host: Option<String>,
        /// Automatically provision a per-DID allow-all ACL on the mediator
        /// after the DIDComm connection is established. Defaults to `false`.
        #[serde(default)]
        setup_acl: bool,
    },
    /// Mint a new mediator DID using the built-in `didcomm-mediator`
    /// template. The mediator gets its own trust context (default name
    /// `"mediator"`).
    ///
    /// `url` is the DIDComm service endpoint — what clients dial to send
    /// messages. It becomes the `URL` template var and lands in the
    /// rendered DID document's `serviceEndpoint.uri`.
    ///
    /// `webvh_url` is where the mediator's `did.jsonl` is published; it
    /// determines the `did:webvh:<scid>:host:path` identifier itself.
    /// Optional — defaults to `url` for the common case where DIDComm
    /// traffic and DID hosting share a host. Specify it explicitly when
    /// the mediator endpoint and the DID document live on different
    /// hosts (e.g. DIDComm at `https://mediator.example.com`, DID doc
    /// at `https://trust.example.com/dids/mediator`).
    ///
    /// `mediator_host` — see `Existing::mediator_host`.
    ///
    /// `ws_url` — the mediator's WebSocket endpoint, advertised in the
    /// `didcomm-mediator` template's `#service` block alongside the HTTP
    /// DIDComm endpoint. Optional: when omitted the wizard derives it
    /// from `url` (`http`→`ws` / `https`→`wss`, trailing slash trimmed,
    /// `/ws` appended) — the canonical mediator convention. Set it
    /// explicitly only when your reverse proxy routes the WS upgrade to a
    /// different host or path; an explicit value is used verbatim. This
    /// mirrors the interactive wizard's overridable WS prompt.
    ///
    /// `template_vars` is an escape hatch for overriding optional
    /// `didcomm-mediator` template variables (`ROUTING_KEYS`, `ACCEPT`,
    /// `WEBVH_SERVER`). The `URL` var is always set by the wizard from
    /// `url` and cannot be overridden here; `WS_URL` comes from the
    /// `ws_url` field above (or its `url`-derived default), so setting
    /// `WS_URL` in `template_vars` has no effect.
    ///
    /// `setup_acl` — when `true`, the VTA automatically provisions a
    /// per-DID allow-all ACL on the mediator after connecting. Required
    /// when the mediator uses `ExplicitAllow` mode. Defaults to `false`.
    CreateMediator {
        #[serde(default = "default_mediator_context")]
        context: String,
        url: String,
        #[serde(default)]
        ws_url: Option<String>,
        #[serde(default)]
        webvh_url: Option<String>,
        #[serde(default)]
        mediator_host: Option<String>,
        #[serde(default)]
        template_vars: HashMap<String, serde_json::Value>,
        #[serde(default)]
        setup_acl: bool,
        /// Which transports this mediator will serve, rendered into the
        /// mediator's own DID document.
        ///
        /// Omitted — the normal case — means "whatever this VTA advertises":
        /// DIDComm always, TSP when `services.tsp` is on. We are minting the
        /// mediator, so its capability is a choice rather than a discovery,
        /// and the only choice that keeps the VTA reachable is one that
        /// covers what the VTA advertises.
        ///
        /// Set it explicitly to mint a mediator that serves *more* than this
        /// VTA uses — e.g. a shared mediator carrying TSP for other clients
        /// while this VTA stays on DIDComm. Serving *less* is refused: it
        /// would publish a VTA `#tsp` pointing at a mediator whose own
        /// document says it doesn't carry TSP.
        ///
        /// `rest` is not a mediator transport and is refused here.
        #[serde(default)]
        protocols: Option<Vec<Protocol>>,
    },
}

fn default_mediator_context() -> String {
    "mediator".into()
}

/// Which transports a mediator minted by setup will serve.
///
/// Explicit `messaging.protocols` wins. Omitted — the normal case — it is
/// whatever this VTA advertises: DIDComm always (the `didcomm-mediator`
/// template renders that entry unconditionally), plus TSP when the VTA
/// advertises TSP. Deriving is not a convenience here: the two must agree for
/// the VTA to be reachable, and the operator has no information setup lacks.
///
/// `validate_inputs` refuses an explicit list that serves *less* than the VTA
/// advertises; serving more is legitimate (a shared mediator).
fn mediator_protocols(explicit: Option<&[Protocol]>, services: &ServicesConfig) -> Vec<Protocol> {
    match explicit {
        Some(list) => list.to_vec(),
        None => {
            let mut derived = vec![Protocol::Didcomm];
            if services.tsp {
                derived.push(Protocol::Tsp);
            }
            derived
        }
    }
}

#[derive(Debug, Deserialize, Serialize, Default)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum VtaDidInput {
    /// No VTA DID. REST works; DIDComm and VC issuance do not.
    #[default]
    Skip,
    /// Use a DID that already exists.
    Existing { did: String },
    /// Mint a new `did:key` for the VTA. Uses BIP-32-derived Ed25519
    /// keys from the active seed — same derivation scheme as `did:webvh`
    /// but no external hosting needed. Ideal for local development and
    /// deployments that don't need webvh's portability/rotation.
    CreateDidKey,
    /// Mint a new `did:webvh` for the VTA. Defaults to the operations
    /// layer's "simple mode" (VTA generates keys + document); the optional
    /// `did_document_file` / `did_log_file` / `signing_key_id` fields select
    /// the advanced modes the interactive wizard exposes (see their docs).
    CreateWebvh {
        /// Hosting URL for the DID document, e.g.
        /// `https://trust.example.com/dids/vta`.
        url: String,
        /// Whether the DID is portable (can move to a different domain
        /// later). Default true. Ignored when `did_log_file` is set (the
        /// pre-signed log already fixes portability).
        #[serde(default = "default_true")]
        portable: bool,
        /// Number of pre-rotation keys to publish (defence against key
        /// compromise). Default 1; recommended 1–3. Ignored when
        /// `did_log_file` is set.
        #[serde(default = "default_pre_rotation_count")]
        pre_rotation_count: u32,
        /// Advanced: path to a DID-document JSON template file. The VTA still
        /// mints the keys and fills the document's key material; this only
        /// supplies the document *shape*. Mutually exclusive with
        /// `did_log_file` and `signing_key_id`.
        #[serde(default)]
        did_document_file: Option<PathBuf>,
        /// Advanced: path to a complete, pre-signed `did.jsonl` log to import
        /// verbatim. Mutually exclusive with `did_document_file` and
        /// `signing_key_id`; `portable` / `pre_rotation_count` are ignored.
        #[serde(default)]
        did_log_file: Option<PathBuf>,
        /// Advanced: id of an existing imported key to use as the signing
        /// verification method instead of minting a fresh one. Mutually
        /// exclusive with `did_document_file` and `did_log_file`.
        #[serde(default)]
        signing_key_id: Option<String>,
        /// Advanced: id of an existing imported key to use as the
        /// key-agreement verification method. Requires `signing_key_id`.
        #[serde(default)]
        ka_key_id: Option<String>,
    },
}

/// The interactive wizard's advanced webvh-DID options, lifted into the
/// shared engine. All-`None` (`Default`) is the common "simple mode" where the
/// VTA mints keys and renders the document itself — the only mode the mediator
/// DID path uses. The `CreateDidWebvhParams` layer enforces that
/// `did_document` / `did_log` / `template` are mutually exclusive; setup
/// validation (`validate_inputs`) rejects conflicting combinations up front.
#[derive(Default)]
struct AdvancedWebvhOptions {
    /// Caller-supplied DID-document template (parsed from `did_document_file`).
    did_document: Option<serde_json::Value>,
    /// Pre-signed did.jsonl log (read from `did_log_file`).
    did_log: Option<String>,
    /// Existing signing-key id to reuse.
    signing_key_id: Option<String>,
    /// Existing key-agreement-key id to reuse.
    ka_key_id: Option<String>,
}

fn default_true() -> bool {
    true
}

fn default_pre_rotation_count() -> u32 {
    1
}

/// Entry point for `vta setup --from <file>`.
pub async fn run_setup_from_file(file_path: PathBuf) -> Result<(), Box<dyn std::error::Error>> {
    let raw = std::fs::read_to_string(&file_path)
        .map_err(|e| format!("read setup file {}: {e}", file_path.display()))?;
    let inputs: WizardInputs = toml::from_str(&raw)
        .map_err(|e| format!("parse setup file {}: {e}", file_path.display()))?;

    eprintln!(
        "Running non-interactive setup from {} ...",
        file_path.display()
    );
    apply_inputs(inputs, &SilentUi).await
}

/// Run the setup wizard from a [`WizardInputs`] (the canonical schema for
/// both `vta setup` and `vta setup --from <file>`).
///
/// This is the single setup engine: it owns all the work (store init, seed
/// persistence, mnemonic generation, mediator + VTA DID minting, config write,
/// optional admin seal). The two operator-input points the TOML schema can't
/// carry — confirming the displayed mnemonic and choosing where to write a
/// DID's `did.jsonl` — are delegated to `ui` ([`SetupUi`]). The non-interactive
/// path passes [`SilentUi`] (no display, canonical log path); the interactive
/// wizard passes an impl that prompts.
pub async fn apply_inputs(
    inputs: WizardInputs,
    ui: &dyn SetupUi,
) -> Result<(), Box<dyn std::error::Error>> {
    // 1. Refuse to overwrite an existing config unless the operator asked
    //    for it. Note this only *checks* — the file is not written (and so
    //    not destroyed) until step 13, so a failure or a cancel anywhere in
    //    between leaves the operator's existing install untouched.
    if inputs.config_path.exists() && !inputs.overwrite_config {
        return Err(format!(
            "config file {} already exists — set overwrite_config = true (or delete it) to re-run setup",
            inputs.config_path.display()
        )
        .into());
    }

    // 2. Validate cross-field constraints. `messaging.create_mediator`
    //    needs `services.didcomm = true`, and so on.
    validate_inputs(&inputs)?;

    // 3. Handle data_dir conflict per policy. The gate is "does this
    //    directory hold a *store*", not "does this directory exist" — a
    //    Docker volume, a K8s PVC, and an operator's `mkdir` all pre-create
    //    an empty data_dir, and refusing those makes containerized
    //    first-boot impossible.
    if vti_common::store::local_store_exists(&inputs.data_dir) {
        match inputs.data_dir_exists {
            ExistingDataDirPolicy::Error => {
                return Err(format!(
                    "data directory {} already holds a store — set data_dir_exists = \"delete\" \
                     to wipe it, or \"reuse\" to initialize into it",
                    inputs.data_dir.display()
                )
                .into());
            }
            ExistingDataDirPolicy::Delete => {
                clear_dir_contents(&inputs.data_dir)
                    .map_err(|e| format!("clear {}: {e}", inputs.data_dir.display()))?;
                eprintln!("  Deleted existing data directory contents.");
            }
            ExistingDataDirPolicy::Reuse => {
                eprintln!("  Reusing existing data directory.");
            }
        }
    }

    // 3.5. Hardened configuration: generate the mnemonic + store the seed BEFORE the fjall
    //     store is opened. Deriving the storage key requires the seed, and having
    //     the key before the first store write means all keyspace handles are
    //     wrapped with encryption from the start — there is no plaintext window.
    //
    //     For non-hardened configuration, seed generation stays in steps 5–7 as before.
    let setup_storage_key: Option<[u8; 32]>;
    let pre_generated_seed: Option<[u8; 64]>;
    let early_secrets_config: Option<SecretsConfig>;

    if inputs.hardened.enabled {
        let mnemonic = generate_mnemonic_silent()?;
        ui.confirm_mnemonic(&mnemonic)?;
        let seed = mnemonic.to_seed("");

        let mut sc = secrets_config_from_input(&inputs.secrets)?;
        if matches!(inputs.secrets, SecretsBackendInput::ConfigSeed) {
            sc.seed = Some(hex::encode(seed));
        } else {
            let scratch = scratch_config_for_seed_store(
                inputs.data_dir.clone(),
                sc.clone(),
                inputs.config_path.clone(),
            );
            let seed_store = create_seed_store(&scratch).map_err(|e| format!("{e}"))?;
            seed_store.set(&seed).await.map_err(|e| format!("{e}"))?;
        }

        let key = *crate::hardened_bootstrap::derive_storage_key(
            &seed,
            &inputs.hardened.storage_key_salt,
        );
        setup_storage_key = Some(key);
        pre_generated_seed = Some(seed);
        early_secrets_config = Some(sc);
        eprintln!(
            "  Hardened configuration: seed stored, storage key derived (store will be encrypted from first write)."
        );
    } else {
        setup_storage_key = None;
        pre_generated_seed = None;
        early_secrets_config = None;
    }

    // 4. Open store and wrap every keyspace with encryption when in hardened configuration.
    //    In hardened configuration all writes are encrypted from the first byte — no
    //    plaintext window exists on disk.
    let store = Store::open(&StoreConfig {
        data_dir: inputs.data_dir.clone(),
    })?;

    let maybe_encrypt = |ks: KeyspaceHandle| -> KeyspaceHandle {
        match setup_storage_key {
            Some(key) => ks.with_encryption(key),
            None => ks,
        }
    };

    let keys_ks = maybe_encrypt(store.keyspace(crate::keyspaces::KEYS)?);

    // 4a. Fail closed if the store already holds an initialized VTA. Setup
    //     mints a fresh master seed and writes it as generation 0 (step 8),
    //     which on top of an existing seed silently orphans every key
    //     derived from it. Reachable via `reuse`, and as a backstop for a
    //     `delete` that did not actually clear (an odd mount, a partial
    //     failure) — so the check guards every policy, not just `reuse`.
    if get_seed_record(&keys_ks, 0).await?.is_some() {
        return Err(format!(
            "data directory {} already holds an initialized VTA (master seed generation 0) — \
             refusing to re-run setup over it, which would mint a new master seed and orphan \
             every existing key. Use the existing install, or set data_dir_exists = \"delete\" \
             to start over.",
            inputs.data_dir.display()
        )
        .into());
    }
    let imported_ks = maybe_encrypt(store.keyspace(crate::keyspaces::IMPORTED_SECRETS)?);
    let contexts_ks = maybe_encrypt(store.keyspace(crate::keyspaces::CONTEXTS)?);
    let webvh_ks = maybe_encrypt(store.keyspace(crate::keyspaces::WEBVH)?);
    let audit_ks = maybe_encrypt(store.keyspace(crate::keyspaces::AUDIT)?);
    let did_templates_ks = maybe_encrypt(store.keyspace(crate::keyspaces::DID_TEMPLATES)?);

    let mut vta_ctx = create_seed_context(&contexts_ks, "vta", "Verifiable Trust Agent").await?;
    eprintln!("  Created application context: vta");

    // 5–7. Mnemonic generation, secrets config, and seed persistence.
    //     For hardened configuration these were already completed in step 3.5 — skip them
    //     here to avoid regenerating a different seed.
    let (_seed, secrets_config) =
        if let (Some(s), Some(sc)) = (pre_generated_seed, early_secrets_config) {
            (s, sc)
        } else {
            // 5. Mnemonic
            let mnemonic = generate_mnemonic_silent()?;
            ui.confirm_mnemonic(&mnemonic)?;
            let seed = mnemonic.to_seed("");

            // 6. Translate backend choice.
            let mut sc = secrets_config_from_input(&inputs.secrets)?;

            // 7. Persist seed via the chosen backend.
            if matches!(inputs.secrets, SecretsBackendInput::ConfigSeed) {
                sc.seed = Some(hex::encode(seed));
            } else {
                let scratch_config = scratch_config_for_seed_store(
                    inputs.data_dir.clone(),
                    sc.clone(),
                    inputs.config_path.clone(),
                );
                let seed_store = create_seed_store(&scratch_config).map_err(|e| format!("{e}"))?;
                seed_store.set(&seed).await.map_err(|e| format!("{e}"))?;
            }
            (seed, sc)
        };

    // 8. Initial seed record + JWT signing key.
    let initial_seed_record = SeedRecord {
        id: 0,
        seed_hex: None,
        seed_enc: None,
        created_at: Utc::now(),
        retired_at: None,
    };
    save_seed_record(&keys_ks, &initial_seed_record).await?;
    set_active_seed_id(&keys_ks, 0).await?;

    // In hardened configuration the JWT signing key is derived from the master seed at
    // boot and sealed in the bootstrap keyspace — it is never written to
    // config.toml. In standard mode we generate a random key here and write it.
    let jwt_signing_key: Option<String> = if inputs.hardened.enabled {
        None
    } else {
        let mut jwt_key_bytes = [0u8; 32];
        rand::rng().fill_bytes(&mut jwt_key_bytes);
        Some(BASE64.encode(jwt_key_bytes))
    };

    // 9. Build a scratch AppConfig the messaging/DID builders can use to
    //    open the seed store. The real AppConfig is constructed at the end
    //    once we have the VTA DID.
    let mut wizard_config = scratch_config_for_seed_store(
        inputs.data_dir.clone(),
        secrets_config.clone(),
        inputs.config_path.clone(),
    );
    let wizard_seed_store: Arc<dyn SeedStore> =
        Arc::from(create_seed_store(&wizard_config).map_err(|e| format!("{e}"))?);

    // 10. Messaging.
    let messaging = match &inputs.messaging {
        MessagingInput::Skip => None,
        MessagingInput::Existing {
            did,
            mediator_host,
            setup_acl,
        } => Some(MessagingConfig {
            mediator_url: String::new(),
            mediator_did: did.clone(),
            mediator_host: mediator_host.clone(),
            setup_acl: *setup_acl,
            drain_inbox_on_start: false,
        }),
        MessagingInput::CreateMediator {
            context,
            url,
            ws_url,
            webvh_url,
            mediator_host,
            template_vars,
            setup_acl,
            protocols,
        } => {
            let _med_ctx =
                create_seed_context(&contexts_ks, context, "DIDComm Messaging Mediator").await?;
            // Operator-supplied vars first; then `URL` and `WS_URL` so the
            // wizard's notion of the endpoint always wins even if an
            // operator typo'd it under template_vars. Both are required by
            // the `didcomm-mediator` template since it started advertising
            // HTTP + WSS in a single `#service` block.
            let mut effective_vars: HashMap<String, serde_json::Value> = template_vars.clone();
            effective_vars.insert("URL".into(), json!(url));
            // `WS_URL`: an explicit `ws_url` is used verbatim (for reverse
            // proxies that route the WS upgrade elsewhere); otherwise derive
            // it from `url` via the shared helper — same `{base}/ws`
            // convention the interactive wizard offers as its prompt
            // default, so the two paths agree. Shape of an explicit value is
            // already checked in `validate_inputs`.
            let ws_url = match ws_url {
                Some(explicit) => explicit.trim().to_string(),
                None => super::derive_ws_url(url).ok_or_else(|| {
                    format!(
                        "messaging.url '{url}' must start with http:// or https:// so the \
                         wizard can derive WS_URL (or set messaging.ws_url explicitly)"
                    )
                })?,
            };
            effective_vars.insert("WS_URL".into(), json!(ws_url));

            // TSP: fill the template's `{SERVICE_TSP}` null-pruning slot when
            // this mediator serves TSP. Omitted, the slot prunes and the
            // mediator advertises DIDComm only — which is what happened to
            // every TSP-enabled VTA before this, leaving the VTA's `#tsp`
            // pointing at a mediator whose own document said it didn't carry
            // TSP (transport-neutral-mediator.md §2).
            //
            // The mediator's own entry names its **URL**, the inverse of the
            // VTA's, which names the mediator's DID. The indirection has to
            // terminate at the node that actually serves the transport.
            if mediator_protocols(protocols.as_deref(), &inputs.services).contains(&Protocol::Tsp) {
                let entry = vta_sdk::did_templates::tsp_transport_service(url)
                    .map_err(|e| format!("build the mediator's TSP service entry: {e}"))?;
                effective_vars.insert(vta_sdk::did_templates::TSP_SERVICE_VAR.into(), entry);
                eprintln!("  Mediator will advertise: TSP + DIDComm");
            }

            // `url` is the DIDComm endpoint; `webvh_url` is the DID-document
            // hosting URL. They are usually the same host but are semantically
            // distinct, so we let operators specify them separately. Default to
            // the DIDComm endpoint when no explicit hosting URL is set.
            let did_hosting_url = webvh_url.as_deref().unwrap_or(url);

            let mediator_did = create_simple_webvh_did(
                context,
                context,
                did_hosting_url,
                /* portable */ true,
                /* pre_rotation_count */ 1,
                /* additional_services */ None,
                /* add_mediator_service */ false,
                /* template */ Some("didcomm-mediator".into()),
                effective_vars,
                /* is_vta_identity */ false,
                AdvancedWebvhOptions::default(),
                ui,
                &keys_ks,
                &imported_ks,
                &contexts_ks,
                &webvh_ks,
                &audit_ks,
                &did_templates_ks,
                &*wizard_seed_store,
                &wizard_config,
            )
            .await?;

            Some(MessagingConfig {
                mediator_url: url.clone(),
                mediator_did,
                mediator_host: mediator_host.clone(),
                setup_acl: *setup_acl,
                drain_inbox_on_start: false,
            })
        }
    };

    // Propagate the resolved mediator into the scratch config so the VTA DID
    // builder can embed `DIDCommMessaging` in the DID document. Without this,
    // `build_did_document_inner` sees `config.messaging == None` and silently
    // drops the service even when `add_mediator_service == true`.
    wizard_config.messaging = messaging.clone();

    // 11. VTA DID.
    let vta_did = match &inputs.vta_did {
        VtaDidInput::Skip => None,
        VtaDidInput::Existing { did } => Some(did.clone()),
        VtaDidInput::CreateDidKey => {
            let did =
                create_vta_did_key("vta", &keys_ks, &contexts_ks, &*wizard_seed_store).await?;
            Some(did)
        }
        VtaDidInput::CreateWebvh {
            url,
            portable,
            pre_rotation_count,
            did_document_file,
            did_log_file,
            signing_key_id,
            ka_key_id,
        } => {
            // Resolve the advanced-mode inputs (validated mutually exclusive in
            // `validate_inputs`): a DID-document template file is parsed as
            // JSON, a pre-signed log file is read verbatim.
            let did_document = match did_document_file {
                Some(path) => {
                    let raw = std::fs::read_to_string(path).map_err(|e| {
                        format!("read vta_did.did_document_file {}: {e}", path.display())
                    })?;
                    Some(
                        serde_json::from_str::<serde_json::Value>(&raw).map_err(|e| {
                            format!("parse vta_did.did_document_file {}: {e}", path.display())
                        })?,
                    )
                }
                None => None,
            };
            let did_log =
                match did_log_file {
                    Some(path) => Some(std::fs::read_to_string(path).map_err(|e| {
                        format!("read vta_did.did_log_file {}: {e}", path.display())
                    })?),
                    None => None,
                };
            let advanced = AdvancedWebvhOptions {
                did_document,
                did_log,
                signing_key_id: signing_key_id.clone(),
                ka_key_id: ka_key_id.clone(),
            };
            let services = super::build_vta_additional_services(
                &inputs.services,
                inputs.public_url.as_deref(),
                // `#tsp` points at the DIDComm mediator resolved above.
                // `None` when messaging was skipped — then there is no
                // endpoint to advertise and the entry is dropped rather
                // than published empty.
                messaging.as_ref().map(|m| m.mediator_did.as_str()),
            );
            let did = create_simple_webvh_did(
                "VTA",
                "vta",
                url,
                *portable,
                *pre_rotation_count,
                services,
                /* add_mediator_service */ messaging.is_some(),
                /* template */ None,
                HashMap::new(),
                /* is_vta_identity */ true,
                advanced,
                ui,
                &keys_ks,
                &imported_ks,
                &contexts_ks,
                &webvh_ks,
                &audit_ks,
                &did_templates_ks,
                &*wizard_seed_store,
                &wizard_config,
            )
            .await?;
            Some(did)
        }
    };

    if let Some(ref did) = vta_did {
        vta_ctx.did = Some(did.clone());
        vta_ctx.updated_at = Utc::now();
        store_context(&contexts_ks, &vta_ctx)
            .await
            .map_err(|e| format!("{e}"))?;
    }

    // 13. Flush store and release the directory lock before any later step
    //     that re-opens it. fjall holds an exclusive lock per data dir, so
    //     the admin-seeding step (which reopens the store) would deadlock
    //     if these handles were still alive.
    store.persist().await?;
    drop(wizard_seed_store);
    drop(keys_ks);
    drop(imported_ks);
    drop(contexts_ks);
    drop(webvh_ks);
    drop(audit_ks);
    drop(did_templates_ks);
    drop(store);

    // 14. Save AppConfig.
    let config = AppConfig {
        trusted_presentation_verifiers: Vec::new(),
        credential_holder_did: None,
        vta_did: vta_did.clone(),
        vta_name: inputs.vta_name.clone(),
        public_url: inputs.public_url.clone(),
        server: inputs.server.clone(),
        log: inputs.log.clone(),
        store: StoreConfig {
            data_dir: inputs.data_dir.clone(),
        },
        services: inputs.services.clone(),
        messaging: messaging.clone(),
        mediator_readiness: Default::default(),
        auth: AuthConfig {
            jwt_signing_key,
            ..AuthConfig::default()
        },
        audit: inputs.audit.clone(),
        vault: Default::default(),
        policy: Default::default(),
        secrets: secrets_config,
        #[cfg(feature = "tee")]
        tee: Default::default(),
        hardened: inputs.hardened.clone(),
        resolver_url: inputs.resolver_url.clone(),
        config_path: inputs.config_path.clone(),
        unknown_keys: Vec::new(),
    };
    config.save()?;

    // 15. Optional admin seeding + seal. Atomic from the operator's
    //    perspective — if seeding fails, setup as a whole fails (config is
    //    on disk but the VTA is not declared "ready").
    if let Some(ref admin_did) = inputs.admin_did {
        seed_initial_admin(
            &inputs.data_dir,
            admin_did,
            inputs.admin_label.clone(),
            setup_storage_key,
        )
        .await?;
    }

    // 15b. Enterprise staff provisioning (context + policy + scoped ACL row).
    //     Runs after the owner is seeded; no-op for a personal VTA.
    seed_staff(&inputs.data_dir, &inputs.staff, setup_storage_key).await?;

    // 15. Summary.
    eprintln!();
    eprintln!("\x1b[1;32mSetup complete.\x1b[0m");
    eprintln!("  Config:   {}", config.config_path.display());
    eprintln!("  Data dir: {}", config.store.data_dir.display());
    if let Some(ref name) = config.vta_name {
        eprintln!("  Name:     {name}");
    }
    if let Some(ref url) = config.public_url {
        eprintln!("  URL:      {url}");
    }
    if let Some(ref did) = config.vta_did {
        eprintln!("  VTA DID:  {did}");
    }
    if let Some(ref msg) = config.messaging {
        eprintln!("  Mediator: {}", msg.mediator_did);
    }
    if let Some(admin) = &inputs.admin_did {
        eprintln!("  Admin:    {admin} (sealed)");
    } else {
        eprintln!();
        eprintln!("  ACL is empty. Seed the first admin:");
        eprintln!();
        eprintln!("    Option A (recommended, reversible) — grant admin access to an");
        eprintln!("    existing DID without sealing the VTA. Lets you add more admins");
        eprintln!("    later and re-run offline CLI commands:");
        eprintln!("      vta import-did --did <did:...> --role admin [--label <name>]");
        eprintln!();
        eprintln!("    Option B (one-time, seals the VTA) — for immutable-image");
        eprintln!("    deployments that should refuse any further offline CLI writes");
        eprintln!("    after first admin. Disables `acl`, `keys`, `import-did`,");
        eprintln!("    `export-admin` until you run `vta unseal`:");
        eprintln!("      vta bootstrap-admin --did <did:...> [--label <name>]");
    }
    eprintln!();
    eprintln!("  Mnemonic was generated and stored in the configured backend.");
    eprintln!("  Capture an encrypted backup after the first admin connects:");
    eprintln!("    pnm backup export --output vta-backup.vtabak");
    eprintln!();

    Ok(())
}

fn validate_inputs(inputs: &WizardInputs) -> Result<(), Box<dyn std::error::Error>> {
    let mut errors: Vec<String> = Vec::new();

    if matches!(inputs.messaging, MessagingInput::CreateMediator { .. }) && !inputs.services.didcomm
    {
        errors.push("messaging.kind = \"create_mediator\" requires services.didcomm = true".into());
    }
    if matches!(inputs.messaging, MessagingInput::Existing { .. }) && !inputs.services.didcomm {
        errors.push("messaging.kind = \"existing\" requires services.didcomm = true".into());
    }
    // REST requires a public URL — without it the VTA DID document
    // ends up with no `VTARest` service entry, leaving downstream
    // resolvers no way to reach the REST API. The interactive wizard
    // blocks this at prompt time; this rule does the same for the
    // `--from <toml>` path.
    if inputs.services.rest && inputs.public_url.as_deref().is_none_or(str::is_empty) {
        errors.push(
            "services.rest = true requires `public_url` to be set (e.g. \
             `public_url = \"https://vta.example.com\"`); without it the VTA DID \
             document has no REST service endpoint to publish"
                .into(),
        );
    }
    // TSP advertises the **same** mediator as DIDComm (one dual-protocol
    // mediator — tsp-enablement.md D8), so `services.tsp = true` without
    // DIDComm would point the `#tsp` service at a mediator the VTA never
    // configured. Require DIDComm when TSP is on. (TSP is usually enabled
    // post-setup via `services tsp enable` once it's been verified; this rule
    // guards the declarative `--from <toml>` path.)
    if inputs.services.tsp && !inputs.services.didcomm {
        errors.push(
            "services.tsp = true requires services.didcomm = true — TSP advertises \
             the same mediator as DIDComm. Set services.didcomm = true (and \
             configure messaging), or leave TSP off here and enable it later with \
             `services tsp enable`"
                .into(),
        );
    }
    // A binary built without the `tsp` feature has no TSP dispatcher (the
    // inbound half lives behind that flag), so `services.tsp = true` would
    // advertise `#tsp` — the *first* entry a peer matching on transport
    // preference picks — for a transport this VTA cannot answer on. The
    // interactive wizard handles this by not offering the option; the
    // declarative path has to say it out loud.
    #[cfg(not(feature = "tsp"))]
    if inputs.services.tsp {
        errors.push(
            "services.tsp = true, but this VTA was built without the `tsp` feature and has \
             no TSP dispatcher — advertising `#tsp` would publish a transport it cannot \
             serve, and TSP-preferring peers would fail rather than fall back to DIDComm. \
             Rebuild with `--features tsp`, or set services.tsp = false"
                .into(),
        );
    }
    if let MessagingInput::CreateMediator {
        context,
        webvh_url,
        ws_url,
        protocols,
        ..
    } = &inputs.messaging
    {
        if context.trim().is_empty() {
            errors.push("messaging.context cannot be empty".into());
        }
        if let Some(protocols) = protocols {
            if protocols.is_empty() {
                errors.push(
                    "messaging.protocols = [] — a mediator that carries nothing is not a \
                     mediator. Remove the key to serve what this VTA advertises, or list \
                     the transports it should serve"
                        .into(),
                );
            }
            if protocols.contains(&Protocol::Rest) {
                errors.push(
                    "messaging.protocols contains \"rest\" — REST is not a mediator transport \
                     (a REST peer is reached directly, with no mediator). Use \"tsp\" and/or \
                     \"didcomm\""
                        .into(),
                );
            }
            // Duplicates would render one service entry twice. Always a
            // mistake, and refused rather than de-duplicated (same call as
            // the VTC's `transports`, #929).
            let mut seen = Vec::new();
            for p in protocols {
                if seen.contains(p) {
                    errors.push(format!(
                        "messaging.protocols lists \"{p}\" more than once; each transport is \
                         advertised exactly once"
                    ));
                } else {
                    seen.push(*p);
                }
            }
            // The `didcomm-mediator` template renders its DIDComm `#service`
            // block unconditionally — only `{SERVICE_TSP}` is a pruning slot.
            // So a `protocols` omitting DIDComm describes a document setup
            // does not mint, and would be believed by nothing.
            if !protocols.contains(&Protocol::Didcomm) {
                errors.push(
                    "messaging.protocols omits \"didcomm\", but the `didcomm-mediator` \
                     template always advertises a DIDComm endpoint — a minted mediator \
                     cannot be TSP-only today. Include \"didcomm\", or point at a TSP-only \
                     mediator with kind = \"existing\""
                        .into(),
                );
            }
        }
        // §3's invariant, on the slice setup can enforce today: the VTA must
        // not advertise a transport its own mediator doesn't carry. Since we
        // are the ones minting that mediator, an explicit `protocols` that
        // omits TSP while the VTA advertises it is a contradiction the
        // operator has to resolve, not something to silently widen.
        if inputs.services.tsp
            && protocols
                .as_ref()
                .is_some_and(|p| !p.contains(&Protocol::Tsp))
        {
            errors.push(
                "services.tsp = true but messaging.protocols omits \"tsp\" — the VTA would \
                 advertise `#tsp` pointing at a mediator whose own DID document says it \
                 does not carry TSP. Add \"tsp\" to messaging.protocols, or set \
                 services.tsp = false"
                    .into(),
            );
        }
        if webvh_url.as_deref().is_some_and(str::is_empty) {
            errors.push(
                "messaging.webvh_url is set to an empty string; either remove the key to default \
                 to messaging.url, or provide a hosting URL"
                    .into(),
            );
        }
        // An explicit `ws_url` is used verbatim (reverse proxies that
        // route the WS upgrade elsewhere); validate its shape here so the
        // failure surfaces at parse time, alongside `webvh_url`, rather
        // than mid-`apply_inputs`. An absent `ws_url` is derived from
        // `url` and validated there.
        if let Some(ws) = ws_url {
            let trimmed = ws.trim();
            if trimmed.is_empty() {
                errors.push(
                    "messaging.ws_url is set to an empty string; either remove the key to \
                     derive it from messaging.url, or provide a ws:// or wss:// endpoint"
                        .into(),
                );
            } else if !(trimmed.starts_with("ws://") || trimmed.starts_with("wss://")) {
                errors.push(format!(
                    "messaging.ws_url '{trimmed}' must start with ws:// or wss://"
                ));
            }
        }
    }
    if let VtaDidInput::CreateWebvh {
        pre_rotation_count,
        did_document_file,
        did_log_file,
        signing_key_id,
        ka_key_id,
        ..
    } = &inputs.vta_did
    {
        if *pre_rotation_count > 32 {
            errors.push(format!(
                "vta_did.pre_rotation_count = {pre_rotation_count} is unreasonably large (max 32)"
            ));
        }
        // The advanced modes are mutually exclusive — each selects a different
        // way of supplying the DID document / keys, and the operations layer
        // rejects more than one of `did_document` / `did_log` / existing-key
        // anyway. Surface the conflict at parse time with a clear message.
        let advanced_modes = usize::from(did_document_file.is_some())
            + usize::from(did_log_file.is_some())
            + usize::from(signing_key_id.is_some());
        if advanced_modes > 1 {
            errors.push(
                "vta_did: at most one of `did_document_file`, `did_log_file`, `signing_key_id` \
                 may be set — they select mutually-exclusive advanced DID-creation modes"
                    .into(),
            );
        }
        if ka_key_id.is_some() && signing_key_id.is_none() {
            errors.push(
                "vta_did.ka_key_id requires vta_did.signing_key_id (the key-agreement key pairs \
                 with an existing signing key)"
                    .into(),
            );
        }
    }
    if let Some(did) = &inputs.admin_did
        && !did.starts_with("did:")
    {
        errors.push(format!(
            "admin_did = {did:?} must be a DID (starts with `did:`)"
        ));
    }
    for s in &inputs.staff {
        if !s.did.starts_with("did:") {
            errors.push(format!(
                "staff.did = {:?} must be a DID (starts with `did:`)",
                s.did
            ));
        }
        if s.context.trim().is_empty() {
            errors.push("staff.context must be a non-empty context id".into());
        }
        if let Some(role) = &s.role
            && crate::acl::Role::parse(role).is_err()
        {
            errors.push(format!(
                "staff.role = {role:?} is not a valid role \
                 (admin/initiator/application/reader/monitor)"
            ));
        }
    }
    if inputs.resolver_url.as_deref().is_some_and(str::is_empty) {
        errors.push(
            "resolver_url is set to an empty string; either remove the key or provide a \
             WebSocket URL (e.g. `ws://resolver.example.com/did/v1/ws`)"
                .into(),
        );
    }
    // `retention_days = 0` would silently disable retention. Reject it
    // so an operator who meant "keep forever" has to think about it
    // explicitly (we don't currently support unbounded retention; the
    // sweeper assumes a positive window).
    if inputs.audit.retention_days == 0 {
        errors.push("audit.retention_days must be > 0 (default is 28)".into());
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(format!(
            "setup file has {} validation error(s):\n  - {}",
            errors.len(),
            errors.join("\n  - ")
        )
        .into())
    }
}

/// The explicit `[secrets] backend` selector matching an operator's wizard
/// choice. Every generated config states its backend outright rather than
/// leaving `create_seed_store` to infer one from which fields are populated
/// — inference cannot express "plaintext" at all on a build with `keyring`
/// compiled in, so the wizard's plaintext option used to silently produce a
/// keyring-backed VTA.
fn backend_selector(input: &SecretsBackendInput) -> SecretBackend {
    match input {
        SecretsBackendInput::Keyring { .. } => SecretBackend::Keyring,
        SecretsBackendInput::ConfigSeed => SecretBackend::ConfigSeed,
        SecretsBackendInput::Aws { .. } => SecretBackend::Aws,
        SecretsBackendInput::Gcp { .. } => SecretBackend::Gcp,
        SecretsBackendInput::Azure { .. } => SecretBackend::Azure,
        SecretsBackendInput::Vault { .. } => SecretBackend::Vault,
        SecretsBackendInput::Kubernetes { .. } => SecretBackend::Kubernetes,
        SecretsBackendInput::Plaintext => SecretBackend::Plaintext,
    }
}

fn secrets_config_from_input(
    input: &SecretsBackendInput,
) -> Result<SecretsConfig, Box<dyn std::error::Error>> {
    let selector = backend_selector(input);
    let mut config = match input {
        SecretsBackendInput::Keyring { service } => {
            #[cfg(not(feature = "keyring"))]
            {
                let _ = service;
                return Err(
                    "keyring backend requested but vta-service was built without the `keyring` feature"
                        .into(),
                );
            }
            #[cfg(feature = "keyring")]
            {
                SecretsConfig {
                    keyring_service: service.clone(),
                    ..SecretsConfig::default()
                }
            }
        }
        SecretsBackendInput::ConfigSeed => {
            #[cfg(not(feature = "config-seed"))]
            {
                return Err(
                    "config_seed backend requested but vta-service was built without the `config-seed` feature"
                        .into(),
                );
            }
            #[cfg(feature = "config-seed")]
            {
                SecretsConfig {
                    seed: Some(String::new()), // populated with hex(seed) by caller
                    ..Default::default()
                }
            }
        }
        SecretsBackendInput::Aws {
            region,
            secret_name,
        } => {
            #[cfg(not(feature = "aws-secrets"))]
            {
                let _ = (region, secret_name);
                return Err(
                    "aws backend requested but vta-service was built without the `aws-secrets` feature"
                        .into(),
                );
            }
            #[cfg(feature = "aws-secrets")]
            {
                SecretsConfig {
                    aws_secret_name: Some(secret_name.clone()),
                    aws_region: region.clone(),
                    ..Default::default()
                }
            }
        }
        SecretsBackendInput::Gcp {
            project,
            secret_name,
        } => {
            #[cfg(not(feature = "gcp-secrets"))]
            {
                let _ = (project, secret_name);
                return Err(
                    "gcp backend requested but vta-service was built without the `gcp-secrets` feature"
                        .into(),
                );
            }
            #[cfg(feature = "gcp-secrets")]
            {
                SecretsConfig {
                    gcp_project: Some(project.clone()),
                    gcp_secret_name: Some(secret_name.clone()),
                    ..Default::default()
                }
            }
        }
        SecretsBackendInput::Azure {
            vault_url,
            secret_name,
        } => {
            #[cfg(not(feature = "azure-secrets"))]
            {
                let _ = (vault_url, secret_name);
                return Err(
                    "azure backend requested but vta-service was built without the `azure-secrets` feature"
                        .into(),
                );
            }
            #[cfg(feature = "azure-secrets")]
            {
                SecretsConfig {
                    azure_vault_url: Some(vault_url.clone()),
                    azure_secret_name: Some(secret_name.clone()),
                    ..Default::default()
                }
            }
        }
        SecretsBackendInput::Vault {
            addr,
            secret_path,
            kv_mount,
            secret_key,
            namespace,
            auth_method,
            k8s_role,
            k8s_mount,
            k8s_jwt_path,
            token,
            approle_role_id,
            approle_secret_id,
            approle_mount,
            skip_verify,
        } => {
            #[cfg(not(feature = "vault-secrets"))]
            {
                let _ = (
                    addr,
                    secret_path,
                    kv_mount,
                    secret_key,
                    namespace,
                    auth_method,
                    k8s_role,
                    k8s_mount,
                    k8s_jwt_path,
                    token,
                    approle_role_id,
                    approle_secret_id,
                    approle_mount,
                    skip_verify,
                );
                return Err(
                    "vault backend requested but vta-service was built without the `vault-secrets` feature"
                        .into(),
                );
            }
            #[cfg(feature = "vault-secrets")]
            {
                SecretsConfig {
                    vault_addr: Some(addr.clone()),
                    vault_secret_path: Some(secret_path.clone()),
                    vault_kv_mount: kv_mount.clone(),
                    vault_secret_key: secret_key.clone(),
                    vault_namespace: namespace.clone(),
                    vault_auth_method: auth_method.clone(),
                    vault_k8s_role: k8s_role.clone(),
                    vault_k8s_mount: k8s_mount.clone(),
                    vault_k8s_jwt_path: k8s_jwt_path.clone(),
                    vault_token: token.clone(),
                    vault_approle_role_id: approle_role_id.clone(),
                    vault_approle_secret_id: approle_secret_id.clone(),
                    vault_approle_mount: approle_mount.clone(),
                    vault_skip_verify: *skip_verify,
                    ..SecretsConfig::default()
                }
            }
        }
        SecretsBackendInput::Kubernetes {
            secret_name,
            namespace,
            secret_key,
        } => {
            #[cfg(not(feature = "k8s-secrets"))]
            {
                let _ = (secret_name, namespace, secret_key);
                return Err(
                    "kubernetes backend requested but vta-service was built without the `k8s-secrets` feature"
                        .into(),
                );
            }
            #[cfg(feature = "k8s-secrets")]
            {
                SecretsConfig {
                    k8s_secret_name: Some(secret_name.clone()),
                    k8s_namespace: namespace.clone(),
                    k8s_secret_key: secret_key.clone(),
                    ..SecretsConfig::default()
                }
            }
        }
        SecretsBackendInput::Plaintext => {
            eprintln!();
            eprintln!(
                "\x1b[1;33mWARNING: plaintext seed storage selected. NOT for production.\x1b[0m"
            );
            eprintln!();
            // The plaintext fallback in `create_seed_store` is an explicit
            // opt-in (P0.9) — without `allow_plaintext = true` it errors
            // rather than silently writing the master seed in clear. Since
            // the operator deliberately chose plaintext here, set the flag so
            // the seed store can be created during setup *and* the booted VTA
            // can re-open it. The flag is serialized into `[secrets]` in the
            // generated config.toml, so plaintext deployments stay runnable.
            //
            // `allow_plaintext` is only the *permission*; `backend` below is
            // what actually selects plaintext over the compiled-in keyring.
            SecretsConfig {
                allow_plaintext: true,
                ..SecretsConfig::default()
            }
        }
    };
    config.backend = Some(selector);
    Ok(config)
}

fn scratch_config_for_seed_store(
    data_dir: PathBuf,
    secrets: SecretsConfig,
    config_path: PathBuf,
) -> AppConfig {
    AppConfig {
        trusted_presentation_verifiers: Vec::new(),
        credential_holder_did: None,
        vta_did: None,
        vta_name: None,
        public_url: None,
        server: ServerConfig::default(),
        log: LogConfig::default(),
        store: StoreConfig { data_dir },
        services: ServicesConfig::default(),
        messaging: None,
        mediator_readiness: Default::default(),
        auth: AuthConfig::default(),
        audit: Default::default(),
        vault: Default::default(),
        policy: Default::default(),
        secrets,
        #[cfg(feature = "tee")]
        tee: Default::default(),
        hardened: Default::default(),
        resolver_url: None,
        config_path,
        unknown_keys: Vec::new(),
    }
}

/// Mint a `did:key` for the VTA identity using a BIP-32-derived Ed25519
/// key from the active seed. Stores only the Ed25519 signing record at
/// `{did}#key-0`; the X25519 key-agreement secret is curve-converted
/// from Ed25519 at runtime (per the `did:key` spec) so a separate
/// `#key-1` record would be a misleading second source of truth. No
/// external hosting needed — `did:key` is self-resolving.
pub(crate) async fn create_vta_did_key(
    context_id: &str,
    keys_ks: &KeyspaceHandle,
    contexts_ks: &KeyspaceHandle,
    seed_store: &dyn SeedStore,
) -> Result<String, Box<dyn std::error::Error>> {
    use affinidi_tdk::secrets_resolver::secrets::Secret;
    use vti_common::slip10::{DerivationPath, ExtendedSigningKey};

    use crate::keys;
    use crate::keys::seeds::{get_active_seed_id, load_seed_bytes};
    use vta_sdk::keys::KeyType as SdkKeyType;

    let active_seed_id = get_active_seed_id(keys_ks).await?;
    let seed = load_seed_bytes(keys_ks, seed_store, Some(active_seed_id)).await?;

    // Load context to get base derivation path
    let ctx = crate::contexts::get_context(contexts_ks, context_id)
        .await
        .map_err(|e| format!("{e}"))?
        .ok_or_else(|| format!("context '{context_id}' not found"))?;

    // Allocate a single BIP-32 path for the Ed25519 signing key. Unlike
    // did:webvh we do NOT allocate a second path for X25519 — it is
    // derived from the Ed25519 key at runtime.
    let signing_path = keys::paths::allocate_path(keys_ks, &ctx.base_path)
        .await
        .map_err(|e| format!("{e}"))?;

    let root = ExtendedSigningKey::from_seed(&seed)
        .map_err(|e| format!("Failed to create BIP-32 root key: {e}"))?;
    let derivation_path: DerivationPath = signing_path
        .parse()
        .map_err(|e| format!("Invalid derivation path: {e}"))?;
    let derived = root
        .derive(&derivation_path)
        .map_err(|e| format!("Key derivation failed: {e}"))?;

    let signing_secret = Secret::generate_ed25519(None, Some(derived.signing_key.as_bytes()));
    let signing_pub = signing_secret
        .get_public_keymultibase()
        .map_err(|e| format!("{e}"))?;

    let did = format!("did:key:{signing_pub}");

    keys::save_key_record(
        keys_ks,
        &format!("{did}#key-0"),
        &signing_path,
        SdkKeyType::Ed25519,
        &signing_pub,
        "VTA signing key",
        Some(context_id),
        Some(active_seed_id),
    )
    .await?;

    // Derive and store sealed-transfer key for bootstrap assertions
    let st = keys::derive_sealed_transfer_key(
        &seed,
        &ctx.base_path,
        "VTA sealed-transfer producer-assertion key",
        keys_ks,
    )
    .await?;
    keys::save_sealed_transfer_key_record(
        &did,
        &st,
        keys_ks,
        Some(context_id),
        Some(active_seed_id),
    )
    .await?;

    eprintln!("  Created DID: {did}");

    Ok(did)
}

/// Mint a `did:webvh` via the operations layer with no interactive
/// prompts. Equivalent to the interactive `build_wizard_did` in "simple
/// mode" with all advanced options off.
#[allow(clippy::too_many_arguments)]
async fn create_simple_webvh_did(
    label: &str,
    context_id: &str,
    url: &str,
    portable: bool,
    pre_rotation_count: u32,
    additional_services: Option<Vec<serde_json::Value>>,
    add_mediator_service: bool,
    template: Option<String>,
    template_vars: HashMap<String, serde_json::Value>,
    is_vta_identity: bool,
    advanced: AdvancedWebvhOptions,
    ui: &dyn SetupUi,
    keys_ks: &KeyspaceHandle,
    imported_ks: &KeyspaceHandle,
    contexts_ks: &KeyspaceHandle,
    webvh_ks: &KeyspaceHandle,
    audit_ks: &KeyspaceHandle,
    did_templates_ks: &KeyspaceHandle,
    seed_store: &dyn SeedStore,
    config: &AppConfig,
) -> Result<String, Box<dyn std::error::Error>> {
    let parsed = Url::parse(url).map_err(|e| format!("invalid DID URL {url:?}: {e}"))?;
    let webvh_url =
        WebVHURL::parse_url(&parsed).map_err(|e| format!("invalid webvh URL {url:?}: {e}"))?;
    let url_str = webvh_url
        .get_http_url(None)
        .map_err(|e| format!("{e}"))?
        .to_string();

    let auth = cli_super_admin();
    let did_resolver = DIDCacheClient::new(DIDCacheConfigBuilder::default().build()).await?;
    let no_bridge: Arc<crate::didcomm_bridge::DIDCommBridge> =
        Arc::new(crate::didcomm_bridge::DIDCommBridge::placeholder());

    let params = CreateDidWebvhParams {
        context_id: context_id.to_string(),
        server_id: None,
        url: Some(url_str),
        // Serverless (`server_id: None`) ignores `path_mode`.
        path_mode: vta_sdk::protocols::did_management::create::WebvhPathMode::default(),
        domain: None,
        label: Some(label.to_string()),
        portable,
        add_mediator_service,
        additional_services,
        pre_rotation_count,
        did_document: advanced.did_document,
        did_log: advanced.did_log,
        set_primary: true,
        signing_key_id: advanced.signing_key_id,
        ka_key_id: advanced.ka_key_id,
        template,
        template_context: None,
        template_vars,
        is_vta_identity,
    };

    // Setup wizard: no shared AppState, so create a local per-server
    // auth-lock registry. This path is serverless (mints from a URL),
    // so it won't authenticate to a hosting server, but the deps bundle
    // requires the field.
    let auth_locks = operations::did_webvh::WebvhAuthLocks::new();
    let deps = operations::did_webvh::CreateDidWebvhDeps {
        keys_ks,
        imported_ks,
        contexts_ks,
        webvh_ks,
        did_templates_ks,
        audit_ks,
        seed_store,
        config,
        did_resolver: &did_resolver,
        didcomm_bridge: &no_bridge,
        auth_locks: &auth_locks,
    };
    let result = operations::did_webvh::create_did_webvh(&deps, &auth, params, "setup")
        .await
        .map_err(|e| format!("{e}"))?;

    let final_did = result.did.clone();
    eprintln!("  Created DID: {final_did}");

    // Persist the did.jsonl so operators can re-publish or audit later. The UI
    // picks the destination: `--from` (SilentUi) writes the canonical in-store
    // location (`<data_dir>/did-logs/<label>-did.jsonl`); the interactive
    // wizard prompts. `None` skips the write entirely.
    if let Some(ref log_entry) = result.log_entry {
        let canonical = config
            .store
            .data_dir
            .join("did-logs")
            .join(format!("{label}-did.jsonl"));
        if let Some(log_path) = ui.did_log_path(label, &canonical) {
            if let Some(parent) = log_path.parent() {
                std::fs::create_dir_all(parent)?;
            }
            std::fs::write(&log_path, log_entry)?;
            eprintln!("  DID log:     {}", log_path.display());
        }
    }

    Ok(final_did)
}

/// Seed the first super-admin and seal the VTA. Library counterpart to
/// `vta bootstrap-admin --did <X>`.
///
/// Refuses to proceed if a seal or any super-admin already exists — for the
/// non-interactive setup flow this should never trip (we just initialised
/// the store), and tripping it indicates a bug or a corrupt re-run.
async fn seed_initial_admin(
    data_dir: &Path,
    did: &str,
    label: Option<String>,
    storage_key: Option<[u8; 32]>,
) -> Result<(), Box<dyn std::error::Error>> {
    use crate::{acl, seal};

    let store = Store::open(&StoreConfig {
        data_dir: data_dir.to_path_buf(),
    })?;
    let acl_ks_raw = store.keyspace(crate::keyspaces::ACL)?;
    let acl_ks = match storage_key {
        Some(key) => acl_ks_raw.with_encryption(key),
        None => acl_ks_raw,
    };

    if let Some(existing) = seal::get_seal(&acl_ks).await? {
        return Err(format!(
            "VTA is already sealed (by {} on {}); cannot seed admin during setup",
            existing.sealed_by, existing.sealed_at
        )
        .into());
    }

    let entries = acl::list_acl_entries(&acl_ks).await?;
    let existing_super_admins: Vec<_> = entries.iter().filter(|e| e.is_super_admin()).collect();
    if !existing_super_admins.is_empty() {
        return Err(format!(
            "found {} existing super admin(s); refusing to seed another during setup",
            existing_super_admins.len()
        )
        .into());
    }

    let entry = acl::AclEntry::new(did, acl::Role::Admin, "cli:setup-from-file").with_label(label);
    acl::store_acl_entry(&acl_ks, &entry).await?;
    let _seal_record = seal::seal(&acl_ks, did).await?;
    store.persist().await?;
    Ok(())
}

/// Provision enterprise staff: for each entry, create its context (+ initial
/// `ContextPolicy`) and seed a context-scoped ACL row. Separation of duty — the
/// owner (super-admin) sets the guardrail; the staff entry is bounded by it.
/// No-op when no staff are configured. Setup runs once on a fresh store, so this
/// does not attempt idempotency: a duplicate context id surfaces as an error.
async fn seed_staff(
    data_dir: &Path,
    staff: &[StaffProvision],
    storage_key: Option<[u8; 32]>,
) -> Result<(), Box<dyn std::error::Error>> {
    if staff.is_empty() {
        return Ok(());
    }
    use crate::acl;

    let store = Store::open(&StoreConfig {
        data_dir: data_dir.to_path_buf(),
    })?;
    let contexts_ks_raw = store.keyspace(crate::keyspaces::CONTEXTS)?;
    let acl_ks_raw = store.keyspace(crate::keyspaces::ACL)?;
    let (contexts_ks, acl_ks) = match storage_key {
        Some(key) => (
            contexts_ks_raw.with_encryption(key),
            acl_ks_raw.with_encryption(key),
        ),
        None => (contexts_ks_raw, acl_ks_raw),
    };

    for s in staff {
        let name = s.label.clone().unwrap_or_else(|| s.context.clone());
        let mut record = crate::contexts::create_context(&contexts_ks, &s.context, &name).await?;
        if let Some(policy) = &s.context_policy {
            record.context_policy = Some(policy.clone());
            crate::contexts::store_context(&contexts_ks, &record).await?;
        }

        let role = match s.role.as_deref() {
            Some(r) => acl::Role::parse(r)?,
            None => acl::Role::Application,
        };
        eprintln!("  Staff:    {} → context `{}` ({role:?})", s.did, s.context);
        let entry = acl::AclEntry::new(&s.did, role, "cli:setup-from-file")
            .with_contexts(vec![s.context.clone()])
            .with_label(s.label.clone());
        acl::store_acl_entry(&acl_ks, &entry).await?;
    }
    store.persist().await?;
    Ok(())
}

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

    fn parse(toml_str: &str) -> Result<WizardInputs, Box<dyn std::error::Error>> {
        Ok(toml::from_str::<WizardInputs>(toml_str)?)
    }

    #[test]
    fn staff_section_parses_with_inline_context_policy() {
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"

            [secrets]
            backend = "keyring"

            [[staff]]
            did     = "did:key:z6MkStaff"
            context = "sales"
            label   = "Sales"
            role    = "application"

            [staff.context_policy]
            export_allowed    = false
            trusted_verifiers = ["did:web:partner.example"]
        "#;
        let inputs = parse(raw).expect("parse staff");
        assert_eq!(inputs.staff.len(), 1);
        let s = &inputs.staff[0];
        assert_eq!(s.did, "did:key:z6MkStaff");
        assert_eq!(s.context, "sales");
        assert_eq!(s.role.as_deref(), Some("application"));
        let pol = s.context_policy.as_ref().unwrap();
        assert!(!pol.allows_export());
        assert!(pol.allows_verifier("did:web:partner.example"));
        assert!(!pol.allows_verifier("did:web:other"));
    }

    #[tokio::test]
    async fn seed_staff_creates_context_policy_and_scoped_entry() {
        let dir = tempfile::tempdir().unwrap();
        let staff = vec![StaffProvision {
            did: "did:key:z6MkStaff".into(),
            context: "sales".into(),
            label: Some("Sales".into()),
            role: Some("application".into()),
            context_policy: Some(vta_sdk::context_policy::ContextPolicy {
                export_allowed: false,
                ..vta_sdk::context_policy::ContextPolicy::unrestricted()
            }),
        }];
        seed_staff(dir.path(), &staff, None)
            .await
            .expect("seed_staff");

        let store = Store::open(&StoreConfig {
            data_dir: dir.path().to_path_buf(),
        })
        .unwrap();
        let contexts_ks = store.keyspace(crate::keyspaces::CONTEXTS).unwrap();
        let acl_ks = store.keyspace(crate::keyspaces::ACL).unwrap();

        // The context exists and carries the initial policy (export disabled).
        let ctx = crate::contexts::get_context(&contexts_ks, "sales")
            .await
            .unwrap()
            .unwrap();
        assert!(!ctx.context_policy.unwrap().allows_export());

        // The staff member has a context-scoped Application entry — not a
        // super-admin (allowed_contexts is non-empty).
        let entries = crate::acl::list_acl_entries(&acl_ks).await.unwrap();
        let e = entries
            .iter()
            .find(|e| e.did == "did:key:z6MkStaff")
            .expect("staff entry seeded");
        assert_eq!(e.role, crate::acl::Role::Application);
        assert_eq!(e.allowed_contexts, vec!["sales".to_string()]);
        assert!(!e.allowed_contexts.is_empty(), "staff must be scoped");
    }

    #[test]
    fn minimal_keyring_inputs_round_trip() {
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"

            [secrets]
            backend = "keyring"
        "#;
        let inputs = parse(raw).expect("minimal inputs should parse");
        assert!(matches!(
            inputs.secrets,
            SecretsBackendInput::Keyring { .. }
        ));
        assert!(matches!(inputs.messaging, MessagingInput::Skip));
        assert!(matches!(inputs.vta_did, VtaDidInput::Skip));
        assert!(inputs.admin_did.is_none());
    }

    #[test]
    fn plaintext_backend_sets_allow_plaintext_and_selects_itself() {
        // Selecting the plaintext backend must opt in to the plaintext
        // seed-store fallback (P0.9). Otherwise `create_seed_store` errors
        // during setup and the booted VTA can't re-open the seed. The flag
        // is serialized into `[secrets]` in the generated config.toml.
        let secrets = secrets_config_from_input(&SecretsBackendInput::Plaintext)
            .expect("plaintext backend should convert");
        assert!(
            secrets.allow_plaintext,
            "plaintext backend must set allow_plaintext = true"
        );
        // …and `allow_plaintext` alone is not enough. It is a *permission*
        // to fall back, not a request: with `keyring` compiled in (the
        // default) the implicit chain hits the keyring arm first, so an
        // operator who chose "Plaintext file" in the wizard used to get a
        // keyring-backed VTA. The explicit selector is what makes it stick.
        assert_eq!(
            secrets.backend,
            Some(SecretBackend::Plaintext),
            "the wizard must state the backend it was asked for"
        );

        // Both round-trip into the written config.
        let toml_out = toml::to_string(&secrets).expect("secrets config serializes");
        assert!(
            toml_out.contains("allow_plaintext = true"),
            "generated config must carry the flag, got:\n{toml_out}"
        );
        assert!(
            toml_out.contains("backend = \"plaintext\""),
            "generated config must carry the selector, got:\n{toml_out}"
        );
    }

    #[test]
    fn every_wizard_backend_choice_states_its_selector() {
        // No wizard choice may lean on implicit resolution — that is how
        // plaintext silently became keyring.
        let cases: Vec<(SecretsBackendInput, SecretBackend)> = vec![
            #[cfg(feature = "keyring")]
            (
                SecretsBackendInput::Keyring {
                    service: "vta".into(),
                },
                SecretBackend::Keyring,
            ),
            (SecretsBackendInput::Plaintext, SecretBackend::Plaintext),
        ];
        for (input, expected) in cases {
            let secrets = secrets_config_from_input(&input).expect("converts");
            assert_eq!(secrets.backend, Some(expected), "for {input:?}");
        }
    }

    /// Register an in-memory keyring so the seed-store step works without an
    /// OS credential store. `set_default_store` is process-global, so it is
    /// installed exactly once for the whole test binary.
    ///
    /// The plaintext backend can't stand in here: with the `keyring` feature
    /// compiled in (the default), `create_seed_store` returns a keyring store
    /// before it ever reaches the plaintext arm.
    #[cfg(feature = "keyring")]
    fn install_mock_keyring() {
        static ONCE: std::sync::Once = std::sync::Once::new();
        ONCE.call_once(|| {
            let store = keyring_core::mock::Store::new().expect("build mock keyring store");
            keyring_core::set_default_store(store);
        });
    }

    /// The smallest `WizardInputs` that drives `apply_inputs` end-to-end with
    /// no network and no operator interaction: no services, no mediator, no
    /// DID. Each caller gets a distinct keyring service name so concurrent
    /// tests don't share a seed entry.
    #[cfg(feature = "keyring")]
    fn offline_inputs(root: &Path, keyring_service: &str) -> WizardInputs {
        install_mock_keyring();
        WizardInputs {
            config_path: root.join("config.toml"),
            overwrite_config: false,
            vta_name: None,
            public_url: None,
            data_dir: root.join("data"),
            data_dir_exists: ExistingDataDirPolicy::default(),
            services: ServicesConfig {
                rest: false,
                didcomm: false,
                webauthn: false,
                tsp: false,
            },
            server: ServerConfig::default(),
            log: LogConfig::default(),
            secrets: SecretsBackendInput::Keyring {
                service: keyring_service.to_string(),
            },
            messaging: MessagingInput::Skip,
            vta_did: VtaDidInput::Skip,
            admin_did: None,
            admin_label: None,
            resolver_url: None,
            audit: AuditConfig::default(),
            staff: Vec::new(),
            hardened: Default::default(),
        }
    }

    /// The master seed as the store on disk sees it — the seed *record* for
    /// generation 0. Used to prove a wipe produced fresh key material and
    /// that a refusal left the existing material alone.
    #[cfg(feature = "keyring")]
    async fn seed_record_created_at(data_dir: &Path) -> chrono::DateTime<Utc> {
        let store = Store::open(&StoreConfig {
            data_dir: data_dir.to_path_buf(),
        })
        .expect("open store");
        let keys_ks = store
            .keyspace(crate::keyspaces::KEYS)
            .expect("keys keyspace");
        get_seed_record(&keys_ks, 0)
            .await
            .expect("read seed record")
            .expect("generation 0 must exist after setup")
            .created_at
    }

    #[cfg(feature = "keyring")]
    #[tokio::test]
    async fn a_pre_created_empty_data_dir_is_not_a_conflict() {
        // The reported failure: a Docker volume / K8s PVC / hand-created
        // `mkdir` makes data_dir exist before setup ever runs, and the old
        // `data_dir.exists()` gate turned that into "delete everything or
        // abort" — with no third answer. An empty directory carries nothing
        // to lose, so the default (fail-closed) policy must sail past it.
        let dir = tempfile::tempdir().expect("tempdir");
        let inputs = offline_inputs(dir.path(), "vta-test-precreated");
        std::fs::create_dir_all(&inputs.data_dir).expect("pre-create the mount point");

        apply_inputs(inputs, &SilentUi)
            .await
            .expect("setup must initialize into a pre-created empty data directory");

        assert!(
            vti_common::store::local_store_exists(&dir.path().join("data")),
            "the store must have been created in the pre-existing directory"
        );
        assert!(dir.path().join("config.toml").is_file(), "config written");
    }

    #[cfg(feature = "keyring")]
    #[tokio::test]
    async fn setup_refuses_to_run_over_an_initialized_vta() {
        // `reuse` must not become a foot-gun: re-running setup mints a fresh
        // master seed as generation 0, which on top of an existing seed
        // orphans every key derived from the original.
        let dir = tempfile::tempdir().expect("tempdir");
        let data_dir = dir.path().join("data");
        apply_inputs(
            offline_inputs(dir.path(), "vta-test-initialized"),
            &SilentUi,
        )
        .await
        .expect("first setup succeeds");
        let seed_before = seed_record_created_at(&data_dir).await;

        let mut again = offline_inputs(dir.path(), "vta-test-initialized");
        again.data_dir_exists = ExistingDataDirPolicy::Reuse;
        again.overwrite_config = true;
        let err = apply_inputs(again, &SilentUi)
            .await
            .expect_err("re-running setup over an initialized VTA must fail");
        assert!(
            err.to_string().contains("already holds an initialized VTA"),
            "got: {err}"
        );

        assert_eq!(
            seed_record_created_at(&data_dir).await,
            seed_before,
            "the refusal must leave the existing master seed generation untouched"
        );
    }

    #[cfg(feature = "keyring")]
    #[tokio::test]
    async fn a_failed_run_leaves_the_existing_config_intact() {
        // The config file is only written once everything else has
        // succeeded (step 13), so a run that dies mid-flight — or an
        // operator who backs out — never destroys a working install.
        let dir = tempfile::tempdir().expect("tempdir");
        apply_inputs(
            offline_inputs(dir.path(), "vta-test-config-intact"),
            &SilentUi,
        )
        .await
        .expect("first setup succeeds");

        let config_path = dir.path().join("config.toml");
        let config_before = std::fs::read_to_string(&config_path).expect("config written");

        let mut again = offline_inputs(dir.path(), "vta-test-config-intact");
        again.overwrite_config = true; // permitted to overwrite …
        again.data_dir_exists = ExistingDataDirPolicy::Error; // … but this aborts first
        let err = apply_inputs(again, &SilentUi)
            .await
            .expect_err("`error` policy over an existing store must fail");
        assert!(
            err.to_string().contains("already holds a store"),
            "got: {err}"
        );

        assert_eq!(
            std::fs::read_to_string(&config_path).unwrap(),
            config_before,
            "a failed run must not have touched the existing config"
        );
    }

    #[cfg(feature = "keyring")]
    #[tokio::test]
    async fn delete_policy_wipes_a_store_without_removing_the_directory() {
        let dir = tempfile::tempdir().expect("tempdir");
        let data_dir = dir.path().join("data");
        apply_inputs(offline_inputs(dir.path(), "vta-test-delete"), &SilentUi)
            .await
            .expect("first setup succeeds");
        let seed_before = seed_record_created_at(&data_dir).await;

        // Record the directory's creation stamp so we can prove it was
        // cleared in place rather than removed and recreated — the
        // difference between working and failing with EBUSY on a mount point.
        let created_before = std::fs::metadata(&data_dir)
            .expect("metadata")
            .created()
            .ok();

        let mut again = offline_inputs(dir.path(), "vta-test-delete");
        again.data_dir_exists = ExistingDataDirPolicy::Delete;
        again.overwrite_config = true;
        apply_inputs(again, &SilentUi)
            .await
            .expect("`delete` policy must wipe and re-init");

        assert_ne!(
            seed_record_created_at(&data_dir).await,
            seed_before,
            "a wipe must produce a fresh master seed generation"
        );
        if let (Some(before), Ok(after)) = (created_before, std::fs::metadata(&data_dir)) {
            assert_eq!(
                Some(before),
                after.created().ok(),
                "the data directory must be cleared in place, not recreated"
            );
        }
    }

    #[test]
    fn data_dir_policy_defaults_to_error_and_parses_every_variant() {
        let base = |extra: &str| {
            format!(
                r#"
                config_path = "/tmp/vta-test/config.toml"
                data_dir    = "/tmp/vta-test/data"
                {extra}

                [secrets]
                backend = "keyring"
                "#
            )
        };

        assert_eq!(
            parse(&base("")).unwrap().data_dir_exists,
            ExistingDataDirPolicy::Error,
            "omitting the policy must stay fail-closed"
        );
        assert_eq!(
            parse(&base(r#"data_dir_exists = "delete""#))
                .unwrap()
                .data_dir_exists,
            ExistingDataDirPolicy::Delete
        );
        assert_eq!(
            parse(&base(r#"data_dir_exists = "reuse""#))
                .unwrap()
                .data_dir_exists,
            ExistingDataDirPolicy::Reuse,
            "`reuse` is what lets an operator point setup at existing state"
        );
    }

    #[test]
    fn overwrite_config_defaults_to_false_and_round_trips() {
        let base = |extra: &str| {
            format!(
                r#"
                config_path = "/tmp/vta-test/config.toml"
                data_dir    = "/tmp/vta-test/data"
                {extra}

                [secrets]
                backend = "keyring"
                "#
            )
        };

        assert!(
            !parse(&base("")).unwrap().overwrite_config,
            "clobbering an operator's config must be opt-in"
        );
        assert!(
            parse(&base("overwrite_config = true"))
                .unwrap()
                .overwrite_config
        );
    }

    #[test]
    fn clear_dir_contents_empties_the_dir_but_keeps_it() {
        // The distinction that makes a mounted data_dir work: `rmdir` on a
        // mount point fails with EBUSY no matter how empty it is, so the
        // directory itself must survive the wipe.
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();

        std::fs::write(root.join("version"), b"fjall").expect("file");
        std::fs::create_dir_all(root.join("keyspaces/0/segments")).expect("nested dirs");
        std::fs::write(root.join("keyspaces/0/segments/1.sst"), b"data").expect("nested file");

        clear_dir_contents(root).expect("clearing contents should succeed");

        assert!(root.is_dir(), "the directory itself must survive");
        assert_eq!(
            std::fs::read_dir(root).unwrap().count(),
            0,
            "every entry must be gone"
        );
        assert!(
            !vti_common::store::local_store_exists(root),
            "a cleared directory must no longer look like a store"
        );
    }

    #[test]
    fn unknown_field_rejected() {
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"
            bogus_field = "no"

            [secrets]
            backend = "keyring"
        "#;
        let err = parse(raw).expect_err("unknown top-level field should fail");
        assert!(err.to_string().contains("bogus_field"), "got: {err}");
    }

    #[test]
    fn create_mediator_webvh_url_optional_defaults_to_none() {
        // Back-compat: TOML without `webvh_url` parses; the runtime falls
        // back to `url` when none is set.
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"
            public_url  = "https://trust.example.com"

            [secrets]
            backend = "keyring"

            [messaging]
            kind = "create_mediator"
            url  = "https://mediator.example.com"
        "#;
        let inputs = parse(raw).expect("parses");
        match &inputs.messaging {
            MessagingInput::CreateMediator { webvh_url, .. } => assert!(webvh_url.is_none()),
            other => panic!("expected CreateMediator, got {other:?}"),
        }
        validate_inputs(&inputs).expect("absent webvh_url should validate");
    }

    #[test]
    fn create_mediator_webvh_url_can_be_set() {
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"
            public_url  = "https://trust.example.com"

            [secrets]
            backend = "keyring"

            [messaging]
            kind      = "create_mediator"
            url       = "https://mediator.example.com"
            webvh_url = "https://trust.example.com/dids/mediator"
        "#;
        let inputs = parse(raw).expect("parses");
        match &inputs.messaging {
            MessagingInput::CreateMediator { webvh_url, .. } => {
                assert_eq!(
                    webvh_url.as_deref(),
                    Some("https://trust.example.com/dids/mediator")
                );
            }
            other => panic!("expected CreateMediator, got {other:?}"),
        }
        validate_inputs(&inputs).expect("explicit webvh_url should validate");
    }

    #[test]
    fn create_mediator_empty_webvh_url_rejected() {
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"
            public_url  = "https://trust.example.com"

            [secrets]
            backend = "keyring"

            [messaging]
            kind      = "create_mediator"
            url       = "https://mediator.example.com"
            webvh_url = ""
        "#;
        let inputs = parse(raw).expect("parses");
        let err = validate_inputs(&inputs).expect_err("empty webvh_url must be rejected");
        assert!(
            err.to_string().contains("messaging.webvh_url"),
            "got: {err}"
        );
    }

    #[test]
    fn create_mediator_ws_url_optional_defaults_to_none() {
        // Back-compat: TOML without `ws_url` parses; `apply_inputs`
        // derives `WS_URL` from `url`.
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"
            public_url  = "https://trust.example.com"

            [secrets]
            backend = "keyring"

            [messaging]
            kind = "create_mediator"
            url  = "https://mediator.example.com"
        "#;
        let inputs = parse(raw).expect("parses");
        match &inputs.messaging {
            MessagingInput::CreateMediator { ws_url, .. } => assert!(ws_url.is_none()),
            other => panic!("expected CreateMediator, got {other:?}"),
        }
        validate_inputs(&inputs).expect("absent ws_url should validate");
    }

    #[test]
    fn create_mediator_explicit_ws_url_round_trips() {
        // An operator whose reverse proxy routes WS to a different host
        // can express it; the value is taken verbatim, not derived.
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"
            public_url  = "https://trust.example.com"

            [secrets]
            backend = "keyring"

            [messaging]
            kind   = "create_mediator"
            url    = "https://mediator.example.com"
            ws_url = "wss://ws.example.com/mediator/socket"
        "#;
        let inputs = parse(raw).expect("parses");
        match &inputs.messaging {
            MessagingInput::CreateMediator { ws_url, .. } => {
                assert_eq!(
                    ws_url.as_deref(),
                    Some("wss://ws.example.com/mediator/socket")
                );
            }
            other => panic!("expected CreateMediator, got {other:?}"),
        }
        validate_inputs(&inputs).expect("explicit ws:// ws_url should validate");
    }

    #[test]
    fn create_mediator_empty_ws_url_rejected() {
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"
            public_url  = "https://trust.example.com"

            [secrets]
            backend = "keyring"

            [messaging]
            kind   = "create_mediator"
            url    = "https://mediator.example.com"
            ws_url = ""
        "#;
        let inputs = parse(raw).expect("parses");
        let err = validate_inputs(&inputs).expect_err("empty ws_url must be rejected");
        assert!(err.to_string().contains("messaging.ws_url"), "got: {err}");
    }

    #[test]
    fn create_mediator_non_ws_scheme_ws_url_rejected() {
        // A `ws_url` that isn't a ws(s) URL (e.g. an https typo) must be
        // rejected — the template advertises it as a WebSocket endpoint.
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"
            public_url  = "https://trust.example.com"

            [secrets]
            backend = "keyring"

            [messaging]
            kind   = "create_mediator"
            url    = "https://mediator.example.com"
            ws_url = "https://mediator.example.com/ws"
        "#;
        let inputs = parse(raw).expect("parses");
        let err = validate_inputs(&inputs).expect_err("non-ws scheme must be rejected");
        assert!(err.to_string().contains("ws:// or wss://"), "got: {err}");
    }

    #[test]
    fn create_mediator_mediator_host_round_trips() {
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"
            public_url  = "https://trust.example.com"

            [secrets]
            backend = "keyring"

            [messaging]
            kind          = "create_mediator"
            url           = "https://mediator.example.com"
            mediator_host = "mediator.example.com"
        "#;
        let inputs = parse(raw).expect("parses");
        match &inputs.messaging {
            MessagingInput::CreateMediator { mediator_host, .. } => {
                assert_eq!(mediator_host.as_deref(), Some("mediator.example.com"));
            }
            other => panic!("expected CreateMediator, got {other:?}"),
        }
        validate_inputs(&inputs).expect("mediator_host should validate");
    }

    #[test]
    fn existing_mediator_mediator_host_round_trips() {
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"
            public_url  = "https://trust.example.com"

            [secrets]
            backend = "keyring"

            [messaging]
            kind          = "existing"
            did           = "did:webvh:scid:mediator.example.com:mediator"
            mediator_host = "mediator.example.com"
        "#;
        let inputs = parse(raw).expect("parses");
        match &inputs.messaging {
            MessagingInput::Existing { mediator_host, .. } => {
                assert_eq!(mediator_host.as_deref(), Some("mediator.example.com"));
            }
            other => panic!("expected Existing, got {other:?}"),
        }
        validate_inputs(&inputs).expect("Existing+mediator_host should validate");
    }

    /// `setup_acl` is optional and defaults to `false` when absent — back-compat
    /// for existing configs that predate the field.
    #[test]
    fn setup_acl_defaults_to_false() {
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"
            public_url  = "https://trust.example.com"

            [secrets]
            backend = "keyring"

            [messaging]
            kind = "create_mediator"
            url  = "https://mediator.example.com"
        "#;
        let inputs = parse(raw).expect("parses");
        match &inputs.messaging {
            MessagingInput::CreateMediator { setup_acl, .. } => {
                assert!(!setup_acl, "setup_acl must default to false");
            }
            other => panic!("expected CreateMediator, got {other:?}"),
        }
        validate_inputs(&inputs).expect("absent setup_acl should validate");
    }

    /// `setup_acl = true` is preserved through parsing and carried into
    /// `MessagingConfig` — the value in TOML must appear in the final config.
    #[test]
    fn setup_acl_true_is_preserved_and_propagates() {
        use crate::config::MessagingConfig;

        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"
            public_url  = "https://trust.example.com"

            [secrets]
            backend = "keyring"

            [messaging]
            kind      = "existing"
            did       = "did:webvh:scid:mediator.example.com:mediator"
            setup_acl = true
        "#;
        let inputs = parse(raw).expect("parses");
        let (did, mediator_host, setup_acl) = match &inputs.messaging {
            MessagingInput::Existing {
                did,
                mediator_host,
                setup_acl,
            } => (did.clone(), mediator_host.clone(), *setup_acl),
            other => panic!("expected Existing, got {other:?}"),
        };
        assert!(setup_acl, "setup_acl must be true after parsing");
        validate_inputs(&inputs).expect("setup_acl = true should validate");

        let cfg = MessagingConfig {
            mediator_url: String::new(),
            mediator_did: did,
            mediator_host,
            setup_acl,
            drain_inbox_on_start: false,
        };
        assert!(
            cfg.setup_acl,
            "setup_acl must propagate into MessagingConfig"
        );
    }

    #[test]
    fn create_mediator_template_vars_round_trip() {
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"
            public_url  = "https://trust.example.com"

            [secrets]
            backend = "keyring"

            [messaging]
            kind = "create_mediator"
            url  = "https://mediator.example.com"

            [messaging.template_vars]
            ROUTING_KEYS = ["did:key:zUpstream"]
            ACCEPT       = ["didcomm/v2"]
        "#;
        let inputs = parse(raw).expect("parses");
        match &inputs.messaging {
            MessagingInput::CreateMediator { template_vars, .. } => {
                assert!(template_vars.contains_key("ROUTING_KEYS"));
                assert!(template_vars.contains_key("ACCEPT"));
            }
            other => panic!("expected CreateMediator, got {other:?}"),
        }
    }

    #[test]
    fn resolver_url_round_trips() {
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"
            public_url  = "https://trust.example.com"
            resolver_url = "ws://resolver.example.com/did/v1/ws"

            [secrets]
            backend = "keyring"
        "#;
        let inputs = parse(raw).expect("parses");
        assert_eq!(
            inputs.resolver_url.as_deref(),
            Some("ws://resolver.example.com/did/v1/ws")
        );
        validate_inputs(&inputs).expect("resolver_url should validate");
    }

    #[test]
    fn empty_resolver_url_rejected() {
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"
            public_url  = "https://trust.example.com"
            resolver_url = ""

            [secrets]
            backend = "keyring"
        "#;
        let inputs = parse(raw).expect("parses");
        let err = validate_inputs(&inputs).expect_err("empty resolver_url must be rejected");
        assert!(err.to_string().contains("resolver_url"), "got: {err}");
    }

    #[test]
    fn audit_retention_days_round_trips() {
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"
            public_url  = "https://trust.example.com"

            [secrets]
            backend = "keyring"

            [audit]
            retention_days = 365
        "#;
        let inputs = parse(raw).expect("parses");
        assert_eq!(inputs.audit.retention_days, 365);
        validate_inputs(&inputs).expect("retention_days = 365 should validate");
    }

    #[test]
    fn audit_retention_days_zero_rejected() {
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"
            public_url  = "https://trust.example.com"

            [secrets]
            backend = "keyring"

            [audit]
            retention_days = 0
        "#;
        let inputs = parse(raw).expect("parses");
        let err = validate_inputs(&inputs).expect_err("retention_days = 0 must be rejected");
        assert!(
            err.to_string().contains("audit.retention_days"),
            "got: {err}"
        );
    }

    #[test]
    fn vault_backend_round_trips() {
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"
            public_url  = "https://trust.example.com"

            [secrets]
            backend     = "vault"
            addr        = "https://vault.example.com:8200"
            secret_path = "vta/master-seed"
            auth_method = "kubernetes"
            k8s_role    = "vta"
        "#;
        let inputs = parse(raw).expect("parses");
        match &inputs.secrets {
            SecretsBackendInput::Vault {
                addr,
                secret_path,
                auth_method,
                k8s_role,
                kv_mount,
                secret_key,
                ..
            } => {
                assert_eq!(addr, "https://vault.example.com:8200");
                assert_eq!(secret_path, "vta/master-seed");
                assert_eq!(auth_method, "kubernetes");
                assert_eq!(k8s_role.as_deref(), Some("vta"));
                // Defaults applied.
                assert_eq!(kv_mount, "secret");
                assert_eq!(secret_key, "seed");
            }
            other => panic!("expected Vault, got {other:?}"),
        }
        validate_inputs(&inputs).expect("vault backend should validate");
    }

    #[test]
    fn create_mediator_without_didcomm_rejected() {
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"

            [services]
            rest    = true
            didcomm = false

            [secrets]
            backend = "keyring"

            [messaging]
            kind = "create_mediator"
            url  = "http://localhost:8000"
        "#;
        let inputs = parse(raw).expect("parses");
        let err = validate_inputs(&inputs).expect_err("validation should fail");
        assert!(
            err.to_string().contains("services.didcomm = true"),
            "got: {err}"
        );
    }

    #[test]
    fn services_rest_without_public_url_rejected() {
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"

            [services]
            rest    = true
            didcomm = false

            [secrets]
            backend = "keyring"
        "#;
        let inputs = parse(raw).expect("parses");
        let err = validate_inputs(&inputs).expect_err("validation should fail");
        let msg = err.to_string();
        assert!(
            msg.contains("services.rest = true requires `public_url`"),
            "got: {err}"
        );
    }

    #[test]
    fn services_rest_with_empty_public_url_rejected() {
        // Operators sometimes leave the value as an empty string rather
        // than removing the key entirely; treat that as not-set.
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"
            public_url  = ""

            [services]
            rest    = true
            didcomm = false

            [secrets]
            backend = "keyring"
        "#;
        let inputs = parse(raw).expect("parses");
        let err = validate_inputs(&inputs).expect_err("empty public_url must be rejected");
        assert!(
            err.to_string()
                .contains("services.rest = true requires `public_url`"),
            "got: {err}"
        );
    }

    #[test]
    fn services_rest_with_public_url_passes() {
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"
            public_url  = "https://vta.example.com"

            [services]
            rest    = true
            didcomm = false

            [secrets]
            backend = "keyring"
        "#;
        let inputs = parse(raw).expect("parses");
        validate_inputs(&inputs).expect("rest + public_url should pass");
    }

    #[test]
    fn services_rest_disabled_does_not_require_public_url() {
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"

            [services]
            rest    = false
            didcomm = true

            [secrets]
            backend = "keyring"
        "#;
        let inputs = parse(raw).expect("parses");
        validate_inputs(&inputs).expect("rest disabled means public_url is optional");
    }

    /// A minted mediator serves what the VTA advertises, unless the operator
    /// says otherwise. This is what decides whether `{SERVICE_TSP}` gets
    /// filled, so it is the difference between a reachable `#tsp` and one
    /// pointing at a mediator that doesn't carry TSP.
    #[test]
    fn minted_mediator_protocols_follow_the_vtas_services() {
        let didcomm_only = ServicesConfig {
            rest: true,
            didcomm: true,
            webauthn: false,
            tsp: false,
        };
        let with_tsp = ServicesConfig {
            tsp: true,
            ..didcomm_only
        };

        // Derived: DIDComm always (the template renders it unconditionally),
        // TSP iff the VTA advertises TSP.
        assert_eq!(
            mediator_protocols(None, &didcomm_only),
            vec![Protocol::Didcomm]
        );
        assert_eq!(
            mediator_protocols(None, &with_tsp),
            vec![Protocol::Didcomm, Protocol::Tsp]
        );

        // Explicit wins, including serving more than this VTA uses — a
        // shared mediator carrying TSP for other clients.
        assert_eq!(
            mediator_protocols(Some(&[Protocol::Didcomm, Protocol::Tsp]), &didcomm_only),
            vec![Protocol::Didcomm, Protocol::Tsp]
        );
    }

    /// The mint-time slice of the §3 invariant: a VTA that advertises TSP
    /// cannot mint itself a mediator that doesn't carry it.
    #[test]
    fn a_minted_mediator_may_not_serve_less_than_the_vta_advertises() {
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"

            [services]
            rest    = false
            didcomm = true
            tsp     = true

            [secrets]
            backend = "keyring"

            [messaging]
            kind      = "create_mediator"
            url       = "https://mediator.example.com"
            protocols = ["didcomm"]
        "#;
        let inputs = parse(raw).expect("parses");
        let err = validate_inputs(&inputs).expect_err("must refuse a TSP-less mediator");
        assert!(
            err.to_string()
                .contains("messaging.protocols omits \"tsp\""),
            "got: {err}"
        );
    }

    /// The other ways `messaging.protocols` can be wrong. Each is refused by
    /// name rather than normalised — a config that means something other than
    /// it says is how the `#tsp`-at-a-DIDComm-mediator state arose.
    #[test]
    fn messaging_protocols_rejects_malformed_lists() {
        let cases = [
            (r#"protocols = []"#, "a mediator that carries nothing"),
            (
                r#"protocols = ["didcomm", "rest"]"#,
                "REST is not a mediator transport",
            ),
            (r#"protocols = ["didcomm", "didcomm"]"#, "more than once"),
            (r#"protocols = ["tsp"]"#, "always advertises a DIDComm"),
        ];
        for (line, expected) in cases {
            let raw = format!(
                r#"
                config_path = "/tmp/vta-test/config.toml"
                data_dir    = "/tmp/vta-test/data"

                [services]
                rest    = false
                didcomm = true
                tsp     = false

                [secrets]
                backend = "keyring"

                [messaging]
                kind = "create_mediator"
                url  = "https://mediator.example.com"
                {line}
            "#
            );
            let inputs = parse(&raw).unwrap_or_else(|e| panic!("{line} should parse: {e}"));
            let err = validate_inputs(&inputs)
                .expect_err(&format!("{line} must be refused"))
                .to_string();
            assert!(err.contains(expected), "{line}: got {err}");
        }
    }

    #[test]
    fn services_tsp_without_didcomm_is_rejected() {
        // TSP shares the DIDComm mediator, so it can't be advertised without
        // DIDComm — the `--from <toml>` path must reject the combination.
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"

            [services]
            rest    = false
            didcomm = false
            tsp     = true

            [secrets]
            backend = "keyring"
        "#;
        let inputs = parse(raw).expect("parses");
        let err = validate_inputs(&inputs).expect_err("tsp without didcomm must be rejected");
        assert!(
            err.to_string()
                .contains("services.tsp = true requires services.didcomm = true"),
            "got: {err}"
        );
    }

    /// A `[services] tsp = true` + DIDComm setup file, whose fate depends
    /// on whether this binary can serve TSP. Both outcomes are asserted
    /// below — one per build.
    #[cfg(test)]
    const TSP_WITH_DIDCOMM_TOML: &str = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"

            [services]
            rest    = false
            didcomm = true
            tsp     = true

            [secrets]
            backend = "keyring"
        "#;

    #[cfg(feature = "tsp")]
    #[test]
    fn services_tsp_with_didcomm_passes_and_carries_through() {
        // The declarative TSP path: `[services] tsp = true` (with DIDComm)
        // parses, validates, and the flag is carried on `WizardInputs.services`
        // (which `apply` writes verbatim to `config.services`).
        let inputs = parse(TSP_WITH_DIDCOMM_TOML).expect("parses");
        validate_inputs(&inputs).expect("tsp + didcomm should validate");
        assert!(inputs.services.tsp, "tsp flag must be carried through");
    }

    #[cfg(not(feature = "tsp"))]
    #[test]
    fn services_tsp_is_refused_when_the_binary_cannot_serve_it() {
        // Same file, a binary with no TSP dispatcher: refused by name
        // rather than minting a DID document that advertises `#tsp` and
        // then never answering on it.
        let inputs = parse(TSP_WITH_DIDCOMM_TOML).expect("parses");
        let err = validate_inputs(&inputs)
            .expect_err("tsp must be refused without the compiled transport");
        assert!(
            err.to_string().contains("built without the `tsp` feature"),
            "got: {err}"
        );
    }

    #[test]
    fn admin_did_validation_rejects_non_did() {
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"
            admin_did   = "not-a-did"

            [secrets]
            backend = "keyring"
        "#;
        let inputs = parse(raw).expect("parses");
        let err = validate_inputs(&inputs).expect_err("validation should fail");
        assert!(err.to_string().contains("admin_did"), "got: {err}");
    }

    /// Catch drift between `WizardInputs` and the operator-facing example
    /// file at `docs/02-vta/examples/vta-setup.example.toml`. If you
    /// change the schema and forget to update the example, this test fails.
    #[test]
    fn shipped_example_parses() {
        let raw = include_str!("../../../docs/02-vta/examples/vta-setup.example.toml");
        let inputs = parse(raw).expect(
            "docs/02-vta/examples/vta-setup.example.toml must be valid against WizardInputs",
        );
        validate_inputs(&inputs)
            .expect("docs/02-vta/examples/vta-setup.example.toml must pass cross-field validation");
    }

    #[test]
    fn full_inputs_parse() {
        let raw = r#"
            config_path = "/srv/vta/config.toml"
            data_dir    = "/srv/vta/data"
            vta_name    = "trust-prod-1"
            public_url  = "https://trust.example.com"
            admin_did   = "did:key:z6MkABC"
            admin_label = "ops-bootstrap"

            [services]
            rest    = true
            didcomm = true

            [server]
            host = "0.0.0.0"
            port = 7080

            [log]
            level  = "info"
            format = "json"

            [secrets]
            backend     = "aws"
            region      = "us-east-1"
            secret_name = "vta/prod/seed"

            [messaging]
            kind    = "create_mediator"
            context = "mediator"
            url     = "https://mediator.example.com"

            [vta_did]
            kind               = "create_webvh"
            url                = "https://trust.example.com/dids/vta"
            portable           = true
            pre_rotation_count = 2
        "#;
        let inputs = parse(raw).expect("full inputs should parse");
        assert_eq!(inputs.vta_name.as_deref(), Some("trust-prod-1"));
        assert!(matches!(inputs.secrets, SecretsBackendInput::Aws { .. }));
        validate_inputs(&inputs).expect("full inputs should validate");
    }

    // ── Advanced webvh-DID options (P1.2a) ──────────────────────────────

    /// Back-compat: a `create_webvh` block without any advanced field parses
    /// with all advanced options absent (plain simple-mode).
    #[test]
    fn create_webvh_advanced_fields_default_absent() {
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"
            public_url  = "https://trust.example.com"

            [secrets]
            backend = "keyring"

            [vta_did]
            kind = "create_webvh"
            url  = "https://trust.example.com/dids/vta"
        "#;
        let inputs = parse(raw).expect("simple create_webvh should parse");
        match &inputs.vta_did {
            VtaDidInput::CreateWebvh {
                did_document_file,
                did_log_file,
                signing_key_id,
                ka_key_id,
                portable,
                pre_rotation_count,
                ..
            } => {
                assert!(did_document_file.is_none());
                assert!(did_log_file.is_none());
                assert!(signing_key_id.is_none());
                assert!(ka_key_id.is_none());
                assert!(*portable, "portable defaults true");
                assert_eq!(*pre_rotation_count, 1, "pre_rotation_count defaults 1");
            }
            other => panic!("expected CreateWebvh, got {other:?}"),
        }
        validate_inputs(&inputs).expect("simple create_webvh should validate");
    }

    /// Each advanced mode parses and, on its own, validates.
    #[test]
    fn create_webvh_single_advanced_mode_validates() {
        for (field, value) in [
            ("did_document_file", "\"/tmp/doc.json\""),
            ("did_log_file", "\"/tmp/did.jsonl\""),
            ("signing_key_id", "\"did:key:z6MkSigner#key-0\""),
        ] {
            let raw = format!(
                r#"
                config_path = "/tmp/vta-test/config.toml"
                data_dir    = "/tmp/vta-test/data"
                public_url  = "https://trust.example.com"

                [secrets]
                backend = "keyring"

                [vta_did]
                kind = "create_webvh"
                url  = "https://trust.example.com/dids/vta"
                {field} = {value}
            "#
            );
            let inputs = parse(&raw).unwrap_or_else(|e| panic!("{field} should parse: {e}"));
            validate_inputs(&inputs)
                .unwrap_or_else(|e| panic!("{field} alone should validate: {e}"));
        }
    }

    /// Two advanced modes at once is rejected (they're mutually exclusive).
    #[test]
    fn create_webvh_conflicting_advanced_modes_rejected() {
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"
            public_url  = "https://trust.example.com"

            [secrets]
            backend = "keyring"

            [vta_did]
            kind              = "create_webvh"
            url               = "https://trust.example.com/dids/vta"
            did_document_file = "/tmp/doc.json"
            signing_key_id    = "did:key:z6MkSigner#key-0"
        "#;
        let inputs = parse(raw).expect("conflicting advanced modes should still parse");
        let err =
            validate_inputs(&inputs).expect_err("conflicting advanced modes must be rejected");
        assert!(err.to_string().contains("mutually-exclusive"), "got: {err}");
    }

    /// `ka_key_id` without `signing_key_id` is rejected.
    #[test]
    fn create_webvh_ka_key_without_signing_key_rejected() {
        let raw = r#"
            config_path = "/tmp/vta-test/config.toml"
            data_dir    = "/tmp/vta-test/data"
            public_url  = "https://trust.example.com"

            [secrets]
            backend = "keyring"

            [vta_did]
            kind      = "create_webvh"
            url       = "https://trust.example.com/dids/vta"
            ka_key_id = "did:key:z6MkKA#key-1"
        "#;
        let inputs = parse(raw).expect("ka_key_id alone should parse");
        let err = validate_inputs(&inputs)
            .expect_err("ka_key_id without signing_key_id must be rejected");
        assert!(err.to_string().contains("ka_key_id requires"), "got: {err}");
    }

    /// SilentUi preserves the `--from` behaviour: never display the mnemonic,
    /// always write the canonical did.jsonl path.
    #[test]
    fn silent_ui_behaviour() {
        let ui = super::super::SilentUi;
        let mnemonic = super::super::generate_mnemonic_silent().expect("mnemonic");
        ui.confirm_mnemonic(&mnemonic)
            .expect("SilentUi must never block on mnemonic confirmation");
        let canonical = std::path::Path::new("/data/did-logs/vta-did.jsonl");
        assert_eq!(
            ui.did_log_path("vta", canonical),
            Some(canonical.to_path_buf()),
            "SilentUi must echo the canonical did.jsonl path"
        );
    }
}