vti-common 0.16.2

Shared server-side infrastructure for VTA and VTC services
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
//! [`AuditEvent`] — the tagged enum of every audit-log variant.
//!
//! Ships the **Phase-0 vocabulary** matching spec §11.4. Phase-1+
//! variants land alongside their owning features (join requests,
//! members, policies, registry, VRC, etc.) and follow the same
//! pattern: one variant per semantically distinct event, with a
//! purpose-built data struct.
//!
//! ## Wire contract
//!
//! - Tagged form `#[serde(tag = "type", content = "data")]` so
//!   external consumers (SIEM, later webhooks) discriminate on the
//!   `type` field. **Variant identifiers are part of the wire
//!   contract — don't rename them without bumping
//!   `EVENT_VERSION`.**
//! - Data structs use `#[serde(rename_all = "camelCase")]` for
//!   downstream tooling friendliness. Field names are also wire
//!   contract.
//!
//! ## Sensitive-field redaction
//!
//! [`ConfigChange::redact_if`] walks a [`ConfigChangedData`] and
//! masks `old_value` / `new_value` for any key matched by the caller-
//! supplied sensitivity predicate. The emitter (config endpoint
//! handlers, M0.8) calls this **before** persisting the event so
//! sensitive values never reach the audit keyspace in cleartext.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;

use super::key_store::RotationReason;

/// Marker used in place of redacted config values. Distinguishable
/// from a JSON null / empty string by callers introspecting an
/// archived audit row.
pub const REDACTED_MARKER: &str = "<redacted>";

// ---------------------------------------------------------------------------
// AuditEvent
// ---------------------------------------------------------------------------

/// Audit-event payload. Tagged on `type` with the variant name and
/// the variant's data under `data`. Phase-0 vocabulary only;
/// Phase-1+ adds variants alongside the features that emit them.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "type", content = "data")]
pub enum AuditEvent {
    /// Bootstrap completed — the first admin DID was written into the
    /// ACL and the install carve-out was permanently closed.
    CommunityInstalled(CommunityInstalledData),

    /// `vtc admin emergency-bootstrap` was invoked with a valid
    /// master-seed mnemonic, re-opening the install carve-out exactly
    /// once. Loud event — surfaced prominently in diagnostics on next
    /// daemon start so a forgotten emergency action is impossible to
    /// miss.
    EmergencyBootstrapInvoked(EmergencyBootstrapData),

    /// A data-room operation — §8 of `docs/05-design-notes/data-rooms.md`.
    ///
    /// One variant for reads and writes alike, because on shared material **reads are the
    /// interesting event**: a write log says what a room contains, a read log says who has
    /// seen it, and the second is the question an incident review asks.
    ///
    /// **`actor_did` is not always a DID here.** On a `private` room the caller passes the
    /// actorless marker, because an audit log naming every actor *is* the membership the
    /// host was built never to learn — assembled one entry at a time. What may be recorded
    /// per tier is decided once, in `vti_rooms::audit`, and never at a call site.
    RoomOperation(RoomOperationData),

    /// A passkey was registered against an admin DID (initial enrol
    /// at install **or** a subsequent additional-device enrolment).
    AdminPasskeyRegistered(AdminPasskeyData),

    /// A passkey was revoked from an admin DID. The CAS check that
    /// refuses to leave zero passkeys runs *before* the event is
    /// emitted, so any persisted `AdminPasskeyRevoked` leaves at
    /// least one passkey behind.
    AdminPasskeyRevoked(AdminPasskeyData),

    /// One or more runtime configuration keys were modified via
    /// `PATCH /v1/admin/config`. Per-key sensitivity is honoured —
    /// values for keys flagged sensitive are redacted via
    /// [`ConfigChange::redact_if`] before persistence.
    ConfigChanged(ConfigChangedData),

    /// `POST /v1/admin/config/reload` applied hot-reloadable settings
    /// in-place. Lists which keys actually re-applied (a key that
    /// was unchanged-or-already-active doesn't appear).
    ConfigReloaded(ConfigReloadedData),

    /// `POST /v1/admin/config/restart` initiated graceful shutdown.
    /// Emitted **before** the process exits so the next-boot replay
    /// can correlate the restart with the prior config patches that
    /// triggered it.
    RestartRequested(RestartRequestedData),

    /// `PUT /v1/community/profile` updated one or more profile
    /// fields. Records which fields changed by name; the values
    /// themselves stay out of the audit log (profile data isn't
    /// security-sensitive by nature, but keeping the event small
    /// is operator-friendly).
    CommunityProfileUpdated(CommunityProfileUpdatedData),

    /// The community `audit_key` was rotated. Emitted under the
    /// **new** key (the rotation itself is what creates the new
    /// epoch), so an investigator can find the row by querying the
    /// `audit_by_type` index without needing to walk the prior
    /// epoch.
    AuditKeyRotated(AuditKeyRotatedData),

    /// `PATCH /v1/members/{did}` updated profile or non-role
    /// metadata on a member's record. Lists the field names that
    /// changed; values stay out of the envelope.
    MemberUpdated(MemberUpdatedData),

    /// `PATCH /v1/members/{did}` reassigned the member's role.
    /// Distinct event from `MemberUpdated` because role changes
    /// are security-significant — SIEM filters key on this
    /// variant separately. Admin promotion uses
    /// [`AdminPromoted`] instead (spec §10.4 keeps the two
    /// paths separate).
    RoleChanged(RoleChangedData),

    /// A role change reached `admin`. Spec §10.4 makes this its own
    /// variant (distinct from `RoleChanged`) so SIEM rules can target
    /// it; admin elevation is the highest-privilege grant the
    /// community emits.
    ///
    /// The authorising user-verification is recorded on its own
    /// [`AuthSteppedUp`](Self::AuthSteppedUp) row, joined by
    /// `authorising_session_id`. See [`AdminPromotedData`].
    AdminPromoted(AdminPromotedData),

    /// A passkey step-up ceremony elevated a session — the
    /// user-verification event that authorises whatever privileged
    /// operation follows inside the elevation window.
    ///
    /// Emitted where the gesture actually happens, which since the
    /// promote-to-admin fold is not the same request as the operation
    /// it authorises. Recording it separately is what keeps the chain
    /// of authority auditable across an API split: this row names the
    /// credential, the operation's row names the session.
    AuthSteppedUp(AuthSteppedUpData),

    /// `POST /v1/join-requests` (REST or DIDComm) accepted a
    /// well-formed submission and persisted it as `Pending`. The
    /// actor on this event is the applicant DID — they're the
    /// principal, even though the daemon's authenticated identity
    /// did not vouch for them.
    JoinRequestSubmitted(JoinRequestData),

    /// An admin / moderator approved a pending join request via
    /// `POST /v1/join-requests/{id}/approve`. Always paired with a
    /// `MemberAdded` emission in the same transaction (the
    /// approve flow writes the ACL + Member rows atomically).
    JoinRequestApproved(JoinRequestData),

    /// An admin / moderator rejected a pending join request. The
    /// `reason` field is operator-supplied and may be empty.
    JoinRequestRejected(JoinRequestRejectedData),

    /// New member row written. Companion event to
    /// `JoinRequestApproved` — the latter is what an audit
    /// query for "who approved this" matches, the former is
    /// what "when did <did> join" matches. Spec §10.1.
    MemberAdded(MemberAddedData),

    /// Member row removed (or anonymised) per spec §10.2. Spec §5
    /// `Disposition` decides whether the row is purged outright,
    /// tombstoned with the DID retained, or kept historical.
    MemberRemoved(MemberRemovedData),

    /// A member discharged the `reciprocate_vmc` obligation: they
    /// counter-signed the issued VMC with a member-issued reciprocal
    /// VC, completing the bidirectional DTG membership edge
    /// (`join-requests/accept/1.0`). The audit envelope's
    /// `target_did` carries the member.
    MembershipReciprocated(MembershipReciprocatedData),

    /// `POST /v1/policies` accepted an upload, compiled the source,
    /// and persisted a new revision. The row is **not yet active** —
    /// activation is a separate event. Spec §7.1; Phase 2 M2.3.
    PolicyUploaded(PolicyUploadedData),

    /// `POST /v1/policies/{id}/activate` flipped the active pointer
    /// for a purpose. Carries the predecessor's id so a forensic
    /// audit can chain backwards through revisions without scanning
    /// the whole `policies:` keyspace. Spec §7.1; Phase 2 M2.3.
    PolicyActivated(PolicyActivatedData),

    /// A new VMC was minted (join-approve or renewal). Spec §6.1.
    VmcIssued(CredentialIssuedData),

    /// A new role VEC was minted (join-approve, renewal, or role
    /// change). Spec §6.1.
    VecIssued(CredentialIssuedData),

    /// `POST /v1/members/me/renew` re-minted the member's VMC +
    /// role VEC. Spec §6.3. `personhood_changed` flips when the
    /// renewal's `personhood.rego` re-eval produced a different
    /// flag than the prior VMC.
    MembershipRenewed(MembershipRenewedData),

    /// A status-list bit was flipped (revocation / suspension).
    /// Spec §6.2.
    StatusListFlipped(StatusListFlippedData),

    /// A member rotated to a fresh DID. The audit envelope's
    /// `actor_did` is the **new** DID (it's the principal going
    /// forward); the prior DID lives in the data struct. Spec
    /// §10.5; Phase 2 M2.15.
    DidRotated(DidRotatedData),

    /// The daemon's trust-registry reachability state flipped
    /// (`active` ↔ `degraded`). Spec §8.1; Phase 3 M3.2. SIEM
    /// filters key on this to alert when the registry connection
    /// drops or recovers.
    RegistryStatusChanged(RegistryStatusChangedData),

    /// A `MembershipSyncer` job completed successfully against
    /// the registry. Spec §8.3; Phase 3 M3.4.
    RegistrySyncSucceeded(RegistrySyncOutcomeData),

    /// A `MembershipSyncer` job flipped to the `Failed` state
    /// after exhausting its retry budget. Spec §8.3 calls these
    /// out for operator attention — failed `Purge` jobs are
    /// silent privacy regressions. Phase 3 M3.4.
    RegistrySyncFailed(RegistrySyncOutcomeData),

    /// A member-initiated `Purge` (RTBF) bypassed the active
    /// `registry.rego.min_disposition` floor. Spec §8.2 calls
    /// these out: RTBF always overrides the policy envelope.
    /// The audit envelope's `actor_did_hash` is the HMAC-hashed
    /// identifier per §11.1; the `actor_did_plain` field is
    /// `None` for these envelopes (privacy-preserving by
    /// construction). Phase 3 M3.6.
    RegistryRecordPolicyOverride(RegistryRecordPolicyOverrideData),

    /// A cross-community session was minted (or denied). Spec
    /// §8.4; Phase 3 M3.10. The `outcome` field discriminates
    /// `minted` from `denied`; the `reason` is populated only
    /// on `denied` and carries one of [`RecognitionError`]'s
    /// stable reason codes
    /// (`issuer-key-unresolved` / `proof-invalid` /
    /// `status-list-failed` / `issuer-not-recognised` /
    /// `registry-unreachable` / `validity-window` / `malformed`
    /// / `role-mapping-denied`).
    CrossCommunitySessionMinted(CrossCommunitySessionMintedData),

