eidetic-engine 0.15.2

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

use std::fmt;
use std::str::FromStr;

use serde::{Deserialize, Serialize};

use crate::policy::import_auth::AuthenticatedHeader;

/// Schema identifier for export header records.
pub const EXPORT_HEADER_SCHEMA_V1: &str = "ee.export.header.v1";

/// Schema identifier for export memory records.
pub const EXPORT_MEMORY_SCHEMA_V1: &str = "ee.export.memory.v1";

/// Schema identifier for export artifact records.
pub const EXPORT_ARTIFACT_SCHEMA_V1: &str = "ee.export.artifact.v1";

/// Schema identifier for export footer records.
pub const EXPORT_FOOTER_SCHEMA_V1: &str = "ee.export.footer.v1";

/// Schema identifier for export audit records.
pub const EXPORT_AUDIT_SCHEMA_V1: &str = "ee.export.audit.v1";

/// Schema identifier for export link records.
pub const EXPORT_LINK_SCHEMA_V1: &str = "ee.export.link.v1";

/// Schema identifier for export tag records.
pub const EXPORT_TAG_SCHEMA_V1: &str = "ee.export.tag.v1";

/// Schema identifier for export agent records.
pub const EXPORT_AGENT_SCHEMA_V1: &str = "ee.export.agent.v1";

/// Schema identifier for export workspace records.
pub const EXPORT_WORKSPACE_SCHEMA_V1: &str = "ee.export.workspace.v1";

/// All JSONL export schema identifiers.
pub const ALL_EXPORT_SCHEMAS: &[&str] = &[
    EXPORT_HEADER_SCHEMA_V1,
    EXPORT_MEMORY_SCHEMA_V1,
    EXPORT_ARTIFACT_SCHEMA_V1,
    EXPORT_FOOTER_SCHEMA_V1,
    EXPORT_AUDIT_SCHEMA_V1,
    EXPORT_LINK_SCHEMA_V1,
    EXPORT_TAG_SCHEMA_V1,
    EXPORT_AGENT_SCHEMA_V1,
    EXPORT_WORKSPACE_SCHEMA_V1,
];

/// Export format version.
pub const EXPORT_FORMAT_VERSION: u32 = 1;

/// Source of imported data for trust tracking.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ImportSource {
    /// Data created natively within ee.
    #[default]
    Native,
    /// Imported from CASS (coding agent session search).
    CassImport,
    /// Imported from legacy Eidetic Engine format.
    LegacyScan,
    /// Imported from external tool/format.
    ExternalImport,
    /// Source unknown or cannot be determined.
    Unknown,
}

impl ImportSource {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Native => "native",
            Self::CassImport => "cass_import",
            Self::LegacyScan => "legacy_scan",
            Self::ExternalImport => "external_import",
            Self::Unknown => "unknown",
        }
    }

    #[must_use]
    pub const fn is_external(self) -> bool {
        !matches!(self, Self::Native)
    }
}

impl fmt::Display for ImportSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParseImportSourceError {
    pub invalid: String,
}

impl fmt::Display for ParseImportSourceError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "invalid import source '{}'; expected one of: native, cass_import, legacy_scan, external_import, unknown",
            self.invalid
        )
    }
}

impl std::error::Error for ParseImportSourceError {}

impl FromStr for ImportSource {
    type Err = ParseImportSourceError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match normalized_jsonl_token(s).as_str() {
            "native" => Ok(Self::Native),
            "cass_import" => Ok(Self::CassImport),
            "legacy_scan" => Ok(Self::LegacyScan),
            "external_import" => Ok(Self::ExternalImport),
            "unknown" => Ok(Self::Unknown),
            _ => Err(ParseImportSourceError {
                invalid: s.to_owned(),
            }),
        }
    }
}

/// Trust level for exported/imported data.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TrustLevel {
    /// Data has not been validated; treat with caution.
    #[default]
    Untrusted,
    /// Data has passed basic validation checks.
    Validated,
    /// Data has been cryptographically verified.
    Verified,
    /// Data is quarantined due to policy violation or detected issue.
    Quarantined,
}

impl TrustLevel {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Untrusted => "untrusted",
            Self::Validated => "validated",
            Self::Verified => "verified",
            Self::Quarantined => "quarantined",
        }
    }

    #[must_use]
    pub const fn is_trusted(self) -> bool {
        matches!(self, Self::Validated | Self::Verified)
    }

    #[must_use]
    pub const fn is_quarantined(self) -> bool {
        matches!(self, Self::Quarantined)
    }
}

impl fmt::Display for TrustLevel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParseTrustLevelError {
    pub invalid: String,
}

impl fmt::Display for ParseTrustLevelError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "invalid trust level '{}'; expected one of: untrusted, validated, verified, quarantined",
            self.invalid
        )
    }
}

impl std::error::Error for ParseTrustLevelError {}

impl FromStr for TrustLevel {
    type Err = ParseTrustLevelError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match normalized_jsonl_token(s).as_str() {
            "untrusted" => Ok(Self::Untrusted),
            "validated" => Ok(Self::Validated),
            "verified" => Ok(Self::Verified),
            "quarantined" => Ok(Self::Quarantined),
            _ => Err(ParseTrustLevelError {
                invalid: s.to_owned(),
            }),
        }
    }
}

/// Export record type discriminator.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ExportRecordType {
    Header,
    Memory,
    Artifact,
    Link,
    Tag,
    Agent,
    Workspace,
    Audit,
    Footer,
}

impl ExportRecordType {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Header => "header",
            Self::Memory => "memory",
            Self::Artifact => "artifact",
            Self::Link => "link",
            Self::Tag => "tag",
            Self::Agent => "agent",
            Self::Workspace => "workspace",
            Self::Audit => "audit",
            Self::Footer => "footer",
        }
    }

    #[must_use]
    pub const fn schema(self) -> &'static str {
        match self {
            Self::Header => EXPORT_HEADER_SCHEMA_V1,
            Self::Memory => EXPORT_MEMORY_SCHEMA_V1,
            Self::Artifact => EXPORT_ARTIFACT_SCHEMA_V1,
            Self::Link => EXPORT_LINK_SCHEMA_V1,
            Self::Tag => EXPORT_TAG_SCHEMA_V1,
            Self::Agent => EXPORT_AGENT_SCHEMA_V1,
            Self::Workspace => EXPORT_WORKSPACE_SCHEMA_V1,
            Self::Audit => EXPORT_AUDIT_SCHEMA_V1,
            Self::Footer => EXPORT_FOOTER_SCHEMA_V1,
        }
    }

    #[must_use]
    pub const fn all() -> &'static [Self] {
        &[
            Self::Header,
            Self::Memory,
            Self::Artifact,
            Self::Link,
            Self::Tag,
            Self::Agent,
            Self::Workspace,
            Self::Audit,
            Self::Footer,
        ]
    }
}

impl fmt::Display for ExportRecordType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParseExportRecordTypeError {
    pub invalid: String,
}

impl fmt::Display for ParseExportRecordTypeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "invalid export record type '{}'; expected one of: header, memory, artifact, link, tag, agent, workspace, audit, footer",
            self.invalid
        )
    }
}

impl std::error::Error for ParseExportRecordTypeError {}

impl FromStr for ExportRecordType {
    type Err = ParseExportRecordTypeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match normalized_jsonl_token(s).as_str() {
            "header" => Ok(Self::Header),
            "memory" => Ok(Self::Memory),
            "artifact" => Ok(Self::Artifact),
            "link" => Ok(Self::Link),
            "tag" => Ok(Self::Tag),
            "agent" => Ok(Self::Agent),
            "workspace" => Ok(Self::Workspace),
            "audit" => Ok(Self::Audit),
            "footer" => Ok(Self::Footer),
            _ => Err(ParseExportRecordTypeError {
                invalid: s.to_owned(),
            }),
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ExportRecordBuildError {
    pub record_type: ExportRecordType,
    pub field: &'static str,
}

impl fmt::Display for ExportRecordBuildError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "missing required non-empty field '{}' for {} export record",
            self.field, self.record_type
        )
    }
}

impl std::error::Error for ExportRecordBuildError {}

fn missing_required(record_type: ExportRecordType, field: &'static str) -> ExportRecordBuildError {
    ExportRecordBuildError { record_type, field }
}

fn required_string(
    record_type: ExportRecordType,
    field: &'static str,
    value: Option<String>,
) -> Result<String, ExportRecordBuildError> {
    match value {
        // Trim BEFORE returning so JSONL export records keep canonical
        // string forms across noisier upstream emitters. Without this,
        // a value like " mem_abc\n" round-trips through export/import
        // as the literal whitespace-padded string, distinct from the
        // clean "mem_abc" and breaking dedup-on-id semantics. Same
        // defensive pattern as src/cass/import.rs (a135ab06).
        Some(value) if !value.trim().is_empty() => Ok(value.trim().to_owned()),
        _ => Err(missing_required(record_type, field)),
    }
}

fn required_u64(
    record_type: ExportRecordType,
    field: &'static str,
    value: Option<u64>,
) -> Result<u64, ExportRecordBuildError> {
    value.ok_or_else(|| missing_required(record_type, field))
}

/// Redaction level for exported data.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum RedactionLevel {
    /// No redaction applied.
    #[default]
    None,
    /// Minimal redaction: secrets and credentials only.
    Minimal,
    /// Standard redaction: secrets, paths, and identifiers.
    Standard,
    /// Strict redaction: secret-bearing content and long bodies are aggressively reduced.
    Strict,
    /// Paranoid redaction: all potentially sensitive content is replaced.
    Paranoid,
    /// Legacy alias retained for older JSONL exports that used `full`.
    Full,
}

impl RedactionLevel {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::None => "none",
            Self::Minimal => "minimal",
            Self::Standard => "standard",
            Self::Strict => "strict",
            Self::Paranoid => "paranoid",
            Self::Full => "full",
        }
    }

    #[must_use]
    pub const fn all() -> &'static [Self] {
        &[
            Self::None,
            Self::Minimal,
            Self::Standard,
            Self::Strict,
            Self::Paranoid,
        ]
    }

    #[must_use]
    pub const fn redacts_secrets(self) -> bool {
        !matches!(self, Self::None)
    }

    #[must_use]
    pub const fn redacts_paths(self) -> bool {
        matches!(
            self,
            Self::Standard | Self::Strict | Self::Paranoid | Self::Full
        )
    }

    #[must_use]
    pub const fn redacts_identifiers(self) -> bool {
        matches!(self, Self::Standard | Self::Paranoid | Self::Full)
    }

    #[must_use]
    pub const fn redacts_content(self) -> bool {
        matches!(self, Self::Strict | Self::Paranoid | Self::Full)
    }
}

impl fmt::Display for RedactionLevel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParseRedactionLevelError {
    pub invalid: String,
}

impl fmt::Display for ParseRedactionLevelError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "invalid redaction level '{}'; expected one of: none, minimal, standard, strict, paranoid, full",
            self.invalid
        )
    }
}

impl std::error::Error for ParseRedactionLevelError {}

impl FromStr for RedactionLevel {
    type Err = ParseRedactionLevelError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match normalized_jsonl_token(s).as_str() {
            "none" => Ok(Self::None),
            "minimal" => Ok(Self::Minimal),
            "standard" => Ok(Self::Standard),
            "strict" => Ok(Self::Strict),
            "paranoid" => Ok(Self::Paranoid),
            "full" => Ok(Self::Full),
            _ => Err(ParseRedactionLevelError {
                invalid: s.to_owned(),
            }),
        }
    }
}

/// Export scope selector.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ExportScope {
    /// Export all data.
    #[default]
    All,
    /// Export only memories.
    Memories,
    /// Export only audit records.
    Audit,
    /// Export only links and relationships.
    Links,
    /// Export metadata only (no content).
    MetadataOnly,
}

impl ExportScope {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::All => "all",
            Self::Memories => "memories",
            Self::Audit => "audit",
            Self::Links => "links",
            Self::MetadataOnly => "metadata_only",
        }
    }

    #[must_use]
    pub const fn all() -> &'static [Self] {
        &[
            Self::All,
            Self::Memories,
            Self::Audit,
            Self::Links,
            Self::MetadataOnly,
        ]
    }

    #[must_use]
    pub const fn includes_memories(self) -> bool {
        matches!(self, Self::All | Self::Memories | Self::MetadataOnly)
    }

    #[must_use]
    pub const fn includes_artifacts(self) -> bool {
        matches!(self, Self::All | Self::MetadataOnly)
    }

    #[must_use]
    pub const fn includes_audit(self) -> bool {
        matches!(self, Self::All | Self::Audit)
    }

    #[must_use]
    pub const fn includes_links(self) -> bool {
        matches!(self, Self::All | Self::Links)
    }

    #[must_use]
    pub const fn includes_content(self) -> bool {
        !matches!(self, Self::MetadataOnly)
    }
}

impl fmt::Display for ExportScope {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParseExportScopeError {
    pub invalid: String,
}

impl fmt::Display for ParseExportScopeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "invalid export scope '{}'; expected one of: all, memories, audit, links, metadata_only",
            self.invalid
        )
    }
}

impl std::error::Error for ParseExportScopeError {}

