sew-proto 0.11.6

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

use std::collections::BTreeMap;

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::api::channels::{ChannelType, Visibility};
use crate::api::compliance::{LegalHold, RetentionPolicy};
use crate::api::files::FileKind;
use crate::api::members::{AgentKind, InstallRole, MemberKind};
use crate::api::messages::ReferenceKind;
use crate::id::Id;
use crate::time::Timestamp;

/// Largest plaintext of one NDJSON part, HTML page or CSV file before it splits (32 MiB).
pub const PART_BYTES_DEFAULT: u64 = 32 * 1024 * 1024;

/// What the manifest lists as never exported.
pub const EXCLUDED: &[&str] = &[
    "keys",
    "keyring",
    "master_key",
    "passwords",
    "sessions",
    "secrets",
    "search_index",
    "change_logs",
    "jobs",
    "idempotency",
    "link_previews",
    "uploads",
    "exports",
];

/// `details.reason` values of archive readers (import, `--verify-only`, the archive reader
/// library).
pub mod reasons {
    /// The identity does not decrypt the archive header.
    pub const IDENTITY_MISMATCH: &str = "identity_mismatch";
    /// The identity file is not root-owned with mode ≤ 0600.
    pub const IDENTITY_UNSAFE: &str = "identity_unsafe";
    /// The archive is truncated, altered, or its entries do not match the trailer.
    pub const ARCHIVE_CORRUPT: &str = "archive_corrupt";
    /// `export_format` is not 1.
    pub const FORMAT_UNSUPPORTED: &str = "format_unsupported";
    /// `format_minor` is newer than this build reads.
    pub const FORMAT_TOO_NEW: &str = "format_too_new";
    /// An eDiscovery archive given to `sew import`.
    pub const NOT_A_FULL_EXPORT: &str = "not_a_full_export";
    /// The archive's identity provider differs from the target's.
    pub const PROVIDER_MISMATCH: &str = "provider_mismatch";
    /// The target install is not pristine.
    pub const TARGET_NOT_EMPTY: &str = "target_not_empty";
    /// Not enough free space.
    pub const STORAGE_FULL: &str = "storage_full";
    /// A record failed validation (entry and line in the details).
    pub const RECORD_INVALID: &str = "record_invalid";
    /// The loaded audit chain does not verify.
    pub const AUDIT_CHAIN_BROKEN: &str = "audit_chain_broken";
    /// The service is running (`systemctl stop sew` first).
    pub const SERVICE_RUNNING: &str = "service_running";
    /// Not run as root.
    pub const NOT_ROOT: &str = "not_root";
    /// The database service is not active.
    pub const DB_NOT_ACTIVE: &str = "db_not_active";
    /// The key mirror folder of the adopted install id already holds keys.
    pub const MIRROR_NOT_EMPTY: &str = "mirror_not_empty";
    /// The identity map file is invalid, or names an id, a Space or a person the archive
    /// does not hold, or two people map to one `local:` id.
    pub const IDENTITY_MAP_INVALID: &str = "identity_map_invalid";
    /// `--to-standalone` needs a `k2` archive and a standalone target (an identity map
    /// needs `--to-standalone`).
    pub const IDENTITY_MAP_NEEDS_STANDALONE: &str = "identity_map_needs_standalone";
}

unit_enum! {
    /// What an archive is.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum ExportKind {
        /// Everything, for a box move (mgmt only).
        Full = "full",
        /// A scoped compliance export.
        Ediscovery = "ediscovery",
    }
}

unit_enum! {
    /// Whether file bytes are in the archive.
    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum FileMode {
        /// `files/<file_id>` entries hold the plaintext bytes.
        #[default]
        Include = "include",
        /// Attachment records keep metadata only; no `files/` entries.
        ManifestOnly = "manifest_only",
    }
}

unit_enum! {
    /// How a member target selects messages in eDiscovery.
    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum MemberMode {
        /// Everything the member wrote or could read (the legal-hold member rule).
        #[default]
        Conversations = "conversations",
        /// Only what the member wrote.
        Authored = "authored",
    }
}

unit_enum! {
    /// Why a message was deleted.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum DeleteKind {
        /// Its author deleted it.
        Own = "own",
        /// A moderator deleted it.
        Moderator = "moderator",
        /// A moderator deleted its whole thread.
        Thread = "thread",
        /// Retention expired it.
        Retention = "retention",
        /// Its author's account was erased with its content (minor 11).
        Erased = "erased",
    }
}

unit_enum! {
    /// Why an attachment was removed.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum RemoveKind {
        /// Its uploader removed it.
        Own = "own",
        /// A moderator removed it.
        Moderator = "moderator",
        /// File retention removed it.
        Retention = "retention",
        /// Its uploader's account was erased with its content (minor 11).
        Erased = "erased",
    }
}

fn is_false(v: &bool) -> bool {
    !*v
}

// ---------------------------------------------------------------- manifest and trailer

/// Who wrote the archive.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Producer {
    /// `sew`, or a converter's name.
    pub name: String,
    /// The producer's version.
    pub version: String,
    /// The source schema version (highest applied migration).
    pub schema_version: u64,
}

/// What an archive holds beyond records.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ArchiveOptions {
    /// File bytes or metadata only.
    pub files: FileMode,
    /// Whether `view/` (HTML and CSV) is present.
    pub views: bool,
    /// Whether `audit.ndjson` is present.
    pub audit: bool,
}

/// An eDiscovery scope as recorded: ids, dates and a keyword count, never the keywords.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ArchiveScope {
    /// The requester's label.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
    /// Member targets.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub members: Vec<Id>,
    /// Channel targets.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub channels: Vec<Id>,
    /// Space targets.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub spaces: Vec<Id>,
    /// Legal holds whose selectors joined the scope.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub holds: Vec<Id>,
    /// Window start (inclusive) of the request's own selector.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub from: Option<Timestamp>,
    /// Window end (exclusive).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub to: Option<Timestamp>,
    /// How member targets select.
    pub member_mode: MemberMode,
    /// How many keywords filtered the scope (the words never leave the request).
    pub keyword_count: u32,
}

/// `manifest.json`, always the first entry.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Manifest {
    /// Always 1 for this format.
    pub export_format: u32,
    /// Additive revisions of format 1; readers refuse a higher one.
    pub format_minor: u32,
    /// Full or eDiscovery.
    pub kind: ExportKind,
    /// Who wrote it.
    pub producer: Producer,
    /// The export id (= the job id).
    pub export_id: Id,
    /// The source install; `null` only from a converter (import keeps the target's id).
    pub install_id: Option<Id>,
    /// The install's name (empty when the install has none).
    pub install_name: String,
    /// `k2` or `standalone`.
    pub identity_provider: String,
    /// The source `sync_epoch` (opaque decimal string).
    pub source_sync_epoch: String,
    /// When the export was requested.
    pub created_at: Timestamp,
    /// The snapshot every record was read from; also every tar entry's mtime.
    pub snapshot_at: Timestamp,
    /// Files, views, audit.
    pub options: ArchiveOptions,
    /// The eDiscovery scope; `null` for a full export (*always*).
    pub scope: Option<ArchiveScope>,
    /// Entity paths in tar order (message and revision parts as globs), not files or views.
    pub entries: Vec<String>,
    /// What is never exported.
    pub excluded: Vec<String>,
    /// The age recipients the archive is encrypted to.
    pub recipients: Vec<String>,
}

/// One entry in the trailer.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct TrailerEntry {
    /// The tar path.
    pub path: String,
    /// Its size.
    pub bytes: u64,
    /// SHA-256 of its bytes, 64 lowercase hex.
    pub sha256: String,
}

/// `trailer.json`, always the last entry.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Trailer {
    /// Every entry before this one, in tar order.
    pub entries: Vec<TrailerEntry>,
    /// Records per entity (and `files`).
    pub counts: BTreeMap<String, u64>,
    /// SHA-256 over `"<path>\t<bytes>\t<sha256>\n"` of every entry, in order, 64 hex.
    pub root_hash: String,
}

/// A converter's reference to the record it came from (ignored and not stored by Sew v1).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct SourceRef {
    /// The source system, e.g. `slack`.
    pub system: String,
    /// Its reference.
    #[serde(rename = "ref")]
    pub reference: String,
}

// ---------------------------------------------------------------- install and people

/// `install.ndjson`: one record.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct InstallRecord {
    /// The install id.
    pub install_id: Id,
    /// The install name (empty when unnamed).
    pub name: String,
    /// When the install was created.
    pub created_at: Timestamp,
    /// Org policy values by key (retention mirrors excluded).
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub policies: BTreeMap<String, serde_json::Value>,
    /// The id clock high-water mark (Unix ms).
    pub id_hwm_ms: u64,
    /// When the install moved from standalone to K2 identity (minor 7);
    /// omitted when it never did.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub identity_switched_at: Option<Timestamp>,
}

impl InstallRecord {
    /// An `InstallRecord` with its required fields: every count 0, every list empty and
    /// every optional field unset.
    pub fn new(install_id: Id, name: impl Into<String>, created_at: Timestamp) -> Self {
        InstallRecord {
            install_id,
            name: name.into(),
            created_at,
            policies: BTreeMap::new(),
            id_hwm_ms: 0,
            identity_switched_at: None,
        }
    }
}