    // ─── Phase 4 lifecycle ─────────────────────────────────
    /// A member published a self-issued Verifiable Relationship
    /// Credential (VRC) — a trust edge `issuer-member → subject-
    /// member` per spec §5.4 + §6.1. Phase 4 M4.6. The actor is
    /// the issuer; the target is the subject DID.
    VrcPublished(VrcPublishedData),

    /// A VRC was revoked — either by the original issuer or by
    /// an admin acting on behalf of the community. Phase 4 M4.6.
    /// Per D7, VRCs carry no `credentialStatus`; revocation is
    /// row deletion in the local `relationships:` keyspace.
    VrcRevoked(VrcRevokedData),

    /// A VRC was suspended: made temporarily ineffective
    /// without being withdrawn. #1079.
    ///
    /// Distinct from [`Self::VrcRevoked`] because the acts are
    /// different, not because the wording is. Revocation deletes
    /// the row and cannot be undone; a suspension leaves the
    /// credential and its signature untouched and has a
    /// supported reversal. Collapsing the two into one event
    /// would leave an operator unable to answer why an edge
    /// stopped counting, which is the question the trail exists
    /// for.
    VrcSuspended(VrcLifecycleData),

    /// A suspension was reversed. #1079.
    ///
    /// Reversal returns the edge to the governance of its own
    /// validity window; it does not extend it, so an edge whose
    /// `validUntil` passed while suspended is restored and still
    /// out of force. See `vtc-service`'s
    /// `credentials::lifecycle`.
    VrcRestored(VrcLifecycleData),

    /// A VRC was displaced by a later one between the same two
    /// parties. #1079.
    ///
    /// Recorded against the *displaced* edge rather than folded
    /// into the [`Self::VrcPublished`] entry for the credential
    /// that replaced it, so an operator asking what happened to
    /// an edge finds the answer under that edge's own id.
    VrcSuperseded(VrcSupersededData),

    /// A member attached a Verifiable Persona Credential (VPC)
    /// to one of their published relationship edges — DTG
    /// Credentials §Annotation Credentials. The actor is the
    /// authenticated member; `persona_did` is the VPC's issuer,
    /// the P-DID the member chose to be correlated under.
    ///
    /// Recording the P-DID alongside the member is the same
    /// deliberate, narrow exception the VRC publish trail makes
    /// for the actor: the audit store is access-controlled,
    /// redactable and tamper-evident, and without it no operator
    /// could answer "who asserted this persona" for moderation.
    /// See `docs/05-design-notes/vpc-persona-annotation.md`.
    VpcAttached(VpcAnnotationData),

    /// A member removed the VPC annotation from one of their
    /// edges. Withdrawing a persona is as much a privacy act as
    /// asserting one, so it leaves the same trail.
    VpcDetached(VpcAnnotationData),

    /// A member's personhood flag was asserted true via
    /// `POST /v1/members/{did}/personhood/assert`. Phase 4
    /// M4.3. The actor is the asserter (admin or issuer); the
    /// target is the member. Per D2 review (VP-only assert),
    /// the presented evidence is verified at assert time and
    /// discarded — no `evidence_sha256` field on this envelope.
    PersonhoodAsserted(PersonhoodAssertedData),

    /// A member's personhood flag was revoked. Phase 4 M4.4 +
    /// M4.2.2. The `reason` discriminator pins which of the
    /// three triggers fired: `"admin"` (admin `DELETE`),
    /// `"self"` (member `DELETE`), or `"renewal-policy"`
    /// (renewal-time policy downgrade per D5 review's
    /// `downgrade` arm).
    PersonhoodRevoked(PersonhoodRevokedData),

    /// A custom (non-role) endorsement credential was issued
    /// by an issuer or admin. Phase 4 M4.8. Per D8 review, the
    /// credential carries a `credentialStatus` entry on the
    /// shared `Revocation` status list — `status_list_index`
    /// records the allocated slot.
    CustomEndorsementIssued(CustomEndorsementIssuedData),

    /// A custom endorsement was revoked. Phase 4 M4.8. Flips
    /// the `Revocation` status-list bit at the credential's
    /// `status_list_index`. Paired with a
    /// `StatusListFlipped { purpose: "revocation", index,
    /// revoked: true }` envelope (existing variant) so the
    /// status-list audit surface stays uniform.
    CustomEndorsementRevoked(CustomEndorsementRevokedData),

    /// An operator registered a new custom endorsement type
    /// via `POST /v1/endorsement-types`. Phase 4 M4.8.1 (D4
    /// review). The actor is the admin; the `type_uri` field
    /// records what was registered.
    EndorsementTypeRegistered(EndorsementTypeRegisteredData),

    /// An operator deleted a custom endorsement type via
    /// `DELETE /v1/endorsement-types/{uri}`. Phase 4 M4.8.1.
    /// The registry refuses deletion when at least one live
    /// endorsement of this type still exists; this envelope
    /// only fires after a successful delete.
    EndorsementTypeDeleted(EndorsementTypeDeletedData),

    /// `PUT /v1/website/files/{path}` succeeded. Phase 5 M5.5.2.
    /// Records the path + size + SHA-256 of the new content so the
    /// audit log carries enough material to reconstruct a deploy
    /// without persisting the full file body.
    WebsiteFileWritten(WebsiteFileWrittenData),

    /// `DELETE /v1/website/files/{path}` succeeded. Phase 5
    /// M5.5.2. Records the path; no content digest because the
    /// file no longer exists.
    WebsiteFileDeleted(WebsiteFileDeletedData),

    /// `POST /v1/website/deploy` succeeded. Phase 5 M5.5.3.
    /// Captures the bundle's SHA-256, byte size, target deploy
    /// mode, and (managed mode only) the new generation number
    /// + how many old generations were pruned.
    WebsiteBundleDeployed(WebsiteBundleDeployedData),

    /// `POST /v1/website/rollback/{gen}` succeeded. Phase 5
    /// M5.5.4. Managed mode only. Records the symlink swap so
    /// the audit log surfaces which generation served before vs.
    /// after.
    WebsiteGenerationRolledBack(WebsiteGenerationRolledBackData),

    /// Emitted exactly once at daemon boot when the embedded
    /// admin UX (`admin-ui` cargo feature) is enabled. Captures
    /// the SHA-256 of the baked `index.html` so an operator can
    /// correlate which build of the admin SPA is currently
    /// serving. Phase 5 M5.7.2.
    AdminUiServed(AdminUiServedData),

    /// An ACL entry was created — a DID was granted a community role
    /// (`POST /v1/acl`). Authorization grants are the highest-value
    /// forensic events: this records who now holds what authority,
    /// scoped to which contexts, until when. Envelope `target_did` is
    /// the granted DID.
    AclGranted(AclChangeData),

    /// An existing ACL entry was modified (`PATCH /v1/acl/{did}`) —
    /// role / contexts / expiry changed. Envelope `target_did` is the
    /// affected DID; the payload carries the new state.
    AclUpdated(AclChangeData),

    /// An ACL entry was deleted (`DELETE /v1/acl/{did}`) — the DID lost
    /// its community authority. Envelope `target_did` is the revoked DID.
    AclRevoked(AclRevokedData),

    /// A Verifiable Invitation Credential (VIC) was issued
    /// (`POST /v1/invitations`). Records the invitee, granted role, and
    /// the revocation slot so the credential's whole lifecycle is
    /// traceable. Envelope `target_did` is the invitee.
    InvitationIssued(InvitationIssuedData),

    /// An invitation was revoked (`DELETE /v1/invitations/{id}`) — its
    /// revocation bit flipped. Envelope `target_did` is the invitee.
    InvitationRevoked(InvitationRevokedData),

    /// One or more authenticated sessions were revoked by an admin
    /// (`DELETE /v1/auth/sessions/{id}` or `?did=`). Cutting off access
    /// is security-relevant and must be attributable. Envelope
    /// `target_did` is the session owner (when revoking by DID).
    SessionRevoked(SessionRevokedData),

    /// A principal ended their **own** session (`POST
    /// /v1/auth/sign-out`).
    ///
    /// Deliberately distinct from [`Self::SessionRevoked`] rather than
    /// a flag on it: voluntary sign-out is routine, admin-forced
    /// revocation is a security signal, and a SIEM rule that has to
    /// tell them apart by comparing actor to target will get it wrong
    /// the first time an admin revokes their own session. Same
    /// reasoning as [`Self::AdminPromoted`] versus [`Self::RoleChanged`].
    SignedOut(SignedOutData),

    /// An encrypted state backup was exported (`POST /v1/backup/export`).
    BackupExported(BackupData),

    /// An encrypted state backup was imported, restoring community state
    /// (`POST /v1/backup/import`). A full-state restore is among the most
    /// sensitive operations — recorded so a restore is never silent.
    BackupImported(BackupData),

    /// An admin onboarding invite was minted (`POST /v1/admin/invites`),
    /// optionally pre-creating an ACL grant. Envelope `target_did` is the
    /// invited admin DID (when bound to one).
    AdminInviteCreated(AdminInviteData),

    /// An admin onboarding invite was revoked (`DELETE /v1/admin/invites/{jti}`).
    AdminInviteRevoked(AdminInviteData),

    /// A credential schema or accepts-criterion was registered
    /// (`POST /v1/schemas` or `/v1/schemas/accepts`) — what the community
    /// accepts/recognises changed.
    SchemaRegistered(SchemaChangeData),

    /// A credential schema or accepts-criterion was deleted
    /// (`DELETE /v1/schemas/{type_uri}` or `/v1/schemas/accepts/{id}`).
    SchemaDeleted(SchemaChangeData),
}