impl FromStr for ExportScope {
    type Err = ParseExportScopeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match normalized_jsonl_token(s).as_str() {
            "all" => Ok(Self::All),
            "memories" => Ok(Self::Memories),
            "audit" => Ok(Self::Audit),
            "links" => Ok(Self::Links),
            "metadata_only" => Ok(Self::MetadataOnly),
            _ => Err(ParseExportScopeError {
                invalid: s.to_owned(),
            }),
        }
    }
}

fn normalized_jsonl_token(input: &str) -> String {
    let trimmed = input.trim();
    let mut normalized = String::with_capacity(trimmed.len());
    let mut previous_was_lowercase = false;
    let mut previous_was_separator = false;

    for character in trimmed.chars() {
        match character {
            '-' | '_' => {
                if !normalized.is_empty() && !previous_was_separator {
                    normalized.push('_');
                }
                previous_was_lowercase = false;
                previous_was_separator = true;
            }
            character if character.is_ascii_uppercase() => {
                if previous_was_lowercase && !previous_was_separator {
                    normalized.push('_');
                }
                normalized.push(character.to_ascii_lowercase());
                previous_was_lowercase = false;
                previous_was_separator = false;
            }
            character => {
                normalized.push(character.to_ascii_lowercase());
                previous_was_lowercase = character.is_ascii_lowercase();
                previous_was_separator = false;
            }
        }
    }

    normalized
}

/// Export header record with trust and import metadata (EE-266).
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ExportHeader {
    pub schema: String,
    pub format_version: u32,
    pub created_at: String,
    pub workspace_id: Option<String>,
    pub workspace_path: Option<String>,
    pub export_scope: ExportScope,
    pub redaction_level: RedactionLevel,
    pub record_count: Option<u64>,
    pub ee_version: String,
    pub hostname: Option<String>,
    pub export_id: String,
    /// Source of the data for trust tracking (EE-266).
    #[serde(default)]
    pub import_source: ImportSource,
    /// Trust classification of the data (EE-266).
    #[serde(default)]
    pub trust_level: TrustLevel,
    /// BLAKE3 checksum of the content records for integrity verification (EE-266).
    pub checksum: Option<String>,
    /// Optional cryptographic signature for audit trails (EE-266).
    pub signature: Option<String>,
    /// Schema version of the source data if imported (EE-266).
    pub source_schema_version: Option<String>,
}

impl ExportHeader {
    #[must_use]
    pub fn builder() -> ExportHeaderBuilder {
        ExportHeaderBuilder::default()
    }
}

#[derive(Clone, Debug, Default)]
pub struct ExportHeaderBuilder {
    created_at: Option<String>,
    workspace_id: Option<String>,
    workspace_path: Option<String>,
    export_scope: ExportScope,
    redaction_level: RedactionLevel,
    record_count: Option<u64>,
    ee_version: Option<String>,
    hostname: Option<String>,
    export_id: Option<String>,
    import_source: ImportSource,
    trust_level: TrustLevel,
    checksum: Option<String>,
    signature: Option<String>,
    source_schema_version: Option<String>,
}

impl ExportHeaderBuilder {
    #[must_use]
    pub fn created_at(mut self, created_at: impl Into<String>) -> Self {
        self.created_at = Some(created_at.into());
        self
    }

    #[must_use]
    pub fn workspace_id(mut self, workspace_id: impl Into<String>) -> Self {
        self.workspace_id = Some(workspace_id.into());
        self
    }

    #[must_use]
    pub fn workspace_path(mut self, workspace_path: impl Into<String>) -> Self {
        self.workspace_path = Some(workspace_path.into());
        self
    }

    #[must_use]
    pub fn export_scope(mut self, export_scope: ExportScope) -> Self {
        self.export_scope = export_scope;
        self
    }

    #[must_use]
    pub fn redaction_level(mut self, redaction_level: RedactionLevel) -> Self {
        self.redaction_level = redaction_level;
        self
    }

    #[must_use]
    pub fn record_count(mut self, record_count: u64) -> Self {
        self.record_count = Some(record_count);
        self
    }

    #[must_use]
    pub fn ee_version(mut self, ee_version: impl Into<String>) -> Self {
        self.ee_version = Some(ee_version.into());
        self
    }

    #[must_use]
    pub fn hostname(mut self, hostname: impl Into<String>) -> Self {
        self.hostname = Some(hostname.into());
        self
    }

    #[must_use]
    pub fn export_id(mut self, export_id: impl Into<String>) -> Self {
        self.export_id = Some(export_id.into());
        self
    }

    #[must_use]
    pub fn import_source(mut self, import_source: ImportSource) -> Self {
        self.import_source = import_source;
        self
    }

    #[must_use]
    pub fn trust_level(mut self, trust_level: TrustLevel) -> Self {
        self.trust_level = trust_level;
        self
    }

    #[must_use]
    pub fn checksum(mut self, checksum: impl Into<String>) -> Self {
        self.checksum = Some(checksum.into());
        self
    }

    #[must_use]
    pub fn signature(mut self, signature: impl Into<String>) -> Self {
        self.signature = Some(signature.into());
        self
    }

    #[must_use]
    pub fn source_schema_version(mut self, version: impl Into<String>) -> Self {
        self.source_schema_version = Some(version.into());
        self
    }

    /// Build the header record.
    ///
    /// # Errors
    ///
    /// Returns an error when a required machine-facing field is missing or blank.
    pub fn build(self) -> Result<ExportHeader, ExportRecordBuildError> {
        Ok(ExportHeader {
            schema: EXPORT_HEADER_SCHEMA_V1.to_owned(),
            format_version: EXPORT_FORMAT_VERSION,
            created_at: required_string(ExportRecordType::Header, "created_at", self.created_at)?,
            workspace_id: self.workspace_id,
            workspace_path: self.workspace_path,
            export_scope: self.export_scope,
            redaction_level: self.redaction_level,
            record_count: self.record_count,
            ee_version: required_string(ExportRecordType::Header, "ee_version", self.ee_version)?,
            hostname: self.hostname,
            export_id: required_string(ExportRecordType::Header, "export_id", self.export_id)?,
            import_source: self.import_source,
            trust_level: self.trust_level,
            checksum: self.checksum,
            signature: self.signature,
            source_schema_version: self.source_schema_version,
        })
    }
}

/// Export footer record.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ExportFooter {
    pub schema: String,
    pub export_id: String,
    pub completed_at: String,
    pub total_records: u64,
    pub memory_count: u64,
    #[serde(default)]
    pub artifact_count: u64,
    pub link_count: u64,
    pub tag_count: u64,
    pub audit_count: u64,
    pub checksum: Option<String>,
    pub success: bool,
    pub error_message: Option<String>,
    /// Store-local authentication block (ADR 0086 TC-D14). Present only when the
    /// exporting store MAC'd the artifact; absent artifacts import at external
    /// (non-native) trust. Skipped when absent so unauthenticated artifacts are
    /// byte-identical to the historical footer.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub authentication: Option<AuthenticatedHeader>,
}

impl ExportFooter {
    #[must_use]
    pub fn builder() -> ExportFooterBuilder {
        ExportFooterBuilder::default()
    }
}

#[derive(Clone, Debug, Default)]
pub struct ExportFooterBuilder {
    export_id: Option<String>,
    completed_at: Option<String>,
    total_records: u64,
    memory_count: u64,
    artifact_count: u64,
    link_count: u64,
    tag_count: u64,
    audit_count: u64,
    checksum: Option<String>,
    success: bool,
    error_message: Option<String>,
    authentication: Option<AuthenticatedHeader>,
}

impl ExportFooterBuilder {
    #[must_use]
    pub fn export_id(mut self, export_id: impl Into<String>) -> Self {
        self.export_id = Some(export_id.into());
        self
    }

    #[must_use]
    pub fn completed_at(mut self, completed_at: impl Into<String>) -> Self {
        self.completed_at = Some(completed_at.into());
        self
    }

    #[must_use]
    pub fn total_records(mut self, total_records: u64) -> Self {
        self.total_records = total_records;
        self
    }

    #[must_use]
    pub fn memory_count(mut self, memory_count: u64) -> Self {
        self.memory_count = memory_count;
        self
    }

    #[must_use]
    pub fn artifact_count(mut self, artifact_count: u64) -> Self {
        self.artifact_count = artifact_count;
        self
    }

    #[must_use]
    pub fn link_count(mut self, link_count: u64) -> Self {
        self.link_count = link_count;
        self
    }

    #[must_use]
    pub fn tag_count(mut self, tag_count: u64) -> Self {
        self.tag_count = tag_count;
        self
    }

    #[must_use]
    pub fn audit_count(mut self, audit_count: u64) -> Self {
        self.audit_count = audit_count;
        self
    }

    #[must_use]
    pub fn checksum(mut self, checksum: impl Into<String>) -> Self {
        self.checksum = Some(checksum.into());
        self
    }

    #[must_use]
    pub fn success(mut self, success: bool) -> Self {
        self.success = success;
        self
    }

    #[must_use]
    pub fn error_message(mut self, error_message: impl Into<String>) -> Self {
        self.error_message = Some(error_message.into());
        self
    }

    /// Attach (or clear) the store-local authentication block.
    #[must_use]
    pub fn authentication(mut self, authentication: Option<AuthenticatedHeader>) -> Self {
        self.authentication = authentication;
        self
    }

    /// Build the footer record.
    ///
    /// # Errors
    ///
    /// Returns an error when a required machine-facing field is missing or blank.
    pub fn build(self) -> Result<ExportFooter, ExportRecordBuildError> {
        Ok(ExportFooter {
            schema: EXPORT_FOOTER_SCHEMA_V1.to_owned(),
            export_id: required_string(ExportRecordType::Footer, "export_id", self.export_id)?,
            completed_at: required_string(
                ExportRecordType::Footer,
                "completed_at",
                self.completed_at,
            )?,
            total_records: self.total_records,
            memory_count: self.memory_count,
            artifact_count: self.artifact_count,
            link_count: self.link_count,
            tag_count: self.tag_count,
            audit_count: self.audit_count,
            checksum: self.checksum,
            success: self.success,
            error_message: self.error_message,
            authentication: self.authentication,
        })
    }
}

/// Attempt-family multiplicity block on an exported memory
/// (bd-multiplicity-aware-trust-p0u7g): the family pointer plus this
/// memory's own ledger slot/disposition, so backup restore can rebuild both
/// the pointer columns and the attempt-family ledger without inferring
/// anything. `origin` preserves whether the declaration was ledger-native
/// (`declared`) or seeded from the pre-ledger V094 columns (`legacy_v094`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExportAttemptFamilyRecord {
    pub family_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub declared_size: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attempt_index: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub disposition: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub origin: Option<String>,
}

/// Export memory record.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ExportMemoryRecord {
    pub schema: String,
    pub memory_id: String,
    /// Root memory identity shared by immutable revisions. Omitted for a
    /// singleton record whose logical identity is its own memory ID.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub logical_id: Option<String>,
    pub workspace_id: String,
    pub level: String,
    pub kind: String,
    pub content: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub content_hash: Option<String>,
    pub importance: Option<f64>,
    pub confidence: Option<f64>,
    pub utility: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pagerank_score: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub betweenness_score: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hits_authority: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hits_hub: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub onion_layer: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub k_truss_max: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub articulation_point: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bayes_alpha: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bayes_beta: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trust_class: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trust_subclass: Option<String>,
    pub created_at: String,
    pub updated_at: Option<String>,
    pub tombstoned_at: Option<String>,
    pub tombstoned_reason: Option<String>,
    pub valid_from: Option<String>,
    pub valid_to: Option<String>,
    pub expires_at: Option<String>,
    pub source_agent: Option<String>,
    pub provenance_uri: Option<String>,
    pub superseded_by: Option<String>,
    pub supersedes: Option<String>,
    pub redacted: bool,
    pub redaction_reason: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attempt_family: Option<ExportAttemptFamilyRecord>,
}

impl ExportMemoryRecord {
    #[must_use]
    pub fn builder() -> ExportMemoryRecordBuilder {
        ExportMemoryRecordBuilder::default()
    }
}

#[derive(Clone, Debug, Default)]
pub struct ExportMemoryRecordBuilder {
    memory_id: Option<String>,
    logical_id: Option<String>,
    workspace_id: Option<String>,
    level: Option<String>,
    kind: Option<String>,
    content: Option<String>,
    content_hash: Option<String>,
    importance: Option<f64>,
    confidence: Option<f64>,
    utility: Option<f64>,
    pagerank_score: Option<f64>,
    betweenness_score: Option<f64>,
    hits_authority: Option<f64>,
    hits_hub: Option<f64>,
    onion_layer: Option<u32>,
    k_truss_max: Option<u32>,
    articulation_point: Option<bool>,
    bayes_alpha: Option<f64>,
    bayes_beta: Option<f64>,
    trust_class: Option<String>,
    trust_subclass: Option<String>,
    created_at: Option<String>,
    updated_at: Option<String>,
    tombstoned_at: Option<String>,
    tombstoned_reason: Option<String>,
    valid_from: Option<String>,
    valid_to: Option<String>,
    expires_at: Option<String>,
    source_agent: Option<String>,
    provenance_uri: Option<String>,
    superseded_by: Option<String>,
    supersedes: Option<String>,
    redacted: bool,
    redaction_reason: Option<String>,
    attempt_family: Option<ExportAttemptFamilyRecord>,
}