/// `profile_fields.ndjson`: a custom profile field definition.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct ProfileFieldRecord {
    /// The field id.
    pub id: Id,
    /// Its key.
    pub key: String,
    /// Its label.
    pub label: String,
    /// `text`, `url`, `select`, `date`.
    pub kind: String,
    /// Select options.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub options: Option<serde_json::Value>,
    /// `member` or `provider`.
    pub managed_by: String,
    /// `everyone`, `non_guests`, `admins`.
    pub visibility: String,
    /// Order.
    pub position: u32,
    /// Created.
    pub created_at: Timestamp,
    /// Last change.
    pub updated_at: Timestamp,
    /// Soft-deleted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deleted_at: Option<Timestamp>,
    /// Converter reference.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<SourceRef>,
}

impl ProfileFieldRecord {
    /// A `ProfileFieldRecord` with its required fields: every count 0 and every optional
    /// field unset.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        id: Id,
        key: impl Into<String>,
        label: impl Into<String>,
        kind: impl Into<String>,
        managed_by: impl Into<String>,
        visibility: impl Into<String>,
        created_at: Timestamp,
        updated_at: Timestamp,
    ) -> Self {
        ProfileFieldRecord {
            id,
            key: key.into(),
            label: label.into(),
            kind: kind.into(),
            options: None,
            managed_by: managed_by.into(),
            visibility: visibility.into(),
            position: 0,
            created_at,
            updated_at,
            deleted_at: None,
            source: None,
        }
    }
}

/// A member's status in `members.ndjson`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct StatusRecord {
    /// The status text.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    /// The status emoji.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub emoji: Option<String>,
    /// When it clears.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<Timestamp>,
    /// When it was set.
    pub set_at: Timestamp,
}

impl StatusRecord {
    /// A `StatusRecord` with its required fields: every optional field unset.
    pub fn new(set_at: Timestamp) -> Self {
        StatusRecord {
            text: None,
            emoji: None,
            expires_at: None,
            set_at,
        }
    }
}

/// A member's avatar in `members.ndjson`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct AvatarRecord {
    /// The image (`files/<file>`; also the avatar link id).
    pub file: Id,
    /// The public avatar version id (in avatar URLs).
    pub avatar_id: Id,
    /// `member` or `provider`.
    pub source: String,
}

impl AvatarRecord {
    /// A `AvatarRecord` from all its fields.
    pub fn new(file: Id, avatar_id: Id, source: impl Into<String>) -> Self {
        AvatarRecord {
            file,
            avatar_id,
            source: source.into(),
        }
    }
}

/// `members.ndjson`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct MemberRecord {
    /// The member id.
    pub id: Id,
    /// The external id (`k2:principal:<uuid>`, `local:<name>`, `import:<system>:<id>`).
    pub external_id: String,
    /// Person or agent.
    pub kind: MemberKind,
    /// For agents.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_kind: Option<AgentKind>,
    /// For pinned assistants: their person.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub assistant_of: Option<Id>,
    /// When the assistant was pinned.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pinned_at: Option<Timestamp>,
    /// Install role.
    pub install_role: InstallRole,
    /// The compliance flag.
    pub compliance: bool,
    /// When the flag last changed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub compliance_set_at: Option<Timestamp>,
    /// Who changed it (absent for the mgmt service).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub compliance_set_by: Option<Id>,
    /// Handle.
    pub username: String,
    /// Display name.
    pub display_name: String,
    /// Email.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,
    /// Title.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Pronouns.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pronouns: Option<String>,
    /// IANA time zone.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timezone: Option<String>,
    /// Custom field values by field id.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub fields: BTreeMap<String, String>,
    /// Status.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status: Option<StatusRecord>,
    /// Avatar.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub avatar: Option<AvatarRecord>,
    /// Created.
    pub created_at: Timestamp,
    /// Deactivated.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deactivated_at: Option<Timestamp>,
    /// The `local:` id a relinked member had before its K2 id (minor 7);
    /// omitted when the member was never relinked.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub relinked_from: Option<String>,
    /// When the account was erased (minor 11); omitted for a member never erased. An erased
    /// member's `external_id` is `erased:<id>`, and the two always go together.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub erased_at: Option<Timestamp>,
    /// What the erase did with the content (minor 11); present exactly when `erased_at` is.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub erase_mode: Option<crate::mgmt::EraseMode>,
    /// The member change-log head (*always*; full exports).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub head_seq: Option<u64>,
    /// Converter reference.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<SourceRef>,
}

impl MemberRecord {
    /// A `MemberRecord` with its required fields: every flag `false`, every list empty and
    /// every optional field unset.
    pub fn new(
        id: Id,
        external_id: impl Into<String>,
        kind: MemberKind,
        install_role: InstallRole,
        username: impl Into<String>,
        display_name: impl Into<String>,
        created_at: Timestamp,
    ) -> Self {
        MemberRecord {
            id,
            external_id: external_id.into(),
            kind,
            agent_kind: None,
            assistant_of: None,
            pinned_at: None,
            install_role,
            compliance: false,
            compliance_set_at: None,
            compliance_set_by: None,
            username: username.into(),
            display_name: display_name.into(),
            email: None,
            title: None,
            pronouns: None,
            timezone: None,
            fields: BTreeMap::new(),
            status: None,
            avatar: None,
            created_at,
            deactivated_at: None,
            relinked_from: None,
            erased_at: None,
            erase_mode: None,
            head_seq: None,
            source: None,
        }
    }
}

/// `presence_settings.ndjson`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct PresenceSettingsRecord {
    /// The member.
    pub member_id: Id,
    /// `none`, `away`, `dnd`, `invisible`.
    pub manual: String,
    /// When a timed manual status ends.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub manual_until: Option<Timestamp>,
    /// The weekly DND schedule.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dnd_schedule: Option<serde_json::Value>,
    /// A skipped DND window ends.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dnd_skip_until: Option<Timestamp>,
    /// Last change.
    pub updated_at: Timestamp,
}

impl PresenceSettingsRecord {
    /// A `PresenceSettingsRecord` with its required fields: every optional field unset.
    pub fn new(member_id: Id, manual: impl Into<String>, updated_at: Timestamp) -> Self {
        PresenceSettingsRecord {
            member_id,
            manual: manual.into(),
            manual_until: None,
            dnd_schedule: None,
            dnd_skip_until: None,
            updated_at,
        }
    }
}

// ---------------------------------------------------------------- structure

/// `spaces.ndjson`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct SpaceRecord {
    /// The space id.
    pub id: Id,
    /// Slug.
    pub slug: String,
    /// Name.
    pub name: String,
    /// Owner.
    pub owner_id: Id,
    /// Creator.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub created_by: Option<Id>,
    /// The icon.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon: Option<IconRecord>,
    /// Created.
    pub created_at: Timestamp,
    /// `open` or `invite`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub join_policy: Option<String>,
    /// Default channels in their set order (minor 1).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub default_channel_ids: Vec<Id>,
    /// Description (minor 1).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Rules channel (minor 1).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rules_channel_id: Option<Id>,
    /// Welcome channel (minor 1).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub welcome_channel_id: Option<Id>,
    /// The App the space belongs to (minor 2).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub app_id: Option<String>,
    /// The participant Apps (minor 10, Sew 0.8.0): Apps whose sessions also see the Space,
    /// sorted; omitted when none. Only with `app_id`, never naming it, at most 8.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub participant_app_ids: Vec<String>,
    /// A hidden Space, such as the Meetings Space (minor 3); omitted when `false`.
    #[serde(default, skip_serializing_if = "is_false")]
    pub hidden: bool,
    /// A private Space (minor 6); omitted when `false`. Always invite-only.
    #[serde(default, skip_serializing_if = "is_false")]
    pub private: bool,
    /// The App an orphaned Space was unbound from (minor 7); omitted for a
    /// Space that is not an orphan. Never with `app_id`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub orphaned_from: Option<String>,
    /// Who governs the Space (minor 8); omitted for `sew`. `app` only with `app_id`.
    #[serde(
        default = "crate::api::spaces::SpaceGovernance::default_sew",
        skip_serializing_if = "crate::api::spaces::SpaceGovernance::is_sew"
    )]
    pub governance: crate::api::spaces::SpaceGovernance,
    /// Minor 12: the Space's own recording start level (over its governing App's); omitted
    /// when it inherits.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recording_start_level: Option<crate::recording::RecordingStartLevel>,
    /// Minor 12: the Space's own "record every call with more than one person"; omitted when
    /// it inherits.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recording_required: Option<bool>,
    /// Converter reference.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<SourceRef>,
}