impl AuditEvent {
    /// The serde tag for this variant — the same string that appears as
    /// `{"type": ...}` on the stored envelope.
    ///
    /// This is what the canonical `audit/list` Trust Task exposes as
    /// `action`, and what `audit/list`'s `action` filter matches on, so
    /// it must stay identical to the serialized tag. Kept as an explicit
    /// match (rather than round-tripping through `serde_json`) so listing
    /// does not pay a serialization per row just to learn the name.
    pub fn variant_name(&self) -> &'static str {
        match self {
            Self::CommunityInstalled(..) => "CommunityInstalled",
            Self::EmergencyBootstrapInvoked(..) => "EmergencyBootstrapInvoked",
            Self::AdminPasskeyRegistered(..) => "AdminPasskeyRegistered",
            Self::AdminPasskeyRevoked(..) => "AdminPasskeyRevoked",
            Self::ConfigChanged(..) => "ConfigChanged",
            Self::ConfigReloaded(..) => "ConfigReloaded",
            Self::RestartRequested(..) => "RestartRequested",
            Self::RoomOperation(..) => "RoomOperation",
            Self::CommunityProfileUpdated(..) => "CommunityProfileUpdated",
            Self::AuditKeyRotated(..) => "AuditKeyRotated",
            Self::MemberUpdated(..) => "MemberUpdated",
            Self::RoleChanged(..) => "RoleChanged",
            Self::AdminPromoted(..) => "AdminPromoted",
            Self::AuthSteppedUp(..) => "AuthSteppedUp",
            Self::JoinRequestSubmitted(..) => "JoinRequestSubmitted",
            Self::JoinRequestApproved(..) => "JoinRequestApproved",
            Self::JoinRequestRejected(..) => "JoinRequestRejected",
            Self::MemberAdded(..) => "MemberAdded",
            Self::MemberRemoved(..) => "MemberRemoved",
            Self::MembershipReciprocated(..) => "MembershipReciprocated",
            Self::PolicyUploaded(..) => "PolicyUploaded",
            Self::PolicyActivated(..) => "PolicyActivated",
            Self::VmcIssued(..) => "VmcIssued",
            Self::VecIssued(..) => "VecIssued",
            Self::MembershipRenewed(..) => "MembershipRenewed",
            Self::StatusListFlipped(..) => "StatusListFlipped",
            Self::DidRotated(..) => "DidRotated",
            Self::RegistryStatusChanged(..) => "RegistryStatusChanged",
            Self::RegistrySyncSucceeded(..) => "RegistrySyncSucceeded",
            Self::RegistrySyncFailed(..) => "RegistrySyncFailed",
            Self::RegistryRecordPolicyOverride(..) => "RegistryRecordPolicyOverride",
            Self::CrossCommunitySessionMinted(..) => "CrossCommunitySessionMinted",
            Self::VrcPublished(..) => "VrcPublished",
            Self::VrcRevoked(..) => "VrcRevoked",
            Self::VrcSuspended(..) => "VrcSuspended",
            Self::VrcRestored(..) => "VrcRestored",
            Self::VrcSuperseded(..) => "VrcSuperseded",
            Self::VpcAttached(..) => "VpcAttached",
            Self::VpcDetached(..) => "VpcDetached",
            Self::PersonhoodAsserted(..) => "PersonhoodAsserted",
            Self::PersonhoodRevoked(..) => "PersonhoodRevoked",
            Self::CustomEndorsementIssued(..) => "CustomEndorsementIssued",
            Self::CustomEndorsementRevoked(..) => "CustomEndorsementRevoked",
            Self::EndorsementTypeRegistered(..) => "EndorsementTypeRegistered",
            Self::EndorsementTypeDeleted(..) => "EndorsementTypeDeleted",
            Self::WebsiteFileWritten(..) => "WebsiteFileWritten",
            Self::WebsiteFileDeleted(..) => "WebsiteFileDeleted",
            Self::WebsiteBundleDeployed(..) => "WebsiteBundleDeployed",
            Self::WebsiteGenerationRolledBack(..) => "WebsiteGenerationRolledBack",
            Self::AdminUiServed(..) => "AdminUiServed",
            Self::AclGranted(..) => "AclGranted",
            Self::AclUpdated(..) => "AclUpdated",
            Self::AclRevoked(..) => "AclRevoked",
            Self::InvitationIssued(..) => "InvitationIssued",
            Self::InvitationRevoked(..) => "InvitationRevoked",
            Self::SessionRevoked(..) => "SessionRevoked",
            Self::SignedOut(..) => "SignedOut",
            Self::BackupExported(..) => "BackupExported",
            Self::BackupImported(..) => "BackupImported",
            Self::AdminInviteCreated(..) => "AdminInviteCreated",
            Self::AdminInviteRevoked(..) => "AdminInviteRevoked",
            Self::SchemaRegistered(..) => "SchemaRegistered",
            Self::SchemaDeleted(..) => "SchemaDeleted",
        }
    }
}

// ---------------------------------------------------------------------------
// Variant data structs
// ---------------------------------------------------------------------------

/// Payload for [`AuditEvent::AclGranted`] / [`AuditEvent::AclUpdated`] — the
/// state of an ACL entry after the change.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct AclChangeData {
    /// The DID whose authority changed.
    pub did: String,
    /// The role granted / now held (e.g. `"admin"`, `"moderator"`, `"member"`).
    pub role: String,
    /// Context scoping (empty = super-admin / community-wide).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub contexts: Vec<String>,
    /// Expiry (RFC3339), if the grant is time-bounded.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<String>,
}

/// Payload for [`AuditEvent::AclRevoked`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct AclRevokedData {
    pub did: String,
    /// The role the DID held immediately before revocation, if known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prior_role: Option<String>,
}

/// Payload for [`AuditEvent::InvitationIssued`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct InvitationIssuedData {
    /// The VIC's `id` (its consumption / revocation handle).
    pub invitation_id: String,
    /// The invited DID (`credentialSubject.id`).
    pub subject_did: String,
    /// Role the invite grants on redemption, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,
    /// Expiry (RFC3339).
    pub valid_until: String,
    /// Revocation status-list slot allocated to this invite.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status_list_index: Option<u32>,
}

/// Payload for [`AuditEvent::InvitationRevoked`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct InvitationRevokedData {
    pub invitation_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subject_did: Option<String>,
    /// `true` if this call flipped the bit, `false` if it was already revoked.
    pub newly_revoked: bool,
}

/// Payload for [`AuditEvent::SessionRevoked`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct SessionRevokedData {
    /// The specific session id revoked, for a single-session revoke.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    /// Number of sessions revoked (1 for a single id, N for revoke-by-DID).
    pub revoked_count: u32,
}

/// Payload for [`AuditEvent::SignedOut`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct SignedOutData {
    /// Session ended. Always known — the caller's own JWT names it.
    ///
    /// There is deliberately no "did it exist" flag: the `AuthClaims`
    /// extractor rejects a token whose session row is gone, so the
    /// handler only ever runs against a live session. A second
    /// sign-out with the same token 401s and never reaches here.
    pub session_id: String,
}

/// Payload for [`AuditEvent::BackupExported`] / [`AuditEvent::BackupImported`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct BackupData {
    /// Number of keyspaces included in the backup.
    pub keyspace_count: u32,
    /// The `vtc_did` the backup belongs to (compatibility anchor).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vtc_did: Option<String>,
}

/// Payload for [`AuditEvent::AdminInviteCreated`] / [`AuditEvent::AdminInviteRevoked`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct AdminInviteData {
    /// The invite token's `jti`.
    pub jti: String,
    /// The admin DID the invite is bound to, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub admin_did: Option<String>,
}