impl ExportMemoryRecordBuilder {
    #[must_use]
    pub fn memory_id(mut self, memory_id: impl Into<String>) -> Self {
        self.memory_id = Some(memory_id.into());
        self
    }

    #[must_use]
    pub fn logical_id(mut self, logical_id: impl Into<String>) -> Self {
        self.logical_id = Some(logical_id.into());
        self
    }

    #[must_use]
    pub fn workspace_id(mut self, workspace_id: impl Into<String>) -> Self {
        self.workspace_id = Some(workspace_id.into());
        self
    }

    #[must_use]
    pub fn level(mut self, level: impl Into<String>) -> Self {
        self.level = Some(level.into());
        self
    }

    #[must_use]
    pub fn kind(mut self, kind: impl Into<String>) -> Self {
        self.kind = Some(kind.into());
        self
    }

    #[must_use]
    pub fn content(mut self, content: impl Into<String>) -> Self {
        self.content = Some(content.into());
        self
    }

    #[must_use]
    pub fn content_hash(mut self, content_hash: impl Into<String>) -> Self {
        self.content_hash = Some(content_hash.into());
        self
    }

    #[must_use]
    pub fn importance(mut self, importance: f64) -> Self {
        self.importance = Some(importance);
        self
    }

    #[must_use]
    pub fn confidence(mut self, confidence: f64) -> Self {
        self.confidence = Some(confidence);
        self
    }

    #[must_use]
    pub fn utility(mut self, utility: f64) -> Self {
        self.utility = Some(utility);
        self
    }

    #[must_use]
    pub fn pagerank_score(mut self, pagerank_score: f64) -> Self {
        self.pagerank_score = Some(pagerank_score);
        self
    }

    #[must_use]
    pub fn betweenness_score(mut self, betweenness_score: f64) -> Self {
        self.betweenness_score = Some(betweenness_score);
        self
    }

    #[must_use]
    pub fn hits_authority(mut self, hits_authority: f64) -> Self {
        self.hits_authority = Some(hits_authority);
        self
    }

    #[must_use]
    pub fn hits_hub(mut self, hits_hub: f64) -> Self {
        self.hits_hub = Some(hits_hub);
        self
    }

    #[must_use]
    pub fn onion_layer(mut self, onion_layer: u32) -> Self {
        self.onion_layer = Some(onion_layer);
        self
    }

    #[must_use]
    pub fn k_truss_max(mut self, k_truss_max: u32) -> Self {
        self.k_truss_max = Some(k_truss_max);
        self
    }

    #[must_use]
    pub fn articulation_point(mut self, articulation_point: bool) -> Self {
        self.articulation_point = Some(articulation_point);
        self
    }

    #[must_use]
    pub fn bayes_alpha(mut self, bayes_alpha: f64) -> Self {
        self.bayes_alpha = Some(bayes_alpha);
        self
    }

    #[must_use]
    pub fn bayes_beta(mut self, bayes_beta: f64) -> Self {
        self.bayes_beta = Some(bayes_beta);
        self
    }

    #[must_use]
    pub fn trust_class(mut self, trust_class: impl Into<String>) -> Self {
        self.trust_class = Some(trust_class.into());
        self
    }

    #[must_use]
    pub fn trust_subclass(mut self, trust_subclass: impl Into<String>) -> Self {
        self.trust_subclass = Some(trust_subclass.into());
        self
    }

    #[must_use]
    pub fn created_at(mut self, created_at: impl Into<String>) -> Self {
        self.created_at = Some(created_at.into());
        self
    }

    #[must_use]
    pub fn updated_at(mut self, updated_at: impl Into<String>) -> Self {
        self.updated_at = Some(updated_at.into());
        self
    }

    #[must_use]
    pub fn tombstoned_at(mut self, tombstoned_at: impl Into<String>) -> Self {
        self.tombstoned_at = Some(tombstoned_at.into());
        self
    }

    #[must_use]
    pub fn tombstoned_reason(mut self, tombstoned_reason: impl Into<String>) -> Self {
        self.tombstoned_reason = Some(tombstoned_reason.into());
        self
    }

    #[must_use]
    pub fn valid_from(mut self, valid_from: impl Into<String>) -> Self {
        self.valid_from = Some(valid_from.into());
        self
    }

    #[must_use]
    pub fn valid_to(mut self, valid_to: impl Into<String>) -> Self {
        self.valid_to = Some(valid_to.into());
        self
    }

    #[must_use]
    pub fn expires_at(mut self, expires_at: impl Into<String>) -> Self {
        self.expires_at = Some(expires_at.into());
        self
    }

    #[must_use]
    pub fn source_agent(mut self, source_agent: impl Into<String>) -> Self {
        self.source_agent = Some(source_agent.into());
        self
    }

    #[must_use]
    pub fn provenance_uri(mut self, provenance_uri: impl Into<String>) -> Self {
        self.provenance_uri = Some(provenance_uri.into());
        self
    }

    #[must_use]
    pub fn superseded_by(mut self, superseded_by: impl Into<String>) -> Self {
        self.superseded_by = Some(superseded_by.into());
        self
    }

    #[must_use]
    pub fn supersedes(mut self, supersedes: impl Into<String>) -> Self {
        self.supersedes = Some(supersedes.into());
        self
    }

    #[must_use]
    pub fn redacted(mut self, redacted: bool) -> Self {
        self.redacted = redacted;
        self
    }

    #[must_use]
    pub fn redaction_reason(mut self, redaction_reason: impl Into<String>) -> Self {
        self.redaction_reason = Some(redaction_reason.into());
        self
    }

    #[must_use]
    pub fn attempt_family(mut self, attempt_family: ExportAttemptFamilyRecord) -> Self {
        self.attempt_family = Some(attempt_family);
        self
    }

    /// Build the memory export record.
    ///
    /// # Errors
    ///
    /// Returns an error when a required machine-facing field is missing or blank.
    pub fn build(self) -> Result<ExportMemoryRecord, ExportRecordBuildError> {
        Ok(ExportMemoryRecord {
            schema: EXPORT_MEMORY_SCHEMA_V1.to_owned(),
            memory_id: required_string(ExportRecordType::Memory, "memory_id", self.memory_id)?,
            logical_id: self.logical_id,
            workspace_id: required_string(
                ExportRecordType::Memory,
                "workspace_id",
                self.workspace_id,
            )?,
            level: required_string(ExportRecordType::Memory, "level", self.level)?,
            kind: required_string(ExportRecordType::Memory, "kind", self.kind)?,
            // Preserve the stored body's exact bytes for export and
            // content-hash verification; import validates content separately.
            content: self
                .content
                .filter(|content| !content.trim().is_empty())
                .ok_or_else(|| missing_required(ExportRecordType::Memory, "content"))?,
            content_hash: self.content_hash,
            importance: self.importance,
            confidence: self.confidence,
            utility: self.utility,
            pagerank_score: self.pagerank_score,
            betweenness_score: self.betweenness_score,
            hits_authority: self.hits_authority,
            hits_hub: self.hits_hub,
            onion_layer: self.onion_layer,
            k_truss_max: self.k_truss_max,
            articulation_point: self.articulation_point,
            bayes_alpha: self.bayes_alpha,
            bayes_beta: self.bayes_beta,
            trust_class: self.trust_class,
            trust_subclass: self.trust_subclass,
            created_at: required_string(ExportRecordType::Memory, "created_at", self.created_at)?,
            updated_at: self.updated_at,
            tombstoned_at: self.tombstoned_at,
            tombstoned_reason: self.tombstoned_reason,
            valid_from: self.valid_from,
            valid_to: self.valid_to,
            expires_at: self.expires_at,
            source_agent: self.source_agent,
            provenance_uri: self.provenance_uri,
            superseded_by: self.superseded_by,
            supersedes: self.supersedes,
            redacted: self.redacted,
            redaction_reason: self.redaction_reason,
            attempt_family: self.attempt_family,
        })
    }
}

/// Export artifact record.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ExportArtifactRecord {
    pub schema: String,
    pub artifact_id: String,
    pub workspace_id: String,
    pub source_kind: String,
    pub artifact_type: String,
    pub original_path: Option<String>,
    pub canonical_path: Option<String>,
    pub external_ref: Option<String>,
    pub content_hash: String,
    pub media_type: String,
    pub size_bytes: u64,
    pub redaction_status: String,
    pub snippet: Option<String>,
    pub snippet_hash: Option<String>,
    pub provenance_uri: Option<String>,
    pub metadata: Option<serde_json::Value>,
    pub created_at: String,
    pub updated_at: String,
}

impl ExportArtifactRecord {
    #[must_use]
    pub fn builder() -> ExportArtifactRecordBuilder {
        ExportArtifactRecordBuilder::default()
    }
}

#[derive(Clone, Debug, Default)]
pub struct ExportArtifactRecordBuilder {
    artifact_id: Option<String>,
    workspace_id: Option<String>,
    source_kind: Option<String>,
    artifact_type: Option<String>,
    original_path: Option<String>,
    canonical_path: Option<String>,
    external_ref: Option<String>,
    content_hash: Option<String>,
    media_type: Option<String>,
    size_bytes: Option<u64>,
    redaction_status: Option<String>,
    snippet: Option<String>,
    snippet_hash: Option<String>,
    provenance_uri: Option<String>,
    metadata: Option<serde_json::Value>,
    created_at: Option<String>,
    updated_at: Option<String>,
}

impl ExportArtifactRecordBuilder {
    #[must_use]
    pub fn artifact_id(mut self, artifact_id: impl Into<String>) -> Self {
        self.artifact_id = Some(artifact_id.into());
        self
    }

    #[must_use]
    pub fn workspace_id(mut self, workspace_id: impl Into<String>) -> Self {
        self.workspace_id = Some(workspace_id.into());
        self
    }

    #[must_use]
    pub fn source_kind(mut self, source_kind: impl Into<String>) -> Self {
        self.source_kind = Some(source_kind.into());
        self
    }

    #[must_use]
    pub fn artifact_type(mut self, artifact_type: impl Into<String>) -> Self {
        self.artifact_type = Some(artifact_type.into());
        self
    }

    #[must_use]
    pub fn original_path(mut self, original_path: impl Into<String>) -> Self {
        self.original_path = Some(original_path.into());
        self
    }

    #[must_use]
    pub fn canonical_path(mut self, canonical_path: impl Into<String>) -> Self {
        self.canonical_path = Some(canonical_path.into());
        self
    }

    #[must_use]
    pub fn external_ref(mut self, external_ref: impl Into<String>) -> Self {
        self.external_ref = Some(external_ref.into());
        self
    }

    #[must_use]
    pub fn content_hash(mut self, content_hash: impl Into<String>) -> Self {
        self.content_hash = Some(content_hash.into());
        self
    }

    #[must_use]
    pub fn media_type(mut self, media_type: impl Into<String>) -> Self {
        self.media_type = Some(media_type.into());
        self
    }

    #[must_use]
    pub fn size_bytes(mut self, size_bytes: u64) -> Self {
        self.size_bytes = Some(size_bytes);
        self
    }

    #[must_use]
    pub fn redaction_status(mut self, redaction_status: impl Into<String>) -> Self {
        self.redaction_status = Some(redaction_status.into());
        self
    }

    #[must_use]
    pub fn snippet(mut self, snippet: impl Into<String>) -> Self {
        self.snippet = Some(snippet.into());
        self
    }

    #[must_use]
    pub fn snippet_hash(mut self, snippet_hash: impl Into<String>) -> Self {
        self.snippet_hash = Some(snippet_hash.into());
        self
    }

    #[must_use]
    pub fn provenance_uri(mut self, provenance_uri: impl Into<String>) -> Self {
        self.provenance_uri = Some(provenance_uri.into());
        self
    }

    #[must_use]
    pub fn metadata(mut self, metadata: serde_json::Value) -> Self {
        self.metadata = Some(metadata);
        self
    }

    #[must_use]
    pub fn created_at(mut self, created_at: impl Into<String>) -> Self {
        self.created_at = Some(created_at.into());
        self
    }

    #[must_use]
    pub fn updated_at(mut self, updated_at: impl Into<String>) -> Self {
        self.updated_at = Some(updated_at.into());
        self
    }