impl SpaceRecord {
    /// A Space record with its required fields; every optional field unset, governance `sew`.
    pub fn new(id: Id, slug: String, name: String, owner_id: Id, created_at: Timestamp) -> Self {
        SpaceRecord {
            id,
            slug,
            name,
            owner_id,
            created_by: None,
            icon: None,
            created_at,
            join_policy: None,
            default_channel_ids: Vec::new(),
            description: None,
            rules_channel_id: None,
            welcome_channel_id: None,
            app_id: None,
            participant_app_ids: Vec::new(),
            hidden: false,
            private: false,
            orphaned_from: None,
            governance: crate::api::spaces::SpaceGovernance::Sew,
            recording_start_level: None,
            recording_required: None,
            source: None,
        }
    }
}

/// A space icon in `spaces.ndjson`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct IconRecord {
    /// The image (`files/<file>`).
    pub file: Id,
    /// The icon's own link id.
    pub link_id: Id,
    /// The public icon version id.
    pub icon_id: Id,
}

impl IconRecord {
    /// A `IconRecord` from all its fields.
    pub fn new(file: Id, link_id: Id, icon_id: Id) -> Self {
        IconRecord {
            file,
            link_id,
            icon_id,
        }
    }
}

/// `roles.ndjson` (the `@everyone` role has the space's id).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct RoleRecord {
    /// The role id.
    pub id: Id,
    /// Its space.
    pub space_id: Id,
    /// Name.
    pub name: String,
    /// Position (0 = `@everyone`).
    pub position: u32,
    /// Permission bits, decimal string.
    pub perms: String,
    /// RGB color.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub color: Option<u32>,
    /// Mentionable.
    pub mentionable: bool,
    /// Shown apart in member lists.
    pub hoist: bool,
    /// Created.
    pub created_at: Timestamp,
    /// Last change.
    pub updated_at: Timestamp,
    /// A managed role's level (minor 8: `moderator` or `admin`); omitted for every other
    /// role.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub managed: Option<crate::api::spaces::SpaceLevel>,
}

impl RoleRecord {
    /// A `RoleRecord` with its required fields: every count 0, every flag `false` and every
    /// optional field unset.
    pub fn new(
        id: Id,
        space_id: Id,
        name: impl Into<String>,
        perms: impl Into<String>,
        created_at: Timestamp,
        updated_at: Timestamp,
    ) -> Self {
        RoleRecord {
            id,
            space_id,
            name: name.into(),
            position: 0,
            perms: perms.into(),
            color: None,
            mentionable: false,
            hoist: false,
            created_at,
            updated_at,
            managed: None,
        }
    }
}

/// `space_members.ndjson`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct SpaceMemberRecord {
    /// The space.
    pub space_id: Id,
    /// The member.
    pub member_id: Id,
    /// Joined.
    pub joined_at: Timestamp,
    /// Who added them.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub added_by: Option<Id>,
    /// Roles held (not `@everyone`), ascending.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub role_ids: Vec<Id>,
    /// Timed out until.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timeout_until: Option<Timestamp>,
}

impl SpaceMemberRecord {
    /// A `SpaceMemberRecord` with its required fields: every list empty and every optional
    /// field unset.
    pub fn new(space_id: Id, member_id: Id, joined_at: Timestamp) -> Self {
        SpaceMemberRecord {
            space_id,
            member_id,
            joined_at,
            added_by: None,
            role_ids: Vec::new(),
            timeout_until: None,
        }
    }
}

/// `user_groups.ndjson`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct UserGroupRecord {
    /// The group id.
    pub id: Id,
    /// Its space; absent = install-wide.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub space_id: Option<Id>,
    /// Handle.
    pub handle: String,
    /// Name.
    pub name: String,
    /// Description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Mentionable.
    pub mentionable: bool,
    /// Members, ascending.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub member_ids: Vec<Id>,
    /// Creator.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub created_by: Option<Id>,
    /// Created.
    pub created_at: Timestamp,
    /// Last change.
    pub updated_at: Timestamp,
    /// Soft-deleted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deleted_at: Option<Timestamp>,
}

impl UserGroupRecord {
    /// A `UserGroupRecord` with its required fields: every flag `false`, every list empty
    /// and every optional field unset.
    pub fn new(
        id: Id,
        handle: impl Into<String>,
        name: impl Into<String>,
        created_at: Timestamp,
        updated_at: Timestamp,
    ) -> Self {
        UserGroupRecord {
            id,
            space_id: None,
            handle: handle.into(),
            name: name.into(),
            description: None,
            mentionable: false,
            member_ids: Vec::new(),
            created_by: None,
            created_at,
            updated_at,
            deleted_at: None,
        }
    }
}

/// A permission overwrite on a category or channel.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct OverwriteRecord {
    /// `role` or `member`.
    pub target_kind: String,
    /// The role or member.
    pub target_id: Id,
    /// Allowed bits, decimal string.
    pub allow: String,
    /// Denied bits, decimal string.
    pub deny: String,
}

impl OverwriteRecord {
    /// A `OverwriteRecord` from all its fields.
    pub fn new(
        target_kind: impl Into<String>,
        target_id: Id,
        allow: impl Into<String>,
        deny: impl Into<String>,
    ) -> Self {
        OverwriteRecord {
            target_kind: target_kind.into(),
            target_id,
            allow: allow.into(),
            deny: deny.into(),
        }
    }
}

/// `categories.ndjson`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct CategoryRecord {
    /// The category id.
    pub id: Id,
    /// Its space.
    pub space_id: Id,
    /// Name.
    pub name: String,
    /// Position.
    pub position: u32,
    /// Overwrites, by target.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub overwrites: Vec<OverwriteRecord>,
    /// Created.
    pub created_at: Timestamp,
}

impl CategoryRecord {
    /// A `CategoryRecord` with its required fields: every count 0 and every list empty.
    pub fn new(id: Id, space_id: Id, name: impl Into<String>, created_at: Timestamp) -> Self {
        CategoryRecord {
            id,
            space_id,
            name: name.into(),
            position: 0,
            overwrites: Vec::new(),
            created_at,
        }
    }
}

/// `channels.ndjson`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct ChannelRecord {
    /// The channel id.
    pub id: Id,
    /// Its space (absent for DMs).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub space_id: Option<Id>,
    /// Its category.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub category_id: Option<Id>,
    /// Type.
    #[serde(rename = "type")]
    pub kind: ChannelType,
    /// Public or private.
    pub visibility: Visibility,
    /// Slug.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub slug: Option<String>,
    /// Name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Topic.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub topic: Option<String>,
    /// Purpose.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub purpose: Option<String>,
    /// Position.
    pub position: u32,
    /// Overwrites follow the category.
    pub synced: bool,
    /// The channel's own overwrites (full exports).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub overwrites: Vec<OverwriteRecord>,
    /// Slow mode seconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub slow_mode_s: Option<u32>,
    /// DM and group DM members, in DM-key order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub dm_member_ids: Vec<Id>,
    /// Creator.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub created_by: Option<Id>,
    /// Created.
    pub created_at: Timestamp,
    /// Archived.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub archived_at: Option<Timestamp>,
    /// Archived by.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub archived_by: Option<Id>,
    /// The channel change-log head (*always* in full exports).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub head_seq: Option<u64>,
    /// Auto-record (voice channels).
    #[serde(default, skip_serializing_if = "is_false")]
    pub recording_auto: bool,
    /// The channel's default audio keep days.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recording_audio_days: Option<u16>,
    /// Declining means not joining (absent: the org policy).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recording_require_consent: Option<bool>,
    /// Minor 12: a voice channel's own "record every call with more than one person"; omitted
    /// when it inherits. Only on voice channels.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recording_required: Option<bool>,
    /// Minor 9: a voice room K2 is closing (archived when its last person
    /// leaves). Absent when `false`; never set on an archived channel.
    #[serde(default, skip_serializing_if = "is_false")]
    pub closing: bool,
    /// Minor 13: the members of this channel in a governed Space may leave it. Absent when
    /// `false` (and in older archives).
    #[serde(default, skip_serializing_if = "is_false")]
    pub members_can_leave: bool,
    /// Converter reference.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<SourceRef>,
}

impl ChannelRecord {
    /// A channel record with its required fields: position 0, not synced, every optional field
    /// unset.
    pub fn new(id: Id, kind: ChannelType, visibility: Visibility, created_at: Timestamp) -> Self {
        ChannelRecord {
            id,
            space_id: None,
            category_id: None,
            kind,
            visibility,
            slug: None,
            name: None,
            topic: None,
            purpose: None,
            position: 0,
            synced: false,
            overwrites: Vec::new(),
            slow_mode_s: None,
            dm_member_ids: Vec::new(),
            created_by: None,
            created_at,
            archived_at: None,
            archived_by: None,
            head_seq: None,
            recording_auto: false,
            recording_audio_days: None,
            recording_require_consent: None,
            recording_required: None,
            closing: false,
            members_can_leave: false,
            source: None,
        }
    }
}

/// `channel_members.ndjson`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct ChannelMemberRecord {
    /// The channel.
    pub channel_id: Id,
    /// The member.
    pub member_id: Id,
    /// Joined.
    pub joined_at: Timestamp,
    /// Who added them.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub added_by: Option<Id>,
}