/// Payload for [`AuditEvent::SchemaRegistered`] / [`AuditEvent::SchemaDeleted`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct SchemaChangeData {
    /// The schema `type_uri` or accepts-criterion id.
    pub id: String,
    /// `"schema"` or `"accepts"`.
    pub kind: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct CommunityInstalledData {
    pub community_did: String,
    /// `jti` of the install token that was consumed. Lets a forensic
    /// audit correlate the bootstrap with the specific install URL
    /// the operator clicked.
    pub install_token_jti: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct EmergencyBootstrapData {
    /// Host name of the machine running the CLI command, as
    /// reported by the OS. Recorded for forensic context — the CLI
    /// can't be trusted, but a mismatch with the expected operator
    /// host is a useful smoke signal.
    pub operator_hostname: String,
    /// Wall clock at the time the CLI ran. Distinct from the
    /// envelope timestamp, which is when the daemon next started
    /// and emitted the event — the gap between the two is itself
    /// audit-worthy.
    pub invoked_at: DateTime<Utc>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct AdminPasskeyData {
    /// Hex-encoded WebAuthn credential id. Operator-recognisable;
    /// distinct from the cred_id bytes the storage layer holds.
    pub credential_id_hex: String,
    /// Operator-friendly label (e.g. `"MacBook Air Touch ID"`).
    pub label: String,
    /// `usb` / `nfc` / `ble` / `internal` etc., as WebAuthn reports
    /// them. Helpful for "which device just got revoked" UX.
    pub transports: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ConfigChangedData {
    pub changes: Vec<ConfigChange>,
    /// `true` when at least one changed key is restart-required.
    /// Emitter computes this from the per-key taxonomy (M0.8) so the
    /// audit consumer doesn't need to know the schema.
    pub requires_restart: bool,
}

/// One field's worth of change. `old_value` is `None` if the key
/// wasn't previously set (default-only); `new_value` is the
/// post-PATCH value. Use [`Self::redact_if`] before persisting to
/// mask sensitive values.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ConfigChange {
    pub key: String,
    pub old_value: Option<Value>,
    pub new_value: Value,
    pub source_before: ConfigSource,
}

impl ConfigChange {
    /// Mask the value fields in-place if `sensitive(&self.key)`.
    /// Returns `true` if a redaction was applied so the caller can
    /// log it.
    pub fn redact_if<F>(&mut self, sensitive: F) -> bool
    where
        F: Fn(&str) -> bool,
    {
        if sensitive(&self.key) {
            self.old_value = Some(Value::String(REDACTED_MARKER.to_string()));
            self.new_value = Value::String(REDACTED_MARKER.to_string());
            true
        } else {
            false
        }
    }
}

/// Where the prior value came from in the three-layer config
/// overlay. Mirrors the source annotation surfaced on
/// `GET /v1/admin/config` (spec §14.6). Reproduced here so the
/// audit log is self-contained and doesn't need the config module's
/// type to deserialise.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ConfigSource {
    Env,
    Db,
    Toml,
    Default,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ConfigReloadedData {
    /// Keys that actually re-applied. Excludes keys whose new value
    /// equalled the live value (no-op).
    pub keys_reloaded: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct RoomOperationData {
    /// The room's own identifier.
    pub room_id: String,
    /// The `room.*` action — `room.records.get`, `room.records.put`, `room.epoch.mint`, …
    pub action: String,
    /// The record acted on, where the operation named one.
    ///
    /// Opaque on the sealed tiers by schema requirement, so it identifies a record without
    /// describing it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub record_key: Option<String>,
    /// The room's visibility, so a reader can tell an actorless entry from a missing one.
    pub visibility: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct RestartRequestedData {
    /// `restart.drain_timeout` value (seconds) the daemon will use
    /// when draining in-flight requests. Lets an oncall correlate a
    /// long-tail timeout with a restart.
    pub drain_timeout_seconds: u64,
}

/// One field's before/after change, recorded on enrichable "Updated"
/// audit events so the log can reconstruct *what* changed, not just
/// which field. `old` / `new` are JSON values; either is omitted when
/// the field was newly set or cleared.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "camelCase")]
pub struct FieldChange {
    pub field: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub old: Option<Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub new: Option<Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "camelCase")]
pub struct CommunityProfileUpdatedData {
    /// Names of fields that changed (e.g. `name`, `description`,
    /// `logo_url`, `extensions`).
    pub fields_changed: Vec<String>,
    /// Before/after values for each changed field. Additive over
    /// `fields_changed` (kept for back-compat); empty on pre-enrichment
    /// rows and emitters that don't diff.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub changes: Vec<FieldChange>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct AuditKeyRotatedData {
    pub previous_key_id: String,
    pub new_key_id: String,
    pub rotation_reason: RotationReason,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct MemberUpdatedData {
    /// Names of the fields changed on this PATCH (e.g.
    /// `["publishConsent", "departurePreference"]`).
    pub fields_changed: Vec<String>,
    /// Before/after values for each changed field, so the change is
    /// reconstructable. Additive over `fields_changed`; empty on
    /// pre-enrichment rows.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub changes: Vec<FieldChange>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct RoleChangedData {
    /// Previous role, serialised via the service's role-enum
    /// `Display` impl (e.g. `"moderator"`, `"custom:editor"`).
    /// String-typed so this struct stays in vti-common without
    /// taking a dep on vtc-service's `VtcRole`.
    pub previous_role: String,
    pub new_role: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct AdminPromotedData {
    /// Role the member held immediately before promotion.
    pub previous_role: String,
    /// Credential id of the passkey whose UV authorised the promotion.
    ///
    /// Populated when the ceremony and the promotion were the same request
    /// (the retired fused `promote-to-admin` endpoint). Since the fold, the UV
    /// happens in a separate step-up ceremony, so this is empty and
    /// `authorising_session_id` is the link to the
    /// [`AuthSteppedUp`](AuditEvent::AuthSteppedUp) row carrying the
    /// credential. Retained rather than removed so archived envelopes still
    /// deserialise — `#[serde(default)]` on both fields means rows written on
    /// either side of the fold read back cleanly.
    #[serde(default)]
    pub authorising_credential_id: String,
    /// Session whose live step-up elevation authorised this promotion. Join
    /// key to the `AuthSteppedUp` row for the credential and the moment of
    /// user verification.
    #[serde(default)]
    pub authorising_session_id: String,
}

/// Payload for [`AuditEvent::AuthSteppedUp`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct AuthSteppedUpData {
    /// The elevated session. Privileged operations performed inside the
    /// window record this id, so a reviewer can walk from an operation back to
    /// the gesture that authorised it.
    pub session_id: String,
    /// Credential id (hex) of the passkey that asserted user verification.
    pub credential_id: String,
    /// Assurance level the session now holds.
    pub acr: String,
    /// When the elevation lapses. After this, the same session must re-run the
    /// ceremony before it can authorise anything else.
    pub expires_at: DateTime<Utc>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct JoinRequestData {
    /// UUID of the JoinRequest row in the `join_requests:` keyspace.
    pub request_id: String,
    /// Transport the request arrived over (`"rest"` / `"didcomm"`),
    /// recorded for diagnostics.
    pub transport: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct JoinRequestRejectedData {
    pub request_id: String,
    /// Operator-supplied reason, capped at 1024 chars at the
    /// route layer. May be empty.
    pub reason: String,
    /// Structured policy verdict that drove an automatic rejection
    /// (the serialized `Verdict::Deny`, incl. its `code`). `None` for
    /// a manual admin reject, where `reason` is the operator's words.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub policy_decision: Option<Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct MemberAddedData {
    /// Role assigned at admission. Phase 1 always emits
    /// `"member"` (the default role on approve); future phases
    /// may emit `"moderator"` / `"issuer"` etc. when invite
    /// flows admit at higher tiers.
    pub role: String,
    /// `request_id` of the JoinRequest the admission resolved.
    /// `None` for out-of-band additions (e.g. emergency bootstrap)
    /// that don't pass through a join request.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub via_join_request_id: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct MemberRemovedData {
    /// `disposition` after resolving `PolicyDefault`. One of
    /// `"purge"`, `"tombstone"`, `"historical"`.
    pub disposition: String,
    /// Optional operator-supplied reason on admin removal. Empty
    /// for self-removal.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub reason: String,
    /// Role the member held immediately before removal (e.g.
    /// `"admin"`, `"member"`). `None` when removing a tombstone that
    /// no longer has an ACL row. The credential-revocation cascade is
    /// audited separately via the paired `StatusListFlipped` event.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prior_role: Option<String>,
}

/// Payload for [`AuditEvent::PolicyUploaded`].
///
/// Records the *immutable* outcome of compilation: the new id, what
/// purpose this revision targets, the source hash, and the
/// monotone per-purpose version. The actual Rego source stays in
/// the `policies:<id>` row — the audit envelope only carries the
/// hash so the log doesn't bloat for large policies.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct PolicyUploadedData {
    /// UUID of the new Policy row.
    pub policy_id: String,
    /// Wire-form camelCase purpose (`"join"`, `"removal"`, …).
    pub purpose: String,
    /// SHA-256 of the source, lowercase hex.
    pub sha256: String,
    /// Per-purpose monotone counter the upload landed under.
    pub version: u32,
}

/// Payload for [`AuditEvent::MembershipReciprocated`].
///
/// The audit envelope's `target_did` already carries the member; this
/// adds the join request that admitted them, the VMC they reciprocated,
/// and the id of the member-issued reciprocal VC, so an investigator can
/// chain "admitted → reciprocated" without scanning the members keyspace.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct MembershipReciprocatedData {
    /// UUID of the JoinRequest the reciprocation closes.
    pub request_id: String,
    /// `id` of the VMC the member reciprocated (the community → member
    /// half of the edge).
    pub vmc_id: String,
    /// `id` of the member-issued reciprocal VC (the member → community
    /// half).
    pub reciprocal_vc_id: String,
}

/// Payload for [`AuditEvent::VmcIssued`] + [`AuditEvent::VecIssued`].
///
/// The audit envelope's `target_did` already carries the member;
/// this struct adds the credential id + type + the issuance
/// window so an investigator can correlate "who got which VC
/// when" without cross-referencing the credential store.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct CredentialIssuedData {
    /// VC `id` URI (typically `urn:uuid:<server-allocated>`).
    pub credential_id: String,
    /// Wire-form credential type — the DTG tag exactly as issued
    /// (`"MembershipCredential"`, `"EndorsementCredential"`).
    ///
    /// This recorded `"MembershipCredential"` /
    /// `"EndorsementCredential"` until the naming cleanup: tags no
    /// credential ever carried, in the one record meant to be authoritative
    /// after the fact.
    pub credential_type: String,
    /// RFC3339 `validFrom` from the issued VC.
    pub valid_from: String,
    /// RFC3339 `validUntil` from the issued VC.
    pub valid_until: String,
    /// Status-list slot for VMCs (revocation list). `None` for
    /// VECs and other credential types that don't carry a
    /// status-list entry.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status_list_index: Option<u32>,
}

/// Payload for [`AuditEvent::MembershipRenewed`]. Phase 2 M2.13.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct MembershipRenewedData {
    /// New VMC id.
    pub vmc_id: String,
    /// New role VEC id.
    pub role_vec_id: String,
    /// Whether the `personhood.rego` re-eval produced a different
    /// flag than the prior VMC (spec §6.3 step 3). Phase 2 ships
    /// the deny-all stub so this is always `false` in MVP; the
    /// field is on the wire from day one so Phase 4's
    /// `assert`/`revoke` endpoints don't break the audit schema.
    pub personhood_changed: bool,
}

/// Payload for [`AuditEvent::StatusListFlipped`]. Phase 2 M2.14.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct StatusListFlippedData {
    /// Wire-form status purpose (`"revocation"` / `"suspension"`).
    pub purpose: String,
    /// Slot index that was flipped.
    pub index: u32,
    /// Direction of the flip — `true` = revoked/suspended,
    /// `false` = un-suspended. Revocation flips are one-way per
    /// spec §6.2; suspension flips can go either direction.
    pub revoked: bool,
}

/// Payload for [`AuditEvent::RegistryRecordPolicyOverride`].
/// Phase 3 M3.6. Carries `reason` (always `"rtbf"` in Phase 3
/// — future overrides could land additional reason codes),
/// the attempted disposition the policy would have enforced,
/// and the effective disposition the override produced.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct RegistryRecordPolicyOverrideData {
    /// Short reason code. Phase 3 only emits `"rtbf"`; the
    /// field is shaped as a free string so Phase 4+ can
    /// introduce additional codes (`"legal-hold"`, etc.)
    /// without bumping the envelope version.
    pub reason: String,
    /// The disposition the active `registry.rego.min_disposition`
    /// would have enforced (e.g. `"tombstone"`).
    pub attempted_disposition: String,
    /// The disposition the override applied (always `"purge"`
    /// for RTBF overrides; Phase 4+ may add new effective
    /// dispositions for legal-hold paths).
    pub effective_disposition: String,
}

/// Payload for [`AuditEvent::RegistrySyncSucceeded`] +
/// [`AuditEvent::RegistrySyncFailed`]. Phase 3 M3.4. The
/// `actor_did` on the envelope is the VTC's own DID; the
/// `target_did` is the member being synced.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct RegistrySyncOutcomeData {
    /// UUID of the `SyncJob` row.
    pub job_id: String,
    /// Wire-form `SyncJobKind` — `"publishMember"`,
    /// `"updateMember"`, `"deleteMember"`, or
    /// `"markDeparted"`.
    pub kind: String,
    /// Number of attempts the job made (1 for happy-path
    /// succeed-on-first-try, higher when retries fired).
    pub attempts: u32,
    /// On failure: the last error message. On success:
    /// `None`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_error: Option<String>,
}

/// Payload for [`AuditEvent::CrossCommunitySessionMinted`].
/// Phase 3 M3.10. The envelope's `actor_did` (HMAC-hashed per
/// §11.1) is the bearer of the foreign credentials — i.e. the
/// caller of `POST /v1/auth/recognise`. The envelope's
/// `target_did` is the local subject DID the session was minted
/// to (same value on `minted`; absent on `denied` because no
/// local subject was established).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct CrossCommunitySessionMintedData {
    /// `"minted"` or `"denied"`. Stable wire form so SIEM
    /// rules can key on it.
    pub outcome: String,
    /// Foreign community's issuer DID (e.g.
    /// `did:webvh:peer.example.com:abc`).
    pub foreign_issuer_did: String,
    /// Role claim from the foreign VEC — present even on
    /// `denied` so operators can see what was attempted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub foreign_role: Option<String>,
    /// Local role the foreign role mapped onto. Populated on
    /// `minted` only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mapped_role: Option<String>,
    /// Clamped session TTL in seconds. `min(jwt_default,
    /// vec.validUntil - now, vmc.validUntil - now)`. Populated
    /// on `minted` only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ttl_seconds: Option<u64>,
    /// On `denied`: a short reason code from
    /// [`RecognitionError::reason_code`] or
    /// `"role-mapping-denied"` for the policy-rejection arm.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

// ─── Phase 4 payload structs ──────────────────────────────

/// Payload for [`AuditEvent::VrcPublished`]. Phase 4 M4.6.
/// Self-issued trust edge from one member to another.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct VrcPublishedData {
    /// Server-allocated id (UUID) of the relationship row.
    /// The wire-form `id` lives at `urn:uuid:<vrc_id>` on the
    /// VRC's top-level `id` field.
    pub vrc_id: String,
    /// Subject DID — the *other* member the edge points at.
    /// HMAC-hashed in `target_did_hash` on the envelope; the
    /// raw value lives here only when operator policy allows
    /// (default: omitted).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subject_did: Option<String>,
    /// Free-form trust-relationship type tag from the VRC's
    /// `endorsement.type`. Examples: `"endorses"`, `"reports-to"`,
    /// `"collaborates-with"` — operator-defined.
    pub edge_type: String,
}

/// Payload for [`AuditEvent::VrcRevoked`]. Phase 4 M4.6.
/// Issued whether the original issuer or an admin performed
/// the revocation; the envelope's `actor_did` distinguishes.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct VrcRevokedData {
    pub vrc_id: String,
    /// `"issuer"` (the original member revoked their own VRC)
    /// or `"admin"` (an admin revoked on behalf of the
    /// community).
    pub revoked_by: String,
}