    /// Build the artifact export record.
    ///
    /// # Errors
    ///
    /// Returns an error when a required machine-facing field is missing or blank.
    pub fn build(self) -> Result<ExportArtifactRecord, ExportRecordBuildError> {
        Ok(ExportArtifactRecord {
            schema: EXPORT_ARTIFACT_SCHEMA_V1.to_owned(),
            artifact_id: required_string(
                ExportRecordType::Artifact,
                "artifact_id",
                self.artifact_id,
            )?,
            workspace_id: required_string(
                ExportRecordType::Artifact,
                "workspace_id",
                self.workspace_id,
            )?,
            source_kind: required_string(
                ExportRecordType::Artifact,
                "source_kind",
                self.source_kind,
            )?,
            artifact_type: required_string(
                ExportRecordType::Artifact,
                "artifact_type",
                self.artifact_type,
            )?,
            original_path: self.original_path,
            canonical_path: self.canonical_path,
            external_ref: self.external_ref,
            content_hash: required_string(
                ExportRecordType::Artifact,
                "content_hash",
                self.content_hash,
            )?,
            media_type: required_string(ExportRecordType::Artifact, "media_type", self.media_type)?,
            size_bytes: required_u64(ExportRecordType::Artifact, "size_bytes", self.size_bytes)?,
            redaction_status: required_string(
                ExportRecordType::Artifact,
                "redaction_status",
                self.redaction_status,
            )?,
            snippet: self.snippet,
            snippet_hash: self.snippet_hash,
            provenance_uri: self.provenance_uri,
            metadata: self.metadata,
            created_at: required_string(ExportRecordType::Artifact, "created_at", self.created_at)?,
            updated_at: required_string(ExportRecordType::Artifact, "updated_at", self.updated_at)?,
        })
    }
}

/// Export link record (memory relationships).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ExportLinkRecord {
    pub schema: String,
    pub link_id: String,
    pub source_memory_id: String,
    pub target_memory_id: String,
    pub link_type: String,
    pub weight: Option<f64>,
    pub created_at: String,
    pub metadata: Option<serde_json::Value>,
}

impl ExportLinkRecord {
    #[must_use]
    pub fn builder() -> ExportLinkRecordBuilder {
        ExportLinkRecordBuilder::default()
    }
}

#[derive(Clone, Debug, Default)]
pub struct ExportLinkRecordBuilder {
    link_id: Option<String>,
    source_memory_id: Option<String>,
    target_memory_id: Option<String>,
    link_type: Option<String>,
    weight: Option<f64>,
    created_at: Option<String>,
    metadata: Option<serde_json::Value>,
}

impl ExportLinkRecordBuilder {
    #[must_use]
    pub fn link_id(mut self, link_id: impl Into<String>) -> Self {
        self.link_id = Some(link_id.into());
        self
    }

    #[must_use]
    pub fn source_memory_id(mut self, source_memory_id: impl Into<String>) -> Self {
        self.source_memory_id = Some(source_memory_id.into());
        self
    }

    #[must_use]
    pub fn target_memory_id(mut self, target_memory_id: impl Into<String>) -> Self {
        self.target_memory_id = Some(target_memory_id.into());
        self
    }

    #[must_use]
    pub fn link_type(mut self, link_type: impl Into<String>) -> Self {
        self.link_type = Some(link_type.into());
        self
    }

    #[must_use]
    pub fn weight(mut self, weight: f64) -> Self {
        self.weight = Some(weight);
        self
    }

    #[must_use]
    pub fn created_at(mut self, created_at: impl Into<String>) -> Self {
        self.created_at = Some(created_at.into());
        self
    }

    #[must_use]
    pub fn metadata(mut self, metadata: serde_json::Value) -> Self {
        self.metadata = Some(metadata);
        self
    }

    /// Build the link export record.
    ///
    /// # Errors
    ///
    /// Returns an error when a required machine-facing field is missing or blank.
    pub fn build(self) -> Result<ExportLinkRecord, ExportRecordBuildError> {
        Ok(ExportLinkRecord {
            schema: EXPORT_LINK_SCHEMA_V1.to_owned(),
            link_id: required_string(ExportRecordType::Link, "link_id", self.link_id)?,
            source_memory_id: required_string(
                ExportRecordType::Link,
                "source_memory_id",
                self.source_memory_id,
            )?,
            target_memory_id: required_string(
                ExportRecordType::Link,
                "target_memory_id",
                self.target_memory_id,
            )?,
            link_type: required_string(ExportRecordType::Link, "link_type", self.link_type)?,
            weight: self.weight,
            created_at: required_string(ExportRecordType::Link, "created_at", self.created_at)?,
            metadata: self.metadata,
        })
    }
}

/// Export tag record.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ExportTagRecord {
    pub schema: String,
    pub memory_id: String,
    pub tag: String,
    pub created_at: String,
}

impl ExportTagRecord {
    #[must_use]
    pub fn builder() -> ExportTagRecordBuilder {
        ExportTagRecordBuilder::default()
    }
}

#[derive(Clone, Debug, Default)]
pub struct ExportTagRecordBuilder {
    memory_id: Option<String>,
    tag: Option<String>,
    created_at: Option<String>,
}

impl ExportTagRecordBuilder {
    #[must_use]
    pub fn memory_id(mut self, memory_id: impl Into<String>) -> Self {
        self.memory_id = Some(memory_id.into());
        self
    }

    #[must_use]
    pub fn tag(mut self, tag: impl Into<String>) -> Self {
        self.tag = Some(tag.into());
        self
    }

    #[must_use]
    pub fn created_at(mut self, created_at: impl Into<String>) -> Self {
        self.created_at = Some(created_at.into());
        self
    }

    /// Build the tag export record.
    ///
    /// # Errors
    ///
    /// Returns an error when a required machine-facing field is missing or blank.
    pub fn build(self) -> Result<ExportTagRecord, ExportRecordBuildError> {
        Ok(ExportTagRecord {
            schema: EXPORT_TAG_SCHEMA_V1.to_owned(),
            memory_id: required_string(ExportRecordType::Tag, "memory_id", self.memory_id)?,
            tag: required_string(ExportRecordType::Tag, "tag", self.tag)?,
            created_at: required_string(ExportRecordType::Tag, "created_at", self.created_at)?,
        })
    }
}

/// Export audit record.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "UncheckedExportAuditRecord")]
pub struct ExportAuditRecord {
    pub schema: String,
    pub audit_id: String,
    pub operation: String,
    pub target_type: Option<String>,
    pub target_id: Option<String>,
    pub performed_at: String,
    pub performed_by: Option<String>,
    pub details: Option<serde_json::Value>,
}

#[derive(Deserialize)]
struct UncheckedExportAuditRecord {
    schema: String,
    audit_id: String,
    operation: String,
    target_type: Option<String>,
    target_id: Option<String>,
    performed_at: String,
    performed_by: Option<String>,
    details: Option<serde_json::Value>,
}

impl TryFrom<UncheckedExportAuditRecord> for ExportAuditRecord {
    type Error = ExportRecordBuildError;

    fn try_from(record: UncheckedExportAuditRecord) -> Result<Self, Self::Error> {
        let (target_type, target_id) =
            validated_audit_target_fields(record.target_type, record.target_id)?;
        Ok(Self {
            schema: record.schema,
            audit_id: record.audit_id,
            operation: record.operation,
            target_type,
            target_id,
            performed_at: record.performed_at,
            performed_by: record.performed_by,
            details: record.details,
        })
    }
}

fn validated_audit_target_fields(
    target_type: Option<String>,
    target_id: Option<String>,
) -> Result<(Option<String>, Option<String>), ExportRecordBuildError> {
    let target_type = target_type
        .map(|value| required_string(ExportRecordType::Audit, "target_type", Some(value)))
        .transpose()?;
    let target_id = target_id
        .map(|value| required_string(ExportRecordType::Audit, "target_id", Some(value)))
        .transpose()?;
    Ok((target_type, target_id))
}

impl ExportAuditRecord {
    #[must_use]
    pub fn builder() -> ExportAuditRecordBuilder {
        ExportAuditRecordBuilder::default()
    }
}

#[derive(Clone, Debug, Default)]
pub struct ExportAuditRecordBuilder {
    audit_id: Option<String>,
    operation: Option<String>,
    target_type: Option<String>,
    target_id: Option<String>,
    performed_at: Option<String>,
    performed_by: Option<String>,
    details: Option<serde_json::Value>,
}

impl ExportAuditRecordBuilder {
    #[must_use]
    pub fn audit_id(mut self, audit_id: impl Into<String>) -> Self {
        self.audit_id = Some(audit_id.into());
        self
    }

    #[must_use]
    pub fn operation(mut self, operation: impl Into<String>) -> Self {
        self.operation = Some(operation.into());
        self
    }

    #[must_use]
    pub fn target_type(mut self, target_type: impl Into<String>) -> Self {
        self.target_type = Some(target_type.into());
        self
    }

    #[must_use]
    pub fn target_id(mut self, target_id: impl Into<String>) -> Self {
        self.target_id = Some(target_id.into());
        self
    }

    #[must_use]
    pub fn performed_at(mut self, performed_at: impl Into<String>) -> Self {
        self.performed_at = Some(performed_at.into());
        self
    }

    #[must_use]
    pub fn performed_by(mut self, performed_by: impl Into<String>) -> Self {
        self.performed_by = Some(performed_by.into());
        self
    }

    #[must_use]
    pub fn details(mut self, details: serde_json::Value) -> Self {
        self.details = Some(details);
        self
    }

    /// Build the audit export record.
    ///
    /// # Errors
    ///
    /// Returns an error when a required machine-facing field, or an optional target field that
    /// is present, is blank.
    pub fn build(self) -> Result<ExportAuditRecord, ExportRecordBuildError> {
        let (target_type, target_id) =
            validated_audit_target_fields(self.target_type, self.target_id)?;
        Ok(ExportAuditRecord {
            schema: EXPORT_AUDIT_SCHEMA_V1.to_owned(),
            audit_id: required_string(ExportRecordType::Audit, "audit_id", self.audit_id)?,
            operation: required_string(ExportRecordType::Audit, "operation", self.operation)?,
            target_type,
            target_id,
            performed_at: required_string(
                ExportRecordType::Audit,
                "performed_at",
                self.performed_at,
            )?,
            performed_by: self.performed_by,
            details: self.details,
        })
    }
}

/// Export workspace record.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ExportWorkspaceRecord {
    pub schema: String,
    pub workspace_id: String,
    pub path: String,
    pub name: Option<String>,
    pub created_at: String,
    pub last_accessed: Option<String>,
}

impl ExportWorkspaceRecord {
    #[must_use]
    pub fn builder() -> ExportWorkspaceRecordBuilder {
        ExportWorkspaceRecordBuilder::default()
    }
}

#[derive(Clone, Debug, Default)]
pub struct ExportWorkspaceRecordBuilder {
    workspace_id: Option<String>,
    path: Option<String>,
    name: Option<String>,
    created_at: Option<String>,
    last_accessed: Option<String>,
}

impl ExportWorkspaceRecordBuilder {
    #[must_use]
    pub fn workspace_id(mut self, workspace_id: impl Into<String>) -> Self {
        self.workspace_id = Some(workspace_id.into());
        self
    }

    #[must_use]
    pub fn path(mut self, path: impl Into<String>) -> Self {
        self.path = Some(path.into());
        self
    }

    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    #[must_use]
    pub fn created_at(mut self, created_at: impl Into<String>) -> Self {
        self.created_at = Some(created_at.into());
        self
    }

    #[must_use]
    pub fn last_accessed(mut self, last_accessed: impl Into<String>) -> Self {
        self.last_accessed = Some(last_accessed.into());
        self
    }

    /// Build the workspace export record.
    ///
    /// # Errors
    ///
    /// Returns an error when a required machine-facing field is missing or blank.
    pub fn build(self) -> Result<ExportWorkspaceRecord, ExportRecordBuildError> {
        Ok(ExportWorkspaceRecord {
            schema: EXPORT_WORKSPACE_SCHEMA_V1.to_owned(),
            workspace_id: required_string(
                ExportRecordType::Workspace,
                "workspace_id",
                self.workspace_id,
            )?,
            path: required_string(ExportRecordType::Workspace, "path", self.path)?,
            name: self.name,
            created_at: required_string(
                ExportRecordType::Workspace,
                "created_at",
                self.created_at,
            )?,
            last_accessed: self.last_accessed,
        })
    }
}

/// Export agent record.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ExportAgentRecord {
    pub schema: String,
    pub agent_id: String,
    pub name: String,
    pub program: Option<String>,
    pub model: Option<String>,
    pub created_at: String,
    pub last_seen: Option<String>,
}

impl ExportAgentRecord {
    #[must_use]
    pub fn builder() -> ExportAgentRecordBuilder {
        ExportAgentRecordBuilder::default()
    }
}

#[derive(Clone, Debug, Default)]
pub struct ExportAgentRecordBuilder {
    agent_id: Option<String>,
    name: Option<String>,
    program: Option<String>,
    model: Option<String>,
    created_at: Option<String>,
    last_seen: Option<String>,
}

impl ExportAgentRecordBuilder {
    #[must_use]
    pub fn agent_id(mut self, agent_id: impl Into<String>) -> Self {
        self.agent_id = Some(agent_id.into());
        self
    }

    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    #[must_use]
    pub fn program(mut self, program: impl Into<String>) -> Self {
        self.program = Some(program.into());
        self
    }

    #[must_use]
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    #[must_use]
    pub fn created_at(mut self, created_at: impl Into<String>) -> Self {
        self.created_at = Some(created_at.into());
        self
    }

    #[must_use]
    pub fn last_seen(mut self, last_seen: impl Into<String>) -> Self {
        self.last_seen = Some(last_seen.into());
        self
    }