impl ChannelMemberRecord {
    /// A `ChannelMemberRecord` with its required fields: every optional field unset.
    pub fn new(channel_id: Id, member_id: Id, joined_at: Timestamp) -> Self {
        ChannelMemberRecord {
            channel_id,
            member_id,
            joined_at,
            added_by: None,
        }
    }
}

/// `channel_past_members.ndjson`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct ChannelPastMemberRecord {
    /// The channel.
    pub channel_id: Id,
    /// The member.
    pub member_id: Id,
    /// When they left.
    pub left_at: Timestamp,
}

impl ChannelPastMemberRecord {
    /// A `ChannelPastMemberRecord` from all its fields.
    pub fn new(channel_id: Id, member_id: Id, left_at: Timestamp) -> Self {
        ChannelPastMemberRecord {
            channel_id,
            member_id,
            left_at,
        }
    }
}

/// `space_bans.ndjson` (full exports only): one space ban. The archive is
/// decrypted content, so `reason` is plain text inside the age-encrypted archive.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct SpaceBanRecord {
    /// The space.
    pub space_id: Id,
    /// The banned member.
    pub member_id: Id,
    /// When.
    pub banned_at: Timestamp,
    /// Who banned them.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub banned_by: Option<Id>,
    /// The reason, when one was given.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    /// The recent-message delete window chosen at ban time, seconds.
    pub delete_window_s: u32,
}

impl SpaceBanRecord {
    /// A `SpaceBanRecord` with its required fields: every count 0 and every optional field
    /// unset.
    pub fn new(space_id: Id, member_id: Id, banned_at: Timestamp) -> Self {
        SpaceBanRecord {
            space_id,
            member_id,
            banned_at,
            banned_by: None,
            reason: None,
            delete_window_s: 0,
        }
    }
}

/// `space_timeout_carry.ndjson` (full exports only): a running timeout of a
/// member who is not in the space, restored if they return before it ends.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct TimeoutCarryRecord {
    /// The space.
    pub space_id: Id,
    /// The member.
    pub member_id: Id,
    /// When the timeout ends.
    pub timeout_until: Timestamp,
}

impl TimeoutCarryRecord {
    /// A `TimeoutCarryRecord` from all its fields.
    pub fn new(space_id: Id, member_id: Id, timeout_until: Timestamp) -> Self {
        TimeoutCarryRecord {
            space_id,
            member_id,
            timeout_until,
        }
    }
}

/// `emoji.ndjson`: custom emoji (deleted ones keep their row so old tokens render).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct EmojiRecord {
    /// The emoji id.
    pub id: Id,
    /// Its space.
    pub space_id: Id,
    /// Primary name.
    pub name: String,
    /// Other live names.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub aliases: Vec<String>,
    /// Animated.
    pub animated: bool,
    /// Width (px).
    pub width: u32,
    /// Height (px).
    pub height: u32,
    /// The image (`files/<file>`; absent once deleted).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub file: Option<Id>,
    /// The image's own link id.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub link_id: Option<Id>,
    /// Creator.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub created_by: Option<Id>,
    /// Created.
    pub created_at: Timestamp,
    /// Last change.
    pub updated_at: Timestamp,
    /// Deleted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deleted_at: Option<Timestamp>,
    /// Deleted by.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deleted_by: Option<Id>,
}

impl EmojiRecord {
    /// An `EmojiRecord` with its required fields: every count 0, every flag `false`, every
    /// list empty and every optional field unset.
    pub fn new(
        id: Id,
        space_id: Id,
        name: impl Into<String>,
        created_at: Timestamp,
        updated_at: Timestamp,
    ) -> Self {
        EmojiRecord {
            id,
            space_id,
            name: name.into(),
            aliases: Vec::new(),
            animated: false,
            width: 0,
            height: 0,
            file: None,
            link_id: None,
            created_by: None,
            created_at,
            updated_at,
            deleted_at: None,
            deleted_by: None,
        }
    }
}

// ---------------------------------------------------------------- messages

/// A message's reference.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct ReferenceRecord {
    /// Reply, quote or forward.
    pub kind: ReferenceKind,
    /// The referenced message.
    pub message_id: Id,
    /// Its channel.
    pub channel_id: Id,
    /// Forward: the original author.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub forward_author_id: Option<Id>,
    /// Forward: when the original was posted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub forward_created_at: Option<Timestamp>,
    /// Forward: the copied text.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub forward_body: Option<String>,
    /// Forward: the copied text's key is shredded.
    #[serde(default, skip_serializing_if = "is_false")]
    pub forward_unreadable: bool,
}

impl ReferenceRecord {
    /// A `ReferenceRecord` with its required fields: every flag `false` and every optional
    /// field unset.
    pub fn new(kind: ReferenceKind, message_id: Id, channel_id: Id) -> Self {
        ReferenceRecord {
            kind,
            message_id,
            channel_id,
            forward_author_id: None,
            forward_created_at: None,
            forward_body: None,
            forward_unreadable: false,
        }
    }
}

/// Who a message (or revision) mentions.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct MentionsRecord {
    /// Members.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub members: Vec<Id>,
    /// Roles.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub roles: Vec<Id>,
    /// User groups.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub groups: Vec<Id>,
    /// `@channel`.
    #[serde(default, skip_serializing_if = "is_false")]
    pub channel: bool,
    /// `@here`.
    #[serde(default, skip_serializing_if = "is_false")]
    pub here: bool,
}

impl MentionsRecord {
    /// Whether nothing is mentioned.
    pub fn is_empty(&self) -> bool {
        self.members.is_empty()
            && self.roles.is_empty()
            && self.groups.is_empty()
            && !self.channel
            && !self.here
    }
}

/// A message's deletion.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct DeletedRecord {
    /// When.
    pub at: Timestamp,
    /// By whom (absent for retention).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub by: Option<Id>,
    /// Why.
    pub kind: DeleteKind,
}

impl DeletedRecord {
    /// A `DeletedRecord` with its required fields: every optional field unset.
    pub fn new(at: Timestamp, kind: DeleteKind) -> Self {
        DeletedRecord { at, by: None, kind }
    }
}

/// A pin.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct PinRecord {
    /// Who pinned.
    pub by: Id,
    /// When.
    pub at: Timestamp,
}

impl PinRecord {
    /// A `PinRecord` from all its fields.
    pub fn new(by: Id, at: Timestamp) -> Self {
        PinRecord { by, at }
    }
}

/// One emoji's reactions (current state).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct ReactionRecord {
    /// The emoji key: `u:<unicode>` or `c:<custom emoji id>`.
    pub emoji: String,
    /// Who reacted, in reaction order.
    pub member_ids: Vec<Id>,
    /// When each reacted (same order as `member_ids`).
    pub at: Vec<Timestamp>,
}

impl ReactionRecord {
    /// A `ReactionRecord` with its required fields: every list empty.
    pub fn new(emoji: impl Into<String>) -> Self {
        ReactionRecord {
            emoji: emoji.into(),
            member_ids: Vec::new(),
            at: Vec::new(),
        }
    }
}

/// An attachment's removal.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct RemovedRecord {
    /// When.
    pub at: Timestamp,
    /// By whom.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub by: Option<Id>,
    /// Why.
    pub kind: RemoveKind,
}

impl RemovedRecord {
    /// A `RemovedRecord` with its required fields: every optional field unset.
    pub fn new(at: Timestamp, kind: RemoveKind) -> Self {
        RemovedRecord { at, by: None, kind }
    }
}

/// An attachment (its id is also its file link id).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct AttachmentRecord {
    /// The attachment id.
    pub id: Id,
    /// Order on the message, 0–9.
    pub position: u32,
    /// Uploader.
    pub uploader_id: Id,
    /// File name (absent when purged or unreadable).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub filename: Option<String>,
    /// The name's key is shredded.
    #[serde(default, skip_serializing_if = "is_false")]
    pub unreadable: bool,
    /// Sniffed content type.
    pub content_type: String,
    /// Kind.
    pub kind: FileKind,
    /// Shown inline.
    pub inline: bool,
    /// Plaintext size.
    pub size: u64,
    /// Width (images, video).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub width: Option<u32>,
    /// Height (images, video).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub height: Option<u32>,
    /// Animated.
    #[serde(default, skip_serializing_if = "is_false")]
    pub animated: bool,
    /// The attachment it was forwarded from.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_attachment_id: Option<Id>,
    /// Created.
    pub created_at: Timestamp,
    /// Removed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub removed: Option<RemovedRecord>,
    /// Purged.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub purged_at: Option<Timestamp>,
    /// The bytes (`files/<file>`); absent when purged or with `files: manifest_only`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub file: Option<Id>,
}

impl AttachmentRecord {
    /// An `AttachmentRecord` with its required fields: every count 0, every flag `false` and
    /// every optional field unset.
    pub fn new(
        id: Id,
        uploader_id: Id,
        content_type: impl Into<String>,
        kind: FileKind,
        created_at: Timestamp,
    ) -> Self {
        AttachmentRecord {
            id,
            position: 0,
            uploader_id,
            filename: None,
            unreadable: false,
            content_type: content_type.into(),
            kind,
            inline: false,
            size: 0,
            width: None,
            height: None,
            animated: false,
            source_attachment_id: None,
            created_at,
            removed: None,
            purged_at: None,
            file: None,
        }
    }
}