/// Payload for [`AuditEvent::VrcSuspended`] and
/// [`AuditEvent::VrcRestored`]. #1079. One shape for both
/// because the facts are the same in each direction — which
/// edge, who did it, why — and the verb is already the variant,
/// the same reasoning [`VpcAnnotationData`] records.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct VrcLifecycleData {
    /// Server-allocated id (UUID) of the relationship row whose
    /// lifecycle changed.
    pub vrc_id: String,
    /// `"issuer"` (the member who controls the edge, proven
    /// either by the session DID or by an authorization object)
    /// or `"admin"` (moderation on behalf of the community).
    /// Proving control of the issuing key *is* being the issuer,
    /// so a pairwise member's own decision is not misattributed
    /// to an admin.
    pub recorded_by: String,
    /// Free text supplied by whoever recorded the event.
    ///
    /// Held because a suspension a reader cannot interpret gives
    /// the counterparty nothing to act on. Nothing branches on
    /// it, and it is absent whenever the caller supplied none —
    /// never synthesised, so an empty reason stays visibly
    /// empty.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

/// Payload for [`AuditEvent::VrcSuperseded`]. #1079.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct VrcSupersededData {
    /// The displaced relationship row.
    pub vrc_id: String,
    /// Digest of the credential that displaced it, in the form
    /// DTG Credentials specifies (SHA-256 over the RFC 8785
    /// canonicalization, multihash, base58btc multibase) — the
    /// same value `POST /v1/relationships` returned for it.
    ///
    /// Named by digest rather than by row id so the record stays
    /// meaningful to a reader holding the credential but not
    /// this service's storage.
    pub superseded_by_digest_multibase: String,
}

/// Payload for [`AuditEvent::VpcAttached`] and
/// [`AuditEvent::VpcDetached`]. One shape for both because the
/// facts are the same in each direction — which edge, which
/// persona — and the verb is already the variant.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct VpcAnnotationData {
    /// Server-allocated id (UUID) of the relationship row the
    /// VPC annotates. Annotation credentials do not create graph
    /// structure, so a VPC is always recorded against an edge
    /// that already exists.
    pub vrc_id: String,
    /// The VPC's `issuer` — the persona DID (P-DID) the member
    /// asserted. Unlike a relationship DID, a P-DID is *meant*
    /// to recur across edges: that is what makes the correlation
    /// deliberate rather than accidental.
    pub persona_did: String,
}

/// Payload for [`AuditEvent::PersonhoodAsserted`]. Phase 4
/// M4.3. The envelope's `actor_did` is the asserter (admin or
/// issuer); `target_did_hash` is the member.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct PersonhoodAssertedData {
    /// VMC id minted with the new `personhood: true` flag.
    /// Empty when the assert ran inside an idempotent retry
    /// that didn't mint a fresh credential.
    pub vmc_id: String,
    /// `now` at assert time, in RFC3339. Persisted on the
    /// Member row as `personhood_asserted_at` (per D2 review,
    /// only the timestamp persists — not the VP itself).
    pub asserted_at: String,
}

/// Payload for [`AuditEvent::PersonhoodRevoked`]. Phase 4
/// M4.4 / M4.2.2.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct PersonhoodRevokedData {
    /// VMC id minted with the new `personhood: false` flag.
    /// `None` on the `refuse` arm of `on_personhood_fail`
    /// (no VMC re-mint).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vmc_id: Option<String>,
    /// Discriminator for the three triggers: `"admin"`,
    /// `"self"`, or `"renewal-policy"`.
    pub reason: String,
}

/// Payload for [`AuditEvent::CustomEndorsementIssued`]. Phase 4
/// M4.8.2. The envelope's `actor_did` is the issuer (issuer-
/// role member or admin); `target_did_hash` is the subject.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct CustomEndorsementIssuedData {
    /// Server-allocated id (UUID) of the endorsement row.
    pub endorsement_id: String,
    /// The registered endorsement type URI.
    pub endorsement_type: String,
    /// Allocated slot index on the shared `Revocation` status
    /// list (D8 review). Paired with the credential's
    /// `credentialStatus.statusListIndex` field.
    pub status_list_index: u32,
}

/// Payload for [`AuditEvent::CustomEndorsementRevoked`]. Phase 4
/// M4.8.4. Paired with the existing `StatusListFlipped` envelope
/// so the bit-flip is independently auditable.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct CustomEndorsementRevokedData {
    pub endorsement_id: String,
    pub endorsement_type: String,
}

/// Payload for [`AuditEvent::EndorsementTypeRegistered`].
/// Phase 4 M4.8.1 (D4 review).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct EndorsementTypeRegisteredData {
    /// The newly-registered type URI. Operators use this on
    /// the issuance path's `body.type` field.
    pub type_uri: String,
    /// Optional human-readable description supplied at
    /// registration time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// Payload for [`AuditEvent::EndorsementTypeDeleted`]. Phase 4
/// M4.8.1.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct EndorsementTypeDeletedData {
    pub type_uri: String,
    /// Count of live endorsements of this type at deletion. Deletion
    /// is refused while any exist, so this is `0` on success — recorded
    /// so the audit trail documents that the no-orphans precondition
    /// held. `default` keeps pre-enrichment rows parseable.
    #[serde(default)]
    pub live_endorsements_at_delete: u32,
}

/// Payload for [`AuditEvent::WebsiteFileWritten`]. Phase 5 M5.5.2.
/// Records enough material to audit the deploy without persisting
/// the file body itself — the SHA-256 + size pin what was written.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct WebsiteFileWrittenData {
    /// Path **relative to** `website.root_dir`, NFC-normalised
    /// and free of `..` segments.
    pub path: String,
    /// File size in bytes (post-write).
    pub size_bytes: u64,
    /// SHA-256 of the written content, hex-encoded. Doubles as
    /// the ETag value the response returns to the caller.
    pub sha256: String,
}

/// Payload for [`AuditEvent::WebsiteFileDeleted`]. Phase 5 M5.5.2.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct WebsiteFileDeletedData {
    /// Path **relative to** `website.root_dir`, NFC-normalised.
    pub path: String,
}

/// Payload for [`AuditEvent::WebsiteBundleDeployed`]. Phase 5
/// M5.5.3. Live + managed modes share this variant; the
/// `target_generation` + `pruned_generations` fields are populated
/// in managed mode and zero in live mode.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct WebsiteBundleDeployedData {
    /// SHA-256 of the uploaded tar.gz, hex-encoded.
    pub bundle_sha256: String,
    /// Size of the uploaded tar.gz, in bytes.
    pub bundle_size_bytes: u64,
    /// `"live"` or `"managed"` (matches
    /// `website.deploy_mode`).
    pub deploy_mode: String,
    /// New generation number in managed mode; `0` in live mode.
    pub target_generation: u32,
    /// Number of old generations pruned to honour
    /// `managed_generations_keep` (managed mode only; `0` in
    /// live mode).
    pub pruned_generations: u32,
}

/// Payload for [`AuditEvent::WebsiteGenerationRolledBack`]. Phase
/// 5 M5.5.4. Managed mode only — the symlink swap is the audit
/// surface.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct WebsiteGenerationRolledBackData {
    /// Generation `current` pointed at before the rollback.
    pub from_generation: u32,
    /// Generation `current` now points at.
    pub to_generation: u32,
}

/// Payload for [`AuditEvent::AdminUiServed`]. Phase 5 M5.7.2.
/// Captures enough material that an operator who suspects an
/// admin UX compromise can pin the exact bytes that were baked
/// into the running daemon.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct AdminUiServedData {
    /// SHA-256 of the baked `index.html` (hex-encoded). Doubles
    /// as the `version` field of `GET /admin/build-info.json`.
    pub index_sha256: String,
    /// Number of files baked into the binary (informational —
    /// surfaces accidental directory bloat).
    pub file_count: u32,
    /// `"embedded"` or `"external"`. Embedded serves the baked
    /// SPA; external delegates to an operator-supplied origin.
    pub mode: String,
    /// Daemon build version (`CARGO_PKG_VERSION`) that served this
    /// SPA, so the running admin-UI build correlates with a specific
    /// release. `None` on pre-enrichment rows.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub daemon_version: Option<String>,
}

/// Payload for [`AuditEvent::RegistryStatusChanged`]. Phase 3
/// M3.2.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct RegistryStatusChangedData {
    /// Status before the flip — `"active"` or `"degraded"`.
    pub from: String,
    /// Status after the flip.
    pub to: String,
    /// Optional reason — error string from the last health
    /// probe when flipping to `degraded`, or a short
    /// confirmation message when flipping back to `active`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

/// Payload for [`AuditEvent::DidRotated`]. Phase 2 M2.15.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct DidRotatedData {
    pub old_did: String,
    pub new_did: String,
    /// DID method of the new DID — `"did:key"` /
    /// `"did:webvh"`. Spec §10.5 keeps the two paths
    /// cryptographically distinct so SIEM rules can target
    /// each.
    pub method: String,
    /// New VMC id minted in the same transaction (status-list
    /// slot reused). `None` if issuance was skipped (e.g.
    /// daemon misconfiguration).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vmc_id: Option<String>,
    /// New role VEC id minted in the same transaction.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub role_vec_id: Option<String>,
    /// Role the rotating member held before the rotation, carried
    /// across unchanged. Lets a reviewer see the privilege level a
    /// rotated key inherits. `None` on pre-enrichment rows.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prior_role: Option<String>,
    /// Why the member rotated, as declared when they requested the
    /// rotation challenge. `None` on pre-enrichment rows and whenever
    /// the member declined to say.
    ///
    /// **Self-asserted, not proven.** The rotation signatures cover
    /// `{rotationId, oldDid, newDid, expiresAt}` and nothing else, so
    /// this value is the member's own claim about their motive. It is
    /// bound to the authenticated session that opened the ceremony and
    /// cannot be altered by whoever submits the finish request, but a
    /// member who lies about *why* they rotated will be recorded
    /// faithfully lying. Treat it as intent, never as evidence.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rotation_reason: Option<DidRotationReason>,
}

/// Why a member rotated their DID, as declared at challenge time.
///
/// Separate from [`crate::audit::RotationReason`], which describes
/// *audit-HMAC-key* rotation: that enum serializes PascalCase, is
/// already persisted in `audit_key:` rows (so it cannot be re-cased),
/// and its variants (`Initial`, `Routine` meaning "the background task
/// fired") carry no sensible reading in this domain.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub enum DidRotationReason {
    /// Routine hygiene — scheduled or self-directed key refresh, no
    /// suspected compromise.
    Routine,
    /// The old key is believed exposed. The security-relevant value:
    /// a SIEM rule keying on this should escalate, and everything the
    /// old DID did before the rotation is suspect.
    Compromise,
    /// The device holding the old key was lost, destroyed, or
    /// replaced. Distinct from `Compromise` — no exposure claimed.
    DeviceLoss,
    /// Moving between DID methods or hosts (e.g. `did:key` →
    /// `did:webvh`), the identity being otherwise unchanged.
    Migration,
    /// The member gave no reason.
    Unspecified,
}