    /// Build the agent export record.
    ///
    /// # Errors
    ///
    /// Returns an error when a required machine-facing field is missing or blank.
    pub fn build(self) -> Result<ExportAgentRecord, ExportRecordBuildError> {
        Ok(ExportAgentRecord {
            schema: EXPORT_AGENT_SCHEMA_V1.to_owned(),
            agent_id: required_string(ExportRecordType::Agent, "agent_id", self.agent_id)?,
            name: required_string(ExportRecordType::Agent, "name", self.name)?,
            program: self.program,
            model: self.model,
            created_at: required_string(ExportRecordType::Agent, "created_at", self.created_at)?,
            last_seen: self.last_seen,
        })
    }
}

/// Typed union of all export record types.
#[derive(Clone, Debug, Serialize)]
#[serde(untagged)]
pub enum ExportRecord {
    Header(ExportHeader),
    Memory(Box<ExportMemoryRecord>),
    Artifact(ExportArtifactRecord),
    Link(ExportLinkRecord),
    Tag(ExportTagRecord),
    Agent(ExportAgentRecord),
    Workspace(ExportWorkspaceRecord),
    Audit(ExportAuditRecord),
    Footer(ExportFooter),
}

impl<'de> Deserialize<'de> for ExportRecord {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = serde_json::Value::deserialize(deserializer)?;
        let schema = value
            .get("schema")
            .and_then(serde_json::Value::as_str)
            .ok_or_else(|| serde::de::Error::custom("export record requires string schema"))?;
        match schema {
            EXPORT_HEADER_SCHEMA_V1 => serde_json::from_value(value)
                .map(Self::Header)
                .map_err(serde::de::Error::custom),
            EXPORT_MEMORY_SCHEMA_V1 => serde_json::from_value(value)
                .map(Box::new)
                .map(Self::Memory)
                .map_err(serde::de::Error::custom),
            EXPORT_ARTIFACT_SCHEMA_V1 => serde_json::from_value(value)
                .map(Self::Artifact)
                .map_err(serde::de::Error::custom),
            EXPORT_LINK_SCHEMA_V1 => serde_json::from_value(value)
                .map(Self::Link)
                .map_err(serde::de::Error::custom),
            EXPORT_TAG_SCHEMA_V1 => serde_json::from_value(value)
                .map(Self::Tag)
                .map_err(serde::de::Error::custom),
            EXPORT_AGENT_SCHEMA_V1 => serde_json::from_value(value)
                .map(Self::Agent)
                .map_err(serde::de::Error::custom),
            EXPORT_WORKSPACE_SCHEMA_V1 => serde_json::from_value(value)
                .map(Self::Workspace)
                .map_err(serde::de::Error::custom),
            EXPORT_AUDIT_SCHEMA_V1 => serde_json::from_value(value)
                .map(Self::Audit)
                .map_err(serde::de::Error::custom),
            EXPORT_FOOTER_SCHEMA_V1 => serde_json::from_value(value)
                .map(Self::Footer)
                .map_err(serde::de::Error::custom),
            _ => Err(serde::de::Error::custom(format!(
                "unsupported export record schema `{schema}`"
            ))),
        }
    }
}

impl ExportRecord {
    #[must_use]
    pub fn record_type(&self) -> ExportRecordType {
        match self {
            Self::Header(_) => ExportRecordType::Header,
            Self::Memory(_) => ExportRecordType::Memory,
            Self::Artifact(_) => ExportRecordType::Artifact,
            Self::Link(_) => ExportRecordType::Link,
            Self::Tag(_) => ExportRecordType::Tag,
            Self::Agent(_) => ExportRecordType::Agent,
            Self::Workspace(_) => ExportRecordType::Workspace,
            Self::Audit(_) => ExportRecordType::Audit,
            Self::Footer(_) => ExportRecordType::Footer,
        }
    }