/// A poll option.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct PollOptionRecord {
    /// The option row id.
    pub id: Id,
    /// 0-based index.
    pub index: u32,
    /// Text (absent when purged or unreadable).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    /// Voters (absent in eDiscovery for anonymous polls).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub voter_ids: Vec<Id>,
    /// When each voted (same order as `voter_ids`).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub voted_at: Vec<Timestamp>,
    /// Votes (*always*).
    pub count: u64,
}

impl PollOptionRecord {
    /// A `PollOptionRecord` with its required fields: every count 0, every list empty and
    /// every optional field unset.
    pub fn new(id: Id) -> Self {
        PollOptionRecord {
            id,
            index: 0,
            text: None,
            voter_ids: Vec::new(),
            voted_at: Vec::new(),
            count: 0,
        }
    }
}

/// A poll on its message.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct PollRecord {
    /// The question (absent when purged or unreadable).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub question: Option<String>,
    /// The poll text's key is shredded.
    #[serde(default, skip_serializing_if = "is_false")]
    pub unreadable: bool,
    /// Options in order.
    pub options: Vec<PollOptionRecord>,
    /// Choices per voter.
    pub max_choices: u32,
    /// Anonymous.
    pub anonymous: bool,
    /// `always` or `after_close`.
    pub results_visibility: String,
    /// Timed close.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub closes_at: Option<Timestamp>,
    /// Closed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub closed_at: Option<Timestamp>,
    /// Closed by.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub closed_by: Option<Id>,
    /// Created.
    pub created_at: Timestamp,
}

impl PollRecord {
    /// A `PollRecord` with its required fields: every count 0, every flag `false`, every
    /// list empty and every optional field unset.
    pub fn new(results_visibility: impl Into<String>, created_at: Timestamp) -> Self {
        PollRecord {
            question: None,
            unreadable: false,
            options: Vec::new(),
            max_choices: 0,
            anonymous: false,
            results_visibility: results_visibility.into(),
            closes_at: None,
            closed_at: None,
            closed_by: None,
            created_at,
        }
    }
}

/// `messages/<channel_id>/<part>.ndjson`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct MessageRecord {
    /// The message id (`id_to_time(id) == created_at`).
    pub id: Id,
    /// Its channel.
    pub channel_id: Id,
    /// Author.
    pub author_id: Id,
    /// For assistant posts: the person.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub on_behalf_of: Option<Id>,
    /// For assistant posts (minor 5): whether the person approved the post. Absent in
    /// older archives, where an on-behalf post imports as pending.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub on_behalf_approval: Option<crate::api::messages::OnBehalfApproval>,
    /// The thread root, for replies.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub thread_root_id: Option<Id>,
    /// A reply also sent to the channel.
    #[serde(default, skip_serializing_if = "is_false")]
    pub also_in_channel: bool,
    /// Reply, quote or forward reference.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reference: Option<ReferenceRecord>,
    /// The body as stored (markdown); absent when purged or unreadable.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
    /// Edit version (0 = never edited).
    pub version: u32,
    /// The channel seq of the message's latest change (full exports).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub seq: Option<u64>,
    /// Mentions (absent when purged).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mentions: Option<MentionsRecord>,
    /// Usable custom emoji ids of the body, ascending.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub custom_emoji_ids: Vec<Id>,
    /// Link previews turned off.
    #[serde(default, skip_serializing_if = "is_false")]
    pub previews_suppressed: bool,
    /// Created.
    pub created_at: Timestamp,
    /// Last edited.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub edited_at: Option<Timestamp>,
    /// Deleted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deleted: Option<DeletedRecord>,
    /// Purged (content destroyed).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub purged_at: Option<Timestamp>,
    /// The body's key is shredded.
    #[serde(default, skip_serializing_if = "is_false")]
    pub unreadable: bool,
    /// Pinned.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pin: Option<PinRecord>,
    /// Reactions (current).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub reactions: Vec<ReactionRecord>,
    /// Attachments (removed ones included).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub attachments: Vec<AttachmentRecord>,
    /// A poll.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub poll: Option<PollRecord>,
    /// eDiscovery: a thread root added so a reviewer can read an included reply.
    #[serde(default, skip_serializing_if = "is_false")]
    pub context: bool,
    /// eDiscovery with keywords: a keyword matched.
    #[serde(default, skip_serializing_if = "is_false")]
    pub matched: bool,
    /// Converter reference.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<SourceRef>,
}

impl MessageRecord {
    /// A `MessageRecord` with its required fields: every count 0, every flag `false`, every
    /// list empty and every optional field unset.
    pub fn new(id: Id, channel_id: Id, author_id: Id, created_at: Timestamp) -> Self {
        MessageRecord {
            id,
            channel_id,
            author_id,
            on_behalf_of: None,
            on_behalf_approval: None,
            thread_root_id: None,
            also_in_channel: false,
            reference: None,
            body: None,
            version: 0,
            seq: None,
            mentions: None,
            custom_emoji_ids: Vec::new(),
            previews_suppressed: false,
            created_at,
            edited_at: None,
            deleted: None,
            purged_at: None,
            unreadable: false,
            pin: None,
            reactions: Vec::new(),
            attachments: Vec::new(),
            poll: None,
            context: false,
            matched: false,
            source: None,
        }
    }
}

/// `revisions/<channel_id>/<part>.ndjson`: edit history.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct RevisionRecord {
    /// The revision row id.
    pub id: Id,
    /// The message.
    pub message_id: Id,
    /// Its channel.
    pub channel_id: Id,
    /// The version this body was.
    pub version: u32,
    /// The body (absent when purged or unreadable).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
    /// Mentions of that version.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mentions: Option<MentionsRecord>,
    /// When the version was written.
    pub created_at: Timestamp,
    /// When it was replaced.
    pub replaced_at: Timestamp,
    /// The body was purged.
    #[serde(default, skip_serializing_if = "is_false")]
    pub purged: bool,
    /// The body's key is shredded.
    #[serde(default, skip_serializing_if = "is_false")]
    pub unreadable: bool,
}

impl RevisionRecord {
    /// A `RevisionRecord` with its required fields: every count 0, every flag `false` and
    /// every optional field unset.
    pub fn new(
        id: Id,
        message_id: Id,
        channel_id: Id,
        created_at: Timestamp,
        replaced_at: Timestamp,
    ) -> Self {
        RevisionRecord {
            id,
            message_id,
            channel_id,
            version: 0,
            body: None,
            mentions: None,
            created_at,
            replaced_at,
            purged: false,
            unreadable: false,
        }
    }
}

/// `bookmarks.ndjson`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct BookmarkRecord {
    /// The bookmark id.
    pub id: Id,
    /// Its channel.
    pub channel_id: Id,
    /// Order.
    pub position: u32,
    /// The decrypted bookmark object (`{title, url, emoji?}`); absent when unreadable.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub data: Option<serde_json::Value>,
    /// Creator.
    pub created_by: Id,
    /// Created.
    pub created_at: Timestamp,
    /// Last change.
    pub updated_at: Timestamp,
}

impl BookmarkRecord {
    /// A `BookmarkRecord` with its required fields: every count 0 and every optional field
    /// unset.
    pub fn new(
        id: Id,
        channel_id: Id,
        created_by: Id,
        created_at: Timestamp,
        updated_at: Timestamp,
    ) -> Self {
        BookmarkRecord {
            id,
            channel_id,
            position: 0,
            data: None,
            created_by,
            created_at,
            updated_at,
        }
    }
}

/// `thread_follows.ndjson`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct ThreadFollowRecord {
    /// The member.
    pub member_id: Id,
    /// The thread root.
    pub root_id: Id,
    /// Its channel.
    pub channel_id: Id,
    /// `following` or `unfollowed`.
    pub state: String,
    /// `root_author`, `replied`, `mentioned`, `manual`.
    pub reason: String,
    /// Last change.
    pub followed_at: Timestamp,
}

impl ThreadFollowRecord {
    /// A `ThreadFollowRecord` from all its fields.
    pub fn new(
        member_id: Id,
        root_id: Id,
        channel_id: Id,
        state: impl Into<String>,
        reason: impl Into<String>,
        followed_at: Timestamp,
    ) -> Self {
        ThreadFollowRecord {
            member_id,
            root_id,
            channel_id,
            state: state.into(),
            reason: reason.into(),
            followed_at,
        }
    }
}

/// `read_states.ndjson` (full exports only): the channel read cursors.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct ReadStateRecord {
    /// The member.
    pub member_id: Id,
    /// The channel.
    pub channel_id: Id,
    /// The cursor (a comparator; mark-unread writes `message_id - 1`). Absent = nothing read.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_read_id: Option<Id>,
    /// Last move.
    pub updated_at: Timestamp,
}

impl ReadStateRecord {
    /// A `ReadStateRecord` with its required fields: every optional field unset.
    pub fn new(member_id: Id, channel_id: Id, updated_at: Timestamp) -> Self {
        ReadStateRecord {
            member_id,
            channel_id,
            last_read_id: None,
            updated_at,
        }
    }
}