/// Payload for [`AuditEvent::PolicyActivated`].
///
/// Records the active-pointer flip for a purpose. `previous_policy_id`
/// is `None` when the purpose had no prior active row (first
/// activation for that purpose) — that case is itself audit-worthy
/// and distinct from "activated a successor". Carries the new
/// revision's hash so consumers don't have to cross-reference the
/// `PolicyUploaded` event to know what bytecode is now live.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct PolicyActivatedData {
    pub policy_id: String,
    pub purpose: String,
    pub sha256: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub previous_policy_id: Option<String>,
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    fn round_trip(event: &AuditEvent) {
        let s = serde_json::to_string(event).unwrap();
        let back: AuditEvent = serde_json::from_str(&s).unwrap();
        assert_eq!(&back, event);
    }

    fn wire_value(event: &AuditEvent) -> Value {
        serde_json::to_value(event).unwrap()
    }

    // ──────────── tag + content shape ────────────

    #[test]
    fn community_installed_tagged_wire_shape() {
        let e = AuditEvent::CommunityInstalled(CommunityInstalledData {
            community_did: "did:webvh:example.com:abc".into(),
            install_token_jti: "jti-1".into(),
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "CommunityInstalled");
        assert_eq!(v["data"]["communityDid"], "did:webvh:example.com:abc");
        assert_eq!(v["data"]["installTokenJti"], "jti-1");
        round_trip(&e);
    }

    #[test]
    fn emergency_bootstrap_tagged_wire_shape() {
        let invoked_at = DateTime::parse_from_rfc3339("2026-05-12T00:00:00Z")
            .unwrap()
            .with_timezone(&Utc);
        let e = AuditEvent::EmergencyBootstrapInvoked(EmergencyBootstrapData {
            operator_hostname: "ops-01.example.com".into(),
            invoked_at,
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "EmergencyBootstrapInvoked");
        assert_eq!(v["data"]["operatorHostname"], "ops-01.example.com");
        round_trip(&e);
    }

    #[test]
    fn admin_passkey_registered_round_trip() {
        let e = AuditEvent::AdminPasskeyRegistered(AdminPasskeyData {
            credential_id_hex: "deadbeef".into(),
            label: "MacBook Air Touch ID".into(),
            transports: vec!["internal".into(), "hybrid".into()],
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "AdminPasskeyRegistered");
        assert_eq!(v["data"]["credentialIdHex"], "deadbeef");
        assert_eq!(v["data"]["transports"][0], "internal");
        round_trip(&e);
    }

    #[test]
    fn admin_passkey_revoked_round_trip() {
        let e = AuditEvent::AdminPasskeyRevoked(AdminPasskeyData {
            credential_id_hex: "feedface".into(),
            label: "iPhone Face ID".into(),
            transports: vec!["hybrid".into()],
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "AdminPasskeyRevoked");
        round_trip(&e);
    }

    #[test]
    fn config_changed_round_trip() {
        let e = AuditEvent::ConfigChanged(ConfigChangedData {
            changes: vec![ConfigChange {
                key: "log.level".into(),
                old_value: Some(json!("info")),
                new_value: json!("debug"),
                source_before: ConfigSource::Toml,
            }],
            requires_restart: false,
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "ConfigChanged");
        assert_eq!(v["data"]["changes"][0]["key"], "log.level");
        assert_eq!(v["data"]["changes"][0]["newValue"], "debug");
        assert_eq!(v["data"]["changes"][0]["sourceBefore"], "toml");
        round_trip(&e);
    }

    #[test]
    fn config_reloaded_round_trip() {
        let e = AuditEvent::ConfigReloaded(ConfigReloadedData {
            keys_reloaded: vec!["log.level".into(), "audit.retention.config_changed".into()],
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "ConfigReloaded");
        assert_eq!(
            v["data"]["keysReloaded"][1],
            "audit.retention.config_changed"
        );
        round_trip(&e);
    }

    #[test]
    fn restart_requested_round_trip() {
        let e = AuditEvent::RestartRequested(RestartRequestedData {
            drain_timeout_seconds: 30,
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "RestartRequested");
        assert_eq!(v["data"]["drainTimeoutSeconds"], 30);
        round_trip(&e);
    }

    #[test]
    fn community_profile_updated_round_trip() {
        let e = AuditEvent::CommunityProfileUpdated(CommunityProfileUpdatedData {
            fields_changed: vec!["name".into(), "logo_url".into()],
            changes: vec![FieldChange {
                field: "name".into(),
                old: Some(json!("Old Name")),
                new: Some(json!("New Name")),
            }],
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "CommunityProfileUpdated");
        assert_eq!(v["data"]["fieldsChanged"][0], "name");
        assert_eq!(v["data"]["changes"][0]["field"], "name");
        assert_eq!(v["data"]["changes"][0]["new"], "New Name");
        round_trip(&e);
    }

    #[test]
    fn audit_key_rotated_round_trip() {
        let e = AuditEvent::AuditKeyRotated(AuditKeyRotatedData {
            previous_key_id: "11111111-1111-1111-1111-111111111111".into(),
            new_key_id: "22222222-2222-2222-2222-222222222222".into(),
            rotation_reason: RotationReason::Rtbf,
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "AuditKeyRotated");
        assert_eq!(v["data"]["rotationReason"], "Rtbf");
        round_trip(&e);
    }

    // ──────────── ConfigChange::redact_if ────────────

    #[test]
    fn redact_if_masks_sensitive_keys() {
        let mut change = ConfigChange {
            key: "server.tls.cert_path".into(),
            old_value: Some(json!("/etc/old.pem")),
            new_value: json!("/etc/new.pem"),
            source_before: ConfigSource::Db,
        };
        let redacted = change.redact_if(|k| k.starts_with("server.tls."));
        assert!(redacted);
        assert_eq!(change.old_value, Some(json!(REDACTED_MARKER)));
        assert_eq!(change.new_value, json!(REDACTED_MARKER));
        // Key + source survive — redaction is value-only.
        assert_eq!(change.key, "server.tls.cert_path");
        assert_eq!(change.source_before, ConfigSource::Db);
    }

    #[test]
    fn redact_if_leaves_non_sensitive_keys_untouched() {
        let mut change = ConfigChange {
            key: "log.level".into(),
            old_value: Some(json!("info")),
            new_value: json!("debug"),
            source_before: ConfigSource::Toml,
        };
        let original = change.clone();
        let redacted = change.redact_if(|k| k.starts_with("server.tls."));
        assert!(!redacted);
        assert_eq!(change, original);
    }

    #[test]
    fn redact_if_handles_unset_old_value() {
        let mut change = ConfigChange {
            key: "server.tls.key_path".into(),
            old_value: None,
            new_value: json!("/etc/new.key"),
            source_before: ConfigSource::Default,
        };
        change.redact_if(|k| k.starts_with("server.tls."));
        // Even when the previous value was unset, redaction inserts a
        // <redacted> marker so the audit record can't be distinguished
        // from "previously empty, now empty" — preserves the
        // sensitivity boundary.
        assert_eq!(change.old_value, Some(json!(REDACTED_MARKER)));
    }

    // ──────────── Variant catalog snapshot ────────────
    //
    // Pins the wire-discriminator strings. Renaming a variant
    // breaks SIEM ingestion and webhook consumers; this test makes
    // such a change visible in review.

    #[test]
    fn policy_uploaded_round_trip() {
        let e = AuditEvent::PolicyUploaded(PolicyUploadedData {
            policy_id: "11111111-1111-1111-1111-111111111111".into(),
            purpose: "join".into(),
            sha256: "abc123".into(),
            version: 4,
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "PolicyUploaded");
        assert_eq!(
            v["data"]["policyId"],
            "11111111-1111-1111-1111-111111111111"
        );
        assert_eq!(v["data"]["purpose"], "join");
        assert_eq!(v["data"]["sha256"], "abc123");
        assert_eq!(v["data"]["version"], 4);
        round_trip(&e);
    }

    #[test]
    fn policy_activated_round_trip_with_predecessor() {
        let e = AuditEvent::PolicyActivated(PolicyActivatedData {
            policy_id: "22222222-2222-2222-2222-222222222222".into(),
            purpose: "removal".into(),
            sha256: "deadbeef".into(),
            previous_policy_id: Some("11111111-1111-1111-1111-111111111111".into()),
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "PolicyActivated");
        assert_eq!(
            v["data"]["previousPolicyId"],
            "11111111-1111-1111-1111-111111111111"
        );
        round_trip(&e);
    }

    #[test]
    fn policy_activated_omits_predecessor_when_none() {
        // First activation for a purpose has no predecessor — verify
        // the field is omitted on the wire (Option skip), not
        // serialised as `null`. SIEM filters key on field presence.
        let e = AuditEvent::PolicyActivated(PolicyActivatedData {
            policy_id: "22222222-2222-2222-2222-222222222222".into(),
            purpose: "personhood".into(),
            sha256: "cafe".into(),
            previous_policy_id: None,
        });
        let v = wire_value(&e);
        assert!(
            v["data"].get("previousPolicyId").is_none(),
            "previousPolicyId should be omitted, got {v}"
        );
        round_trip(&e);
    }

    #[test]
    fn vmc_issued_round_trip() {
        let e = AuditEvent::VmcIssued(CredentialIssuedData {
            credential_id: "urn:uuid:11111111-1111-1111-1111-111111111111".into(),
            credential_type: "MembershipCredential".into(),
            valid_from: "2026-05-12T00:00:00Z".into(),
            valid_until: "2026-06-11T00:00:00Z".into(),
            status_list_index: Some(42),
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "VmcIssued");
        assert_eq!(v["data"]["credentialType"], "MembershipCredential");
        assert_eq!(v["data"]["statusListIndex"], 42);
        round_trip(&e);
    }

    #[test]
    fn vec_issued_round_trip_omits_status_list_index_when_none() {
        let e = AuditEvent::VecIssued(CredentialIssuedData {
            credential_id: "urn:uuid:22222222-2222-2222-2222-222222222222".into(),
            credential_type: "EndorsementCredential".into(),
            valid_from: "2026-05-12T00:00:00Z".into(),
            valid_until: "2026-06-11T00:00:00Z".into(),
            status_list_index: None,
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "VecIssued");
        assert!(
            v["data"].get("statusListIndex").is_none(),
            "statusListIndex should be omitted when None, got {v}"
        );
        round_trip(&e);
    }

    #[test]
    fn membership_renewed_round_trip() {
        let e = AuditEvent::MembershipRenewed(MembershipRenewedData {
            vmc_id: "urn:uuid:vmc-1".into(),
            role_vec_id: "urn:uuid:vec-1".into(),
            personhood_changed: true,
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "MembershipRenewed");
        assert_eq!(v["data"]["personhoodChanged"], true);
        round_trip(&e);
    }

    #[test]
    fn status_list_flipped_round_trip() {
        let e = AuditEvent::StatusListFlipped(StatusListFlippedData {
            purpose: "revocation".into(),
            index: 7,
            revoked: true,
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "StatusListFlipped");
        assert_eq!(v["data"]["purpose"], "revocation");
        assert_eq!(v["data"]["index"], 7);
        assert_eq!(v["data"]["revoked"], true);
        round_trip(&e);
    }

    #[test]
    fn did_rotated_round_trip_with_credential_ids() {
        let e = AuditEvent::DidRotated(DidRotatedData {
            old_did: "did:key:zOld".into(),
            new_did: "did:key:zNew".into(),
            method: "did:key".into(),
            vmc_id: Some("urn:uuid:vmc-2".into()),
            role_vec_id: Some("urn:uuid:vec-2".into()),
            prior_role: Some("member".into()),
            rotation_reason: Some(DidRotationReason::Compromise),
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "DidRotated");
        assert_eq!(v["data"]["method"], "did:key");
        assert_eq!(v["data"]["oldDid"], "did:key:zOld");
        assert_eq!(v["data"]["newDid"], "did:key:zNew");
        assert_eq!(v["data"]["vmcId"], "urn:uuid:vmc-2");
        round_trip(&e);
    }

    #[test]
    fn did_rotated_omits_credential_ids_when_none() {
        let e = AuditEvent::DidRotated(DidRotatedData {
            old_did: "did:key:zOld".into(),
            new_did: "did:key:zNew".into(),
            method: "did:key".into(),
            vmc_id: None,
            role_vec_id: None,
            prior_role: None,
            rotation_reason: None,
        });
        let v = wire_value(&e);
        assert!(v["data"].get("vmcId").is_none());
        assert!(v["data"].get("roleVecId").is_none());
        round_trip(&e);
    }

    #[test]
    fn registry_sync_succeeded_round_trip() {
        let e = AuditEvent::RegistrySyncSucceeded(RegistrySyncOutcomeData {
            job_id: "11111111-1111-1111-1111-111111111111".into(),
            kind: "publishMember".into(),
            attempts: 1,
            last_error: None,
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "RegistrySyncSucceeded");
        assert_eq!(v["data"]["kind"], "publishMember");
        assert_eq!(v["data"]["attempts"], 1);
        assert!(
            v["data"].get("lastError").is_none(),
            "lastError should be omitted on success: {v}"
        );
        round_trip(&e);
    }

    #[test]
    fn registry_sync_failed_round_trip_carries_last_error() {
        let e = AuditEvent::RegistrySyncFailed(RegistrySyncOutcomeData {
            job_id: "22222222-2222-2222-2222-222222222222".into(),
            kind: "deleteMember".into(),
            attempts: 17,
            last_error: Some("permanent: bad input".into()),
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "RegistrySyncFailed");
        assert_eq!(v["data"]["attempts"], 17);
        assert_eq!(v["data"]["lastError"], "permanent: bad input");
        round_trip(&e);
    }

    #[test]
    fn registry_status_changed_round_trip() {
        let e = AuditEvent::RegistryStatusChanged(RegistryStatusChangedData {
            from: "active".into(),
            to: "degraded".into(),
            reason: Some("connection refused".into()),
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "RegistryStatusChanged");
        assert_eq!(v["data"]["from"], "active");
        assert_eq!(v["data"]["to"], "degraded");
        assert_eq!(v["data"]["reason"], "connection refused");
        round_trip(&e);
    }

    #[test]
    fn registry_status_changed_omits_reason_when_none() {
        let e = AuditEvent::RegistryStatusChanged(RegistryStatusChangedData {
            from: "degraded".into(),
            to: "active".into(),
            reason: None,
        });
        let v = wire_value(&e);
        assert!(
            v["data"].get("reason").is_none(),
            "reason should be omitted when None, got {v}"
        );
        round_trip(&e);
    }

    #[test]
    fn registry_record_policy_override_round_trip() {
        let e = AuditEvent::RegistryRecordPolicyOverride(RegistryRecordPolicyOverrideData {
            reason: "rtbf".into(),
            attempted_disposition: "tombstone".into(),
            effective_disposition: "purge".into(),
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "RegistryRecordPolicyOverride");
        assert_eq!(v["data"]["reason"], "rtbf");
        assert_eq!(v["data"]["attemptedDisposition"], "tombstone");
        assert_eq!(v["data"]["effectiveDisposition"], "purge");
        round_trip(&e);
    }

    #[test]
    fn cross_community_session_minted_round_trip() {
        let e = AuditEvent::CrossCommunitySessionMinted(CrossCommunitySessionMintedData {
            outcome: "minted".into(),
            foreign_issuer_did: "did:webvh:peer.example.com:abc".into(),
            foreign_role: Some("moderator".into()),
            mapped_role: Some("monitor".into()),
            ttl_seconds: Some(900),
            reason: None,
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "CrossCommunitySessionMinted");
        assert_eq!(v["data"]["outcome"], "minted");
        assert_eq!(
            v["data"]["foreignIssuerDid"],
            "did:webvh:peer.example.com:abc"
        );
        assert_eq!(v["data"]["foreignRole"], "moderator");
        assert_eq!(v["data"]["mappedRole"], "monitor");
        assert_eq!(v["data"]["ttlSeconds"], 900);
        assert!(
            v["data"].get("reason").is_none(),
            "reason should be omitted on minted: {v}"
        );
        round_trip(&e);
    }

    #[test]
    fn cross_community_session_minted_denied_carries_reason() {
        let e = AuditEvent::CrossCommunitySessionMinted(CrossCommunitySessionMintedData {
            outcome: "denied".into(),
            foreign_issuer_did: "did:webvh:peer.example.com:abc".into(),
            foreign_role: Some("admin".into()),
            mapped_role: None,
            ttl_seconds: None,
            reason: Some("issuer-not-recognised".into()),
        });
        let v = wire_value(&e);
        assert_eq!(v["data"]["outcome"], "denied");
        assert_eq!(v["data"]["reason"], "issuer-not-recognised");
        assert!(v["data"].get("mappedRole").is_none());
        assert!(v["data"].get("ttlSeconds").is_none());
        round_trip(&e);
    }

    // ─── Phase 4 round-trip coverage ───────────────────

    #[test]
    fn vrc_published_round_trip() {
        let e = AuditEvent::VrcPublished(VrcPublishedData {
            vrc_id: "11111111-1111-1111-1111-111111111111".into(),
            subject_did: Some("did:key:zSubject".into()),
            edge_type: "endorses".into(),
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "VrcPublished");
        assert_eq!(v["data"]["vrcId"], "11111111-1111-1111-1111-111111111111");
        assert_eq!(v["data"]["subjectDid"], "did:key:zSubject");
        assert_eq!(v["data"]["edgeType"], "endorses");
        round_trip(&e);
    }

    #[test]
    fn vrc_published_omits_subject_did_when_none() {
        let e = AuditEvent::VrcPublished(VrcPublishedData {
            vrc_id: "id".into(),
            subject_did: None,
            edge_type: "reports-to".into(),
        });
        let v = wire_value(&e);
        assert!(v["data"].get("subjectDid").is_none());
        round_trip(&e);
    }

    #[test]
    fn vrc_revoked_round_trip() {
        let e = AuditEvent::VrcRevoked(VrcRevokedData {
            vrc_id: "id".into(),
            revoked_by: "issuer".into(),
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "VrcRevoked");
        assert_eq!(v["data"]["revokedBy"], "issuer");
        round_trip(&e);
    }

    /// #1079. The two verbs the graph had no vocabulary for. Asserted on the
    /// wire shape because the field names are what an operator's log query and
    /// the admin UI's label map both key on — a silent rename here is a
    /// silently unlabelled event, not a compile error.
    #[test]
    fn vrc_suspend_and_restore_share_one_payload_shape() {
        for (e, expected) in [
            (
                AuditEvent::VrcSuspended(VrcLifecycleData {
                    vrc_id: "id".into(),
                    recorded_by: "issuer".into(),
                    reason: Some("under moderation".into()),
                }),
                "VrcSuspended",
            ),
            (
                AuditEvent::VrcRestored(VrcLifecycleData {
                    vrc_id: "id".into(),
                    recorded_by: "admin".into(),
                    reason: None,
                }),
                "VrcRestored",
            ),
        ] {
            let v = wire_value(&e);
            assert_eq!(v["type"], expected);
            assert_eq!(v["data"]["vrcId"], "id");
            assert!(v["data"]["recordedBy"].is_string());
            round_trip(&e);
        }

        // An omitted reason stays omitted rather than becoming `null` — the
        // trail should not suggest a reason was recorded when none was.
        let none = wire_value(&AuditEvent::VrcRestored(VrcLifecycleData {
            vrc_id: "id".into(),
            recorded_by: "admin".into(),
            reason: None,
        }));
        assert!(none["data"].get("reason").is_none());
    }

    /// Supersession names the displacing credential by digest, not by row id,
    /// so the record still means something to a reader who holds the
    /// credential but not this service's storage.
    #[test]
    fn vrc_superseded_names_the_displacing_credential_by_digest() {
        let e = AuditEvent::VrcSuperseded(VrcSupersededData {
            vrc_id: "old".into(),
            superseded_by_digest_multibase: "zQmNew".into(),
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "VrcSuperseded");
        assert_eq!(v["data"]["supersededByDigestMultibase"], "zQmNew");
        round_trip(&e);
    }

    #[test]
    fn vpc_attach_and_detach_share_one_payload_shape() {
        for (e, expected) in [
            (
                AuditEvent::VpcAttached(VpcAnnotationData {
                    vrc_id: "id".into(),
                    persona_did: "did:key:zPersona".into(),
                }),
                "VpcAttached",
            ),
            (
                AuditEvent::VpcDetached(VpcAnnotationData {
                    vrc_id: "id".into(),
                    persona_did: "did:key:zPersona".into(),
                }),
                "VpcDetached",
            ),
        ] {
            let v = wire_value(&e);
            assert_eq!(v["type"], expected);
            assert_eq!(v["data"]["vrcId"], "id");
            assert_eq!(v["data"]["personaDid"], "did:key:zPersona");
            round_trip(&e);
        }
    }

    #[test]
    fn personhood_asserted_round_trip() {
        let e = AuditEvent::PersonhoodAsserted(PersonhoodAssertedData {
            vmc_id: "vmc-7".into(),
            asserted_at: "2026-05-14T10:00:00Z".into(),
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "PersonhoodAsserted");
        assert_eq!(v["data"]["vmcId"], "vmc-7");
        assert_eq!(v["data"]["assertedAt"], "2026-05-14T10:00:00Z");
        round_trip(&e);
    }

    #[test]
    fn personhood_revoked_round_trip() {
        let e = AuditEvent::PersonhoodRevoked(PersonhoodRevokedData {
            vmc_id: Some("vmc-8".into()),
            reason: "admin".into(),
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "PersonhoodRevoked");
        assert_eq!(v["data"]["vmcId"], "vmc-8");
        assert_eq!(v["data"]["reason"], "admin");
        round_trip(&e);
    }

    #[test]
    fn personhood_revoked_omits_vmc_id_when_refuse_arm() {
        // `refuse` arm of on_personhood_fail doesn't re-mint
        // a VMC, so vmc_id is None.
        let e = AuditEvent::PersonhoodRevoked(PersonhoodRevokedData {
            vmc_id: None,
            reason: "renewal-policy".into(),
        });
        let v = wire_value(&e);
        assert!(v["data"].get("vmcId").is_none());
        assert_eq!(v["data"]["reason"], "renewal-policy");
        round_trip(&e);
    }

    #[test]
    fn custom_endorsement_issued_round_trip() {
        let e = AuditEvent::CustomEndorsementIssued(CustomEndorsementIssuedData {
            endorsement_id: "end-1".into(),
            endorsement_type: "https://example.com/v1/skills/rust".into(),
            status_list_index: 42,
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "CustomEndorsementIssued");
        assert_eq!(
            v["data"]["endorsementType"],
            "https://example.com/v1/skills/rust"
        );
        assert_eq!(v["data"]["statusListIndex"], 42);
        round_trip(&e);
    }

    #[test]
    fn custom_endorsement_revoked_round_trip() {
        let e = AuditEvent::CustomEndorsementRevoked(CustomEndorsementRevokedData {
            endorsement_id: "end-1".into(),
            endorsement_type: "https://example.com/v1/skills/rust".into(),
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "CustomEndorsementRevoked");
        round_trip(&e);
    }

    #[test]
    fn endorsement_type_registered_round_trip() {
        let e = AuditEvent::EndorsementTypeRegistered(EndorsementTypeRegisteredData {
            type_uri: "https://example.com/v1/skills/rust".into(),
            description: Some("Rust proficiency endorsement".into()),
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "EndorsementTypeRegistered");
        assert_eq!(v["data"]["typeUri"], "https://example.com/v1/skills/rust");
        assert_eq!(v["data"]["description"], "Rust proficiency endorsement");
        round_trip(&e);
    }

    #[test]
    fn endorsement_type_registered_omits_description_when_none() {
        let e = AuditEvent::EndorsementTypeRegistered(EndorsementTypeRegisteredData {
            type_uri: "https://example.com/v1/x".into(),
            description: None,
        });
        let v = wire_value(&e);
        assert!(v["data"].get("description").is_none());
        round_trip(&e);
    }

    #[test]
    fn endorsement_type_deleted_round_trip() {
        let e = AuditEvent::EndorsementTypeDeleted(EndorsementTypeDeletedData {
            type_uri: "https://example.com/v1/skills/rust".into(),
            live_endorsements_at_delete: 0,
        });
        let v = wire_value(&e);
        assert_eq!(v["type"], "EndorsementTypeDeleted");
        round_trip(&e);
    }

    #[test]
    fn variant_discriminator_strings() {
        let cases: Vec<(AuditEvent, &str)> = vec![
            (
                AuditEvent::CommunityInstalled(CommunityInstalledData {
                    community_did: "did:webvh:x".into(),
                    install_token_jti: "j".into(),
                }),
                "CommunityInstalled",
            ),
            (
                AuditEvent::EmergencyBootstrapInvoked(EmergencyBootstrapData {
                    operator_hostname: "h".into(),
                    invoked_at: Utc::now(),
                }),
                "EmergencyBootstrapInvoked",
            ),
            (
                AuditEvent::AdminPasskeyRegistered(AdminPasskeyData {
                    credential_id_hex: "0".into(),
                    label: "x".into(),
                    transports: vec![],
                }),
                "AdminPasskeyRegistered",
            ),
            (
                AuditEvent::AdminPasskeyRevoked(AdminPasskeyData {
                    credential_id_hex: "0".into(),
                    label: "x".into(),
                    transports: vec![],
                }),
                "AdminPasskeyRevoked",
            ),
            (
                AuditEvent::ConfigChanged(ConfigChangedData {
                    changes: vec![],
                    requires_restart: false,
                }),
                "ConfigChanged",
            ),
            (
                AuditEvent::ConfigReloaded(ConfigReloadedData {
                    keys_reloaded: vec![],
                }),
                "ConfigReloaded",
            ),
            (
                AuditEvent::RestartRequested(RestartRequestedData {
                    drain_timeout_seconds: 0,
                }),
                "RestartRequested",
            ),
            (
                AuditEvent::CommunityProfileUpdated(CommunityProfileUpdatedData {
                    fields_changed: vec![],
                    changes: vec![],
                }),
                "CommunityProfileUpdated",
            ),
            (
                AuditEvent::AuditKeyRotated(AuditKeyRotatedData {
                    previous_key_id: "p".into(),
                    new_key_id: "n".into(),
                    rotation_reason: RotationReason::Initial,
                }),
                "AuditKeyRotated",
            ),
            (
                AuditEvent::PolicyUploaded(PolicyUploadedData {
                    policy_id: "p".into(),
                    purpose: "join".into(),
                    sha256: "x".into(),
                    version: 1,
                }),
                "PolicyUploaded",
            ),
            (
                AuditEvent::PolicyActivated(PolicyActivatedData {
                    policy_id: "p".into(),
                    purpose: "join".into(),
                    sha256: "x".into(),
                    previous_policy_id: None,
                }),
                "PolicyActivated",
            ),
            (
                AuditEvent::VmcIssued(CredentialIssuedData {
                    credential_id: "id".into(),
                    credential_type: "MembershipCredential".into(),
                    valid_from: "vf".into(),
                    valid_until: "vu".into(),
                    status_list_index: None,
                }),
                "VmcIssued",
            ),
            (
                AuditEvent::VecIssued(CredentialIssuedData {
                    credential_id: "id".into(),
                    credential_type: "EndorsementCredential".into(),
                    valid_from: "vf".into(),
                    valid_until: "vu".into(),
                    status_list_index: None,
                }),
                "VecIssued",
            ),
            (
                AuditEvent::MembershipRenewed(MembershipRenewedData {
                    vmc_id: "v".into(),
                    role_vec_id: "r".into(),
                    personhood_changed: false,
                }),
                "MembershipRenewed",
            ),
            (
                AuditEvent::StatusListFlipped(StatusListFlippedData {
                    purpose: "revocation".into(),
                    index: 0,
                    revoked: true,
                }),
                "StatusListFlipped",
            ),
            (
                AuditEvent::DidRotated(DidRotatedData {
                    old_did: "o".into(),
                    new_did: "n".into(),
                    method: "did:key".into(),
                    vmc_id: None,
                    role_vec_id: None,
                    prior_role: None,
                    rotation_reason: None,
                }),
                "DidRotated",
            ),
            (
                AuditEvent::RegistryStatusChanged(RegistryStatusChangedData {
                    from: "active".into(),
                    to: "degraded".into(),
                    reason: None,
                }),
                "RegistryStatusChanged",
            ),
            (
                AuditEvent::RegistrySyncSucceeded(RegistrySyncOutcomeData {
                    job_id: "j".into(),
                    kind: "publishMember".into(),
                    attempts: 1,
                    last_error: None,
                }),
                "RegistrySyncSucceeded",
            ),
            (
                AuditEvent::RegistrySyncFailed(RegistrySyncOutcomeData {
                    job_id: "j".into(),
                    kind: "deleteMember".into(),
                    attempts: 1,
                    last_error: Some("x".into()),
                }),
                "RegistrySyncFailed",
            ),
            (
                AuditEvent::RegistryRecordPolicyOverride(RegistryRecordPolicyOverrideData {
                    reason: "rtbf".into(),
                    attempted_disposition: "tombstone".into(),
                    effective_disposition: "purge".into(),
                }),
                "RegistryRecordPolicyOverride",
            ),
            (
                AuditEvent::CrossCommunitySessionMinted(CrossCommunitySessionMintedData {
                    outcome: "minted".into(),
                    foreign_issuer_did: "did:webvh:peer".into(),
                    foreign_role: Some("moderator".into()),
                    mapped_role: Some("monitor".into()),
                    ttl_seconds: Some(900),
                    reason: None,
                }),
                "CrossCommunitySessionMinted",
            ),
            (
                AuditEvent::VrcPublished(VrcPublishedData {
                    vrc_id: "id".into(),
                    subject_did: Some("did:key:zX".into()),
                    edge_type: "endorses".into(),
                }),
                "VrcPublished",
            ),
            (
                AuditEvent::VrcRevoked(VrcRevokedData {
                    vrc_id: "id".into(),
                    revoked_by: "admin".into(),
                }),
                "VrcRevoked",
            ),
            (
                AuditEvent::VrcSuspended(VrcLifecycleData {
                    vrc_id: "id".into(),
                    recorded_by: "issuer".into(),
                    reason: None,
                }),
                "VrcSuspended",
            ),
            (
                AuditEvent::VrcRestored(VrcLifecycleData {
                    vrc_id: "id".into(),
                    recorded_by: "issuer".into(),
                    reason: None,
                }),
                "VrcRestored",
            ),
            (
                AuditEvent::VrcSuperseded(VrcSupersededData {
                    vrc_id: "id".into(),
                    superseded_by_digest_multibase: "zQmNew".into(),
                }),
                "VrcSuperseded",
            ),
            (
                AuditEvent::VpcAttached(VpcAnnotationData {
                    vrc_id: "id".into(),
                    persona_did: "did:key:zPersona".into(),
                }),
                "VpcAttached",
            ),
            (
                AuditEvent::VpcDetached(VpcAnnotationData {
                    vrc_id: "id".into(),
                    persona_did: "did:key:zPersona".into(),
                }),
                "VpcDetached",
            ),
            (
                AuditEvent::PersonhoodAsserted(PersonhoodAssertedData {
                    vmc_id: "v".into(),
                    asserted_at: "2026-05-14T10:00:00Z".into(),
                }),
                "PersonhoodAsserted",
            ),
            (
                AuditEvent::PersonhoodRevoked(PersonhoodRevokedData {
                    vmc_id: Some("v".into()),
                    reason: "self".into(),
                }),
                "PersonhoodRevoked",
            ),
            (
                AuditEvent::CustomEndorsementIssued(CustomEndorsementIssuedData {
                    endorsement_id: "end".into(),
                    endorsement_type: "https://x/v1/t".into(),
                    status_list_index: 0,
                }),
                "CustomEndorsementIssued",
            ),
            (
                AuditEvent::CustomEndorsementRevoked(CustomEndorsementRevokedData {
                    endorsement_id: "end".into(),
                    endorsement_type: "https://x/v1/t".into(),
                }),
                "CustomEndorsementRevoked",
            ),
            (
                AuditEvent::EndorsementTypeRegistered(EndorsementTypeRegisteredData {
                    type_uri: "https://x/v1/t".into(),
                    description: None,
                }),
                "EndorsementTypeRegistered",
            ),
            (
                AuditEvent::EndorsementTypeDeleted(EndorsementTypeDeletedData {
                    type_uri: "https://x/v1/t".into(),
                    live_endorsements_at_delete: 0,
                }),
                "EndorsementTypeDeleted",
            ),
            (
                AuditEvent::WebsiteFileWritten(WebsiteFileWrittenData {
                    path: "index.html".into(),
                    size_bytes: 42,
                    sha256: "deadbeef".into(),
                }),
                "WebsiteFileWritten",
            ),
            (
                AuditEvent::WebsiteFileDeleted(WebsiteFileDeletedData {
                    path: "old.html".into(),
                }),
                "WebsiteFileDeleted",
            ),
            (
                AuditEvent::WebsiteBundleDeployed(WebsiteBundleDeployedData {
                    bundle_sha256: "deadbeef".into(),
                    bundle_size_bytes: 1024,
                    deploy_mode: "managed".into(),
                    target_generation: 7,
                    pruned_generations: 2,
                }),
                "WebsiteBundleDeployed",
            ),
            (
                AuditEvent::WebsiteGenerationRolledBack(WebsiteGenerationRolledBackData {
                    from_generation: 7,
                    to_generation: 5,
                }),
                "WebsiteGenerationRolledBack",
            ),
            (
                AuditEvent::AdminUiServed(AdminUiServedData {
                    index_sha256: "deadbeef".into(),
                    file_count: 3,
                    mode: "embedded".into(),
                    daemon_version: None,
                }),
                "AdminUiServed",
            ),
        ];
        for (event, expected) in cases {
            let v = serde_json::to_value(&event).unwrap();
            assert_eq!(v["type"], expected, "discriminator drift for {expected}");
        }
    }
}