    #[must_use]
    pub fn schema(&self) -> &str {
        match self {
            Self::Header(h) => &h.schema,
            Self::Memory(m) => &m.schema,
            Self::Artifact(a) => &a.schema,
            Self::Link(l) => &l.schema,
            Self::Tag(t) => &t.schema,
            Self::Agent(a) => &a.schema,
            Self::Workspace(w) => &w.schema,
            Self::Audit(a) => &a.schema,
            Self::Footer(f) => &f.schema,
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    type TestResult = Result<(), String>;

    fn ensure<T: std::fmt::Debug + PartialEq>(actual: T, expected: T, ctx: &str) -> TestResult {
        if actual == expected {
            Ok(())
        } else {
            Err(format!("{ctx}: expected {expected:?}, got {actual:?}"))
        }
    }

    fn ensure_json_round_trip<T>(value: &T, ctx: &str) -> TestResult
    where
        T: serde::Serialize + serde::de::DeserializeOwned + std::fmt::Debug + PartialEq,
    {
        let json = serde_json::to_string(value)
            .map_err(|error| format!("{ctx} must serialize as JSON: {error}"))?;
        let parsed: T = serde_json::from_str(&json)
            .map_err(|error| format!("{ctx} must deserialize from JSON: {error}"))?;
        ensure(&parsed, value, ctx)
    }

    fn ensure_build_error<T: std::fmt::Debug>(
        result: Result<T, ExportRecordBuildError>,
        record_type: ExportRecordType,
        field: &'static str,
        ctx: &str,
    ) -> TestResult {
        let error = result
            .map(|_| ())
            .expect_err("avoid unwrap_err in production code");
        ensure(
            error.record_type,
            record_type,
            &format!("{ctx} record type"),
        )?;
        ensure(error.field, field, &format!("{ctx} field"))
    }

    fn ensure_export_record_match(
        actual: &ExportRecord,
        expected: &ExportRecord,
        ctx: &str,
    ) -> TestResult {
        ensure(
            actual.record_type(),
            expected.record_type(),
            &format!("{ctx} type"),
        )?;
        match (actual, expected) {
            (ExportRecord::Header(actual), ExportRecord::Header(expected)) => {
                ensure(actual, expected, ctx)
            }
            (ExportRecord::Memory(actual), ExportRecord::Memory(expected)) => {
                ensure(actual, expected, ctx)
            }
            (ExportRecord::Artifact(actual), ExportRecord::Artifact(expected)) => {
                ensure(actual, expected, ctx)
            }
            (ExportRecord::Link(actual), ExportRecord::Link(expected)) => {
                ensure(actual, expected, ctx)
            }
            (ExportRecord::Tag(actual), ExportRecord::Tag(expected)) => {
                ensure(actual, expected, ctx)
            }
            (ExportRecord::Agent(actual), ExportRecord::Agent(expected)) => {
                ensure(actual, expected, ctx)
            }
            (ExportRecord::Workspace(actual), ExportRecord::Workspace(expected)) => {
                ensure(actual, expected, ctx)
            }
            (ExportRecord::Audit(actual), ExportRecord::Audit(expected)) => {
                ensure(actual, expected, ctx)
            }
            (ExportRecord::Footer(actual), ExportRecord::Footer(expected)) => {
                ensure(actual, expected, ctx)
            }
            _ => Err(format!("{ctx}: mismatched record variants")),
        }
    }

    #[test]
    fn export_record_type_roundtrip() -> TestResult {
        for rt in ExportRecordType::all() {
            let s = rt.as_str();
            let parsed: ExportRecordType = s
                .parse()
                .map_err(|e: ParseExportRecordTypeError| e.to_string())?;
            ensure(parsed, *rt, &format!("roundtrip {s}"))?;
        }
        Ok(())
    }

    #[test]
    fn export_record_type_parse_normalizes_external_values() -> TestResult {
        ensure(
            " Memory ".parse::<ExportRecordType>(),
            Ok(ExportRecordType::Memory),
            "record type trims and lowercases",
        )?;
        ensure(
            "WORKSPACE".parse::<ExportRecordType>(),
            Ok(ExportRecordType::Workspace),
            "record type accepts uppercase",
        )
    }

    #[test]
    fn export_record_type_display() {
        assert_eq!(ExportRecordType::Header.to_string(), "header");
        assert_eq!(ExportRecordType::Memory.to_string(), "memory");
        assert_eq!(ExportRecordType::Footer.to_string(), "footer");
    }

    #[test]
    fn export_record_type_schema_mapping() {
        assert_eq!(ExportRecordType::Header.schema(), EXPORT_HEADER_SCHEMA_V1);
        assert_eq!(ExportRecordType::Memory.schema(), EXPORT_MEMORY_SCHEMA_V1);
        assert_eq!(
            ExportRecordType::Artifact.schema(),
            EXPORT_ARTIFACT_SCHEMA_V1
        );
        assert_eq!(ExportRecordType::Footer.schema(), EXPORT_FOOTER_SCHEMA_V1);
        assert_eq!(ExportRecordType::Audit.schema(), EXPORT_AUDIT_SCHEMA_V1);
        assert_eq!(ExportRecordType::Link.schema(), EXPORT_LINK_SCHEMA_V1);
        assert_eq!(ExportRecordType::Tag.schema(), EXPORT_TAG_SCHEMA_V1);
        assert_eq!(ExportRecordType::Agent.schema(), EXPORT_AGENT_SCHEMA_V1);
        assert_eq!(
            ExportRecordType::Workspace.schema(),
            EXPORT_WORKSPACE_SCHEMA_V1
        );
    }

    #[test]
    fn redaction_level_roundtrip() -> TestResult {
        for level in RedactionLevel::all() {
            let s = level.as_str();
            let parsed: RedactionLevel = s
                .parse()
                .map_err(|e: ParseRedactionLevelError| e.to_string())?;
            ensure(parsed, *level, &format!("roundtrip {s}"))?;
        }
        Ok(())
    }

    #[test]
    fn redaction_level_parse_normalizes_external_values_and_legacy_alias() -> TestResult {
        ensure(
            " Strict ".parse::<RedactionLevel>(),
            Ok(RedactionLevel::Strict),
            "redaction level trims and lowercases",
        )?;
        ensure(
            "FULL".parse::<RedactionLevel>(),
            Ok(RedactionLevel::Full),
            "redaction level accepts legacy full alias",
        )
    }

    #[test]
    fn redaction_level_capabilities() {
        assert!(!RedactionLevel::None.redacts_secrets());
        assert!(RedactionLevel::Minimal.redacts_secrets());
        assert!(!RedactionLevel::Minimal.redacts_paths());
        assert!(RedactionLevel::Standard.redacts_paths());
        assert!(RedactionLevel::Standard.redacts_identifiers());
        assert!(!RedactionLevel::Standard.redacts_content());
        assert!(RedactionLevel::Strict.redacts_content());
        assert!(RedactionLevel::Paranoid.redacts_content());
        assert!(RedactionLevel::Paranoid.redacts_identifiers());
        assert!(RedactionLevel::Full.redacts_content());
    }

    #[test]
    fn export_scope_roundtrip() -> TestResult {
        for scope in ExportScope::all() {
            let s = scope.as_str();
            let parsed: ExportScope = s
                .parse()
                .map_err(|e: ParseExportScopeError| e.to_string())?;
            ensure(parsed, *scope, &format!("roundtrip {s}"))?;
        }
        Ok(())
    }

    #[test]
    fn export_scope_parse_normalizes_external_values() -> TestResult {
        ensure(
            " Metadata-Only ".parse::<ExportScope>(),
            Ok(ExportScope::MetadataOnly),
            "export scope trims, lowercases, and accepts hyphen separator",
        )?;
        ensure(
            "metadataOnly".parse::<ExportScope>(),
            Ok(ExportScope::MetadataOnly),
            "export scope accepts camelCase",
        )
    }

    #[test]
    fn export_scope_includes_checks() {
        assert!(ExportScope::All.includes_memories());
        assert!(ExportScope::All.includes_audit());
        assert!(ExportScope::All.includes_links());
        assert!(ExportScope::All.includes_content());

        assert!(ExportScope::Memories.includes_memories());
        assert!(!ExportScope::Memories.includes_audit());
        assert!(!ExportScope::Memories.includes_links());

        assert!(!ExportScope::Audit.includes_memories());
        assert!(ExportScope::Audit.includes_audit());

        assert!(ExportScope::MetadataOnly.includes_memories());
        assert!(!ExportScope::MetadataOnly.includes_content());
    }

    #[test]
    fn export_header_builder() {
        let header = ExportHeader::builder()
            .created_at("2026-04-30T12:00:00Z")
            .workspace_id("ws-123")
            .export_scope(ExportScope::Memories)
            .redaction_level(RedactionLevel::Standard)
            .record_count(42)
            .ee_version("0.1.0")
            .export_id("exp-001")
            .build()
            .expect("header has required fields");

        assert_eq!(header.schema, EXPORT_HEADER_SCHEMA_V1);
        assert_eq!(header.format_version, EXPORT_FORMAT_VERSION);
        assert_eq!(header.created_at, "2026-04-30T12:00:00Z");
        assert_eq!(header.workspace_id, Some("ws-123".to_owned()));
        assert_eq!(header.export_scope, ExportScope::Memories);
        assert_eq!(header.redaction_level, RedactionLevel::Standard);
        assert_eq!(header.record_count, Some(42));
        assert_eq!(header.ee_version, "0.1.0");
        assert_eq!(header.export_id, "exp-001");
    }

    #[test]
    fn export_footer_builder() {
        let footer = ExportFooter::builder()
            .export_id("exp-001")
            .completed_at("2026-04-30T12:01:00Z")
            .total_records(100)
            .memory_count(50)
            .artifact_count(7)
            .link_count(20)
            .tag_count(25)
            .audit_count(5)
            .checksum("abc123")
            .success(true)
            .build()
            .expect("footer has required fields");

        assert_eq!(footer.schema, EXPORT_FOOTER_SCHEMA_V1);
        assert_eq!(footer.export_id, "exp-001");
        assert_eq!(footer.total_records, 100);
        assert_eq!(footer.memory_count, 50);
        assert_eq!(footer.artifact_count, 7);
        assert!(footer.success);
        assert_eq!(footer.checksum, Some("abc123".to_owned()));
    }

    #[test]
    fn export_memory_record_builder() {
        let memory = ExportMemoryRecord::builder()
            .memory_id("mem-001")
            .workspace_id("ws-123")
            .level("procedural")
            .kind("rule")
            .content("Always run tests before commit")
            .content_hash("blake3:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")
            .importance(0.8)
            .confidence(0.9)
            .utility(0.7)
            .pagerank_score(0.12)
            .betweenness_score(0.34)
            .hits_authority(0.56)
            .hits_hub(0.78)
            .onion_layer(3)
            .k_truss_max(4)
            .articulation_point(true)
            .bayes_alpha(2.5)
            .bayes_beta(1.5)
            .created_at("2026-04-30T12:00:00Z")
            .tombstoned_at("2026-05-01T12:00:00Z")
            .tombstoned_reason("outdated release procedure")
            .valid_from("2026-04-01T00:00:00Z")
            .valid_to("2026-06-01T00:00:00Z")
            .source_agent("claude-code")
            .redacted(false)
            .build()
            .expect("memory has required fields");

        assert_eq!(memory.schema, EXPORT_MEMORY_SCHEMA_V1);
        assert_eq!(memory.memory_id, "mem-001");
        assert_eq!(memory.level, "procedural");
        assert_eq!(memory.kind, "rule");
        assert_eq!(
            memory.content_hash.as_deref(),
            Some("blake3:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")
        );
        assert_eq!(memory.importance, Some(0.8));
        assert_eq!(memory.utility, Some(0.7));
        assert_eq!(memory.pagerank_score, Some(0.12));
        assert_eq!(memory.betweenness_score, Some(0.34));
        assert_eq!(memory.hits_authority, Some(0.56));
        assert_eq!(memory.hits_hub, Some(0.78));
        assert_eq!(memory.onion_layer, Some(3));
        assert_eq!(memory.k_truss_max, Some(4));
        assert_eq!(memory.articulation_point, Some(true));
        assert_eq!(memory.bayes_alpha, Some(2.5));
        assert_eq!(memory.bayes_beta, Some(1.5));
        assert_eq!(
            memory.tombstoned_at.as_deref(),
            Some("2026-05-01T12:00:00Z")
        );
        assert_eq!(
            memory.tombstoned_reason.as_deref(),
            Some("outdated release procedure")
        );
        assert_eq!(memory.valid_from.as_deref(), Some("2026-04-01T00:00:00Z"));
        assert_eq!(memory.valid_to.as_deref(), Some("2026-06-01T00:00:00Z"));
        assert!(!memory.redacted);
    }

    #[test]
    fn export_memory_builder_preserves_body_whitespace_and_normalizes_identifiers() {
        let content = "\u{2003}  indented evidence\n\tsecond line\r\n";
        let memory = ExportMemoryRecord::builder()
            .memory_id(" mem-001\n")
            .workspace_id(" ws-123 ")
            .level("procedural")
            .kind("rule")
            .content(content)
            .created_at("2026-04-30T12:00:00Z")
            .build()
            .expect("memory has required fields");

        assert_eq!(memory.memory_id, "mem-001");
        assert_eq!(memory.workspace_id, "ws-123");
        assert_eq!(memory.content, content);
        let encoded = serde_json::to_string(&memory).expect("memory serializes");
        let decoded: ExportMemoryRecord =
            serde_json::from_str(&encoded).expect("memory deserializes");
        assert_eq!(decoded.content, content);
    }

    #[test]
    fn export_artifact_record_builder() {
        let artifact = ExportArtifactRecord::builder()
            .artifact_id("art_01234567890123456789012345")
            .workspace_id("ws-123")
            .source_kind("file")
            .artifact_type("log")
            .original_path("logs/build.log")
            .canonical_path("/workspace/logs/build.log")
            .content_hash("blake3:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")
            .media_type("text/plain")
            .size_bytes(42)
            .redaction_status("checked")
            .snippet("build ok")
            .created_at("2026-04-30T12:00:00Z")
            .updated_at("2026-04-30T12:00:00Z")
            .build()
            .expect("artifact has required fields");

        assert_eq!(artifact.schema, EXPORT_ARTIFACT_SCHEMA_V1);
        assert_eq!(artifact.artifact_id, "art_01234567890123456789012345");
        assert_eq!(artifact.source_kind, "file");
        assert_eq!(artifact.artifact_type, "log");
        assert_eq!(artifact.redaction_status, "checked");
        assert_eq!(artifact.snippet, Some("build ok".to_owned()));
    }

    #[test]
    fn export_link_record_builder() {
        let link = ExportLinkRecord::builder()
            .link_id("lnk-001")
            .source_memory_id("mem-001")
            .target_memory_id("mem-002")
            .link_type("supports")
            .weight(0.7)
            .created_at("2026-04-30T12:00:00Z")
            .build()
            .expect("link has required fields");

        assert_eq!(link.schema, EXPORT_LINK_SCHEMA_V1);
        assert_eq!(link.link_id, "lnk-001");
        assert_eq!(link.link_type, "supports");
        assert_eq!(link.weight, Some(0.7));
    }

    #[test]
    fn export_tag_record_builder() {
        let tag = ExportTagRecord::builder()
            .memory_id("mem-001")
            .tag("important")
            .created_at("2026-04-30T12:00:00Z")
            .build()
            .expect("tag has required fields");
        assert_eq!(tag.schema, EXPORT_TAG_SCHEMA_V1);
        assert_eq!(tag.memory_id, "mem-001");
        assert_eq!(tag.tag, "important");
    }

    #[test]
    fn export_audit_record_builder() {
        let audit = ExportAuditRecord::builder()
            .audit_id("aud-001")
            .operation("create")
            .target_type("memory")
            .target_id("mem-001")
            .performed_at("2026-04-30T12:00:00Z")
            .performed_by("claude-code")
            .build()
            .expect("audit has required fields");

        assert_eq!(audit.schema, EXPORT_AUDIT_SCHEMA_V1);
        assert_eq!(audit.audit_id, "aud-001");
        assert_eq!(audit.operation, "create");
        assert_eq!(audit.target_type.as_deref(), Some("memory"));
        assert_eq!(audit.target_id.as_deref(), Some("mem-001"));
        assert_eq!(audit.performed_by, Some("claude-code".to_owned()));
    }

    #[test]
    fn export_targetless_audit_round_trips_with_null_target_pair() -> TestResult {
        let audit = ExportAuditRecord::builder()
            .audit_id("aud-db-check-001")
            .operation("db.check_integrity")
            .performed_at("2026-04-30T12:00:00Z")
            .performed_by("ee db check-integrity")
            .details(serde_json::json!({ "passed": true }))
            .build()
            .map_err(|error| format!("targetless audit must build: {error}"))?;

        ensure(
            audit.target_type.as_deref(),
            None,
            "targetless audit target type",
        )?;
        ensure(
            audit.target_id.as_deref(),
            None,
            "targetless audit target id",
        )?;

        let json = serde_json::to_value(&audit)
            .map_err(|error| format!("targetless audit must serialize: {error}"))?;
        ensure(
            json.get("target_type"),
            Some(&serde_json::Value::Null),
            "targetless audit serializes target_type as null",
        )?;
        ensure(
            json.get("target_id"),
            Some(&serde_json::Value::Null),
            "targetless audit serializes target_id as null",
        )?;

        let parsed: ExportAuditRecord = serde_json::from_value(json)
            .map_err(|error| format!("targetless audit must deserialize: {error}"))?;
        ensure(&parsed, &audit, "targetless audit JSON round trip")?;

        let export_record = ExportRecord::Audit(audit.clone());
        let jsonl = serde_json::to_string(&export_record)
            .map_err(|error| format!("targetless audit record must render as JSONL: {error}"))?;
        let parsed_record: ExportRecord = serde_json::from_str(&jsonl)
            .map_err(|error| format!("targetless audit JSONL must parse: {error}"))?;
        ensure_export_record_match(
            &parsed_record,
            &export_record,
            "targetless audit ExportRecord round trip",
        )?;

        let parsed_without_target_fields: ExportAuditRecord =
            serde_json::from_value(serde_json::json!({
                "schema": EXPORT_AUDIT_SCHEMA_V1,
                "audit_id": "aud-db-check-002",
                "operation": "db.check_integrity",
                "performed_at": "2026-04-30T12:01:00Z",
                "performed_by": "ee db check-integrity",
                "details": { "passed": true }
            }))
            .map_err(|error| format!("omitted target pair must deserialize: {error}"))?;
        ensure(
            parsed_without_target_fields.target_type,
            None,
            "omitted target_type parses as absent",
        )?;
        ensure(
            parsed_without_target_fields.target_id,
            None,
            "omitted target_id parses as absent",
        )
    }

    #[test]
    fn export_audit_round_trips_independently_optional_target_fields() -> TestResult {
        for (audit, expected_type, expected_id, ctx) in [
            (
                ExportAuditRecord::builder()
                    .audit_id("aud-search-completed")
                    .operation("search_completed")
                    .target_type("search")
                    .performed_at("2026-04-30T12:00:00Z")
                    .build()
                    .map_err(|error| format!("type-only audit must build: {error}"))?,
                Some("search"),
                None,
                "type-only search audit",
            ),
            (
                ExportAuditRecord::builder()
                    .audit_id("aud-source-observed")
                    .operation("source_observed")
                    .target_id("source-001")
                    .performed_at("2026-04-30T12:01:00Z")
                    .build()
                    .map_err(|error| format!("id-only audit must build: {error}"))?,
                None,
                Some("source-001"),
                "id-only source audit",
            ),
        ] {
            ensure(
                audit.target_type.as_deref(),
                expected_type,
                &format!("{ctx} target_type"),
            )?;
            ensure(
                audit.target_id.as_deref(),
                expected_id,
                &format!("{ctx} target_id"),
            )?;
            ensure_json_round_trip(&audit, ctx)?;
        }

        Ok(())
    }

    #[test]
    fn export_audit_rejects_blank_present_target_fields() -> TestResult {
        for (builder, field, ctx) in [
            (
                ExportAuditRecord::builder()
                    .audit_id("aud-blank-type")
                    .operation("memory.inspect")
                    .target_type("   ")
                    .target_id("mem-001")
                    .performed_at("2026-04-30T12:00:00Z"),
                "target_type",
                "audit with blank target_type",
            ),
            (
                ExportAuditRecord::builder()
                    .audit_id("aud-blank-id")
                    .operation("memory.inspect")
                    .target_type("memory")
                    .target_id("\n\t")
                    .performed_at("2026-04-30T12:00:00Z"),
                "target_id",
                "audit with blank target_id",
            ),
        ] {
            ensure_build_error(builder.build(), ExportRecordType::Audit, field, ctx)?;
        }

        for (target_fragment, expected_field) in [
            (r#""target_type":" ","target_id":"mem-001""#, "target_type"),
            (r#""target_type":"memory","target_id":"""#, "target_id"),
        ] {
            let json = format!(
                r#"{{"schema":"{EXPORT_AUDIT_SCHEMA_V1}","audit_id":"aud-invalid","operation":"memory.inspect",{target_fragment},"performed_at":"2026-04-30T12:00:00Z","performed_by":null,"details":null}}"#
            );
            let error = serde_json::from_str::<ExportAuditRecord>(&json)
                .expect_err("malformed audit target pair must not deserialize");
            ensure(
                error.to_string().contains(expected_field),
                true,
                &format!("malformed audit error identifies {expected_field}"),
            )?;
            ensure(
                serde_json::from_str::<ExportRecord>(&json).is_err(),
                true,
                "malformed audit must not pass through the untagged ExportRecord union",
            )?;
        }

        Ok(())
    }

    #[test]
    fn export_workspace_record_builder() {
        let workspace = ExportWorkspaceRecord::builder()
            .workspace_id("ws-123")
            .path("/home/user/project")
            .name("My Project")
            .created_at("2026-04-30T12:00:00Z")
            .build()
            .expect("workspace has required fields");

        assert_eq!(workspace.schema, EXPORT_WORKSPACE_SCHEMA_V1);
        assert_eq!(workspace.workspace_id, "ws-123");
        assert_eq!(workspace.path, "/home/user/project");
        assert_eq!(workspace.name, Some("My Project".to_owned()));
    }

    #[test]
    fn export_agent_record_builder() {
        let agent = ExportAgentRecord::builder()
            .agent_id("agt-001")
            .name("claude-code")
            .program("Claude Code")
            .model("claude-opus-4-5-20251101")
            .created_at("2026-04-30T12:00:00Z")
            .build()
            .expect("agent has required fields");

        assert_eq!(agent.schema, EXPORT_AGENT_SCHEMA_V1);
        assert_eq!(agent.agent_id, "agt-001");
        assert_eq!(agent.name, "claude-code");
        assert_eq!(agent.program, Some("Claude Code".to_owned()));
    }

    #[test]
    fn export_record_builders_reject_missing_required_fields() -> TestResult {
        ensure_build_error(
            ExportHeader::builder()
                .ee_version("0.1.0")
                .export_id("exp-001")
                .build(),
            ExportRecordType::Header,
            "created_at",
            "header missing created_at",
        )?;
        ensure_build_error(
            ExportHeader::builder()
                .created_at("   ")
                .ee_version("0.1.0")
                .export_id("exp-001")
                .build(),
            ExportRecordType::Header,
            "created_at",
            "header blank created_at",
        )?;
        ensure_build_error(
            ExportFooter::builder()
                .completed_at("2026-04-30T12:00:00Z")
                .build(),
            ExportRecordType::Footer,
            "export_id",
            "footer missing export_id",
        )?;
        ensure_build_error(
            ExportMemoryRecord::builder()
                .memory_id("mem-001")
                .workspace_id("ws-123")
                .level("procedural")
                .kind("rule")
                .created_at("2026-04-30T12:00:00Z")
                .build(),
            ExportRecordType::Memory,
            "content",
            "memory missing content",
        )?;
        for content in ["", " \t\r\n", "\u{2003}"] {
            ensure_build_error(
                ExportMemoryRecord::builder()
                    .memory_id("mem-001")
                    .workspace_id("ws-123")
                    .level("procedural")
                    .kind("rule")
                    .content(content)
                    .created_at("2026-04-30T12:00:00Z")
                    .build(),
                ExportRecordType::Memory,
                "content",
                "memory blank content",
            )?;
        }
        ensure_build_error(
            ExportArtifactRecord::builder()
                .artifact_id("art-001")
                .workspace_id("ws-123")
                .source_kind("file")
                .artifact_type("log")
                .content_hash("blake3:abc123")
                .media_type("text/plain")
                .redaction_status("checked")
                .created_at("2026-04-30T12:00:00Z")
                .updated_at("2026-04-30T12:00:00Z")
                .build(),
            ExportRecordType::Artifact,
            "size_bytes",
            "artifact missing size_bytes",
        )?;
        ensure_build_error(
            ExportLinkRecord::builder()
                .link_id("lnk-001")
                .source_memory_id("mem-001")
                .link_type("supports")
                .created_at("2026-04-30T12:00:00Z")
                .build(),
            ExportRecordType::Link,
            "target_memory_id",
            "link missing target_memory_id",
        )?;
        ensure_build_error(
            ExportTagRecord::builder()
                .memory_id("mem-001")
                .created_at("2026-04-30T12:00:00Z")
                .build(),
            ExportRecordType::Tag,
            "tag",
            "tag record missing tag",
        )?;
        ensure_build_error(
            ExportTagRecord::builder()
                .memory_id("   ")
                .tag("important")
                .created_at("2026-04-30T12:00:00Z")
                .build(),
            ExportRecordType::Tag,
            "memory_id",
            "tag record blank memory_id",
        )?;
        ensure_build_error(
            ExportAuditRecord::builder()
                .audit_id("aud-001")
                .operation("create")
                .target_id("mem-001")
                .build(),
            ExportRecordType::Audit,
            "performed_at",
            "audit missing performed_at",
        )?;
        ensure_build_error(
            ExportWorkspaceRecord::builder()
                .workspace_id("ws-123")
                .created_at("2026-04-30T12:00:00Z")
                .build(),
            ExportRecordType::Workspace,
            "path",
            "workspace missing path",
        )?;
        ensure_build_error(
            ExportAgentRecord::builder()
                .agent_id("agt-001")
                .created_at("2026-04-30T12:00:00Z")
                .build(),
            ExportRecordType::Agent,
            "name",
            "agent missing name",
        )
    }

    #[test]
    fn export_record_union_type_detection() {
        let header = ExportRecord::Header(
            ExportHeader::builder()
                .created_at("2026-04-30T12:00:00Z")
                .ee_version("0.1.0")
                .export_id("exp-union")
                .build()
                .expect("header has required fields"),
        );
        assert_eq!(header.record_type(), ExportRecordType::Header);
        assert_eq!(header.schema(), EXPORT_HEADER_SCHEMA_V1);

        let memory = ExportRecord::Memory(Box::new(
            ExportMemoryRecord::builder()
                .memory_id("mem-union")
                .workspace_id("ws-union")
                .level("procedural")
                .kind("rule")
                .content("Union memory")
                .created_at("2026-04-30T12:00:00Z")
                .build()
                .expect("memory has required fields"),
        ));
        assert_eq!(memory.record_type(), ExportRecordType::Memory);
        assert_eq!(memory.schema(), EXPORT_MEMORY_SCHEMA_V1);

        let artifact = ExportRecord::Artifact(
            ExportArtifactRecord::builder()
                .artifact_id("art-union")
                .workspace_id("ws-union")
                .source_kind("file")
                .artifact_type("log")
                .content_hash("blake3:union")
                .media_type("text/plain")
                .size_bytes(0)
                .redaction_status("checked")
                .created_at("2026-04-30T12:00:00Z")
                .updated_at("2026-04-30T12:00:00Z")
                .build()
                .expect("artifact has required fields"),
        );
        assert_eq!(artifact.record_type(), ExportRecordType::Artifact);
        assert_eq!(artifact.schema(), EXPORT_ARTIFACT_SCHEMA_V1);

        let footer = ExportRecord::Footer(
            ExportFooter::builder()
                .export_id("exp-union")
                .completed_at("2026-04-30T12:00:00Z")
                .build()
                .expect("footer has required fields"),
        );
        assert_eq!(footer.record_type(), ExportRecordType::Footer);
        assert_eq!(footer.schema(), EXPORT_FOOTER_SCHEMA_V1);
    }

    #[test]
    fn concrete_export_records_round_trip_through_json() -> TestResult {
        ensure_json_round_trip(
            &ExportHeader::builder()
                .created_at("2026-04-30T12:00:00Z")
                .workspace_id("wsp_01234567890123456789012345")
                .workspace_path("/workspace/project")
                .export_scope(ExportScope::All)
                .redaction_level(RedactionLevel::Standard)
                .record_count(6)
                .ee_version("0.1.0")
                .hostname("agent-host")
                .export_id("exp-round-trip")
                .import_source(ImportSource::Native)
                .trust_level(TrustLevel::Validated)
                .checksum("blake3:export")
                .signature("sigstore:fixture")
                .source_schema_version("ee.export.v1")
                .build()
                .expect("header has required fields"),
            "header round-trip",
        )?;
        ensure_json_round_trip(
            &ExportMemoryRecord::builder()
                .memory_id("mem_01234567890123456789012345")
                .workspace_id("wsp_01234567890123456789012345")
                .level("procedural")
                .kind("rule")
                .content("Run cargo fmt --check before release.")
                .content_hash(
                    "blake3:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
                )
                .importance(0.8)
                .confidence(0.9)
                .utility(0.7)
                .pagerank_score(0.12)
                .betweenness_score(0.34)
                .hits_authority(0.56)
                .hits_hub(0.78)
                .onion_layer(3)
                .k_truss_max(4)
                .articulation_point(false)
                .bayes_alpha(2.5)
                .bayes_beta(1.5)
                .created_at("2026-04-30T12:00:00Z")
                .updated_at("2026-04-30T12:01:00Z")
                .expires_at("2026-05-30T12:00:00Z")
                .source_agent("NobleCardinal")
                .provenance_uri("ee-export://round-trip")
                .supersedes("mem_00234567890123456789012345")
                .superseded_by("mem_00334567890123456789012345")
                .redacted(true)
                .redaction_reason("standard_export")
                .build()
                .expect("memory has required fields"),
            "memory round-trip",
        )?;
        ensure_json_round_trip(
            &ExportArtifactRecord::builder()
                .artifact_id("art_01234567890123456789012345")
                .workspace_id("wsp_01234567890123456789012345")
                .source_kind("file")
                .artifact_type("log")
                .original_path("logs/build.log")
                .canonical_path("/workspace/project/logs/build.log")
                .content_hash(
                    "blake3:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
                )
                .media_type("text/plain")
                .size_bytes(256)
                .redaction_status("checked")
                .snippet("cargo fmt passed")
                .snippet_hash(
                    "blake3:abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
                )
                .provenance_uri("file:///workspace/project/logs/build.log")
                .metadata(serde_json::json!({"title":"build log"}))
                .created_at("2026-04-30T12:01:00Z")
                .updated_at("2026-04-30T12:01:00Z")
                .build()
                .expect("artifact has required fields"),
            "artifact round-trip",
        )?;
        ensure_json_round_trip(
            &ExportLinkRecord::builder()
                .link_id("lnk_01234567890123456789012345")
                .source_memory_id("mem_01234567890123456789012345")
                .target_memory_id("mem_00334567890123456789012345")
                .link_type("supersedes")
                .weight(0.75)
                .created_at("2026-04-30T12:02:00Z")
                .metadata(serde_json::json!({"reason":"round_trip"}))
                .build()
                .expect("link has required fields"),
            "link round-trip",
        )?;
        ensure_json_round_trip(
            &ExportTagRecord::builder()
                .memory_id("mem_01234567890123456789012345")
                .tag("release")
                .created_at("2026-04-30T12:03:00Z")
                .build()
                .expect("tag has required fields"),
            "tag round-trip",
        )?;
        ensure_json_round_trip(
            &ExportAuditRecord::builder()
                .audit_id("aud_01234567890123456789012345")
                .operation("export")
                .target_type("memory")
                .target_id("mem_01234567890123456789012345")
                .performed_at("2026-04-30T12:04:00Z")
                .performed_by("NobleCardinal")
                .details(serde_json::json!({"records":6}))
                .build()
                .expect("audit has required fields"),
            "audit round-trip",
        )?;
        ensure_json_round_trip(
            &ExportWorkspaceRecord::builder()
                .workspace_id("wsp_01234567890123456789012345")
                .path("/workspace/project")
                .name("Round Trip")
                .created_at("2026-04-30T11:00:00Z")
                .last_accessed("2026-04-30T12:05:00Z")
                .build()
                .expect("workspace has required fields"),
            "workspace round-trip",
        )?;
        ensure_json_round_trip(
            &ExportAgentRecord::builder()
                .agent_id("agt_01234567890123456789012345")
                .name("NobleCardinal")
                .program("codex-cli")
                .model("gpt-5")
                .created_at("2026-04-30T11:30:00Z")
                .last_seen("2026-04-30T12:06:00Z")
                .build()
                .expect("agent has required fields"),
            "agent round-trip",
        )?;
        ensure_json_round_trip(
            &ExportFooter::builder()
                .export_id("exp-round-trip")
                .completed_at("2026-04-30T12:07:00Z")
                .total_records(6)
                .memory_count(1)
                .artifact_count(1)
                .link_count(1)
                .tag_count(1)
                .audit_count(1)
                .checksum("blake3:footer")
                .success(true)
                .build()
                .expect("footer has required fields"),
            "footer round-trip",
        )
    }

    #[test]
    fn export_record_union_round_trips_line_delimited_jsonl() -> TestResult {
        let records = [
            ExportRecord::Header(
                ExportHeader::builder()
                    .created_at("2026-04-30T12:00:00Z")
                    .workspace_id("wsp_01234567890123456789012345")
                    .export_scope(ExportScope::All)
                    .redaction_level(RedactionLevel::Minimal)
                    .record_count(6)
                    .ee_version("0.1.0")
                    .export_id("exp-jsonl-round-trip")
                    .import_source(ImportSource::Native)
                    .trust_level(TrustLevel::Validated)
                    .build()
                    .expect("header has required fields"),
            ),
            ExportRecord::Workspace(
                ExportWorkspaceRecord::builder()
                    .workspace_id("wsp_01234567890123456789012345")
                    .path("/workspace/project")
                    .name("Round Trip")
                    .created_at("2026-04-30T11:00:00Z")
                    .build()
                    .expect("workspace has required fields"),
            ),
            ExportRecord::Agent(
                ExportAgentRecord::builder()
                    .agent_id("agt_01234567890123456789012345")
                    .name("NobleCardinal")
                    .program("codex-cli")
                    .model("gpt-5")
                    .created_at("2026-04-30T11:30:00Z")
                    .build()
                    .expect("agent has required fields"),
            ),
            ExportRecord::Memory(Box::new(
                ExportMemoryRecord::builder()
                    .memory_id("mem_01234567890123456789012345")
                    .workspace_id("wsp_01234567890123456789012345")
                    .level("procedural")
                    .kind("rule")
                    .content("Run cargo fmt --check before release.")
                    .created_at("2026-04-30T12:00:00Z")
                    .source_agent("NobleCardinal")
                    .redacted(false)
                    .build()
                    .expect("memory has required fields"),
            )),
            ExportRecord::Artifact(
                ExportArtifactRecord::builder()
                    .artifact_id("art_01234567890123456789012345")
                    .workspace_id("wsp_01234567890123456789012345")
                    .source_kind("file")
                    .artifact_type("log")
                    .original_path("logs/build.log")
                    .canonical_path("/workspace/project/logs/build.log")
                    .content_hash(
                        "blake3:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
                    )
                    .media_type("text/plain")
                    .size_bytes(256)
                    .redaction_status("checked")
                    .snippet("cargo fmt passed")
                    .created_at("2026-04-30T12:01:00Z")
                    .updated_at("2026-04-30T12:01:00Z")
                    .build()
                    .expect("artifact has required fields"),
            ),
            ExportRecord::Tag(
                ExportTagRecord::builder()
                    .memory_id("mem_01234567890123456789012345")
                    .tag("release")
                    .created_at("2026-04-30T12:03:00Z")
                    .build()
                    .expect("tag has required fields"),
            ),
            ExportRecord::Link(
                ExportLinkRecord::builder()
                    .link_id("lnk_01234567890123456789012345")
                    .source_memory_id("mem_01234567890123456789012345")
                    .target_memory_id("mem_00334567890123456789012345")
                    .link_type("supports")
                    .weight(0.75)
                    .created_at("2026-04-30T12:02:00Z")
                    .build()
                    .expect("link has required fields"),
            ),
            ExportRecord::Audit(
                ExportAuditRecord::builder()
                    .audit_id("aud_01234567890123456789012345")
                    .operation("export")
                    .target_type("memory")
                    .target_id("mem_01234567890123456789012345")
                    .performed_at("2026-04-30T12:04:00Z")
                    .performed_by("NobleCardinal")
                    .build()
                    .expect("audit has required fields"),
            ),
            ExportRecord::Footer(
                ExportFooter::builder()
                    .export_id("exp-jsonl-round-trip")
                    .completed_at("2026-04-30T12:07:00Z")
                    .total_records(6)
                    .memory_count(1)
                    .artifact_count(1)
                    .link_count(1)
                    .tag_count(1)
                    .audit_count(1)
                    .success(true)
                    .build()
                    .expect("footer has required fields"),
            ),
        ];
        let jsonl = records
            .iter()
            .map(|record| serde_json::to_string(record).map_err(|error| error.to_string()))
            .collect::<Result<Vec<_>, _>>()?
            .join("\n");

        let mut lines = jsonl.lines();
        for (position, expected) in records.iter().enumerate() {
            let line = lines
                .next()
                .ok_or_else(|| format!("missing JSONL record {position}"))?;
            let parsed: ExportRecord = serde_json::from_str(line)
                .map_err(|error| format!("JSONL record {position} must parse: {error}"))?;
            ensure_export_record_match(&parsed, expected, &format!("JSONL record {position}"))?;
        }
        ensure(lines.next().is_none(), true, "no extra JSONL records")?;

        Ok(())
    }

    #[test]
    fn header_serializes_to_json() {
        let header = ExportHeader::builder()
            .created_at("2026-04-30T12:00:00Z")
            .ee_version("0.1.0")
            .export_id("test-export")
            .build()
            .expect("header has required fields");

        let json = serde_json::to_string(&header).expect("serialize");
        assert!(json.contains(r#""schema":"ee.export.header.v1""#));
        assert!(json.contains(r#""format_version":1"#));
        assert!(json.contains(r#""created_at":"2026-04-30T12:00:00Z""#));
    }

    #[test]
    fn memory_record_deserializes_from_json() {
        let json = r#"{
            "schema": "ee.export.memory.v1",
            "memory_id": "mem-001",
            "workspace_id": "ws-123",
            "level": "procedural",
            "kind": "rule",
            "content": "Test content",
            "importance": 0.8,
            "confidence": 0.9,
            "utility": 0.7,
            "pagerank_score": 0.12,
            "betweenness_score": 0.34,
            "hits_authority": 0.56,
            "hits_hub": 0.78,
            "onion_layer": 3,
            "k_truss_max": 4,
            "articulation_point": true,
            "bayes_alpha": 2.5,
            "bayes_beta": 1.5,
            "trust_class": "human_explicit",
            "trust_subclass": "project-rule",
            "created_at": "2026-04-30T12:00:00Z",
            "tombstoned_at": "2026-05-01T12:00:00Z",
            "tombstoned_reason": "outdated release procedure",
            "valid_from": "2026-04-01T00:00:00Z",
            "valid_to": "2026-06-01T00:00:00Z",
            "redacted": false
        }"#;

        let memory: ExportMemoryRecord = serde_json::from_str(json).expect("deserialize");
        assert_eq!(memory.schema, EXPORT_MEMORY_SCHEMA_V1);
        assert_eq!(memory.memory_id, "mem-001");
        assert_eq!(memory.importance, Some(0.8));
        assert_eq!(memory.pagerank_score, Some(0.12));
        assert_eq!(memory.betweenness_score, Some(0.34));
        assert_eq!(memory.hits_authority, Some(0.56));
        assert_eq!(memory.hits_hub, Some(0.78));
        assert_eq!(memory.onion_layer, Some(3));
        assert_eq!(memory.k_truss_max, Some(4));
        assert_eq!(memory.articulation_point, Some(true));
        assert_eq!(memory.bayes_alpha, Some(2.5));
        assert_eq!(memory.bayes_beta, Some(1.5));
        assert!(memory.content_hash.is_none());
        assert_eq!(memory.trust_class.as_deref(), Some("human_explicit"));
        assert_eq!(memory.trust_subclass.as_deref(), Some("project-rule"));
        assert_eq!(
            memory.tombstoned_at.as_deref(),
            Some("2026-05-01T12:00:00Z")
        );
        assert_eq!(
            memory.tombstoned_reason.as_deref(),
            Some("outdated release procedure")
        );
        assert_eq!(memory.valid_from.as_deref(), Some("2026-04-01T00:00:00Z"));
        assert_eq!(memory.valid_to.as_deref(), Some("2026-06-01T00:00:00Z"));
        assert!(!memory.redacted);
    }

    #[test]
    fn all_export_schemas_follow_naming_convention() {
        for schema in ALL_EXPORT_SCHEMAS {
            assert!(
                schema.starts_with("ee.export.") && schema.ends_with(".v1"),
                "schema {schema} should follow ee.export.<type>.v1 pattern"
            );
        }
    }

    #[test]
    fn parse_invalid_export_record_type_error() {
        let result: Result<ExportRecordType, _> = "invalid".parse();
        assert!(result.is_err());
        let err = result.expect_err("avoid unwrap_err in production code");
        assert!(err.to_string().contains("invalid export record type"));
        assert!(err.to_string().contains("'invalid'"));
    }

    #[test]
    fn parse_invalid_redaction_level_error() {
        let result: Result<RedactionLevel, _> = "invalid".parse();
        assert!(result.is_err());
        let err = result.expect_err("avoid unwrap_err in production code");
        assert!(err.to_string().contains("invalid redaction level"));
    }

    #[test]
    fn parse_invalid_export_scope_error() {
        let result: Result<ExportScope, _> = "invalid".parse();
        assert!(result.is_err());
        let err = result.expect_err("avoid unwrap_err in production code");
        assert!(err.to_string().contains("invalid export scope"));
    }

    // --- ImportSource tests (EE-266) ---

    #[test]
    fn import_source_roundtrip() -> TestResult {
        for source in [
            ImportSource::Native,
            ImportSource::CassImport,
            ImportSource::LegacyScan,
            ImportSource::ExternalImport,
            ImportSource::Unknown,
        ] {
            let s = source.as_str();
            let parsed: ImportSource = s
                .parse()
                .map_err(|e: ParseImportSourceError| e.to_string())?;
            ensure(parsed, source, &format!("roundtrip {s}"))?;
        }
        Ok(())
    }

    #[test]
    fn import_source_parse_normalizes_external_values() -> TestResult {
        ensure(
            " CASS-Import ".parse::<ImportSource>(),
            Ok(ImportSource::CassImport),
            "import source trims, lowercases, and accepts hyphen separator",
        )?;
        ensure(
            "cassImport".parse::<ImportSource>(),
            Ok(ImportSource::CassImport),
            "import source accepts camelCase",
        )?;
        ensure(
            "LegacyScan".parse::<ImportSource>(),
            Ok(ImportSource::LegacyScan),
            "import source accepts PascalCase",
        )?;
        ensure(
            "externalImport".parse::<ImportSource>(),
            Ok(ImportSource::ExternalImport),
            "import source accepts camelCase for external imports",
        )
    }

    #[test]
    fn import_source_display() {
        assert_eq!(ImportSource::Native.to_string(), "native");
        assert_eq!(ImportSource::CassImport.to_string(), "cass_import");
        assert_eq!(ImportSource::LegacyScan.to_string(), "legacy_scan");
        assert_eq!(ImportSource::ExternalImport.to_string(), "external_import");
        assert_eq!(ImportSource::Unknown.to_string(), "unknown");
    }

    #[test]
    fn import_source_is_external() {
        assert!(!ImportSource::Native.is_external());
        assert!(ImportSource::CassImport.is_external());
        assert!(ImportSource::LegacyScan.is_external());
        assert!(ImportSource::ExternalImport.is_external());
        assert!(ImportSource::Unknown.is_external());
    }

    #[test]
    fn parse_invalid_import_source_error() {
        let result: Result<ImportSource, _> = "invalid".parse();
        assert!(result.is_err());
        let err = result.expect_err("avoid unwrap_err in production code");
        assert!(err.to_string().contains("invalid import source"));
    }

    // --- TrustLevel tests (EE-266) ---

    #[test]
    fn trust_level_roundtrip() -> TestResult {
        for level in [
            TrustLevel::Untrusted,
            TrustLevel::Validated,
            TrustLevel::Verified,
            TrustLevel::Quarantined,
        ] {
            let s = level.as_str();
            let parsed: TrustLevel = s.parse().map_err(|e: ParseTrustLevelError| e.to_string())?;
            ensure(parsed, level, &format!("roundtrip {s}"))?;
        }
        Ok(())
    }

    #[test]
    fn trust_level_parse_normalizes_external_values() -> TestResult {
        ensure(
            " Quarantined ".parse::<TrustLevel>(),
            Ok(TrustLevel::Quarantined),
            "trust level trims and lowercases",
        )
    }

    #[test]
    fn trust_level_display() {
        assert_eq!(TrustLevel::Untrusted.to_string(), "untrusted");
        assert_eq!(TrustLevel::Validated.to_string(), "validated");
        assert_eq!(TrustLevel::Verified.to_string(), "verified");
        assert_eq!(TrustLevel::Quarantined.to_string(), "quarantined");
    }

    #[test]
    fn trust_level_is_trusted() {
        assert!(!TrustLevel::Untrusted.is_trusted());
        assert!(TrustLevel::Validated.is_trusted());
        assert!(TrustLevel::Verified.is_trusted());
        assert!(!TrustLevel::Quarantined.is_trusted());
    }

    #[test]
    fn trust_level_is_quarantined() {
        assert!(!TrustLevel::Untrusted.is_quarantined());
        assert!(!TrustLevel::Validated.is_quarantined());
        assert!(!TrustLevel::Verified.is_quarantined());
        assert!(TrustLevel::Quarantined.is_quarantined());
    }

    #[test]
    fn parse_invalid_trust_level_error() {
        let result: Result<TrustLevel, _> = "invalid".parse();
        assert!(result.is_err());
        let err = result.expect_err("avoid unwrap_err in production code");
        assert!(err.to_string().contains("invalid trust level"));
    }

    // --- Header metadata tests (EE-266) ---

    #[test]
    fn export_header_with_trust_metadata() {
        let header = ExportHeader::builder()
            .created_at("2026-04-30T12:00:00Z")
            .ee_version("0.1.0")
            .export_id("trust-metadata")
            .import_source(ImportSource::CassImport)
            .trust_level(TrustLevel::Validated)
            .checksum("abc123")
            .source_schema_version("cass.session.v1")
            .build()
            .expect("header has required fields");

        assert_eq!(header.import_source, ImportSource::CassImport);
        assert_eq!(header.trust_level, TrustLevel::Validated);
        assert_eq!(header.checksum, Some("abc123".to_owned()));
        assert_eq!(
            header.source_schema_version,
            Some("cass.session.v1".to_owned())
        );
    }

    #[test]
    fn export_header_defaults_to_native_untrusted() {
        let header = ExportHeader::builder()
            .created_at("2026-04-30T12:00:00Z")
            .ee_version("0.1.0")
            .export_id("native-untrusted")
            .build()
            .expect("header has required fields");

        assert_eq!(header.import_source, ImportSource::Native);
        assert_eq!(header.trust_level, TrustLevel::Untrusted);
        assert!(header.checksum.is_none());
        assert!(header.signature.is_none());
    }

    #[test]
    fn export_header_serializes_trust_metadata() {
        let header = ExportHeader::builder()
            .created_at("2026-04-30T12:00:00Z")
            .ee_version("0.1.0")
            .export_id("quarantined-header")
            .import_source(ImportSource::LegacyScan)
            .trust_level(TrustLevel::Quarantined)
            .build()
            .expect("header has required fields");

        let json = serde_json::to_string(&header).expect("serialize");
        assert!(json.contains(r#""import_source":"legacy_scan""#));
        assert!(json.contains(r#""trust_level":"quarantined""#));
    }
}