/// `thread_reads.ndjson` (full exports only): the thread read cursors.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct ThreadReadRecord {
    /// The member.
    pub member_id: Id,
    /// The thread root.
    pub root_id: Id,
    /// Its channel.
    pub channel_id: Id,
    /// The cursor (≥ the root id).
    pub last_read_id: Id,
    /// Last move.
    pub updated_at: Timestamp,
}

impl ThreadReadRecord {
    /// A `ThreadReadRecord` from all its fields.
    pub fn new(
        member_id: Id,
        root_id: Id,
        channel_id: Id,
        last_read_id: Id,
        updated_at: Timestamp,
    ) -> Self {
        ThreadReadRecord {
            member_id,
            root_id,
            channel_id,
            last_read_id,
            updated_at,
        }
    }
}

/// `dm_seen.ndjson` (full exports only, since minor 14): the seen positions of DM members
/// (read receipts).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct DmSeenRecord {
    /// The DM or group DM.
    pub channel_id: Id,
    /// The member.
    pub member_id: Id,
    /// Seen up to here (a comparator).
    pub seen_id: Id,
    /// Last move.
    pub seen_at: Timestamp,
}

impl DmSeenRecord {
    /// A record.
    pub fn new(channel_id: Id, member_id: Id, seen_id: Id, seen_at: Timestamp) -> Self {
        DmSeenRecord {
            channel_id,
            member_id,
            seen_id,
            seen_at,
        }
    }
}

/// `read_receipt_prefs.ndjson` (full exports only, since minor 14): members' read-receipt
/// settings. Only members who set it have a record; no record means `share: true`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct ReadReceiptPrefRecord {
    /// The member.
    pub member_id: Id,
    /// The member shares their read receipts.
    pub share: bool,
    /// Last change.
    pub updated_at: Timestamp,
}

impl ReadReceiptPrefRecord {
    /// A record.
    pub fn new(member_id: Id, share: bool, updated_at: Timestamp) -> Self {
        ReadReceiptPrefRecord {
            member_id,
            share,
            updated_at,
        }
    }
}

/// `mentions.ndjson`: the mention inbox.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct MentionRecord {
    /// The member.
    pub member_id: Id,
    /// The channel.
    pub channel_id: Id,
    /// The message.
    pub message_id: Id,
    /// The thread root.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub root_id: Option<Id>,
    /// The notification reason code (1 mention … 6 dm).
    pub reason: u32,
    /// Written.
    pub created_at: Timestamp,
}

impl MentionRecord {
    /// A `MentionRecord` with its required fields: every count 0 and every optional field
    /// unset.
    pub fn new(member_id: Id, channel_id: Id, message_id: Id, created_at: Timestamp) -> Self {
        MentionRecord {
            member_id,
            channel_id,
            message_id,
            root_id: None,
            reason: 0,
            created_at,
        }
    }
}

/// `saved_items.ndjson` (full exports only).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct SavedItemRecord {
    /// The saved item id.
    pub id: Id,
    /// Its member.
    pub member_id: Id,
    /// The message.
    pub message_id: Id,
    /// Its channel.
    pub channel_id: Id,
    /// `active`, `done`, `archived`.
    pub state: String,
    /// The member's note.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
    /// Created.
    pub created_at: Timestamp,
    /// Last change.
    pub updated_at: Timestamp,
    /// Last state change.
    pub state_changed_at: Timestamp,
}

impl SavedItemRecord {
    /// A `SavedItemRecord` with its required fields: every optional field unset.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        id: Id,
        member_id: Id,
        message_id: Id,
        channel_id: Id,
        state: impl Into<String>,
        created_at: Timestamp,
        updated_at: Timestamp,
        state_changed_at: Timestamp,
    ) -> Self {
        SavedItemRecord {
            id,
            member_id,
            message_id,
            channel_id,
            state: state.into(),
            note: None,
            created_at,
            updated_at,
            state_changed_at,
        }
    }
}

/// `reminders.ndjson` (full exports only).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct ReminderRecord {
    /// The reminder id.
    pub id: Id,
    /// Its member.
    pub member_id: Id,
    /// The message (message reminders).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message_id: Option<Id>,
    /// The message's channel.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub channel_id: Option<Id>,
    /// The note (free-text reminders).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
    /// When it is due.
    pub at: Timestamp,
    /// IANA zone it was set in.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timezone: Option<String>,
    /// `pending`, `fired`, `done`.
    pub state: String,
    /// Fired.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fired_at: Option<Timestamp>,
    /// Done.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub done_at: Option<Timestamp>,
    /// Snoozes so far.
    pub snooze_count: u32,
    /// Row version.
    pub version: u32,
    /// Created.
    pub created_at: Timestamp,
    /// Last change.
    pub updated_at: Timestamp,
}

impl ReminderRecord {
    /// A `ReminderRecord` with its required fields: every count 0 and every optional field
    /// unset.
    pub fn new(
        id: Id,
        member_id: Id,
        at: Timestamp,
        state: impl Into<String>,
        created_at: Timestamp,
        updated_at: Timestamp,
    ) -> Self {
        ReminderRecord {
            id,
            member_id,
            message_id: None,
            channel_id: None,
            note: None,
            at,
            timezone: None,
            state: state.into(),
            fired_at: None,
            done_at: None,
            snooze_count: 0,
            version: 0,
            created_at,
            updated_at,
        }
    }
}

/// `drafts.ndjson` (full exports only; drafts holding only pending uploads are not carried).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct DraftRecord {
    /// The draft id.
    pub id: Id,
    /// Its member.
    pub member_id: Id,
    /// Its channel.
    pub channel_id: Id,
    /// Its thread.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub thread_root_id: Option<Id>,
    /// Reply also to the channel.
    #[serde(default, skip_serializing_if = "is_false")]
    pub also_send_to_channel: bool,
    /// The text.
    pub body: String,
    /// Draft revision.
    pub rev: u32,
    /// Created.
    pub created_at: Timestamp,
    /// Last change (its seal month).
    pub updated_at: Timestamp,
}

impl DraftRecord {
    /// A `DraftRecord` with its required fields: every count 0, every flag `false` and
    /// every optional field unset.
    pub fn new(
        id: Id,
        member_id: Id,
        channel_id: Id,
        body: impl Into<String>,
        created_at: Timestamp,
        updated_at: Timestamp,
    ) -> Self {
        DraftRecord {
            id,
            member_id,
            channel_id,
            thread_root_id: None,
            also_send_to_channel: false,
            body: body.into(),
            rev: 0,
            created_at,
            updated_at,
        }
    }
}

/// `scheduled.ndjson`: pending and failed scheduled messages (full exports only).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct ScheduledRecord {
    /// The scheduled message id.
    pub id: Id,
    /// Its author.
    pub member_id: Id,
    /// Its channel.
    pub channel_id: Id,
    /// Its thread.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub thread_root_id: Option<Id>,
    /// Reply also to the channel.
    #[serde(default, skip_serializing_if = "is_false")]
    pub also_send_to_channel: bool,
    /// The text.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
    /// When it sends.
    pub send_at: Timestamp,
    /// IANA zone it was set in.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timezone: Option<String>,
    /// `pending` or `failed`.
    pub state: String,
    /// Failure code (1–13).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fail_reason: Option<u32>,
    /// Failed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub failed_at: Option<Timestamp>,
    /// Row version.
    pub version: u32,
    /// Created.
    pub created_at: Timestamp,
    /// Last change (its seal month).
    pub updated_at: Timestamp,
}

impl ScheduledRecord {
    /// A `ScheduledRecord` with its required fields: every count 0, every flag `false` and
    /// every optional field unset.
    pub fn new(
        id: Id,
        member_id: Id,
        channel_id: Id,
        send_at: Timestamp,
        state: impl Into<String>,
        created_at: Timestamp,
        updated_at: Timestamp,
    ) -> Self {
        ScheduledRecord {
            id,
            member_id,
            channel_id,
            thread_root_id: None,
            also_send_to_channel: false,
            body: None,
            send_at,
            timezone: None,
            state: state.into(),
            fail_reason: None,
            failed_at: None,
            version: 0,
            created_at,
            updated_at,
        }
    }
}

/// `notify_prefs.ndjson`: one record per member with notification settings or explicit
/// channel or space prefs. DND lives in `presence_settings.ndjson`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct NotifyPrefsRecord {
    /// The member.
    pub member_id: Id,
    /// The member's settings row (absent: every default).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub settings: Option<NotifySettingsRecord>,
    /// Explicit channel and DM prefs, by channel id.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub channel_prefs: Vec<NotifyChannelPrefRecord>,
    /// Explicit space levels, by space id.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub space_prefs: Vec<NotifySpacePrefRecord>,
}

impl NotifyPrefsRecord {
    /// A `NotifyPrefsRecord` with its required fields: every list empty and every optional
    /// field unset.
    pub fn new(member_id: Id) -> Self {
        NotifyPrefsRecord {
            member_id,
            settings: None,
            channel_prefs: Vec::new(),
            space_prefs: Vec::new(),
        }
    }
}

/// A member's notification settings (`notify_prefs.settings`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct NotifySettingsRecord {
    /// `all`, `mentions` or `none` (absent: inherit the install default).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_level: Option<String>,
    /// Followed-thread replies notify.
    pub thread_replies: bool,
    /// `@here`/`@channel`/`@everyone` notify.
    pub broad_mentions: bool,
    /// Mentions still notify in a muted channel.
    pub mute_lets_mentions: bool,
    /// `off`, `15m`, `1h` or `1d`.
    pub digest_interval: String,
    /// The normalized keyword list, decrypted (absent: none, or its key is shredded).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub keywords: Vec<String>,
    /// Settings revision (`if_rev`).
    pub rev: u32,
    /// Last change.
    pub updated_at: Timestamp,
}

impl NotifySettingsRecord {
    /// A `NotifySettingsRecord` with its required fields: every count 0, every flag
    /// `false`, every list empty and every optional field unset.
    pub fn new(digest_interval: impl Into<String>, updated_at: Timestamp) -> Self {
        NotifySettingsRecord {
            default_level: None,
            thread_replies: false,
            broad_mentions: false,
            mute_lets_mentions: false,
            digest_interval: digest_interval.into(),
            keywords: Vec::new(),
            rev: 0,
            updated_at,
        }
    }
}

/// One explicit channel or DM pref (`notify_prefs.channel_prefs`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct NotifyChannelPrefRecord {
    /// The channel.
    pub channel_id: Id,
    /// `all`, `mentions` or `none` (absent: inherit).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub level: Option<String>,
    /// Muted.
    #[serde(default, skip_serializing_if = "is_false")]
    pub muted: bool,
    /// When a timed mute ends.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub muted_until: Option<Timestamp>,
    /// Last change.
    pub updated_at: Timestamp,
}

impl NotifyChannelPrefRecord {
    /// A `NotifyChannelPrefRecord` with its required fields: every flag `false` and every
    /// optional field unset.
    pub fn new(channel_id: Id, updated_at: Timestamp) -> Self {
        NotifyChannelPrefRecord {
            channel_id,
            level: None,
            muted: false,
            muted_until: None,
            updated_at,
        }
    }
}

/// One explicit space level (`notify_prefs.space_prefs`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct NotifySpacePrefRecord {
    /// The space.
    pub space_id: Id,
    /// `all`, `mentions` or `none`.
    pub level: String,
    /// Last change.
    pub updated_at: Timestamp,
}

impl NotifySpacePrefRecord {
    /// A `NotifySpacePrefRecord` from all its fields.
    pub fn new(space_id: Id, level: impl Into<String>, updated_at: Timestamp) -> Self {
        NotifySpacePrefRecord {
            space_id,
            level: level.into(),
            updated_at,
        }
    }
}

/// `audit.ndjson`: one audit row, or (`pending`) one outbox row not chained at the snapshot.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct AuditRecord {
    /// The chain position (absent for pending rows).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub chain_seq: Option<u64>,
    /// Previous hash, hex (absent for pending rows).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prev_hash: Option<String>,
    /// This row's hash, hex (absent for pending rows).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hash: Option<String>,
    /// An outbox row.
    #[serde(default, skip_serializing_if = "is_false")]
    pub pending: bool,
    /// The exact canonical event string that was hashed.
    pub event_json: String,
}

impl AuditRecord {
    /// An `AuditRecord` with its required fields: every flag `false` and every optional
    /// field unset.
    pub fn new(event_json: impl Into<String>) -> Self {
        AuditRecord {
            chain_seq: None,
            prev_hash: None,
            hash: None,
            pending: false,
            event_json: event_json.into(),
        }
    }
}

/// `retention_policies.ndjson` (the retention API's wire shape).
pub type RetentionPolicyRecord = RetentionPolicy;
/// `legal_holds.ndjson`, `holds_in_scope.ndjson` (the legal hold API's wire shape).
pub type LegalHoldRecord = LegalHold;

/// Every entity entry name, in tar order. Message and revision parts use the
/// `messages/` and `revisions/` prefixes.
pub const ENTITY_ORDER: &[&str] = &[
    "install.ndjson",
    "profile_fields.ndjson",
    "members.ndjson",
    "presence_settings.ndjson",
    "spaces.ndjson",
    "roles.ndjson",
    "space_members.ndjson",
    "space_bans.ndjson",
    "space_timeout_carry.ndjson",
    "user_groups.ndjson",
    "categories.ndjson",
    "channels.ndjson",
    "channel_members.ndjson",
    "channel_past_members.ndjson",
    "emoji.ndjson",
    "messages/*/*.ndjson",
    "revisions/*/*.ndjson",
    "bookmarks.ndjson",
    "thread_follows.ndjson",
    "read_states.ndjson",
    "thread_reads.ndjson",
    "mentions.ndjson",
    "saved_items.ndjson",
    "reminders.ndjson",
    "drafts.ndjson",
    "scheduled.ndjson",
    "recordings.ndjson",
    "notify_prefs.ndjson",
    "retention_policies.ndjson",
    "legal_holds.ndjson",
    "holds_in_scope.ndjson",
    "audit.ndjson",
];

// ---------------------------------------------------------------- recordings

coded_enum! {
    /// A recording segment's state (`recording_segments.state`).
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum SegmentState {
        /// Stored; awaiting transcription.
        Stored = "stored" => 1,
        /// Transcribed.
        Transcribed = "transcribed" => 2,
        /// No speech.
        Empty = "empty" => 3,
        /// Transcription failed (or the audio went first).
        Failed = "failed" => 4,
        /// Every piece posted.
        Posted = "posted" => 5,
    }
}

coded_enum! {
    /// Why a recorder run ended (`recording_runs.end_reason`).
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum RunEnd {
        /// The recording stopped.
        Stopped = "stopped" => 1,
        /// The recorder restarted.
        Restarted = "restarted" => 2,
        /// The recorder rejoined with a new admit.
        Reconnected = "reconnected" => 3,
        /// The run failed.
        Failed = "failed" => 4,
    }
}

/// One participant's consent record (`recording_participants`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct RecordingParticipantRecord {
    /// The member.
    pub member_id: Id,
    /// What the person said.
    pub consent: crate::recording::Consent,
    /// Where they said it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub via: Option<crate::recording::ConsentVia>,
    /// Whether their audio was captured.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capture: Option<crate::recording::Capture>,
    /// Why not, when not recorded.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capture_reason: Option<crate::recording::NotRecordedReason>,
    /// First seen.
    pub first_at: Timestamp,
    /// When they answered.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub answered_at: Option<Timestamp>,
    /// Last change.
    pub updated_at: Timestamp,
    /// In the room at the snapshot.
    #[serde(default, skip_serializing_if = "is_false")]
    pub in_room: bool,
    /// Ever granted.
    #[serde(default, skip_serializing_if = "is_false")]
    pub ever_granted: bool,
    /// The prompt version the answer echoed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub notice_version: Option<u64>,
    /// The surface of the answer.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub surface: Option<crate::recording::ConsentSurface>,
}

impl RecordingParticipantRecord {
    /// A `RecordingParticipantRecord` with its required fields: every flag `false` and
    /// every optional field unset.
    pub fn new(
        member_id: Id,
        consent: crate::recording::Consent,
        first_at: Timestamp,
        updated_at: Timestamp,
    ) -> Self {
        RecordingParticipantRecord {
            member_id,
            consent,
            via: None,
            capture: None,
            capture_reason: None,
            first_at,
            answered_at: None,
            updated_at,
            in_room: false,
            ever_granted: false,
            notice_version: None,
            surface: None,
        }
    }
}

/// One recorder run (`recording_runs`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct RecordingRunRecord {
    /// From 1.
    pub run: u16,
    /// Started.
    pub started_at: Timestamp,
    /// Joined the room.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub joined_at: Option<Timestamp>,
    /// Ended.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ended_at: Option<Timestamp>,
    /// Why.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub end_reason: Option<RunEnd>,
}

impl RecordingRunRecord {
    /// A `RecordingRunRecord` with its required fields: every count 0 and every optional
    /// field unset.
    pub fn new(started_at: Timestamp) -> Self {
        RecordingRunRecord {
            run: 0,
            started_at,
            joined_at: None,
            ended_at: None,
            end_reason: None,
        }
    }
}

/// One speaker's track progress (`recording_tracks`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct RecordingTrackRecord {
    /// The speaker.
    pub member_id: Id,
    /// Captured through (ms from the start).
    pub through_ms: u64,
    /// Open at the snapshot.
    #[serde(default, skip_serializing_if = "is_false")]
    pub open: bool,
    /// Last progress.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_progress_at: Option<Timestamp>,
}

impl RecordingTrackRecord {
    /// A `RecordingTrackRecord` with its required fields: every count 0, every flag `false`
    /// and every optional field unset.
    pub fn new(member_id: Id) -> Self {
        RecordingTrackRecord {
            member_id,
            through_ms: 0,
            open: false,
            last_progress_at: None,
        }
    }
}

/// One missing span (`recording_gaps`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct RecordingGapRecord {
    /// The speaker (absent: everyone).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub member_id: Option<Id>,
    /// From (ms from the start).
    pub from_ms: u64,
    /// To.
    pub to_ms: u64,
    /// Why.
    pub reason: crate::recording::GapReason,
}

impl RecordingGapRecord {
    /// A `RecordingGapRecord` with its required fields: every count 0 and every optional
    /// field unset.
    pub fn new(reason: crate::recording::GapReason) -> Self {
        RecordingGapRecord {
            member_id: None,
            from_ms: 0,
            to_ms: 0,
            reason,
        }
    }
}

/// One stored segment's metadata (`recording_segments`, without `result_ct`). Its audio is
/// `files/<file>`: the **recorder-sealed** Ogg (the encrypted file stream format under the segment
/// key derived from the recording's `content_key`, run, `join_id` and `seq`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct RecordingSegmentRecord {
    /// The segment.
    pub id: Id,
    /// The speaker.
    pub member_id: Id,
    /// The recorder run.
    pub run: u16,
    /// The identity's join (32 hex; an input of the segment key).
    pub join_id: String,
    /// Per run and identity, from 1.
    pub seq: u32,
    /// Offset from the recording start.
    pub start_ms: u64,
    /// Length.
    pub duration_ms: u32,
    /// Speech in it.
    pub speech_ms: u32,
    /// Mean level of its speech frames (dBov).
    pub level_dbov: f32,
    /// The sealed audio (absent once purged, or when the archive carries no files).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub file: Option<Id>,
    /// Sealed size.
    pub bytes: u32,
    /// Plaintext size.
    pub plain_bytes: u32,
    /// Its state.
    pub state: SegmentState,
    /// Counted attempts.
    #[serde(default, skip_serializing_if = "is_zero_u16")]
    pub attempts: u16,
    /// The last error code.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// Detected language.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lang: Option<String>,
    /// Its probability.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lang_prob: Option<f32>,
    /// Pieces posted through.
    #[serde(default, skip_serializing_if = "is_zero_u64")]
    pub posted_through_ms: u64,
    /// Ingest time.
    pub created_at: Timestamp,
}

impl RecordingSegmentRecord {
    /// A `RecordingSegmentRecord` with its required fields: every count 0 and every
    /// optional field unset.
    pub fn new(
        id: Id,
        member_id: Id,
        join_id: impl Into<String>,
        state: SegmentState,
        created_at: Timestamp,
    ) -> Self {
        RecordingSegmentRecord {
            id,
            member_id,
            run: 0,
            join_id: join_id.into(),
            seq: 0,
            start_ms: 0,
            duration_ms: 0,
            speech_ms: 0,
            level_dbov: 0.0,
            file: None,
            bytes: 0,
            plain_bytes: 0,
            state,
            attempts: 0,
            error: None,
            lang: None,
            lang_prob: None,
            posted_through_ms: 0,
            created_at,
        }
    }
}

/// One mixed part (`recording_mixes`); its audio is `files/<file>`, recorder-sealed under the
/// part key.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct RecordingMixRecord {
    /// From 1.
    pub part: u16,
    /// Offset from the recording start.
    pub offset_ms: u64,
    /// Length.
    pub duration_ms: u64,
    /// The sealed audio.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub file: Option<Id>,
    /// Sealed size.
    pub bytes: u64,
}

/// One transcript turn's timing (`transcript_turns`; the text is its message's body).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct TranscriptTurnRecord {
    /// The turn message.
    pub message_id: Id,
    /// The speaker.
    pub speaker_id: Id,
    /// Start (ms from the recording start).
    pub start_ms: u64,
    /// End.
    pub end_ms: u64,
    /// When it was said.
    pub spoken_at: Timestamp,
    /// Its language.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lang: Option<String>,
    /// The pieces (numbers only).
    pub pieces: serde_json::Value,
}

impl TranscriptTurnRecord {
    /// A `TranscriptTurnRecord` with its required fields: every count 0 and every optional
    /// field unset.
    pub fn new(
        message_id: Id,
        speaker_id: Id,
        spoken_at: Timestamp,
        pieces: serde_json::Value,
    ) -> Self {
        TranscriptTurnRecord {
            message_id,
            speaker_id,
            start_ms: 0,
            end_ms: 0,
            spoken_at,
            lang: None,
            pieces,
        }
    }
}

/// `recordings.ndjson`: one call recording with its consent record, runs,
/// tracks, gaps, segment and mix metadata, and turn timings. The audio leaves only as
/// recorder-sealed `files/…` plus `content_key`, and only inside the age layer.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct RecordingRecord {
    /// The recording.
    pub id: Id,
    /// The voice channel or DM.
    pub channel_id: Id,
    /// The DM call.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub call_record_id: Option<Id>,
    /// The record message.
    pub message_id: Id,
    /// The starter.
    pub started_by: Id,
    /// When.
    pub started_at: Timestamp,
    /// Auto-started.
    #[serde(default, skip_serializing_if = "is_false")]
    pub auto: bool,
    /// Minor 12: what started it, when `auto` alone does not say: `required` (the room
    /// reached two people while it records every call with more than one person; `auto` is
    /// set too). Omitted for `manual` and `auto`, which `auto` tells.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trigger: Option<crate::recording::RecordingTrigger>,
    /// Its state (an import loads active ones `stopped`, `disabled`).
    pub state: crate::recording::RecordingState,
    /// When it stopped.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stopped_at: Option<Timestamp>,
    /// Why.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stop_reason: Option<crate::recording::StopReason>,
    /// When the recorder first joined.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recorder_joined_at: Option<Timestamp>,
    /// Recorder runs.
    #[serde(default, skip_serializing_if = "is_zero_u16")]
    pub recorder_runs: u16,
    /// The language hint.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub language: Option<String>,
    /// A mixed file was asked for.
    #[serde(default, skip_serializing_if = "is_false")]
    pub mixed: bool,
    /// Audio keep days.
    pub audio_keep_days: u16,
    /// The audio's state.
    pub audio_state: crate::recording::AudioState,
    /// When the audio expires.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub audio_expires_at: Option<Timestamp>,
    /// Stored sealed bytes.
    #[serde(default, skip_serializing_if = "is_zero_u64")]
    pub audio_bytes: u64,
    /// The transcript's state.
    pub transcript_state: crate::recording::TranscriptState,
    /// When it became final.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub transcript_final_at: Option<Timestamp>,
    /// The merge frontier.
    #[serde(default, skip_serializing_if = "is_zero_u64")]
    pub posted_through_ms: u64,
    /// Turns posted.
    #[serde(default, skip_serializing_if = "is_zero_u32")]
    pub turn_count: u32,
    /// The transcriber's model.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    /// Its backend.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub backend: Option<String>,
    /// The record message was deleted or expired.
    #[serde(default, skip_serializing_if = "is_false")]
    pub hidden: bool,
    /// When the purge hook stubbed it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub purged_at: Option<Timestamp>,
    /// The 32-byte content key, base64url without padding: only when the archive carries the
    /// audio files and the audio is not purged (never outside the age layer).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub content_key: Option<String>,
    /// The consent record.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub participants: Vec<RecordingParticipantRecord>,
    /// Recorder runs.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub runs: Vec<RecordingRunRecord>,
    /// Track progress.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tracks: Vec<RecordingTrackRecord>,
    /// Gaps.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub gaps: Vec<RecordingGapRecord>,
    /// Segments (metadata; audio in `files/`).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub segments: Vec<RecordingSegmentRecord>,
    /// Mixed parts.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub mixes: Vec<RecordingMixRecord>,
    /// Transcript turn timings.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub turns: Vec<TranscriptTurnRecord>,
}

impl RecordingRecord {
    /// A recording record with its required fields: keep days 0, every optional field and
    /// list unset.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        id: Id,
        channel_id: Id,
        message_id: Id,
        started_by: Id,
        started_at: Timestamp,
        state: crate::recording::RecordingState,
        audio_state: crate::recording::AudioState,
        transcript_state: crate::recording::TranscriptState,
    ) -> Self {
        RecordingRecord {
            id,
            channel_id,
            call_record_id: None,
            message_id,
            started_by,
            started_at,
            auto: false,
            trigger: None,
            state,
            stopped_at: None,
            stop_reason: None,
            recorder_joined_at: None,
            recorder_runs: 0,
            language: None,
            mixed: false,
            audio_keep_days: 0,
            audio_state,
            audio_expires_at: None,
            audio_bytes: 0,
            transcript_state,
            transcript_final_at: None,
            posted_through_ms: 0,
            turn_count: 0,
            model: None,
            backend: None,
            hidden: false,
            purged_at: None,
            content_key: None,
            participants: Vec::new(),
            runs: Vec::new(),
            tracks: Vec::new(),
            gaps: Vec::new(),
            segments: Vec::new(),
            mixes: Vec::new(),
            turns: Vec::new(),
        }
    }
}

fn is_zero_u16(v: &u16) -> bool {
    *v == 0
}

fn is_zero_u32(v: &u32) -> bool {
    *v == 0
}

fn is_zero_u64(v: &u64) -> bool {
    *v == 0
}