faculties 0.21.0

An office suite for AI agents: kanban, wiki, files, messaging, and a Lissajous-backed viewer — all persisted in a TribleSpace pile.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
//! Collection-native Mail values, projections, validation, and protocol seams.
//!
//! This module deliberately separates facts from effects.  Constructors
//! produce self-contained immutable fragments; callers validate the exact
//! collection union and durably publish those fragments before asking a POP
//! or SMTP transport to perform an irreversible action.

pub mod cli;
pub mod mcp;
pub mod operations;
pub mod render;

pub use operations::{
    AccountFetched, AccountOptions, AccountSetReceipt, AccountState, AccountSummary,
    DraftAttachment, DraftDelivery, DraftReceipt, DraftRequest, DraftStatus, InboxMessage, Mail,
    ReadReceipt, ReplyRequest, SendReceipt, SendStatus,
};

use std::collections::{BTreeMap, BTreeSet, HashMap};

use anybytes::View;
use anyhow::{anyhow, bail, Context, Result};
use ed25519_dalek::SigningKey;
use hifitime::Epoch;
use lettre::message::{header, Mailbox, MultiPart, SinglePart};
use lettre::Message;
use triblespace::core::metadata;
use triblespace::core::query::TriblePattern;
use triblespace::core::repo::pile::PileSnapshot;
use triblespace::core::repo::BlobStoreGet;
use triblespace::prelude::*;

use crate::decide::{self, Resolution};
use crate::files;
use crate::relations::IdentityComponents;
use crate::schemas::decide::KIND_DECISION;
use crate::schemas::files::{file as file_schema, KIND_FILE, KIND_MEDIA_TYPE};
use crate::schemas::mail::{
    acceptance, account, attachment_occurrence, attempt, draft, imported, imported_legacy,
    observation, projection, read, wire, IMPORT_DRAFT, IMPORT_RECEIVED, IMPORT_SENT,
    KIND_ACCOUNT_CONFIG, KIND_ATTACHMENT_OCCURRENCE, KIND_DRAFT_INTENT, KIND_IMPORTED_OBSERVATION,
    KIND_MAIL_ACCOUNT, KIND_OUTGOING_OBSERVATION, KIND_PARSED_PROJECTION, KIND_POP_OBSERVATION,
    KIND_READ_OBSERVATION, KIND_SEND_ATTEMPT, KIND_SMTP_ACCEPTANCE, KIND_WIRE_MESSAGE,
    LEGACY_KIND_MESSAGE, LEGACY_KIND_SPAM, RECIPE_RFC5322_V1,
};
use crate::schemas::message::local as legacy_read;
use crate::secrets::SecretsSnapshot;

pub type TextHandle = Inline<inlineencodings::Handle<blobencodings::UTF8String>>;
pub type BytesHandle = Inline<inlineencodings::Handle<blobencodings::RawBytes>>;
pub type DigestValue = Inline<inlineencodings::Hash<inlineencodings::Blake3>>;
pub type IntervalValue = Inline<inlineencodings::NsTAIInterval>;
pub type CountValue = Inline<inlineencodings::U256BE>;
pub type ArchiveHandle = Inline<inlineencodings::Handle<blobencodings::SimpleArchive>>;

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AccountConfigInput {
    pub address: String,
    pub display_name: String,
    pub pop_endpoint: String,
    pub smtp_endpoint: String,
    pub username: String,
    pub credential: Id,
    pub enabled: bool,
    pub predecessors: Vec<Id>,
}

impl AccountConfigInput {
    /// Canonicalize the complete immutable account snapshot before comparing
    /// it with a predecessor or deriving its entity identity.
    pub fn canonicalized(mut self) -> Result<Self> {
        self.address = canonical_nonempty(self.address, "account address")?;
        self.display_name = canonical_nonempty(self.display_name, "display name")?;
        self.pop_endpoint = canonical_nonempty(self.pop_endpoint, "POP endpoint")?;
        self.smtp_endpoint = canonical_nonempty(self.smtp_endpoint, "SMTP endpoint")?;
        self.username = canonical_nonempty(self.username, "account username")?;
        self.predecessors = sorted_ids(self.predecessors);
        Ok(self)
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AccountConfigRecord {
    pub id: Id,
    pub account: Id,
    pub address: TextHandle,
    pub display_name: TextHandle,
    pub pop_endpoint: TextHandle,
    pub smtp_endpoint: TextHandle,
    pub username: TextHandle,
    pub credential: Id,
    pub enabled: bool,
    pub predecessors: Vec<Id>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OpenAccount {
    pub anchor: Id,
    pub config: Id,
    pub address: String,
    pub display_name: String,
    pub pop_endpoint: String,
    pub smtp_endpoint: String,
    pub username: String,
    pub password: String,
    pub enabled: bool,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Head {
    Missing,
    Unique(Id),
    Forked(Vec<Id>),
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AttachmentData {
    pub filename: String,
    pub media_type: String,
    pub bytes: Vec<u8>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum WireIdentity {
    /// An opaque identity explicitly claimed in exactly one Message-ID field.
    Claimed(String),
    /// A digest of the exact raw bytes, used only when Message-ID is absent.
    RawDigest(DigestValue),
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParsedMessage {
    pub identity: WireIdentity,
    pub from: Option<String>,
    pub to: Vec<String>,
    pub cc: Vec<String>,
    pub bcc: Vec<String>,
    pub subject: String,
    pub body: String,
    pub claimed_date: Option<IntervalValue>,
    pub in_reply_to: Vec<String>,
    pub references: Vec<String>,
    pub spam: bool,
    pub attachments: Vec<AttachmentData>,
}

#[derive(Debug)]
pub struct SourcePublication {
    pub mail: Fragment,
    pub files: Fragment,
    pub wire: Id,
    pub observation: Id,
    pub projection: Id,
}

/// Canonical publication recovered from one exact historical Mail record.
/// A draft without raw wire bytes intentionally has no parser projection.
#[derive(Debug)]
pub struct ImportedPublication {
    pub mail: Fragment,
    pub files: Fragment,
    pub wire: Id,
    pub observation: Id,
    pub projection: Option<Id>,
}

/// Strict structural view of one embedded historical Mail record.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ImportedPayloadRecord {
    pub legacy_entity: Id,
    pub direction: Id,
    pub message_id: TextHandle,
    pub from: Option<Id>,
    pub to: Vec<Id>,
    pub cc: Vec<Id>,
    pub bcc: Vec<Id>,
    pub subject: TextHandle,
    pub body: TextHandle,
    pub in_reply_to: Vec<Id>,
    pub references: Vec<Id>,
    pub sent_at: Option<IntervalValue>,
    pub raw: Option<BytesHandle>,
    pub attachments: Vec<Id>,
    pub created_at: IntervalValue,
    pub spam: bool,
    pub tags: Vec<Id>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DraftInput {
    pub nonce: Id,
    pub account: Id,
    pub envelope_from: String,
    pub to: Vec<String>,
    pub cc: Vec<String>,
    pub bcc: Vec<String>,
    pub subject: String,
    pub body: String,
    pub attachments: Vec<Id>,
    pub in_reply_to: Vec<Id>,
    pub references: Vec<Id>,
    pub created_at: IntervalValue,
}

#[derive(Debug)]
pub struct DraftPublication {
    pub mail: Fragment,
    pub decide: Fragment,
    pub draft: Id,
    pub decision: Id,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DraftRecord {
    pub id: Id,
    pub nonce: Id,
    pub account: Id,
    pub envelope_from: TextHandle,
    pub to: Vec<TextHandle>,
    pub cc: Vec<TextHandle>,
    pub bcc: Vec<TextHandle>,
    pub subject: TextHandle,
    pub body: TextHandle,
    pub attachments: Vec<Id>,
    pub in_reply_to: Vec<Id>,
    pub references: Vec<Id>,
    pub created_at: IntervalValue,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SendAttemptInput {
    pub draft: Id,
    pub config: Id,
    pub decision: Id,
    pub decision_heads: Vec<Id>,
    pub raw: Vec<u8>,
    pub envelope_from: String,
    pub to: Vec<String>,
    pub cc: Vec<String>,
    pub bcc: Vec<String>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SendAttemptRecord {
    pub id: Id,
    pub draft: Id,
    pub config: Id,
    pub decision: Id,
    pub decision_heads: Vec<Id>,
    pub raw: BytesHandle,
    pub envelope_from: TextHandle,
    pub to: Vec<TextHandle>,
    pub cc: Vec<TextHandle>,
    pub bcc: Vec<TextHandle>,
}

/// A locally validated, immutable SMTP effect plan.
///
/// Its fields are private so the exact attempt, envelope, wire bytes, and
/// outgoing evidence cannot be mixed with pieces from another plan between
/// validation and the irreversible transport call.
#[derive(Debug)]
pub struct PreparedSend {
    attempt: Fragment,
    attempt_id: Id,
    outgoing: SourcePublication,
    envelope: SmtpEnvelope,
    raw: Vec<u8>,
}

impl PreparedSend {
    pub fn attempt_fragment(&self) -> &Fragment {
        &self.attempt
    }

    pub fn attempt_id(&self) -> Id {
        self.attempt_id
    }

    pub fn outgoing_files(&self) -> &Fragment {
        &self.outgoing.files
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct InboxProjection {
    pub wire: Id,
    pub projection: Id,
    pub source: Id,
    pub unread: bool,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MaterializedDraft {
    pub id: Id,
    pub account: Id,
    pub envelope_from: String,
    pub to: Vec<String>,
    pub cc: Vec<String>,
    pub bcc: Vec<String>,
    pub subject: String,
    pub body: String,
    pub attachments: Vec<AttachmentData>,
    pub in_reply_to: Vec<String>,
    pub references: Vec<String>,
    pub created_at: IntervalValue,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RenderedMail {
    pub raw: Vec<u8>,
    pub envelope: SmtpEnvelope,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ProjectionView {
    pub id: Id,
    pub source: Id,
    pub wire: Id,
    pub message_id: Option<String>,
    pub from: Option<String>,
    pub to: Vec<String>,
    pub cc: Vec<String>,
    pub bcc: Vec<String>,
    pub subject: String,
    pub body: String,
    pub claimed_date: Option<IntervalValue>,
    pub in_reply_to: Vec<Id>,
    pub references: Vec<Id>,
    pub spam: bool,
    pub attachments: Vec<Id>,
}

/// The exact structural fields needed to decide and summarize inbox
/// attention, without reading a body, envelope address set, attachment, or
/// other parser payload.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ProjectionSummaryRecord {
    pub id: Id,
    pub source: Id,
    pub wire: Id,
    pub from: Option<TextHandle>,
    pub subject: TextHandle,
    pub claimed_date: Option<IntervalValue>,
    pub spam: bool,
}

/// Transport meaning of the immutable source observation behind a parser
/// projection. This is source evidence, not mutable mailbox state.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ProjectionDirection {
    Received,
    Sent,
    Draft,
}

fn sorted_ids(values: impl IntoIterator<Item = Id>) -> Vec<Id> {
    let mut values: Vec<_> = values.into_iter().collect();
    values.sort_unstable();
    values.dedup();
    values
}

fn canonical_nonempty(value: impl Into<String>, field: &str) -> Result<String> {
    let value = value.into();
    let value = value.trim();
    if value.is_empty() || value.bytes().any(|byte| byte == 0) {
        bail!("{field} is empty or contains a NUL byte");
    }
    Ok(value.to_owned())
}

fn exact_text(value: impl Into<String>, field: &str) -> Result<String> {
    let value = value.into();
    if value.bytes().any(|byte| byte == 0) {
        bail!("{field} contains a NUL byte");
    }
    Ok(value)
}

fn point_interval(value: IntervalValue, field: &str) -> Result<()> {
    let (low, high): (i128, i128) = value
        .try_from_inline()
        .map_err(|error| anyhow!("decode {field}: {error:?}"))?;
    if low != high {
        bail!("{field} must be a point interval");
    }
    Ok(())
}

fn one<T: Ord>(mut values: BTreeSet<T>, field: &str) -> Result<Option<T>> {
    match values.len() {
        0 => Ok(None),
        1 => Ok(values.pop_first()),
        count => bail!("{field} is ambiguous ({count} distinct values)"),
    }
}

fn required<T: Ord>(values: BTreeSet<T>, field: &str) -> Result<T> {
    one(values, field)?.ok_or_else(|| anyhow!("missing {field}"))
}

fn ids_of_kind<P>(facts: &P, kind: Id) -> BTreeSet<Id>
where
    P: TriblePattern,
{
    find!(id: Id, pattern!(facts, [{ ?id @ metadata::tag: &kind }])).collect()
}

/// Every canonical RFC-5322 parser projection in stable id order.
pub fn projection_ids<P>(facts: &P) -> Vec<Id>
where
    P: TriblePattern,
{
    ids_of_kind(facts, KIND_PARSED_PROJECTION)
        .into_iter()
        .collect()
}

/// Every immutable native draft intent in stable id order.
pub fn draft_ids<P>(facts: &P) -> Vec<Id>
where
    P: TriblePattern,
{
    ids_of_kind(facts, KIND_DRAFT_INTENT).into_iter().collect()
}

fn entity_facts(facts: &TribleSet, entity: Id) -> TribleSet {
    facts
        .iter()
        .filter(|fact| fact.e() == &entity)
        .copied()
        .collect()
}

fn ensure_intrinsic(id: Id, fragment: Fragment, label: &str) -> Result<Fragment> {
    let expected = fragment
        .root()
        .ok_or_else(|| anyhow!("{label} does not export exactly one root"))?;
    if id != expected {
        bail!("{label} {id:x} does not match intrinsic core {expected:x}");
    }
    Ok(fragment)
}

fn imported_payload_record(record: &ImportedPayloadRecord) -> Fragment {
    entity! { ExclusiveId::force_ref(&record.legacy_entity) @
        metadata::tag*: record.tags.iter(),
        metadata::created_at: record.created_at,
        imported_legacy::from?: record.from.as_ref(),
        imported_legacy::to*: record.to.iter(),
        imported_legacy::cc*: record.cc.iter(),
        imported_legacy::bcc*: record.bcc.iter(),
        imported_legacy::subject: record.subject,
        imported_legacy::body: record.body,
        imported_legacy::message_id: record.message_id,
        imported_legacy::in_reply_to*: record.in_reply_to.iter(),
        imported_legacy::reference*: record.references.iter(),
        imported_legacy::sent_at?: record.sent_at.as_ref(),
        imported_legacy::raw?: record.raw.as_ref(),
        imported_legacy::attachment*: record.attachments.iter(),
    }
}

/// Apply the historical one-shot direction rule exactly once at the import
/// boundary. Explicit direction evidence wins; conflicting evidence fails.
pub fn legacy_import_direction(facts: &TribleSet, legacy_entity: Id) -> Result<Id> {
    let tags: BTreeSet<Id> =
        find!(tag: Id, pattern!(facts, [{ legacy_entity @ metadata::tag: ?tag }])).collect();
    if tags.contains(&IMPORT_RECEIVED) && tags.contains(&IMPORT_SENT) {
        bail!("legacy Mail entity {legacy_entity:x} has conflicting direction tags");
    }
    if tags.contains(&IMPORT_RECEIVED) {
        return Ok(IMPORT_RECEIVED);
    }
    if tags.contains(&IMPORT_SENT) {
        return Ok(IMPORT_SENT);
    }
    let message = tags.contains(&LEGACY_KIND_MESSAGE);
    let draft = tags.contains(&IMPORT_DRAFT);
    match (message, draft) {
        (true, true) => Ok(IMPORT_SENT),
        (true, false) => Ok(IMPORT_RECEIVED),
        (false, true) => Ok(IMPORT_DRAFT),
        (false, false) => {
            bail!("legacy Mail entity {legacy_entity:x} is neither a message nor a draft")
        }
    }
}

fn imported_payload_union<Overlay: BlobStoreGet>(
    reader: &impl BlobStoreGet,
    overlay: Option<&Overlay>,
    facts: &TribleSet,
    legacy_entity: Id,
) -> Result<ImportedPayloadRecord> {
    let entities: BTreeSet<Id> = facts.iter().map(|fact| *fact.e()).collect();
    if entities != BTreeSet::from([legacy_entity]) {
        bail!(
            "imported Mail payload for {legacy_entity:x} contains {} entity subjects",
            entities.len()
        );
    }
    let direction = legacy_import_direction(facts, legacy_entity)?;
    let tags =
        sorted_ids(find!(tag: Id, pattern!(facts, [{ legacy_entity @ metadata::tag: ?tag }])));
    for tag in &tags {
        if ![
            LEGACY_KIND_MESSAGE,
            LEGACY_KIND_SPAM,
            IMPORT_DRAFT,
            IMPORT_RECEIVED,
            IMPORT_SENT,
        ]
        .contains(tag)
        {
            bail!("legacy Mail entity {legacy_entity:x} has unknown tag {tag:x}");
        }
    }

    let message_id = required(
        find!(v: TextHandle, pattern!(facts, [{ legacy_entity @ imported_legacy::message_id: ?v }]))
            .collect(),
        "legacy Message-ID",
    )?;
    let subject = required(
        find!(v: TextHandle, pattern!(facts, [{ legacy_entity @ imported_legacy::subject: ?v }]))
            .collect(),
        "legacy mail subject",
    )?;
    let body = required(
        find!(v: TextHandle, pattern!(facts, [{ legacy_entity @ imported_legacy::body: ?v }]))
            .collect(),
        "legacy mail body",
    )?;
    let created_at = required(
        find!(v: IntervalValue, pattern!(facts, [{ legacy_entity @ metadata::created_at: ?v }]))
            .collect(),
        "legacy mail creation time",
    )?;
    let sent_at = one(
        find!(v: IntervalValue, pattern!(facts, [{ legacy_entity @ imported_legacy::sent_at: ?v }]))
            .collect(),
        "legacy claimed send time",
    )?;
    let raw = one(
        find!(v: BytesHandle, pattern!(facts, [{ legacy_entity @ imported_legacy::raw: ?v }]))
            .collect(),
        "legacy raw message",
    )?;
    let record = ImportedPayloadRecord {
        legacy_entity,
        direction,
        message_id,
        from: one(
            find!(v: Id, pattern!(facts, [{ legacy_entity @ imported_legacy::from: ?v }]))
                .collect(),
            "legacy From relation",
        )?,
        to: sorted_ids(
            find!(v: Id, pattern!(facts, [{ legacy_entity @ imported_legacy::to: ?v }])),
        ),
        cc: sorted_ids(
            find!(v: Id, pattern!(facts, [{ legacy_entity @ imported_legacy::cc: ?v }])),
        ),
        bcc: sorted_ids(
            find!(v: Id, pattern!(facts, [{ legacy_entity @ imported_legacy::bcc: ?v }])),
        ),
        subject,
        body,
        in_reply_to: sorted_ids(
            find!(v: Id, pattern!(facts, [{ legacy_entity @ imported_legacy::in_reply_to: ?v }])),
        ),
        references: sorted_ids(
            find!(v: Id, pattern!(facts, [{ legacy_entity @ imported_legacy::reference: ?v }])),
        ),
        sent_at,
        raw,
        attachments: sorted_ids(
            find!(v: Id, pattern!(facts, [{ legacy_entity @ imported_legacy::attachment: ?v }])),
        ),
        created_at,
        spam: tags.contains(&LEGACY_KIND_SPAM),
        tags,
    };

    point_interval(record.created_at, "legacy mail creation time")?;
    if let Some(sent_at) = record.sent_at {
        point_interval(sent_at, "legacy claimed send time")?;
    }
    match record.direction {
        IMPORT_DRAFT if record.raw.is_some() || record.sent_at.is_some() => {
            bail!("legacy unsent draft {legacy_entity:x} carries sent/raw evidence")
        }
        IMPORT_RECEIVED | IMPORT_SENT if record.raw.is_none() || record.sent_at.is_none() => {
            bail!("legacy transmitted mail {legacy_entity:x} lacks sent/raw evidence")
        }
        _ => {}
    }

    let message_id_text = text_union(reader, overlay, record.message_id)?;
    canonical_message_id_value(&message_id_text)
        .with_context(|| format!("validate legacy Message-ID on {legacy_entity:x}"))?;
    exact_text(
        text_union(reader, overlay, record.subject)?,
        "legacy mail subject",
    )?;
    exact_text(
        text_union(reader, overlay, record.body)?,
        "legacy mail body",
    )?;
    if let Some(raw) = record.raw {
        bytes_union(reader, overlay, raw)?;
    }

    let current_identity = entity! { imported_legacy::message_id: record.message_id }
        .root()
        .expect("legacy Message-ID identity has one root");
    let historical_identity = triblespace::core::trible::intrinsic_entity_id_v1(vec![(
        imported_legacy::message_id.id(),
        record.message_id.raw,
    )]);
    // The first Mail implementation predated intrinsic entity ids and named a
    // message with the first 128 bits of BLAKE3(trim(Message-ID)).  This is an
    // imported identity epoch, not a current-catalog tolerance: prove the
    // exact historical algorithm over the resident Message-ID text, then
    // rebuild the observation under today's intrinsic identities.
    let historical_v0_digest = blake3::hash(message_id_text.trim().as_bytes());
    let historical_v0_identity = Id::new(
        historical_v0_digest.as_bytes()[..16]
            .try_into()
            .expect("BLAKE3 prefix is 16 bytes"),
    )
    .expect("BLAKE3 Message-ID prefix is non-nil");
    if legacy_entity != current_identity
        && legacy_entity != historical_identity
        && legacy_entity != historical_v0_identity
    {
        bail!(
            "legacy Mail entity {legacy_entity:x} is not derived from its exact Message-ID under the current ({current_identity:x}), historical-v1 ({historical_identity:x}), or historical-v0 ({historical_v0_identity:x}) rule"
        );
    }

    if imported_payload_record(&record).facts() != facts {
        bail!("legacy Mail entity {legacy_entity:x} is not an exact supported record");
    }
    Ok(record)
}

/// Strictly decode one exact historical payload from a resident pile.
pub fn imported_payload(
    reader: &impl BlobStoreGet,
    facts: &TribleSet,
    legacy_entity: Id,
) -> Result<ImportedPayloadRecord> {
    imported_payload_union(reader, None::<&PileSnapshot>, facts, legacy_entity)
}

// ── accounts ──────────────────────────────────────────────────────────────

fn account_anchor_record(anchor: Id) -> Fragment {
    entity! { ExclusiveId::force_ref(&anchor) @ metadata::tag: &KIND_MAIL_ACCOUNT }
}

fn account_config_record(record: &AccountConfigRecord) -> Fragment {
    entity! {
        metadata::tag: &KIND_ACCOUNT_CONFIG,
        account::of: &record.account,
        account::address: record.address,
        account::display_name: record.display_name,
        account::pop_endpoint: record.pop_endpoint,
        account::smtp_endpoint: record.smtp_endpoint,
        account::username: record.username,
        account::credential: &record.credential,
        account::enabled: record.enabled,
        metadata::supersedes*: record.predecessors.iter(),
    }
}

/// Build one account anchor plus one intrinsic full-state configuration.
pub fn account_config_fragment(anchor: Id, input: AccountConfigInput) -> Result<(Fragment, Id)> {
    let input = input.canonicalized()?;
    let mut fragment = Fragment::empty();
    let record = AccountConfigRecord {
        id: anchor,
        account: anchor,
        address: fragment.put(input.address),
        display_name: fragment.put(input.display_name),
        pop_endpoint: fragment.put(input.pop_endpoint),
        smtp_endpoint: fragment.put(input.smtp_endpoint),
        username: fragment.put(input.username),
        credential: input.credential,
        enabled: input.enabled,
        predecessors: input.predecessors,
    };
    let config = account_config_record(&record);
    let id = config
        .root()
        .expect("account config has one intrinsic root");
    fragment += account_anchor_record(anchor);
    fragment += config;
    Ok((fragment, id))
}

pub fn account_anchors<P>(facts: &P) -> BTreeSet<Id>
where
    P: TriblePattern,
{
    ids_of_kind(facts, KIND_MAIL_ACCOUNT)
}

pub fn account_config<P>(facts: &P, id: Id) -> Result<AccountConfigRecord>
where
    P: TriblePattern,
{
    Ok(AccountConfigRecord {
        id,
        account: required(
            find!(v: Id, pattern!(facts, [{ id @ account::of: ?v }])).collect(),
            "account config owner",
        )?,
        address: required(
            find!(v: TextHandle, pattern!(facts, [{ id @ account::address: ?v }])).collect(),
            "account address",
        )?,
        display_name: required(
            find!(v: TextHandle, pattern!(facts, [{ id @ account::display_name: ?v }])).collect(),
            "account display name",
        )?,
        pop_endpoint: required(
            find!(v: TextHandle, pattern!(facts, [{ id @ account::pop_endpoint: ?v }])).collect(),
            "POP endpoint",
        )?,
        smtp_endpoint: required(
            find!(v: TextHandle, pattern!(facts, [{ id @ account::smtp_endpoint: ?v }])).collect(),
            "SMTP endpoint",
        )?,
        username: required(
            find!(v: TextHandle, pattern!(facts, [{ id @ account::username: ?v }])).collect(),
            "account username",
        )?,
        credential: required(
            find!(v: Id, pattern!(facts, [{ id @ account::credential: ?v }])).collect(),
            "account credential",
        )?,
        enabled: required(
            find!(v: bool, pattern!(facts, [{ id @ account::enabled: ?v }])).collect(),
            "account enabled flag",
        )?,
        predecessors: sorted_ids(
            find!(v: Id, pattern!(facts, [{ id @ metadata::supersedes: ?v }])),
        ),
    })
}

fn dag_heads(graph: &BTreeMap<Id, Vec<Id>>, label: &str) -> Result<Vec<Id>> {
    for (&id, predecessors) in graph {
        for predecessor in predecessors {
            if !graph.contains_key(predecessor) {
                bail!("{label} node {id:x} names missing predecessor {predecessor:x}");
            }
        }
    }
    fn visit(
        id: Id,
        graph: &BTreeMap<Id, Vec<Id>>,
        visiting: &mut BTreeSet<Id>,
        done: &mut BTreeSet<Id>,
        label: &str,
    ) -> Result<()> {
        if done.contains(&id) {
            return Ok(());
        }
        if !visiting.insert(id) {
            bail!("{label} contains a cycle through {id:x}");
        }
        for predecessor in &graph[&id] {
            visit(*predecessor, graph, visiting, done, label)?;
        }
        visiting.remove(&id);
        done.insert(id);
        Ok(())
    }
    let mut visiting = BTreeSet::new();
    let mut done = BTreeSet::new();
    for &id in graph.keys() {
        visit(id, graph, &mut visiting, &mut done, label)?;
    }
    let superseded: BTreeSet<_> = graph.values().flatten().copied().collect();
    Ok(graph
        .keys()
        .filter(|id| !superseded.contains(*id))
        .copied()
        .collect())
}

pub fn account_head<P>(facts: &P, anchor: Id) -> Result<Head>
where
    P: TriblePattern,
{
    let mut graph = BTreeMap::new();
    for id in ids_of_kind(facts, KIND_ACCOUNT_CONFIG) {
        let record = account_config(facts, id)?;
        if record.account == anchor {
            graph.insert(id, record.predecessors);
        }
    }
    let heads = dag_heads(&graph, &format!("account {anchor:x} configuration DAG"))?;
    Ok(match heads.as_slice() {
        [] => Head::Missing,
        [id] => Head::Unique(*id),
        _ => Head::Forked(heads),
    })
}

// ── RFC 5322 identity and projection ──────────────────────────────────────

fn header_values(parsed: &mailparse::ParsedMail<'_>, name: &str) -> Vec<String> {
    parsed
        .headers
        .iter()
        .filter(|header| header.get_key().eq_ignore_ascii_case(name))
        .map(|header| header.get_value())
        .collect()
}

fn canonical_message_id_value(raw: &str) -> Result<String> {
    let raw = raw.trim();
    if raw.is_empty() {
        bail!("empty Message-ID field");
    }
    let value = if raw.starts_with('<') || raw.ends_with('>') {
        if !(raw.starts_with('<') && raw.ends_with('>')) || raw.len() < 3 {
            bail!("malformed Message-ID field {raw:?}");
        }
        &raw[1..raw.len() - 1]
    } else {
        raw
    };
    if value.trim() != value
        || value.is_empty()
        || value.chars().any(char::is_whitespace)
        || value.contains(['<', '>'])
    {
        bail!("Message-ID must contain one opaque id, got {raw:?}");
    }
    Ok(value.to_owned())
}

/// Canonical opaque Message-ID claim, or a structurally distinct full
/// raw-byte digest when that header is absent.
pub fn canonical_wire_identity(
    parsed: &mailparse::ParsedMail<'_>,
    raw: &[u8],
) -> Result<WireIdentity> {
    let values = header_values(parsed, "Message-ID");
    match values.as_slice() {
        [] => Ok(WireIdentity::RawDigest(Inline::new(
            *blake3::hash(raw).as_bytes(),
        ))),
        [value] => canonical_message_id_value(value).map(WireIdentity::Claimed),
        _ => bail!("message has multiple Message-ID fields"),
    }
}

fn message_id_list(value: &str) -> Result<Vec<String>> {
    let mut values = Vec::new();
    let mut rest = value;
    while let Some(start) = rest.find('<') {
        let after = &rest[start + 1..];
        let end = after
            .find('>')
            .ok_or_else(|| anyhow!("unterminated message id in {value:?}"))?;
        values.push(canonical_message_id_value(&format!("<{}>", &after[..end]))?);
        rest = &after[end + 1..];
    }
    if values.is_empty() && !value.trim().is_empty() {
        values.push(canonical_message_id_value(value)?);
    }
    Ok(values)
}

fn message_ids_from_headers(parsed: &mailparse::ParsedMail<'_>, name: &str) -> Result<Vec<String>> {
    let mut values = Vec::new();
    for header in header_values(parsed, name) {
        values.extend(message_id_list(&header)?);
    }
    values.sort();
    values.dedup();
    Ok(values)
}

fn collect_parts(
    part: &mailparse::ParsedMail<'_>,
    plain: &mut Option<String>,
    html: &mut Option<String>,
    attachments: &mut Vec<AttachmentData>,
) {
    let media_type = part.ctype.mimetype.to_ascii_lowercase();
    let disposition = part.get_content_disposition();
    let is_attachment = matches!(
        disposition.disposition,
        mailparse::DispositionType::Attachment
    ) || disposition
        .params
        .get("filename")
        .is_some_and(|name| !name.is_empty());

    if media_type.starts_with("multipart/") {
        for child in &part.subparts {
            collect_parts(child, plain, html, attachments);
        }
    } else if is_attachment || !media_type.starts_with("text/") {
        if let Ok(bytes) = part.get_body_raw() {
            let filename = disposition
                .params
                .get("filename")
                .or_else(|| part.ctype.params.get("name"))
                .cloned()
                .unwrap_or_else(|| "attachment.bin".to_owned());
            attachments.push(AttachmentData {
                filename,
                media_type: files::normalize_media_type_or_default(&media_type),
                bytes,
            });
        }
    } else if media_type == "text/plain" && plain.is_none() {
        *plain = part.get_body().ok();
    } else if media_type == "text/html" && html.is_none() {
        *html = part.get_body().ok();
    }
}

/// Parse immutable source bytes without inventing clock or identity evidence.
pub fn parse_rfc5322(raw: &[u8]) -> Result<ParsedMessage> {
    let parsed = mailparse::parse_mail(raw).context("parse RFC 5322")?;
    let identity = canonical_wire_identity(&parsed, raw)?;
    let singular = |name: &str| -> Result<Option<String>> {
        let values = header_values(&parsed, name);
        match values.as_slice() {
            [] => Ok(None),
            [value] => Ok(Some(value.trim().to_owned())),
            _ => bail!("message has multiple {name} fields"),
        }
    };
    let claimed_date = singular("Date")?
        .map(|value| {
            let seconds = mailparse::dateparse(&value).context("parse claimed Date header")?;
            let epoch = Epoch::from_unix_seconds(seconds as f64);
            (epoch, epoch)
                .try_to_inline()
                .map_err(|error| anyhow!("encode claimed Date: {error:?}"))
        })
        .transpose()?;
    let mut plain = None;
    let mut html = None;
    let mut attachments = Vec::new();
    collect_parts(&parsed, &mut plain, &mut html, &mut attachments);
    let spam = header_values(&parsed, "X-Spam-Status")
        .iter()
        .any(|value| value.trim_start().to_ascii_lowercase().starts_with("yes"));
    Ok(ParsedMessage {
        identity,
        from: singular("From")?,
        to: header_values(&parsed, "To"),
        cc: header_values(&parsed, "Cc"),
        bcc: header_values(&parsed, "Bcc"),
        subject: singular("Subject")?.unwrap_or_default(),
        body: plain.or(html).unwrap_or_default(),
        claimed_date,
        in_reply_to: message_ids_from_headers(&parsed, "In-Reply-To")?,
        references: message_ids_from_headers(&parsed, "References")?,
        spam,
        attachments,
    })
}

fn claimed_wire_record(message_id: TextHandle) -> Fragment {
    entity! { metadata::tag: &KIND_WIRE_MESSAGE, wire::claimed_message_id: message_id }
}

fn digest_wire_record(digest: DigestValue) -> Fragment {
    entity! { metadata::tag: &KIND_WIRE_MESSAGE, wire::raw_digest: digest }
}

fn add_claimed_wire(fragment: &mut Fragment, message_id: &str) -> Result<Id> {
    let message_id = fragment.put(canonical_message_id_value(message_id)?);
    let wire = claimed_wire_record(message_id);
    let id = wire.root().expect("claimed wire message has one root");
    *fragment += wire;
    Ok(id)
}

pub fn wire_id_for(message_id: &str) -> Result<Id> {
    let mut fragment = Fragment::empty();
    add_claimed_wire(&mut fragment, message_id)
}

fn attachment_occurrence_record(source: Id, ordinal: u64, file: Id) -> Fragment {
    entity! {
        metadata::tag: &KIND_ATTACHMENT_OCCURRENCE,
        attachment_occurrence::source: &source,
        attachment_occurrence::recipe: &RECIPE_RFC5322_V1,
        attachment_occurrence::ordinal: ordinal,
        attachment_occurrence::file: &file,
    }
}

#[allow(clippy::too_many_arguments)]
fn projection_record(
    source: Id,
    from: Option<TextHandle>,
    to: &[TextHandle],
    cc: &[TextHandle],
    bcc: &[TextHandle],
    subject: TextHandle,
    body: TextHandle,
    claimed_date: Option<IntervalValue>,
    in_reply_to: &[Id],
    references: &[Id],
    spam: bool,
    attachments: &[Id],
) -> Fragment {
    entity! {
        metadata::tag: &KIND_PARSED_PROJECTION,
        projection::source: &source,
        projection::recipe: &RECIPE_RFC5322_V1,
        projection::from?: from.as_ref(),
        projection::to*: to.iter(),
        projection::cc*: cc.iter(),
        projection::bcc*: bcc.iter(),
        projection::subject: subject,
        projection::body: body,
        projection::claimed_date?: claimed_date.as_ref(),
        projection::in_reply_to*: in_reply_to.iter(),
        projection::reference*: references.iter(),
        projection::spam: spam,
        projection::attachment*: attachments.iter(),
    }
}

fn finish_source_projection(
    mut mail_fragment: Fragment,
    parsed: ParsedMessage,
    wire: Id,
    observation: Id,
) -> Result<SourcePublication> {
    let mut files_fragment = Fragment::empty();
    let mut occurrence_ids = Vec::new();
    for (index, attachment) in parsed.attachments.iter().enumerate() {
        let file_fragment = files::stage(
            attachment.bytes.clone(),
            attachment.filename.clone(),
            &attachment.media_type,
        )?;
        let file = file_fragment.root().expect("canonical file root");
        files_fragment += file_fragment;
        let occurrence = attachment_occurrence_record(observation, index as u64, file);
        occurrence_ids.push(occurrence.root().expect("attachment occurrence root"));
        mail_fragment += occurrence;
    }

    let from = parsed.from.map(|value| mail_fragment.put(value));
    let to: Vec<TextHandle> = parsed
        .to
        .into_iter()
        .map(|value| mail_fragment.put(value))
        .collect();
    let cc: Vec<TextHandle> = parsed
        .cc
        .into_iter()
        .map(|value| mail_fragment.put(value))
        .collect();
    let bcc: Vec<TextHandle> = parsed
        .bcc
        .into_iter()
        .map(|value| mail_fragment.put(value))
        .collect();
    let subject = mail_fragment.put(parsed.subject);
    let body = mail_fragment.put(parsed.body);
    let mut in_reply_to = Vec::new();
    for value in &parsed.in_reply_to {
        in_reply_to.push(add_claimed_wire(&mut mail_fragment, value)?);
    }
    let mut references = Vec::new();
    for value in &parsed.references {
        references.push(add_claimed_wire(&mut mail_fragment, value)?);
    }
    let projection_fragment = projection_record(
        observation,
        from,
        &to,
        &cc,
        &bcc,
        subject,
        body,
        parsed.claimed_date,
        &in_reply_to,
        &references,
        parsed.spam,
        &occurrence_ids,
    );
    let projection = projection_fragment.root().expect("projection root");
    mail_fragment += projection_fragment;
    Ok(SourcePublication {
        mail: mail_fragment,
        files: files_fragment,
        wire,
        observation,
        projection,
    })
}

fn source_publication(
    account_id: Option<Id>,
    config_id: Option<Id>,
    uidl: Option<&str>,
    attempt_id: Option<Id>,
    raw: &[u8],
) -> Result<SourcePublication> {
    let parsed = parse_rfc5322(raw)?;
    let mut mail_fragment = Fragment::empty();
    let wire = match &parsed.identity {
        WireIdentity::Claimed(message_id) => add_claimed_wire(&mut mail_fragment, message_id)?,
        WireIdentity::RawDigest(digest) => {
            let wire_fragment = digest_wire_record(*digest);
            let wire = wire_fragment.root().expect("digest wire root");
            mail_fragment += wire_fragment;
            wire
        }
    };
    let raw_handle: BytesHandle = mail_fragment.put(raw.to_vec());
    let observation_fragment = match (account_id, config_id, uidl, attempt_id) {
        (Some(account_id), Some(config_id), Some(uidl), None) => {
            let uidl = mail_fragment.put(canonical_nonempty(uidl, "POP UIDL")?);
            entity! {
                metadata::tag: &KIND_POP_OBSERVATION,
                observation::wire: &wire,
                observation::account: &account_id,
                observation::config: &config_id,
                observation::uidl: uidl,
                observation::raw: raw_handle,
            }
        }
        (None, None, None, Some(attempt_id)) => entity! {
            metadata::tag: &KIND_OUTGOING_OBSERVATION,
            observation::wire: &wire,
            observation::attempt: &attempt_id,
            observation::raw: raw_handle,
        },
        _ => bail!("source publication requires exactly POP coordinates or a send attempt"),
    };
    let observation = observation_fragment.root().expect("observation root");
    mail_fragment += observation_fragment;
    finish_source_projection(mail_fragment, parsed, wire, observation)
}

pub fn pop_publication(
    account: Id,
    config: Id,
    uidl: &str,
    raw: &[u8],
) -> Result<SourcePublication> {
    source_publication(Some(account), Some(config), Some(uidl), None, raw)
}

pub fn outgoing_publication(attempt: Id, raw: &[u8]) -> Result<SourcePublication> {
    source_publication(None, None, None, Some(attempt), raw)
}

/// Rebuild one honest imported observation from an exact historical payload.
/// No POP mailbox, UIDL, account snapshot, send attempt, or SMTP acceptance is
/// invented. Raw-backed observations receive the same reproducible RFC parser
/// projection as native transport evidence; raw-less drafts remain imported
/// records with no fabricated modern intent/effect state.
pub fn imported_publication(
    legacy_entity: Id,
    direction: Id,
    payload: ArchiveHandle,
    message_id: &str,
    raw: Option<&[u8]>,
) -> Result<ImportedPublication> {
    if ![IMPORT_RECEIVED, IMPORT_SENT, IMPORT_DRAFT].contains(&direction) {
        bail!("unknown imported Mail direction {direction:x}");
    }
    if direction == IMPORT_DRAFT && raw.is_some() {
        bail!("an imported unsent draft cannot claim raw transport bytes");
    }
    if direction != IMPORT_DRAFT && raw.is_none() {
        bail!("imported transmitted mail requires exact raw bytes");
    }

    let canonical_message_id = canonical_message_id_value(message_id)?;
    let mut mail_fragment = Fragment::empty();
    let wire = add_claimed_wire(&mut mail_fragment, &canonical_message_id)?;
    let parsed = raw.map(parse_rfc5322).transpose()?;
    if let Some(parsed) = &parsed {
        match &parsed.identity {
            WireIdentity::Claimed(claimed) if claimed == &canonical_message_id => {}
            WireIdentity::Claimed(claimed) => bail!(
                "legacy Message-ID {canonical_message_id:?} differs from raw claim {claimed:?}"
            ),
            WireIdentity::RawDigest(_) => {
                bail!("legacy raw mail has no Message-ID matching its stored identity")
            }
        }
    }
    let raw_handle =
        raw.map(|bytes| mail_fragment.put::<blobencodings::RawBytes, _>(bytes.to_vec()));
    let observation_fragment = entity! {
        metadata::tag: &KIND_IMPORTED_OBSERVATION,
        imported::legacy_entity: &legacy_entity,
        imported::direction: &direction,
        imported::payload: payload,
        observation::wire: &wire,
        observation::raw?: raw_handle.as_ref(),
    };
    let observation = observation_fragment
        .root()
        .expect("imported observation has one root");
    mail_fragment += observation_fragment;

    if let Some(mut parsed) = parsed {
        // Historical Files identities predate media-type entities and are
        // preserved additively by the Files migration. Re-parsing the raw MIME
        // bytes would therefore mint a second set of modern file identities.
        // Keep the useful canonical message projection but leave attachments
        // on the exact embedded/top-level legacy evidence until a separate
        // cross-collection derivation explicitly maps that identity epoch.
        parsed.attachments.clear();
        let publication = finish_source_projection(mail_fragment, parsed, wire, observation)?;
        Ok(ImportedPublication {
            mail: publication.mail,
            files: publication.files,
            wire,
            observation,
            projection: Some(publication.projection),
        })
    } else {
        Ok(ImportedPublication {
            mail: mail_fragment,
            files: Fragment::empty(),
            wire,
            observation,
            projection: None,
        })
    }
}

// ── immutable draft / attempt / acceptance values ─────────────────────────

fn draft_record(record: &DraftRecord) -> Fragment {
    entity! {
        metadata::tag: &KIND_DRAFT_INTENT,
        draft::nonce: &record.nonce,
        draft::account: &record.account,
        draft::envelope_from: record.envelope_from,
        draft::to*: record.to.iter(),
        draft::cc*: record.cc.iter(),
        draft::bcc*: record.bcc.iter(),
        draft::subject: record.subject,
        draft::body: record.body,
        draft::attachment*: record.attachments.iter(),
        draft::in_reply_to*: record.in_reply_to.iter(),
        draft::reference*: record.references.iter(),
        metadata::created_at: record.created_at,
    }
}

pub fn draft_decision_id(draft_id: Id) -> Id {
    entity! { draft::decision_for: &draft_id }
        .root()
        .expect("draft decision derivation has one root")
}

pub fn draft_publication(input: DraftInput) -> Result<DraftPublication> {
    point_interval(input.created_at, "draft creation time")?;
    if input.to.is_empty() && input.cc.is_empty() && input.bcc.is_empty() {
        bail!("draft has no recipients");
    }
    let mut mail_fragment = Fragment::empty();
    let to = input
        .to
        .into_iter()
        .map(|value| Ok(mail_fragment.put(canonical_nonempty(value, "To recipient")?)))
        .collect::<Result<Vec<_>>>()?;
    let cc = input
        .cc
        .into_iter()
        .map(|value| Ok(mail_fragment.put(canonical_nonempty(value, "Cc recipient")?)))
        .collect::<Result<Vec<_>>>()?;
    let bcc = input
        .bcc
        .into_iter()
        .map(|value| Ok(mail_fragment.put(canonical_nonempty(value, "Bcc recipient")?)))
        .collect::<Result<Vec<_>>>()?;
    let record = DraftRecord {
        id: input.account,
        nonce: input.nonce,
        account: input.account,
        envelope_from: mail_fragment.put(canonical_nonempty(
            input.envelope_from,
            "draft envelope sender",
        )?),
        to,
        cc,
        bcc,
        subject: mail_fragment.put(exact_text(input.subject, "draft subject")?),
        body: mail_fragment.put(exact_text(input.body, "draft body")?),
        attachments: sorted_ids(input.attachments),
        in_reply_to: sorted_ids(input.in_reply_to),
        references: sorted_ids(input.references),
        created_at: input.created_at,
    };
    let draft_fragment = draft_record(&record);
    let draft_id = draft_fragment.root().expect("draft has one intrinsic root");
    mail_fragment += draft_fragment;
    let decision = draft_decision_id(draft_id);
    let title = format!(
        "Send mail: {}",
        read_local_text(&mail_fragment, record.subject)?
    );
    let (decide_fragment, _) = decide::decision_fragment(
        decision,
        title,
        Some("Authorize exactly this immutable DraftIntent".to_owned()),
        Some(draft_id),
        record.created_at,
    )?;
    Ok(DraftPublication {
        mail: mail_fragment,
        decide: decide_fragment,
        draft: draft_id,
        decision,
    })
}

fn attempt_record(record: &SendAttemptRecord) -> Fragment {
    entity! {
        metadata::tag: &KIND_SEND_ATTEMPT,
        attempt::draft: &record.draft,
        attempt::config: &record.config,
        attempt::decision: &record.decision,
        attempt::decision_head*: record.decision_heads.iter(),
        attempt::raw: record.raw,
        attempt::envelope_from: record.envelope_from,
        attempt::to*: record.to.iter(),
        attempt::cc*: record.cc.iter(),
        attempt::bcc*: record.bcc.iter(),
    }
}

pub fn send_attempt_fragment(input: SendAttemptInput) -> Result<(Fragment, Id)> {
    if input.to.is_empty() && input.cc.is_empty() && input.bcc.is_empty() {
        bail!("send attempt has no recipients");
    }
    let mut fragment = Fragment::empty();
    let record = SendAttemptRecord {
        id: input.draft,
        draft: input.draft,
        config: input.config,
        decision: input.decision,
        decision_heads: sorted_ids(input.decision_heads),
        raw: fragment.put(input.raw),
        envelope_from: fragment.put(canonical_nonempty(
            input.envelope_from,
            "attempt envelope sender",
        )?),
        to: input
            .to
            .into_iter()
            .map(|value| Ok(fragment.put(canonical_nonempty(value, "attempt To recipient")?)))
            .collect::<Result<_>>()?,
        cc: input
            .cc
            .into_iter()
            .map(|value| Ok(fragment.put(canonical_nonempty(value, "attempt Cc recipient")?)))
            .collect::<Result<_>>()?,
        bcc: input
            .bcc
            .into_iter()
            .map(|value| Ok(fragment.put(canonical_nonempty(value, "attempt Bcc recipient")?)))
            .collect::<Result<_>>()?,
    };
    let attempt = attempt_record(&record);
    let id = attempt.root().expect("send attempt has one intrinsic root");
    fragment += attempt;
    Ok((fragment, id))
}

pub fn smtp_acceptance_fragment(
    attempt_id: Id,
    response_code: u64,
    response: impl Into<String>,
) -> Result<(Fragment, Id)> {
    if !(200..=299).contains(&response_code) {
        bail!("SMTP acceptance code must be a final positive 2xx reply");
    }
    let mut fragment = Fragment::empty();
    let response = fragment.put(canonical_nonempty(response, "SMTP acceptance response")?);
    let acceptance = entity! {
        metadata::tag: &KIND_SMTP_ACCEPTANCE,
        acceptance::attempt: &attempt_id,
        acceptance::response_code: response_code,
        acceptance::response: response,
    };
    let id = acceptance.root().expect("SMTP acceptance has one root");
    fragment += acceptance;
    Ok((fragment, id))
}

/// Record that `reader` opened any resident wire value. Direction is not part
/// of read evidence; inbox projection separately restricts unread state to
/// inbound sources.
pub fn read_observation_fragment(wire_id: Id, reader: Id) -> (Fragment, Id) {
    let fragment = entity! {
        metadata::tag: &KIND_READ_OBSERVATION,
        read::wire: &wire_id,
        read::reader: &reader,
    };
    let id = fragment.root().expect("read observation has one root");
    (fragment, id)
}

fn read_local_text(fragment: &Fragment, handle: TextHandle) -> Result<String> {
    let mut local = fragment.clone();
    let reader = local
        .blobs_mut()
        .snapshot()
        .expect("memory blob reader creation is infallible");
    let value: View<str> = reader.get(handle).context("read staged Mail text")?;
    Ok(value.to_string())
}

pub fn read_text(reader: &impl BlobStoreGet, handle: TextHandle) -> Result<String> {
    let value: View<str> = reader
        .get(handle)
        .with_context(|| format!("read Mail text blob {}", hex::encode(handle.raw)))?;
    Ok(value.to_string())
}

pub fn read_bytes(reader: &impl BlobStoreGet, handle: BytesHandle) -> Result<Vec<u8>> {
    let value: anybytes::Bytes = reader
        .get(handle)
        .with_context(|| format!("read Mail byte blob {}", hex::encode(handle.raw)))?;
    Ok(value.as_ref().to_vec())
}

fn text_union<Overlay: BlobStoreGet>(
    reader: &impl BlobStoreGet,
    overlay: Option<&Overlay>,
    handle: TextHandle,
) -> Result<String> {
    if let Ok(value) = reader.get::<View<str>, _>(handle) {
        return Ok(value.to_string());
    }
    if let Some(overlay) = overlay {
        let value: View<str> = overlay
            .get(handle)
            .with_context(|| format!("read staged Mail text {}", hex::encode(handle.raw)))?;
        return Ok(value.to_string());
    }
    bail!("missing Mail text blob {}", hex::encode(handle.raw))
}

fn bytes_union<Overlay: BlobStoreGet>(
    reader: &impl BlobStoreGet,
    overlay: Option<&Overlay>,
    handle: BytesHandle,
) -> Result<Vec<u8>> {
    if let Ok(value) = reader.get::<anybytes::Bytes, _>(handle) {
        return Ok(value.as_ref().to_vec());
    }
    if let Some(overlay) = overlay {
        let value: anybytes::Bytes = overlay
            .get(handle)
            .with_context(|| format!("read staged Mail bytes {}", hex::encode(handle.raw)))?;
        return Ok(value.as_ref().to_vec());
    }
    bail!("missing Mail byte blob {}", hex::encode(handle.raw))
}

fn archive_union<Overlay: BlobStoreGet>(
    reader: &impl BlobStoreGet,
    overlay: Option<&Overlay>,
    handle: ArchiveHandle,
) -> Result<TribleSet> {
    if let Ok(value) = reader.get::<TribleSet, _>(handle) {
        return Ok(value);
    }
    if let Some(overlay) = overlay {
        return overlay
            .get(handle)
            .with_context(|| format!("read staged Mail archive {}", hex::encode(handle.raw)));
    }
    bail!("missing Mail archive blob {}", hex::encode(handle.raw))
}

/// Decode and prove one exact canonical Files record through the same blob
/// overlay used for an unpublished cross-collection candidate.
fn file_attachment_union<Overlay: BlobStoreGet>(
    reader: &impl BlobStoreGet,
    overlay: Option<&Overlay>,
    facts: &TribleSet,
    file: Id,
) -> Result<AttachmentData> {
    if !exists!(pattern!(facts, [{ file @ metadata::tag: &KIND_FILE }])) {
        bail!("{file:x} is not tagged as a canonical file");
    }
    let content = required(
        find!(value: BytesHandle, pattern!(facts, [{ file @ file_schema::content: ?value }]))
            .collect(),
        "file content",
    )?;
    let name = required(
        find!(value: TextHandle, pattern!(facts, [{ file @ file_schema::name: ?value }])).collect(),
        "file name",
    )?;
    let media_type = required(
        find!(value: Id, pattern!(facts, [{ file @ file_schema::media_type: ?value }])).collect(),
        "file media type",
    )?;
    if !exists!(pattern!(facts, [{ media_type @ metadata::tag: &KIND_MEDIA_TYPE }])) {
        bail!("file {file:x} names untyped media entity {media_type:x}");
    }
    let media_name = required(
        find!(value: TextHandle, pattern!(facts, [{ media_type @ metadata::name: ?value }]))
            .collect(),
        "media type name",
    )?;

    let bytes = bytes_union(reader, overlay, content)?;
    let filename = text_union(reader, overlay, name)?;
    let media_type_name = text_union(reader, overlay, media_name)?;
    let canonical = files::stage(bytes.clone(), filename.clone(), &media_type_name)?;
    if canonical.root() != Some(file) {
        bail!("file {file:x} does not match its canonical content/name/media identity");
    }
    let canonical_file = entity_facts(canonical.facts(), file);
    if entity_facts(facts, file) != canonical_file {
        bail!("file {file:x} is not one exact canonical file record");
    }
    for fact in canonical.facts() {
        if fact.e() == &media_type && !facts.contains(fact) {
            bail!("file {file:x} is missing canonical media-type evidence");
        }
    }
    Ok(AttachmentData {
        filename,
        media_type: media_type_name,
        bytes,
    })
}

/// Decode one attachment for an ordinary typed read.
///
/// The query itself selects the Files vocabulary this consumer understands.
/// Unlike import validation, this path neither reconstructs the intrinsic id
/// nor rejects additive facts that another version may understand.
fn file_attachment<P>(reader: &impl BlobStoreGet, facts: &P, file: Id) -> Result<AttachmentData>
where
    P: TriblePattern,
{
    let content = required(
        find!(value: BytesHandle, pattern!(facts, [{ file @
            metadata::tag: &KIND_FILE,
            file_schema::content: ?value,
        }]))
        .collect(),
        "file content",
    )?;
    let name = required(
        find!(value: TextHandle, pattern!(facts, [{ file @
            metadata::tag: &KIND_FILE,
            file_schema::name: ?value,
        }]))
        .collect(),
        "file name",
    )?;
    let media_name = required(
        find!(value: TextHandle, pattern!(facts, [
            { file @
                metadata::tag: &KIND_FILE,
                file_schema::media_type: _?media_type,
            },
            { _?media_type @
                metadata::tag: &KIND_MEDIA_TYPE,
                metadata::name: ?value,
            },
        ]))
        .collect(),
        "media type name",
    )?;
    Ok(AttachmentData {
        filename: read_text(reader, name)?,
        media_type: read_text(reader, media_name)?,
        bytes: read_bytes(reader, content)?,
    })
}

fn validate_source_text_payloads<Overlay: BlobStoreGet>(
    reader: &impl BlobStoreGet,
    overlay: Option<&Overlay>,
    source_facts: &TribleSet,
) -> Result<()> {
    let attributes = BTreeSet::from([
        wire::claimed_message_id.id(),
        projection::from.id(),
        projection::to.id(),
        projection::cc.id(),
        projection::bcc.id(),
        projection::subject.id(),
        projection::body.id(),
    ]);
    let handles: BTreeSet<TextHandle> = source_facts
        .iter()
        .filter(|fact| attributes.contains(fact.a()))
        .map(|fact| *fact.v::<inlineencodings::Handle<blobencodings::UTF8String>>())
        .collect();
    for handle in handles {
        text_union(reader, overlay, handle)?;
    }
    Ok(())
}

fn draft_from_facts<P>(facts: &P, id: Id) -> Result<DraftRecord>
where
    P: TriblePattern,
{
    Ok(DraftRecord {
        id,
        nonce: required(
            find!(v: Id, pattern!(facts, [{ id @ draft::nonce: ?v }])).collect(),
            "draft nonce",
        )?,
        account: required(
            find!(v: Id, pattern!(facts, [{ id @ draft::account: ?v }])).collect(),
            "draft account",
        )?,
        envelope_from: required(
            find!(v: TextHandle, pattern!(facts, [{ id @ draft::envelope_from: ?v }])).collect(),
            "draft envelope sender",
        )?,
        to: find!(v: TextHandle, pattern!(facts, [{ id @ draft::to: ?v }]))
            .collect::<BTreeSet<_>>()
            .into_iter()
            .collect(),
        cc: find!(v: TextHandle, pattern!(facts, [{ id @ draft::cc: ?v }]))
            .collect::<BTreeSet<_>>()
            .into_iter()
            .collect(),
        bcc: find!(v: TextHandle, pattern!(facts, [{ id @ draft::bcc: ?v }]))
            .collect::<BTreeSet<_>>()
            .into_iter()
            .collect(),
        subject: required(
            find!(v: TextHandle, pattern!(facts, [{ id @ draft::subject: ?v }])).collect(),
            "draft subject",
        )?,
        body: required(
            find!(v: TextHandle, pattern!(facts, [{ id @ draft::body: ?v }])).collect(),
            "draft body",
        )?,
        attachments: sorted_ids(find!(v: Id, pattern!(facts, [{ id @ draft::attachment: ?v }]))),
        in_reply_to: sorted_ids(find!(v: Id, pattern!(facts, [{ id @ draft::in_reply_to: ?v }]))),
        references: sorted_ids(find!(v: Id, pattern!(facts, [{ id @ draft::reference: ?v }]))),
        created_at: required(
            find!(v: IntervalValue, pattern!(facts, [{ id @ metadata::created_at: ?v }])).collect(),
            "draft creation time",
        )?,
    })
}

pub fn draft_value<P>(facts: &P, id: Id) -> Result<DraftRecord>
where
    P: TriblePattern,
{
    if !ids_of_kind(facts, KIND_DRAFT_INTENT).contains(&id) {
        bail!("unknown draft {id:x}");
    }
    draft_from_facts(facts, id)
}

fn attempt_from_facts<P>(facts: &P, id: Id) -> Result<SendAttemptRecord>
where
    P: TriblePattern,
{
    Ok(SendAttemptRecord {
        id,
        draft: required(
            find!(v: Id, pattern!(facts, [{ id @ attempt::draft: ?v }])).collect(),
            "attempt draft",
        )?,
        config: required(
            find!(v: Id, pattern!(facts, [{ id @ attempt::config: ?v }])).collect(),
            "attempt config",
        )?,
        decision: required(
            find!(v: Id, pattern!(facts, [{ id @ attempt::decision: ?v }])).collect(),
            "attempt decision",
        )?,
        decision_heads: sorted_ids(
            find!(v: Id, pattern!(facts, [{ id @ attempt::decision_head: ?v }])),
        ),
        raw: required(
            find!(v: BytesHandle, pattern!(facts, [{ id @ attempt::raw: ?v }])).collect(),
            "attempt raw message",
        )?,
        envelope_from: required(
            find!(v: TextHandle, pattern!(facts, [{ id @ attempt::envelope_from: ?v }])).collect(),
            "attempt envelope sender",
        )?,
        to: find!(v: TextHandle, pattern!(facts, [{ id @ attempt::to: ?v }]))
            .collect::<BTreeSet<_>>()
            .into_iter()
            .collect(),
        cc: find!(v: TextHandle, pattern!(facts, [{ id @ attempt::cc: ?v }]))
            .collect::<BTreeSet<_>>()
            .into_iter()
            .collect(),
        bcc: find!(v: TextHandle, pattern!(facts, [{ id @ attempt::bcc: ?v }]))
            .collect::<BTreeSet<_>>()
            .into_iter()
            .collect(),
    })
}

pub fn send_attempt<P>(facts: &P, id: Id) -> Result<SendAttemptRecord>
where
    P: TriblePattern,
{
    if !ids_of_kind(facts, KIND_SEND_ATTEMPT).contains(&id) {
        bail!("unknown send attempt {id:x}");
    }
    attempt_from_facts(facts, id)
}

pub fn attempts_for_draft<P>(facts: &P, draft_id: Id) -> Vec<Id>
where
    P: TriblePattern,
{
    find!(id: Id, pattern!(facts, [{ ?id @ metadata::tag: &KIND_SEND_ATTEMPT, attempt::draft: &draft_id }]))
        .collect::<BTreeSet<_>>()
        .into_iter()
        .collect()
}

pub fn acceptances_for_attempt<P>(facts: &P, attempt_id: Id) -> Vec<Id>
where
    P: TriblePattern,
{
    find!(id: Id, pattern!(facts, [{ ?id @ metadata::tag: &KIND_SMTP_ACCEPTANCE, acceptance::attempt: &attempt_id }]))
        .collect::<BTreeSet<_>>()
        .into_iter()
        .collect()
}

/// Resolve the exact Decide frontier which authorizes a send.
pub fn authorized_send<P>(
    reader: &impl BlobStoreGet,
    decide_facts: &P,
    draft_id: Id,
) -> Result<(Id, Vec<Id>)>
where
    P: TriblePattern,
{
    let decision = draft_decision_id(draft_id);
    let snapshots = match decide::resolution(decide_facts, decision) {
        Resolution::Unique(snapshot) => vec![snapshot],
        Resolution::Agreed(snapshots) => snapshots,
        Resolution::Missing => bail!("send decision {decision:x} has no resolution"),
        Resolution::Forked(heads) => {
            bail!(
                "send decision {decision:x} has divergent heads: {:?}",
                sorted_ids(heads.into_iter().map(|head| head.id))
            )
        }
        Resolution::Invalid(error) => bail!("send decision {decision:x} is invalid: {error}"),
    };
    if snapshots.is_empty() {
        bail!("send decision {decision:x} resolved to an empty frontier");
    }
    for snapshot in &snapshots {
        let outcome = decide::read_text(reader, snapshot.outcome)?;
        if outcome != "send" {
            bail!("send decision {decision:x} resolves to {outcome:?}, not exact outcome \"send\"");
        }
    }
    Ok((
        decision,
        sorted_ids(snapshots.into_iter().map(|snapshot| snapshot.id)),
    ))
}

/// Materialize one current account and open its exact referenced Secrets
/// version with the pile's durable signing key.
///
/// The account schema stores one immutable secret id, so this path performs no
/// name or “latest version” arbitration and has no password-identity fallback.
pub fn open_account<R, P>(
    mail_reader: &impl BlobStoreGet,
    mail_facts: &P,
    secrets: &SecretsSnapshot<R>,
    anchor: Id,
    signing_key: &SigningKey,
) -> Result<OpenAccount>
where
    R: BlobStoreGet,
    P: TriblePattern,
{
    let config_id = match account_head(mail_facts, anchor)? {
        Head::Unique(id) => id,
        Head::Missing => bail!("mail account {anchor:x} has no configuration"),
        Head::Forked(ids) => {
            bail!("mail account {anchor:x} has forked configuration heads: {ids:?}")
        }
    };
    let config = account_config(mail_facts, config_id)?;
    let password = secrets.open(config.credential, signing_key)?;
    Ok(OpenAccount {
        anchor,
        config: config_id,
        address: read_text(mail_reader, config.address)?,
        display_name: read_text(mail_reader, config.display_name)?,
        pop_endpoint: read_text(mail_reader, config.pop_endpoint)?,
        smtp_endpoint: read_text(mail_reader, config.smtp_endpoint)?,
        username: read_text(mail_reader, config.username)?,
        password: String::from_utf8(password).context("mailbox password is not UTF-8")?,
        enabled: config.enabled,
    })
}

fn config_owner_map(facts: &TribleSet) -> Result<HashMap<Id, AccountConfigRecord>> {
    ids_of_kind(facts, KIND_ACCOUNT_CONFIG)
        .into_iter()
        .map(|id| account_config(facts, id).map(|record| (id, record)))
        .collect()
}

fn validate_send_heads<Overlay: BlobStoreGet>(
    reader: &impl BlobStoreGet,
    overlay: Option<&Overlay>,
    decide_facts: &TribleSet,
    decision: Id,
    heads: &[Id],
) -> Result<()> {
    if heads.is_empty() {
        bail!("send attempt records no decision frontier");
    }
    let selected: BTreeSet<Id> = heads.iter().copied().collect();
    let mut forced = BTreeSet::new();
    for &head in heads {
        let snapshot = decide::resolution_snapshot(decide_facts, head)?;
        if snapshot.decision != decision {
            bail!("resolution {head:x} belongs to another decision");
        }
        if text_union(reader, overlay, snapshot.outcome)? != "send" {
            bail!("resolution {head:x} does not carry exact outcome \"send\"");
        }
        forced.insert(snapshot.forced);
    }
    if forced.len() != 1 {
        bail!("stored send frontier does not have Agreed semantics");
    }

    // A genuine frontier is an antichain. Completeness at the historical
    // executor snapshot is an attestation, but an ancestor and descendant can
    // never both have been heads of the same resolution DAG.
    for &head in heads {
        let mut stack = decide::resolution_snapshot(decide_facts, head)?.predecessors;
        let mut visited = BTreeSet::new();
        while let Some(ancestor) = stack.pop() {
            if !visited.insert(ancestor) {
                continue;
            }
            if selected.contains(&ancestor) {
                bail!(
                    "stored send frontier contains both resolution {ancestor:x} and a descendant"
                );
            }
            let snapshot = decide::resolution_snapshot(decide_facts, ancestor)?;
            if snapshot.decision != decision {
                bail!("resolution {ancestor:x} belongs to another decision");
            }
            stack.extend(snapshot.predecessors);
        }
    }
    Ok(())
}

fn normalized_mailboxes(
    values: impl IntoIterator<Item = String>,
) -> Result<Vec<(Option<String>, String)>> {
    let mut out = Vec::new();
    for value in values {
        let parsed = mailparse::addrparse(&value)
            .with_context(|| format!("parse mailbox claim {value:?}"))?;
        for address in parsed.iter() {
            match address {
                mailparse::MailAddr::Single(single) => {
                    out.push((single.display_name.clone(), single.addr.clone()));
                }
                mailparse::MailAddr::Group(group) => {
                    out.extend(
                        group
                            .addrs
                            .iter()
                            .map(|single| (single.display_name.clone(), single.addr.clone())),
                    );
                }
            }
        }
    }
    out.sort();
    out.dedup();
    Ok(out)
}

fn validate_attempt_rendering(
    reader: &impl BlobStoreGet,
    overlay: Option<&impl BlobStoreGet>,
    mail_facts: &TribleSet,
    files_facts: &TribleSet,
    attempt: &SendAttemptRecord,
    draft: &DraftRecord,
    config: &AccountConfigRecord,
) -> Result<()> {
    let raw = bytes_union(reader, overlay, attempt.raw)?;
    let parsed = parse_rfc5322(&raw).context("parse frozen send-attempt bytes")?;
    let materialized = materialize_draft_union(reader, overlay, mail_facts, files_facts, draft.id)?;

    let expected_message_id = format!("mail-{}@triblespace", draft.id);
    if parsed.identity != WireIdentity::Claimed(expected_message_id.clone()) {
        bail!(
            "attempt Message-ID {:?} does not match deterministic draft id {:?}",
            parsed.identity,
            expected_message_id
        );
    }
    if parsed.subject != materialized.subject || parsed.body != materialized.body {
        bail!("attempt wire subject/body does not equal the authorized DraftIntent");
    }
    if parsed.attachments != materialized.attachments {
        bail!("attempt wire attachments do not equal the authorized DraftIntent");
    }
    if parsed.spam {
        bail!("locally rendered attempt unexpectedly claims spam status");
    }
    if !parsed.bcc.is_empty() {
        bail!("attempt wire leaks Bcc headers; Bcc is envelope-only");
    }

    let expected_from = normalized_mailboxes([format!(
        "{} <{}>",
        text_union(reader, overlay, config.display_name)?,
        materialized.envelope_from
    )])?;
    let actual_from = normalized_mailboxes(parsed.from)?;
    if actual_from != expected_from {
        bail!("attempt wire From does not equal the frozen account/draft sender");
    }
    if normalized_mailboxes(parsed.to)? != normalized_mailboxes(materialized.to.clone())?
        || normalized_mailboxes(parsed.cc)? != normalized_mailboxes(materialized.cc.clone())?
    {
        bail!("attempt wire recipients do not equal the authorized DraftIntent");
    }
    let expected_reply = sorted_ids(
        materialized
            .in_reply_to
            .iter()
            .map(|value| wire_id_for(value))
            .collect::<Result<Vec<_>>>()?,
    );
    let expected_references = sorted_ids(
        materialized
            .references
            .iter()
            .map(|value| wire_id_for(value))
            .collect::<Result<Vec<_>>>()?,
    );
    let actual_reply = sorted_ids(
        parsed
            .in_reply_to
            .iter()
            .map(|value| wire_id_for(value))
            .collect::<Result<Vec<_>>>()?,
    );
    let actual_references = sorted_ids(
        parsed
            .references
            .iter()
            .map(|value| wire_id_for(value))
            .collect::<Result<Vec<_>>>()?,
    );
    if actual_reply != expected_reply || actual_references != expected_references {
        bail!("attempt wire thread headers do not equal the authorized DraftIntent");
    }
    let expected_date: (Epoch, Epoch) = draft
        .created_at
        .try_from_inline()
        .map_err(|error| anyhow!("decode draft creation time: {error:?}"))?;
    let actual_date = parsed
        .claimed_date
        .ok_or_else(|| anyhow!("attempt wire has no Date header"))?;
    let actual_date: (Epoch, Epoch) = actual_date
        .try_from_inline()
        .map_err(|error| anyhow!("decode attempt Date: {error:?}"))?;
    if actual_date.0.to_unix_seconds().trunc() as i64
        != expected_date.0.to_unix_seconds().trunc() as i64
    {
        bail!("attempt wire Date does not equal the draft creation second");
    }
    Ok(())
}

/// Exact structural and cross-collection validation for one Mail materialization.
pub fn validate_catalog<R>(
    reader: &impl BlobStoreGet,
    facts: &TribleSet,
    files_facts: &TribleSet,
    decide_facts: &TribleSet,
    relations_facts: &TribleSet,
    secrets: &SecretsSnapshot<R>,
) -> Result<()> {
    validate_catalog_inner(
        reader,
        None::<&PileSnapshot>,
        facts,
        files_facts,
        decide_facts,
        relations_facts,
        true,
    )?;
    validate_secret_references(facts, secrets)
}

/// Validate only Mail's exact immutable references into configured Secrets.
pub fn validate_secret_references<R>(
    facts: &TribleSet,
    secrets: &SecretsSnapshot<R>,
) -> Result<()> {
    for (id, record) in config_owner_map(facts)? {
        if !secrets.contains(record.credential) {
            bail!(
                "account config {id:x} names unknown Secrets version {:x}",
                record.credential
            );
        }
    }
    Ok(())
}

/// Exact local Mail reconstruction without resolving cross-collection edges.
/// The stopped-world cutover uses this while each target collection is being
/// materialized independently; [`validate_catalog`] remains the required
/// final candidate predicate once Files, Decide, and Relations are available.
pub fn validate_local_catalog(reader: &impl BlobStoreGet, facts: &TribleSet) -> Result<()> {
    validate_catalog_inner(
        reader,
        None::<&PileSnapshot>,
        facts,
        &TribleSet::new(),
        &TribleSet::new(),
        &TribleSet::new(),
        false,
    )
}

/// Local preflight counterpart of [`validate_catalog_union`], used by the
/// cutover planner before cross-collection candidate materialization exists.
pub fn validate_local_catalog_union(
    reader: &impl BlobStoreGet,
    current: &TribleSet,
    fragment: &Fragment,
) -> Result<TribleSet> {
    let mut expected = current.clone();
    expected += fragment.facts().clone();
    let mut staged = fragment.clone();
    let overlay = staged
        .blobs_mut()
        .snapshot()
        .expect("memory blob reader creation is infallible");
    validate_catalog_inner(
        reader,
        Some(&overlay),
        &expected,
        &TribleSet::new(),
        &TribleSet::new(),
        &TribleSet::new(),
        false,
    )?;
    Ok(expected)
}

/// Preflight the exact set union a Mail publication would create, including
/// the new fragment's in-memory blobs, without writing pile bytes.
pub fn validate_catalog_union<R>(
    reader: &impl BlobStoreGet,
    current: &TribleSet,
    fragment: &Fragment,
    files_facts: &TribleSet,
    decide_facts: &TribleSet,
    relations_facts: &TribleSet,
    secrets: &SecretsSnapshot<R>,
) -> Result<TribleSet> {
    validate_catalog_union_with_blobs(
        reader,
        current,
        fragment,
        fragment,
        files_facts,
        decide_facts,
        relations_facts,
        secrets,
    )
}

/// Preflight one Mail delta while resolving attachments from a larger staged
/// cross-collection publication. Only `mail_fragment` contributes Mail facts;
/// `blob_overlay` is an ownership carrier for any Mail, Files, or Decide blobs
/// that have not reached the pile yet.
#[allow(clippy::too_many_arguments)]
pub fn validate_catalog_union_with_blobs<R>(
    reader: &impl BlobStoreGet,
    current: &TribleSet,
    mail_fragment: &Fragment,
    blob_overlay: &Fragment,
    files_facts: &TribleSet,
    decide_facts: &TribleSet,
    relations_facts: &TribleSet,
    secrets: &SecretsSnapshot<R>,
) -> Result<TribleSet> {
    let mut expected = current.clone();
    expected += mail_fragment.facts().clone();
    let mut staged = blob_overlay.clone();
    let overlay = staged
        .blobs_mut()
        .snapshot()
        .expect("memory blob reader creation is infallible");
    validate_catalog_inner(
        reader,
        Some(&overlay),
        &expected,
        files_facts,
        decide_facts,
        relations_facts,
        true,
    )?;
    validate_secret_references(&expected, secrets)?;
    Ok(expected)
}

#[allow(clippy::too_many_arguments)]
fn validate_catalog_inner<Overlay: BlobStoreGet>(
    reader: &impl BlobStoreGet,
    overlay: Option<&Overlay>,
    facts: &TribleSet,
    files_facts: &TribleSet,
    decide_facts: &TribleSet,
    relations_facts: &TribleSet,
    validate_cross_collection: bool,
) -> Result<()> {
    let accounts = account_anchors(facts);
    let configs = config_owner_map(facts)?;
    let wires: BTreeSet<_> = ids_of_kind(facts, KIND_WIRE_MESSAGE);
    let drafts: BTreeSet<_> = ids_of_kind(facts, KIND_DRAFT_INTENT);
    let attempts: BTreeSet<_> = ids_of_kind(facts, KIND_SEND_ATTEMPT);
    let acceptances: BTreeSet<_> = ids_of_kind(facts, KIND_SMTP_ACCEPTANCE);
    let reads: BTreeSet<_> = ids_of_kind(facts, KIND_READ_OBSERVATION);
    let pop_observations: BTreeSet<_> = ids_of_kind(facts, KIND_POP_OBSERVATION);
    let outgoing_observations: BTreeSet<_> = ids_of_kind(facts, KIND_OUTGOING_OBSERVATION);
    let imported_observations: BTreeSet<_> = ids_of_kind(facts, KIND_IMPORTED_OBSERVATION);
    let mut expected = validate_legacy_evidence(reader, overlay, facts)?;

    for &anchor in &accounts {
        expected += account_anchor_record(anchor);
    }
    for (&id, record) in &configs {
        if !accounts.contains(&record.account) {
            bail!(
                "account config {id:x} names unknown account {:x}",
                record.account
            );
        }
        for handle in [
            record.address,
            record.display_name,
            record.pop_endpoint,
            record.smtp_endpoint,
            record.username,
        ] {
            canonical_nonempty(text_union(reader, overlay, handle)?, "account config text")?;
        }
        expected += ensure_intrinsic(id, account_config_record(record), "account config")?;
    }
    for &anchor in &accounts {
        if matches!(account_head(facts, anchor)?, Head::Missing) {
            bail!("mail account {anchor:x} has no configuration");
        }
    }

    for &wire_id in &wires {
        wire_claimed_message_id_union(reader, overlay, facts, wire_id)?;
    }

    for &id in &drafts {
        let record = draft_from_facts(facts, id)?;
        point_interval(record.created_at, "draft creation time")?;
        if !accounts.contains(&record.account) {
            bail!("draft {id:x} names unknown account {:x}", record.account);
        }
        if record.to.is_empty() && record.cc.is_empty() && record.bcc.is_empty() {
            bail!("draft {id:x} has no recipients");
        }
        if validate_cross_collection {
            for attachment in &record.attachments {
                file_attachment_union(reader, overlay, files_facts, *attachment).with_context(
                    || format!("draft {id:x} names invalid file attachment {attachment:x}"),
                )?;
            }
        }
        for wire_id in record.in_reply_to.iter().chain(&record.references) {
            if !wires.contains(wire_id) {
                bail!("draft {id:x} names non-resident thread wire {wire_id:x}");
            }
            if wire_claimed_message_id_union(reader, overlay, facts, *wire_id)?.is_none() {
                bail!("draft {id:x} names digest-only thread wire {wire_id:x}");
            }
        }
        for handle in record
            .to
            .iter()
            .chain(&record.cc)
            .chain(&record.bcc)
            .chain([&record.envelope_from])
        {
            canonical_nonempty(
                text_union(reader, overlay, *handle)?,
                "draft envelope address",
            )?;
        }
        exact_text(
            text_union(reader, overlay, record.subject)?,
            "draft subject",
        )?;
        exact_text(text_union(reader, overlay, record.body)?, "draft body")?;
        expected += ensure_intrinsic(id, draft_record(&record), "draft intent")?;

        if validate_cross_collection {
            let decision = draft_decision_id(id);
            if !exists!(pattern!(decide_facts, [{ decision @ metadata::tag: &KIND_DECISION }])) {
                bail!("draft {id:x} has no deterministic Decide anchor {decision:x}");
            }
            let genesis = decide::genesis_for_decision(decide_facts, decision)?
                .ok_or_else(|| anyhow!("draft decision {decision:x} has no genesis"))?;
            if genesis.about != Some(id) {
                bail!("draft decision {decision:x} does not concern draft {id:x}");
            }
        }
    }

    for &id in &attempts {
        let record = attempt_from_facts(facts, id)?;
        let draft = draft_from_facts(facts, record.draft)
            .with_context(|| format!("attempt {id:x} names invalid draft"))?;
        let config = configs
            .get(&record.config)
            .ok_or_else(|| anyhow!("attempt {id:x} names unknown config {:x}", record.config))?;
        if config.account != draft.account {
            bail!("attempt {id:x} config and draft belong to different accounts");
        }
        if !config.enabled {
            bail!("attempt {id:x} cites a disabled account configuration");
        }
        if config.address != draft.envelope_from {
            bail!("attempt {id:x} draft sender differs from its account configuration");
        }
        if record.decision != draft_decision_id(record.draft) {
            bail!("attempt {id:x} names the wrong deterministic decision");
        }
        if validate_cross_collection {
            validate_send_heads(
                reader,
                overlay,
                decide_facts,
                record.decision,
                &record.decision_heads,
            )?;
        }
        if record.envelope_from != draft.envelope_from
            || record.to != draft.to
            || record.cc != draft.cc
            || record.bcc != draft.bcc
        {
            bail!("attempt {id:x} does not preserve the draft's exact envelope");
        }
        if validate_cross_collection {
            validate_attempt_rendering(
                reader,
                overlay,
                facts,
                files_facts,
                &record,
                &draft,
                config,
            )?;
        }
        expected += ensure_intrinsic(id, attempt_record(&record), "send attempt")?;
    }
    for &draft_id in &drafts {
        let draft_attempts = attempts_for_draft(facts, draft_id);
        if draft_attempts.len() > 1 {
            bail!("draft {draft_id:x} has multiple send attempts; uncertain attempts are never retried");
        }
    }

    for &id in &acceptances {
        let attempt_id = required(
            find!(v: Id, pattern!(facts, [{ id @ acceptance::attempt: ?v }])).collect(),
            "SMTP acceptance attempt",
        )?;
        if !attempts.contains(&attempt_id) {
            bail!("SMTP acceptance {id:x} names unknown attempt {attempt_id:x}");
        }
        let response = required(
            find!(v: TextHandle, pattern!(facts, [{ id @ acceptance::response: ?v }])).collect(),
            "SMTP acceptance response",
        )?;
        canonical_nonempty(text_union(reader, overlay, response)?, "SMTP response")?;
        let code = required(
            find!(v: CountValue, pattern!(facts, [{ id @ acceptance::response_code: ?v }]))
                .collect(),
            "SMTP acceptance response code",
        )?;
        let numeric_code = u64::try_from_inline(&code)
            .map_err(|_| anyhow!("SMTP acceptance {id:x} response code exceeds u64"))?;
        if !(200..=299).contains(&numeric_code) {
            bail!("SMTP acceptance {id:x} has non-positive reply code {numeric_code}");
        }
        let outgoing: BTreeSet<Id> = find!(
            source: Id,
            pattern!(facts, [{ ?source @
                metadata::tag: &KIND_OUTGOING_OBSERVATION,
                observation::attempt: &attempt_id,
            }])
        )
        .collect();
        if outgoing.len() != 1 {
            bail!(
                "SMTP acceptance {id:x} must have exactly one outgoing observation, found {}",
                outgoing.len()
            );
        }
        expected += ensure_intrinsic(
            id,
            entity! {
                metadata::tag: &KIND_SMTP_ACCEPTANCE,
                acceptance::attempt: &attempt_id,
                acceptance::response_code: code,
                acceptance::response: response,
            },
            "SMTP acceptance",
        )?;
    }
    for &attempt_id in &attempts {
        let receipts = acceptances_for_attempt(facts, attempt_id);
        if receipts.len() > 1 {
            bail!("send attempt {attempt_id:x} has multiple SMTP acceptance receipts");
        }
        let outgoing: BTreeSet<Id> = find!(
            source: Id,
            pattern!(facts, [{ ?source @
                metadata::tag: &KIND_OUTGOING_OBSERVATION,
                observation::attempt: &attempt_id,
            }])
        )
        .collect();
        if outgoing.len() > 1 {
            bail!("send attempt {attempt_id:x} has multiple outgoing observations");
        }
    }

    let mut pop_uidls = BTreeMap::<(Id, String), (BytesHandle, Id)>::new();
    for &id in &pop_observations {
        let account_id = required(
            find!(v: Id, pattern!(facts, [{ id @ observation::account: ?v }])).collect(),
            "POP observation account",
        )?;
        if !accounts.contains(&account_id) {
            bail!("POP observation {id:x} names unknown account {account_id:x}");
        }
        let config_id = required(
            find!(v: Id, pattern!(facts, [{ id @ observation::config: ?v }])).collect(),
            "POP observation config",
        )?;
        let config = configs
            .get(&config_id)
            .ok_or_else(|| anyhow!("POP observation {id:x} names unknown config {config_id:x}"))?;
        if config.account != account_id {
            bail!("POP observation {id:x} config belongs to another account");
        }
        if !config.enabled {
            bail!("POP observation {id:x} cites a disabled account configuration");
        }
        let uidl = required(
            find!(v: TextHandle, pattern!(facts, [{ id @ observation::uidl: ?v }])).collect(),
            "POP UIDL",
        )?;
        let raw_handle = required(
            find!(v: BytesHandle, pattern!(facts, [{ id @ observation::raw: ?v }])).collect(),
            "POP raw message",
        )?;
        let uidl = text_union(reader, overlay, uidl)?;
        if let Some((previous_raw, previous_id)) =
            pop_uidls.insert((account_id, uidl.clone()), (raw_handle, id))
        {
            if previous_raw != raw_handle {
                bail!(
                    "POP account {account_id:x} UIDL {uidl:?} names different raw messages in observations {previous_id:x} and {id:x}"
                );
            }
        }
        let raw = bytes_union(reader, overlay, raw_handle)?;
        let publication = pop_publication(account_id, config_id, &uidl, &raw)?;
        if publication.observation != id {
            bail!("POP observation {id:x} does not match exact source evidence");
        }
        validate_source_text_payloads(reader, overlay, publication.mail.facts())?;
        if validate_cross_collection {
            for fact in publication.files.facts() {
                if !files_facts.contains(fact) {
                    bail!("POP observation {id:x} has unpublished Files attachment evidence");
                }
            }
        }
        expected += publication.mail.into_facts();
    }

    for &id in &outgoing_observations {
        let attempt_id = required(
            find!(v: Id, pattern!(facts, [{ id @ observation::attempt: ?v }])).collect(),
            "outgoing observation attempt",
        )?;
        if acceptances_for_attempt(facts, attempt_id).is_empty() {
            bail!("outgoing observation {id:x} has no SMTP acceptance");
        }
        let raw = required(
            find!(v: BytesHandle, pattern!(facts, [{ id @ observation::raw: ?v }])).collect(),
            "outgoing raw message",
        )?;
        let attempt_raw = attempt_from_facts(facts, attempt_id)?.raw;
        if raw != attempt_raw {
            bail!("outgoing observation {id:x} bytes differ from its frozen send attempt");
        }
        let raw = bytes_union(reader, overlay, raw)?;
        let publication = outgoing_publication(attempt_id, &raw)?;
        if publication.observation != id {
            bail!("outgoing observation {id:x} does not match accepted bytes");
        }
        validate_source_text_payloads(reader, overlay, publication.mail.facts())?;
        if validate_cross_collection {
            for fact in publication.files.facts() {
                if !files_facts.contains(fact) {
                    bail!("outgoing observation {id:x} has unpublished Files attachment evidence");
                }
            }
        }
        expected += publication.mail.into_facts();
    }

    let identities = IdentityComponents::from_facts(relations_facts)?;
    let mut imported_by_legacy = BTreeMap::new();
    for &id in &imported_observations {
        let legacy_entity = required(
            find!(v: Id, pattern!(facts, [{ id @ imported::legacy_entity: ?v }])).collect(),
            "imported legacy Mail entity",
        )?;
        if let Some(other) = imported_by_legacy.insert(legacy_entity, id) {
            bail!(
                "legacy Mail entity {legacy_entity:x} has two imported observations {other:x} and {id:x}"
            );
        }
        let direction = required(
            find!(v: Id, pattern!(facts, [{ id @ imported::direction: ?v }])).collect(),
            "imported Mail direction",
        )?;
        let payload_handle = required(
            find!(v: ArchiveHandle, pattern!(facts, [{ id @ imported::payload: ?v }])).collect(),
            "imported Mail payload",
        )?;
        let payload = archive_union(reader, overlay, payload_handle)?;
        let record = imported_payload_union(reader, overlay, &payload, legacy_entity)
            .with_context(|| format!("validate imported Mail payload {legacy_entity:x}"))?;
        if record.direction != direction {
            bail!(
                "imported Mail observation {id:x} direction differs from its exact legacy payload"
            );
        }
        let wire_id = required(
            find!(v: Id, pattern!(facts, [{ id @ observation::wire: ?v }])).collect(),
            "imported Mail wire",
        )?;
        let outer_raw = one(
            find!(v: BytesHandle, pattern!(facts, [{ id @ observation::raw: ?v }])).collect(),
            "imported raw message",
        )?;
        if outer_raw != record.raw {
            bail!("imported Mail observation {id:x} does not preserve its payload raw handle");
        }
        let message_id = text_union(reader, overlay, record.message_id)?;
        let raw = record
            .raw
            .map(|handle| bytes_union(reader, overlay, handle))
            .transpose()?;
        let publication = imported_publication(
            legacy_entity,
            direction,
            payload_handle,
            &message_id,
            raw.as_deref(),
        )?;
        if publication.observation != id || publication.wire != wire_id {
            bail!("imported Mail observation {id:x} does not match its exact source evidence");
        }
        validate_source_text_payloads(reader, overlay, publication.mail.facts())?;

        if !publication.files.facts().is_empty() {
            bail!("imported Mail observation {id:x} unexpectedly minted modern Files identities");
        }
        if validate_cross_collection {
            for attachment in &record.attachments {
                let attachment_id = *attachment;
                if !exists!(pattern!(files_facts, [{ attachment_id @ metadata::tag: &KIND_FILE }]))
                {
                    bail!(
                        "imported Mail observation {id:x} names missing legacy Files attachment {attachment:x}"
                    );
                }
            }
            for relation in record
                .from
                .iter()
                .chain(&record.to)
                .chain(&record.cc)
                .chain(&record.bcc)
            {
                identities.component(*relation).with_context(|| {
                    format!(
                        "imported Mail observation {id:x} names missing Relations anchor {relation:x}"
                    )
                })?;
            }
        }
        expected += publication.mail.into_facts();
    }

    // Read evidence records that a persona opened a resident message; it is
    // not itself an inbox-membership assertion. Historical `mail read` and
    // auto-read-on-show applied equally to received, sent, and draft values.
    // Inbox projection below still considers only inbound sources when it
    // computes unread state.
    let mut resident_wires: BTreeSet<Id> = find!(
        wire_id: Id,
        pattern!(facts, [{ _?source @ metadata::tag: &KIND_POP_OBSERVATION, observation::wire: ?wire_id }])
    )
    .collect();
    resident_wires.extend(find!(
        wire_id: Id,
        pattern!(facts, [{ _?source @ metadata::tag: &KIND_OUTGOING_OBSERVATION, observation::wire: ?wire_id }])
    ));
    resident_wires.extend(find!(
        wire_id: Id,
        pattern!(facts, [{ _?source @
            metadata::tag: &KIND_IMPORTED_OBSERVATION,
            observation::wire: ?wire_id,
        }])
    ));
    for &id in &reads {
        let wire_id = required(
            find!(v: Id, pattern!(facts, [{ id @ read::wire: ?v }])).collect(),
            "read wire",
        )?;
        let reader_id = required(
            find!(v: Id, pattern!(facts, [{ id @ read::reader: ?v }])).collect(),
            "read persona",
        )?;
        if !resident_wires.contains(&wire_id) {
            bail!("read observation {id:x} does not name a resident wire message");
        }
        if validate_cross_collection {
            identities.component(reader_id)?;
        }
        expected += ensure_intrinsic(
            id,
            read_observation_fragment(wire_id, reader_id).0,
            "read observation",
        )?;
        let read_times: BTreeSet<IntervalValue> = find!(
            value: IntervalValue,
            pattern!(facts, [{ id @ legacy_read::read_at: ?value }])
        )
        .collect();
        let created_times: BTreeSet<IntervalValue> = find!(
            value: IntervalValue,
            pattern!(facts, [{ id @ metadata::created_at: ?value }])
        )
        .collect();
        for value in read_times.iter().chain(&created_times) {
            point_interval(*value, "Mail read-observation time")?;
        }
        expected += entity! { ExclusiveId::force_ref(&id) @
            legacy_read::read_at*: read_times.iter(),
            metadata::created_at*: created_times.iter(),
        }
        .into_facts();
    }

    if expected != *facts {
        let unexpected = facts.iter().filter(|fact| !expected.contains(fact)).count();
        let missing = expected.iter().filter(|fact| !facts.contains(fact)).count();
        bail!("Mail catalog is not its exact canonical reconstruction ({unexpected} unexpected facts, {missing} missing facts)");
    }
    Ok(())
}

/// Admit only the exact historical records preserved by the additive Mail
/// cutover. They remain inert evidence: native commands never create or query
/// these kinds, while their canonical shadows use the current ontology.
fn validate_legacy_evidence<Overlay: BlobStoreGet>(
    reader: &impl BlobStoreGet,
    overlay: Option<&Overlay>,
    facts: &TribleSet,
) -> Result<TribleSet> {
    let mut expected = TribleSet::new();
    let messages: BTreeSet<Id> = facts
        .iter()
        .filter(|fact| fact.a() == &imported_legacy::message_id.id())
        .map(|fact| *fact.e())
        .collect();
    for message in messages {
        let record = entity_facts(facts, message);
        imported_payload_union(reader, overlay, &record, message)
            .with_context(|| format!("validate preserved legacy Mail record {message:x}"))?;
        expected += record;
    }

    for read_id in ids_of_kind(facts, crate::schemas::message::KIND_READ_ID) {
        let record = entity_facts(facts, read_id);
        let tags: BTreeSet<Id> = find!(
            tag: Id,
            pattern!(&record, [{ read_id @ metadata::tag: ?tag }])
        )
        .collect();
        if tags != BTreeSet::from([crate::schemas::message::KIND_READ_ID]) {
            bail!("legacy Mail read receipt {read_id:x} has an invalid kind set");
        }
        let about = required(
            find!(v: Id, pattern!(&record, [{ read_id @ legacy_read::about_message: ?v }]))
                .collect(),
            "legacy read subject",
        )?;
        let reader_id = required(
            find!(v: Id, pattern!(&record, [{ read_id @ legacy_read::reader: ?v }])).collect(),
            "legacy read reader",
        )?;
        let read_at = required(
            find!(v: IntervalValue, pattern!(&record, [{ read_id @ legacy_read::read_at: ?v }]))
                .collect(),
            "legacy read time",
        )?;
        let created_at = required(
            find!(v: IntervalValue, pattern!(&record, [{ read_id @ metadata::created_at: ?v }]))
                .collect(),
            "legacy read creation time",
        )?;
        point_interval(read_at, "legacy read time")?;
        point_interval(created_at, "legacy read creation time")?;
        let exact = entity! { ExclusiveId::force_ref(&read_id) @
            metadata::tag: &crate::schemas::message::KIND_READ_ID,
            legacy_read::about_message: &about,
            legacy_read::reader: &reader_id,
            legacy_read::read_at: read_at,
            metadata::created_at: created_at,
        };
        if exact.facts() != &record {
            bail!("legacy Mail read receipt {read_id:x} is not an exact supported record");
        }
        expected += record;
    }

    for vocabulary in [
        LEGACY_KIND_MESSAGE,
        LEGACY_KIND_SPAM,
        IMPORT_DRAFT,
        IMPORT_RECEIVED,
        IMPORT_SENT,
        crate::schemas::message::KIND_READ_ID,
    ] {
        let record = entity_facts(facts, vocabulary);
        for fact in &record {
            if fact.a() != &metadata::name.id() {
                bail!(
                    "legacy Mail vocabulary entity {vocabulary:x} has unsupported attribute {:x}",
                    fact.a()
                );
            }
            let handle = *fact.v::<inlineencodings::Handle<blobencodings::UTF8String>>();
            let _: String = text_union(reader, overlay, handle)?;
        }
        expected += record;
    }
    Ok(expected)
}

/// Project every inbound parser result and its read state for one exact
/// persona component.  A later observation of the same WireMessage does not
/// reopen it because read evidence is keyed by `(wire, reader)`.
pub fn inbox_projection<M, R>(
    mail_facts: &M,
    relations_facts: &R,
    persona: Id,
) -> Result<Vec<InboxProjection>>
where
    M: TriblePattern,
    R: TriblePattern,
{
    let identities = IdentityComponents::from_facts(relations_facts)?;
    let component = identities.component(persona)?;
    let read_wires: BTreeSet<Id> = find!(
        (wire_id: Id, reader_id: Id),
        pattern!(mail_facts, [{ _?read @
            metadata::tag: &KIND_READ_OBSERVATION,
            read::wire: ?wire_id,
            read::reader: ?reader_id,
        }])
    )
    .filter_map(|(wire_id, reader_id)| component.contains(&reader_id).then_some(wire_id))
    .collect();
    let mut sources: BTreeMap<Id, Id> = find!(
        (source: Id, wire_id: Id),
        pattern!(mail_facts, [{ ?source @
            metadata::tag: &KIND_POP_OBSERVATION,
            observation::wire: ?wire_id,
        }])
    )
    .collect();
    sources.extend(find!(
        (source: Id, wire_id: Id),
        pattern!(mail_facts, [{ ?source @
            metadata::tag: &KIND_IMPORTED_OBSERVATION,
            imported::direction: &IMPORT_RECEIVED,
            observation::wire: ?wire_id,
        }])
    ));
    let mut rows = Vec::new();
    for (source, wire) in sources {
        for projection_id in find!(
            id: Id,
            pattern!(mail_facts, [{ ?id @
                metadata::tag: &KIND_PARSED_PROJECTION,
                projection::source: &source,
                projection::recipe: &RECIPE_RFC5322_V1,
            }])
        ) {
            rows.push(InboxProjection {
                wire,
                projection: projection_id,
                source,
                unread: !read_wires.contains(&wire),
            });
        }
    }
    rows.sort_by_key(|row| (row.wire, row.source, row.projection));
    Ok(rows)
}

fn text_values<P>(
    reader: &impl BlobStoreGet,
    facts: &P,
    id: Id,
    attribute: &Attribute<inlineencodings::Handle<blobencodings::UTF8String>>,
) -> Result<Vec<String>>
where
    P: TriblePattern,
{
    let handles: BTreeSet<TextHandle> =
        find!(handle: TextHandle, pattern!(facts, [{ id @ attribute: ?handle }])).collect();
    handles
        .into_iter()
        .map(|handle| read_text(reader, handle))
        .collect()
}

/// Read the structural inbox-summary projection without touching any blob.
///
/// This is deliberately smaller than [`projection_view`]: a watcher can
/// decide whether a wire is unread and inspect residency of only the From and
/// Subject it would actually print. Missing Body or attachment bytes are not
/// relevant to that operation.
pub fn projection_summary_record<P>(facts: &P, projection_id: Id) -> Result<ProjectionSummaryRecord>
where
    P: TriblePattern,
{
    if !ids_of_kind(facts, KIND_PARSED_PROJECTION).contains(&projection_id) {
        bail!("unknown Mail projection {projection_id:x}");
    }
    let source = required(
        find!(v: Id, pattern!(facts, [{ projection_id @ projection::source: ?v }])).collect(),
        "projection source",
    )?;
    Ok(ProjectionSummaryRecord {
        id: projection_id,
        source,
        wire: required(
            find!(v: Id, pattern!(facts, [{ source @ observation::wire: ?v }])).collect(),
            "source wire message",
        )?,
        from: one(
            find!(v: TextHandle, pattern!(facts, [{ projection_id @ projection::from: ?v }]))
                .collect(),
            "projection From",
        )?,
        subject: required(
            find!(v: TextHandle, pattern!(facts, [{ projection_id @ projection::subject: ?v }]))
                .collect(),
            "projection subject",
        )?,
        claimed_date: one(
            find!(v: IntervalValue, pattern!(facts, [{ projection_id @ projection::claimed_date: ?v }]))
                .collect(),
            "projection claimed date",
        )?,
        spam: required(
            find!(v: bool, pattern!(facts, [{ projection_id @ projection::spam: ?v }])).collect(),
            "projection spam flag",
        )?,
    })
}

pub fn projection_view<P>(
    reader: &impl BlobStoreGet,
    facts: &P,
    projection_id: Id,
) -> Result<ProjectionView>
where
    P: TriblePattern,
{
    let summary = projection_summary_record(facts, projection_id)?;
    let body = required(
        find!(v: TextHandle, pattern!(facts, [{ projection_id @ projection::body: ?v }])).collect(),
        "projection body",
    )?;
    Ok(ProjectionView {
        id: projection_id,
        source: summary.source,
        wire: summary.wire,
        message_id: wire_claimed_message_id(reader, facts, summary.wire)?,
        from: summary
            .from
            .map(|handle| read_text(reader, handle))
            .transpose()?,
        to: text_values(reader, facts, projection_id, &projection::to)?,
        cc: text_values(reader, facts, projection_id, &projection::cc)?,
        bcc: text_values(reader, facts, projection_id, &projection::bcc)?,
        subject: read_text(reader, summary.subject)?,
        body: read_text(reader, body)?,
        claimed_date: summary.claimed_date,
        in_reply_to: sorted_ids(
            find!(v: Id, pattern!(facts, [{ projection_id @ projection::in_reply_to: ?v }])),
        ),
        references: sorted_ids(
            find!(v: Id, pattern!(facts, [{ projection_id @ projection::reference: ?v }])),
        ),
        spam: summary.spam,
        attachments: sorted_ids(
            find!(v: Id, pattern!(facts, [{ projection_id @ projection::attachment: ?v }])),
        ),
    })
}

/// Resolve the exact immutable transport evidence behind one projection.
/// Conflicting tags or imported directions are rejected rather than reduced
/// to a priority order.
pub fn projection_direction<P>(facts: &P, source: Id) -> Result<ProjectionDirection>
where
    P: TriblePattern,
{
    let mut candidates = BTreeSet::new();
    let tags = find!(value: Id, pattern!(facts, [{ source @ metadata::tag: ?value }]))
        .collect::<BTreeSet<_>>();
    if tags.contains(&KIND_POP_OBSERVATION) {
        candidates.insert(0_u8);
    }
    if tags.contains(&KIND_OUTGOING_OBSERVATION) {
        candidates.insert(1_u8);
    }
    if tags.contains(&KIND_IMPORTED_OBSERVATION) {
        let direction = required(
            find!(value: Id, pattern!(facts, [{ source @ imported::direction: ?value }])).collect(),
            "imported Mail direction",
        )?;
        let code = if direction == IMPORT_RECEIVED {
            0
        } else if direction == IMPORT_SENT {
            1
        } else if direction == IMPORT_DRAFT {
            2
        } else {
            bail!("Mail source {source:x} has unknown imported direction {direction:x}");
        };
        candidates.insert(code);
    }
    let code = required(candidates, "Mail projection source direction")?;
    Ok(match code {
        0 => ProjectionDirection::Received,
        1 => ProjectionDirection::Sent,
        2 => ProjectionDirection::Draft,
        _ => unreachable!("direction codes are closed above"),
    })
}

fn wire_claimed_message_id_union<Overlay: BlobStoreGet>(
    reader: &impl BlobStoreGet,
    overlay: Option<&Overlay>,
    facts: &TribleSet,
    wire_id: Id,
) -> Result<Option<String>> {
    let claimed = one(
        find!(v: TextHandle, pattern!(facts, [{ wire_id @ wire::claimed_message_id: ?v }]))
            .collect(),
        "wire claimed Message-ID",
    )?;
    let digest = one(
        find!(v: DigestValue, pattern!(facts, [{ wire_id @ wire::raw_digest: ?v }])).collect(),
        "wire raw digest",
    )?;
    match (claimed, digest) {
        (Some(handle), None) => Ok(Some(canonical_message_id_value(&text_union(
            reader, overlay, handle,
        )?)?)),
        (None, Some(_)) => Ok(None),
        (Some(_), Some(_)) => bail!("wire {wire_id:x} mixes claimed and raw-digest identity"),
        (None, None) => bail!("wire {wire_id:x} has no identity"),
    }
}

pub fn wire_claimed_message_id<P>(
    reader: &impl BlobStoreGet,
    facts: &P,
    wire_id: Id,
) -> Result<Option<String>>
where
    P: TriblePattern,
{
    if !ids_of_kind(facts, KIND_WIRE_MESSAGE).contains(&wire_id) {
        bail!("unknown wire message {wire_id:x}");
    }
    let claimed = one(
        find!(v: TextHandle, pattern!(facts, [{ wire_id @ wire::claimed_message_id: ?v }]))
            .collect(),
        "wire claimed Message-ID",
    )?;
    let digest = one(
        find!(v: DigestValue, pattern!(facts, [{ wire_id @ wire::raw_digest: ?v }])).collect(),
        "wire raw digest",
    )?;
    match (claimed, digest) {
        (Some(handle), None) => Ok(Some(canonical_message_id_value(&read_text(
            reader, handle,
        )?)?)),
        (None, Some(_)) => Ok(None),
        (Some(_), Some(_)) => bail!("wire {wire_id:x} mixes claimed and raw-digest identity"),
        (None, None) => bail!("wire {wire_id:x} has no identity"),
    }
}

pub fn materialize_draft<M, F>(
    reader: &impl BlobStoreGet,
    mail_facts: &M,
    files_facts: &F,
    id: Id,
) -> Result<MaterializedDraft>
where
    M: TriblePattern,
    F: TriblePattern,
{
    let record = draft_value(mail_facts, id)?;
    let read_all = |handles: &[TextHandle]| -> Result<Vec<String>> {
        handles
            .iter()
            .map(|&handle| read_text(reader, handle))
            .collect()
    };
    let attachments = record
        .attachments
        .iter()
        .map(|&file| file_attachment(reader, files_facts, file))
        .collect::<Result<_>>()?;
    let wires = ids_of_kind(mail_facts, KIND_WIRE_MESSAGE);
    let resolve_wire = |wire: Id, field: &str| -> Result<String> {
        if !wires.contains(&wire) {
            bail!("unknown wire message {wire:x}");
        }
        wire_claimed_message_id(reader, mail_facts, wire)?
            .ok_or_else(|| anyhow!("draft names digest-only {field} wire {wire:x}"))
    };
    Ok(MaterializedDraft {
        id,
        account: record.account,
        envelope_from: read_text(reader, record.envelope_from)?,
        to: read_all(&record.to)?,
        cc: read_all(&record.cc)?,
        bcc: read_all(&record.bcc)?,
        subject: read_text(reader, record.subject)?,
        body: read_text(reader, record.body)?,
        attachments,
        in_reply_to: record
            .in_reply_to
            .iter()
            .map(|&wire| resolve_wire(wire, "In-Reply-To"))
            .collect::<Result<_>>()?,
        references: record
            .references
            .iter()
            .map(|&wire| resolve_wire(wire, "References"))
            .collect::<Result<_>>()?,
        created_at: record.created_at,
    })
}

fn materialize_draft_union<Overlay: BlobStoreGet>(
    reader: &impl BlobStoreGet,
    overlay: Option<&Overlay>,
    mail_facts: &TribleSet,
    files_facts: &TribleSet,
    id: Id,
) -> Result<MaterializedDraft> {
    let record = draft_value(mail_facts, id)?;
    let read_all = |handles: &[TextHandle]| -> Result<Vec<String>> {
        handles
            .iter()
            .map(|&handle| text_union(reader, overlay, handle))
            .collect()
    };
    let mut attachments = Vec::new();
    for file_id in &record.attachments {
        attachments.push(file_attachment_union(
            reader,
            overlay,
            files_facts,
            *file_id,
        )?);
    }
    let wires = ids_of_kind(mail_facts, KIND_WIRE_MESSAGE);
    Ok(MaterializedDraft {
        id,
        account: record.account,
        envelope_from: text_union(reader, overlay, record.envelope_from)?,
        to: read_all(&record.to)?,
        cc: read_all(&record.cc)?,
        bcc: read_all(&record.bcc)?,
        subject: text_union(reader, overlay, record.subject)?,
        body: text_union(reader, overlay, record.body)?,
        attachments,
        in_reply_to: record
            .in_reply_to
            .iter()
            .map(|&wire| {
                if !wires.contains(&wire) {
                    bail!("unknown wire message {wire:x}");
                }
                wire_claimed_message_id_union(reader, overlay, mail_facts, wire)?
                    .ok_or_else(|| anyhow!("draft names digest-only In-Reply-To wire {wire:x}"))
            })
            .collect::<Result<_>>()?,
        references: record
            .references
            .iter()
            .map(|&wire| {
                if !wires.contains(&wire) {
                    bail!("unknown wire message {wire:x}");
                }
                wire_claimed_message_id_union(reader, overlay, mail_facts, wire)?
                    .ok_or_else(|| anyhow!("draft names digest-only References wire {wire:x}"))
            })
            .collect::<Result<_>>()?,
        created_at: record.created_at,
    })
}

/// Format a draft once. The returned bytes and envelope are what a caller must
/// freeze into SendAttempt before invoking SMTP.
pub fn render_draft(draft: &MaterializedDraft, account: &OpenAccount) -> Result<RenderedMail> {
    if draft.account != account.anchor {
        bail!("draft and account do not share an anchor");
    }
    if draft.envelope_from != account.address {
        bail!("draft sender does not match the frozen account address");
    }
    let from: Mailbox = format!("{} <{}>", account.display_name, draft.envelope_from)
        .parse()
        .context("parse draft From mailbox")?;
    let mut builder = Message::builder()
        .from(from)
        .message_id(Some(format!("<mail-{}@triblespace>", draft.id)))
        .subject(draft.subject.clone());
    let (start, _): (Epoch, Epoch) = draft
        .created_at
        .try_from_inline()
        .map_err(|error| anyhow!("decode draft creation time: {error:?}"))?;
    let unix = start.to_unix_seconds();
    if unix >= 0.0 {
        builder = builder.date(std::time::UNIX_EPOCH + std::time::Duration::from_secs_f64(unix));
    }
    for value in &draft.to {
        let mailbox: Mailbox = value
            .parse()
            .with_context(|| format!("parse To {value:?}"))?;
        builder = builder.to(mailbox);
    }
    for value in &draft.cc {
        let mailbox: Mailbox = value
            .parse()
            .with_context(|| format!("parse Cc {value:?}"))?;
        builder = builder.cc(mailbox);
    }
    for value in &draft.bcc {
        let mailbox: Mailbox = value
            .parse()
            .with_context(|| format!("parse Bcc {value:?}"))?;
        builder = builder.bcc(mailbox);
    }
    if !draft.in_reply_to.is_empty() {
        builder = builder.in_reply_to(
            draft
                .in_reply_to
                .iter()
                .map(|value| format!("<{value}>"))
                .collect::<Vec<_>>()
                .join(" "),
        );
    }
    if !draft.references.is_empty() {
        builder = builder.references(
            draft
                .references
                .iter()
                .map(|value| format!("<{value}>"))
                .collect::<Vec<_>>()
                .join(" "),
        );
    }
    let message = if draft.attachments.is_empty() {
        builder
            .header(header::ContentType::TEXT_PLAIN)
            .body(draft.body.clone())
            .context("format draft")?
    } else {
        // Lettre otherwise invents a random boundary here.  The immutable
        // draft id commits to the body and attachment identities, making it a
        // canonical boundary seed and therefore making raw rendering—and the
        // intrinsic SendAttempt that contains it—repeatable.
        let boundary = format!("=_triblespace_{:x}", draft.id);
        let mut multipart = MultiPart::mixed().boundary(boundary).singlepart(
            SinglePart::builder()
                .header(header::ContentType::TEXT_PLAIN)
                .body(draft.body.clone()),
        );
        for attachment in &draft.attachments {
            let content_type = header::ContentType::parse(&attachment.media_type)
                .unwrap_or(header::ContentType::parse(files::DEFAULT_MEDIA_TYPE).unwrap());
            multipart = multipart.singlepart(
                lettre::message::Attachment::new(attachment.filename.clone())
                    .body(attachment.bytes.clone(), content_type),
            );
        }
        builder
            .multipart(multipart)
            .context("format multipart draft")?
    };
    Ok(RenderedMail {
        raw: message.formatted(),
        envelope: smtp_envelope(&draft.envelope_from, &draft.to, &draft.cc, &draft.bcc)?,
    })
}

// ── irreversible-effect protocol seams ────────────────────────────────────

pub use crate::mail_pop::PopItem;

/// One POP transaction. Implementations must make ordinary Drop disconnect
/// without issuing QUIT; only explicit `quit` may commit marked deletions.
pub trait PopTxn {
    fn enumerate_uidls(&mut self) -> Result<Vec<PopItem>>;
    fn retrieve_exact(&mut self, session_seq: u32) -> Result<Vec<u8>>;
    fn mark_delete(&mut self, session_seq: u32) -> Result<()>;
    fn quit(self) -> Result<()>;
}

/// Fetch every UIDL exactly under one frozen account configuration, publish
/// its evidence, then mark it for deletion.
/// Duplicate or zero session identities are protocol errors and no deletion is
/// attempted. A failed explicit QUIT is an uncertain remote transaction, not
/// evidence that already-marked deletions were rolled back.
pub fn drain_pop<T, F>(
    mut transaction: T,
    account_id: Id,
    config_id: Id,
    mut publish: F,
) -> Result<()>
where
    T: PopTxn,
    F: FnMut(&SourcePublication) -> Result<()>,
{
    let items = transaction.enumerate_uidls()?;
    let mut uidls = BTreeSet::new();
    let mut sequences = BTreeSet::new();
    for item in &items {
        if item.session_seq == 0 {
            bail!("POP server returned zero session sequence");
        }
        if !sequences.insert(item.session_seq) {
            bail!(
                "POP server returned duplicate session sequence {}",
                item.session_seq
            );
        }
        if !uidls.insert(item.uidl.clone()) {
            bail!("POP server returned duplicate UIDL {:?}", item.uidl);
        }
    }
    for item in items {
        let raw = transaction.retrieve_exact(item.session_seq)?;
        let publication = pop_publication(account_id, config_id, &item.uidl, &raw)?;
        publish(&publication)?;
        transaction.mark_delete(item.session_seq)?;
    }
    transaction
        .quit()
        .context("POP QUIT failed after delete marks; remote deletion commit is uncertain")
}

impl<S> PopTxn for crate::mail_pop::PopSession<S>
where
    S: std::io::Read + std::io::Write,
{
    fn enumerate_uidls(&mut self) -> Result<Vec<PopItem>> {
        Ok(self.uidl()?)
    }

    fn retrieve_exact(&mut self, session_seq: u32) -> Result<Vec<u8>> {
        Ok(self.retr(session_seq)?)
    }

    fn mark_delete(&mut self, session_seq: u32) -> Result<()> {
        self.dele(session_seq)?;
        Ok(())
    }

    fn quit(self) -> Result<()> {
        crate::mail_pop::PopSession::quit(self)?;
        Ok(())
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SmtpEnvelope {
    pub from: String,
    pub recipients: Vec<String>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AcceptedReply {
    pub code: u16,
    pub message: String,
}

pub trait SmtpSubmit {
    /// Return only a final positive SMTP completion reply. Rejection or an
    /// indeterminate transport outcome is an error, after which the durable
    /// attempt must not be retried automatically.
    fn submit(&mut self, envelope: &SmtpEnvelope, raw: &[u8]) -> Result<AcceptedReply>;
}

fn smtp_envelope(from: &str, to: &[String], cc: &[String], bcc: &[String]) -> Result<SmtpEnvelope> {
    let senders = normalized_mailboxes([from.to_owned()])?;
    let [(_, from)] = senders.as_slice() else {
        bail!("SMTP envelope sender must contain exactly one mailbox");
    };
    let recipients = normalized_mailboxes(to.iter().chain(cc).chain(bcc).cloned())?
        .into_iter()
        .map(|(_, address)| address)
        .collect::<Vec<_>>();
    if recipients.is_empty() {
        bail!("SMTP envelope has no recipients");
    }
    Ok(SmtpEnvelope {
        from: from.clone(),
        recipients,
    })
}

fn smtp_envelope_for_attempt(input: &SendAttemptInput) -> Result<SmtpEnvelope> {
    smtp_envelope(&input.envelope_from, &input.to, &input.cc, &input.bcc)
}

/// Freeze and validate one exact SMTP effect plan against one local snapshot.
///
/// The stored Decide heads are the complete frontier observed by this
/// executor at preparation time. A later resolution does not retroactively
/// invalidate that historical authorization. Conversely, the eventual union
/// cannot prove that this local snapshot was globally fresh or complete: SMTP
/// execution is therefore an affine authority which deployments must
/// serialize per account rather than running concurrently on replicas.
pub fn prepare_send<M, F, D>(
    mail_reader: &impl BlobStoreGet,
    decide_reader: &impl BlobStoreGet,
    mail_facts: &M,
    files_facts: &F,
    decide_facts: &D,
    input: SendAttemptInput,
) -> Result<PreparedSend>
where
    M: TriblePattern,
    F: TriblePattern,
    D: TriblePattern,
{
    let draft = draft_from_facts(mail_facts, input.draft)
        .with_context(|| format!("prepare send for unknown draft {:x}", input.draft))?;
    match account_head(mail_facts, draft.account)? {
        Head::Unique(current) if current == input.config => {}
        Head::Unique(current) => bail!(
            "send config {:x} is stale; current account config is {current:x}",
            input.config
        ),
        Head::Missing => bail!("draft account {:x} has no configuration", draft.account),
        Head::Forked(heads) => bail!(
            "draft account {:x} has forked configurations {heads:?}",
            draft.account
        ),
    }
    let (current_decision, current_heads) =
        authorized_send(decide_reader, decide_facts, input.draft)?;
    if input.decision != current_decision
        || sorted_ids(input.decision_heads.iter().copied()) != current_heads
    {
        bail!("send attempt does not cite the exact locally observed Decide frontier");
    }

    let envelope = smtp_envelope_for_attempt(&input)?;
    let config = account_config(mail_facts, input.config)?;
    let materialized = materialize_draft(mail_reader, mail_facts, files_facts, input.draft)?;
    let expected = render_draft(
        &materialized,
        &OpenAccount {
            anchor: config.account,
            config: config.id,
            address: read_text(mail_reader, config.address)?,
            display_name: read_text(mail_reader, config.display_name)?,
            pop_endpoint: read_text(mail_reader, config.pop_endpoint)?,
            smtp_endpoint: read_text(mail_reader, config.smtp_endpoint)?,
            username: read_text(mail_reader, config.username)?,
            password: String::new(),
            enabled: config.enabled,
        },
    )?;
    if input.raw != expected.raw {
        let first_difference = input
            .raw
            .iter()
            .zip(&expected.raw)
            .position(|(actual, expected)| actual != expected)
            .unwrap_or_else(|| input.raw.len().min(expected.raw.len()));
        bail!(
            "send attempt bytes or envelope do not equal the authorized DraftIntent rendering: raw lengths {} != {} or first byte difference at {first_difference}",
            input.raw.len(),
            expected.raw.len(),
        );
    }
    if envelope != expected.envelope {
        bail!(
            "send attempt bytes or envelope do not equal the authorized DraftIntent rendering: SMTP envelope differs"
        );
    }
    let raw = input.raw.clone();
    let (attempt, attempt_id) = send_attempt_fragment(input)?;
    let outgoing = outgoing_publication(attempt_id, &raw)?;
    Ok(PreparedSend {
        attempt,
        attempt_id,
        outgoing,
        envelope,
        raw,
    })
}

/// Persist attempt-before-effect and acceptance-after-effect.  Any error after
/// attempt publication leaves an intentionally uncertain attempt which callers
/// must never retry automatically. The prepared value binds every byte and
/// address crossing the effect boundary to the exact validated attempt.
pub fn submit_once<T, PA, PC>(
    transport: &mut T,
    prepared: &PreparedSend,
    mut publish_attempt: PA,
    mut publish_acceptance: PC,
) -> Result<AcceptedReply>
where
    T: SmtpSubmit,
    PA: FnMut(&Fragment) -> Result<()>,
    PC: FnMut(&Fragment) -> Result<()>,
{
    publish_attempt(&prepared.attempt)?;
    let accepted = transport.submit(&prepared.envelope, &prepared.raw)?;
    if !(200..=299).contains(&accepted.code) {
        bail!(
            "SMTP submitter returned non-acceptance code {}; attempt outcome remains uncertain",
            accepted.code
        );
    }
    let (mut fragment, _) = smtp_acceptance_fragment(
        prepared.attempt_id,
        u64::from(accepted.code),
        accepted.message.clone(),
    )?;
    fragment += prepared.outgoing.mail.clone();
    publish_acceptance(&fragment)?;
    Ok(accepted)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::RefCell;
    use std::fs::File;
    use std::io::{self, Cursor, Read, Write};
    use std::path::PathBuf;
    use std::rc::Rc;

    use crate::collection_names::open_configured;
    use crate::relations::{self, ProfileInput};
    use crate::schemas::{
        decide as decide_schema, files as files_schema, mail as mail_schema,
        relations as relations_schema,
    };
    use crate::secrets::storage as secret_storage;
    use crate::storage::{
        load_signer, open_pile_strict, open_secrets_collection, open_secrets_collection_read,
        publish_fragment,
    };
    use crate::test_support::initialize_open_collection_fixture;
    use triblespace::core::repo::pile::{Pile, PileSnapshot};

    fn id(byte: u8) -> Id {
        Id::new([byte; 16]).unwrap()
    }

    fn at(second: u8) -> IntervalValue {
        let epoch = Epoch::from_gregorian_utc(2026, 8, 8, 0, 0, second, 0);
        (epoch, epoch).try_to_inline().unwrap()
    }

    fn empty_reader() -> (tempfile::TempDir, PileSnapshot) {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("empty.pile");
        File::create(&path).unwrap();
        let mut pile = Pile::open(&path).unwrap();
        let reader = pile.snapshot().unwrap();
        pile.close().unwrap();
        (directory, reader)
    }

    struct Fixture {
        _directory: tempfile::TempDir,
        pile: PathBuf,
        key: PathBuf,
    }

    struct CollectionView {
        facts: TribleSet,
        reader: PileSnapshot,
    }

    struct Views {
        mail: CollectionView,
        files: CollectionView,
        decide: CollectionView,
        relations: CollectionView,
        secrets: SecretsSnapshot<PileSnapshot>,
    }

    impl Fixture {
        fn new() -> Self {
            let directory = tempfile::tempdir().unwrap();
            let pile = directory.path().join("mail.pile");
            let key = directory.path().join("mail.key");
            File::create(&pile).unwrap();
            initialize_open_collection_fixture(&pile, Some(&key));
            Self {
                _directory: directory,
                pile,
                key,
            }
        }

        fn publish(&self, scope: Id, fragment: Fragment) {
            publish_fragment(&self.pile, Some(&self.key), scope, fragment).unwrap();
        }

        fn views(&self) -> Views {
            let signer = load_signer(&self.pile, Some(&self.key)).unwrap();
            let mut pile = open_pile_strict(&self.pile).unwrap();
            let secrets_collection =
                open_secrets_collection_read(&mut pile, signer.verifying_key()).unwrap();
            let secrets = pollster::block_on(secret_storage::ensure_and_snapshot(
                &mut pile,
                secrets_collection,
                &signer,
            ))
            .unwrap();
            let mail = open_configured(
                &mut pile,
                mail_schema::DEFAULT_SCOPE_ID,
                signer.verifying_key(),
            )
            .unwrap();
            let files = open_configured(
                &mut pile,
                files_schema::DEFAULT_SCOPE_ID,
                signer.verifying_key(),
            )
            .unwrap();
            let decide = open_configured(
                &mut pile,
                decide_schema::DEFAULT_SCOPE_ID,
                signer.verifying_key(),
            )
            .unwrap();
            let relations = open_configured(
                &mut pile,
                relations_schema::DEFAULT_SCOPE_ID,
                signer.verifying_key(),
            )
            .unwrap();
            let store_snapshot = pile.snapshot().unwrap();
            let materialize = |collection| {
                let (facts, _) =
                    crate::storage::read_fact_collection(collection, &store_snapshot).unwrap();
                CollectionView {
                    facts,
                    reader: store_snapshot.clone(),
                }
            };
            let views = Views {
                mail: materialize(mail),
                files: materialize(files),
                decide: materialize(decide),
                relations: materialize(relations),
                secrets,
            };
            pile.close().unwrap();
            views
        }

        fn signer(&self) -> SigningKey {
            load_signer(&self.pile, Some(&self.key)).unwrap()
        }

        fn add_secret(&self, name: &str, plaintext: &[u8], created_at: IntervalValue) -> Id {
            let signer = self.signer();
            let mut pile = open_pile_strict(&self.pile).unwrap();
            let collection = open_secrets_collection(&mut pile, signer.verifying_key()).unwrap();
            let secret = secret_storage::add_secret(
                &mut pile, &signer, collection, name, plaintext, created_at,
            )
            .unwrap();
            pile.close().unwrap();
            secret
        }
    }

    fn add_person(fixture: &Fixture, person: Id) {
        let (fragment, _, _) = relations::person_fragment(
            person,
            ProfileInput {
                label: "operator".into(),
                display_name: Some("Operator".into()),
                emails: vec!["jp@example.test".into()],
                ..ProfileInput::default()
            },
        )
        .unwrap();
        fixture.publish(relations_schema::DEFAULT_SCOPE_ID, fragment);
    }

    fn add_account(fixture: &Fixture, account_id: Id) -> (Id, Id) {
        let credential_id = fixture.add_secret("mail/test", b"smtp-secret", at(3));
        let views = fixture.views();
        let mut fragment = Fragment::empty();
        let (config, config_id) = account_config_fragment(
            account_id,
            AccountConfigInput {
                address: "sender@example.test".into(),
                display_name: "Sender".into(),
                pop_endpoint: "pop.example.test:995".into(),
                smtp_endpoint: "smtp.example.test:465".into(),
                username: "sender@example.test".into(),
                credential: credential_id,
                enabled: true,
                predecessors: Vec::new(),
            },
        )
        .unwrap();
        fragment += config;
        validate_catalog_union(
            &views.mail.reader,
            &views.mail.facts,
            &fragment,
            &views.files.facts,
            &views.decide.facts,
            &views.relations.facts,
            &views.secrets,
        )
        .unwrap();
        fixture.publish(mail_schema::DEFAULT_SCOPE_ID, fragment);
        (config_id, credential_id)
    }

    #[test]
    fn send_head_validation_reads_a_staged_decide_outcome() {
        let (_directory, reader) = empty_reader();
        let decision = id(70);
        let (mut resolution, head) =
            decide::resolution_fragment(decision, "send", None, true, &[], &[], at(1)).unwrap();
        let facts = resolution.facts().clone();
        let snapshot = decide::resolution_snapshot(&facts, head).unwrap();
        assert!(decide::read_text(&reader, snapshot.outcome).is_err());

        let overlay = resolution.blobs_mut().snapshot().unwrap();
        validate_send_heads(&reader, Some(&overlay), &facts, decision, &[head]).unwrap();
    }

    #[test]
    fn draft_materialization_reads_staged_mail_and_file_payloads() {
        let (_directory, reader) = empty_reader();
        let file = files::stage(b"staged attachment".to_vec(), "note.txt", "text/plain").unwrap();
        let file_id = file.root().unwrap();
        let mut staged_mail = Fragment::empty();
        let thread = add_claimed_wire(&mut staged_mail, "parent@example.test").unwrap();
        let draft = draft_publication(DraftInput {
            nonce: id(71),
            account: id(72),
            envelope_from: "sender@example.test".into(),
            to: vec!["reader@example.test".into()],
            cc: Vec::new(),
            bcc: Vec::new(),
            subject: "Staged subject".into(),
            body: "Staged body".into(),
            attachments: vec![file_id],
            in_reply_to: vec![thread],
            references: Vec::new(),
            created_at: at(2),
        })
        .unwrap();
        staged_mail += draft.mail;
        let mail_facts = staged_mail.facts().clone();
        let files_facts = file.facts().clone();
        assert!(materialize_draft(&reader, &mail_facts, &files_facts, draft.draft).is_err());

        let mut staged = staged_mail;
        staged += file;
        let overlay = staged.blobs_mut().snapshot().unwrap();
        let materialized = materialize_draft_union(
            &reader,
            Some(&overlay),
            &mail_facts,
            &files_facts,
            draft.draft,
        )
        .unwrap();
        assert_eq!(materialized.envelope_from, "sender@example.test");
        assert_eq!(materialized.to, ["reader@example.test"]);
        assert_eq!(materialized.subject, "Staged subject");
        assert_eq!(materialized.body, "Staged body");
        assert_eq!(materialized.in_reply_to, ["parent@example.test"]);
        assert_eq!(
            materialized.attachments,
            [AttachmentData {
                filename: "note.txt".into(),
                media_type: "text/plain".into(),
                bytes: b"staged attachment".to_vec(),
            }]
        );
    }

    const RAW_INBOUND: &[u8] = b"From: Alice <alice@example.test>\r\nTo: sender@example.test\r\nSubject: Hello\r\nDate: Sat, 8 Aug 2026 00:00:01 +0000\r\nMessage-ID: <CaseSensitive@Example.TEST>\r\nContent-Type: multipart/mixed; boundary=demo\r\n\r\n--demo\r\nContent-Type: text/plain\r\n\r\nhello body\r\n--demo\r\nContent-Type: application/octet-stream; name=note.bin\r\nContent-Disposition: attachment; filename=note.bin\r\nContent-Transfer-Encoding: base64\r\n\r\nAQID\r\n--demo--\r\n";

    #[test]
    fn message_identity_is_opaque_and_missing_id_hashes_full_raw_bytes() {
        let parsed = parse_rfc5322(RAW_INBOUND).unwrap();
        assert_eq!(
            parsed.identity,
            WireIdentity::Claimed("CaseSensitive@Example.TEST".into())
        );
        assert_eq!(parsed.claimed_date.unwrap(), at(1));
        assert_eq!(parsed.attachments[0].bytes, vec![1, 2, 3]);

        let first = parse_rfc5322(b"From: a@b\r\n\r\none").unwrap();
        let same = parse_rfc5322(b"From: a@b\r\n\r\none").unwrap();
        let other = parse_rfc5322(b"From: a@b\r\n\r\ntwo").unwrap();
        assert_eq!(first.identity, same.identity);
        assert_ne!(first.identity, other.identity);

        let WireIdentity::RawDigest(digest) = first.identity else {
            panic!("missing Message-ID must use raw digest identity")
        };
        let claimed = format!(
            "From: a@b\r\nMessage-ID: <raw-blake3:{}>\r\n\r\nclaim",
            hex::encode(digest.raw)
        );
        let fallback =
            pop_publication(id(86), id(87), "fallback", b"From: a@b\r\n\r\none").unwrap();
        let deliberate = pop_publication(id(86), id(87), "claimed", claimed.as_bytes()).unwrap();
        assert_ne!(fallback.wire, deliberate.wire);
        let rotated = pop_publication(id(86), id(88), "fallback", b"From: a@b\r\n\r\none").unwrap();
        assert_eq!(fallback.wire, rotated.wire);
        assert_ne!(fallback.observation, rotated.observation);
        assert!(parse_rfc5322(b"Message-ID: <a@b>\r\nMessage-ID: <c@d>\r\n\r\n").is_err());
    }

    #[test]
    fn source_validation_requires_every_recomputed_projection_blob_to_be_resident() {
        let fixture = Fixture::new();
        let account = id(97);
        let config = add_account(&fixture, account).0;
        let publication = pop_publication(
            account,
            config,
            "missing-subject",
            b"From: sender@example.test\r\nTo: receiver@example.test\r\nMessage-ID: <missing-payload@example.test>\r\nSubject: uniquely absent projection text\r\n\r\nbody",
        )
        .unwrap();
        let subject = required(
            find!(v: TextHandle, pattern!(publication.mail.facts(), [{ _?projection @ projection::subject: ?v }])).collect(),
            "test projection subject",
        )
        .unwrap();
        let SourcePublication { mail, files, .. } = publication;
        let (facts, mut blobs) = mail.into_facts_and_blobs();
        let survivors: Vec<_> = blobs
            .snapshot()
            .unwrap()
            .into_iter()
            .map(|(handle, _)| handle)
            .filter(|handle| handle.raw != subject.raw)
            .collect();
        blobs.keep(survivors);
        let broken = Fragment::from_facts_and_blobs(facts, blobs);
        let views = fixture.views();
        let mut files_union = views.files.facts.clone();
        files_union += files.facts().clone();
        let error = validate_catalog_union(
            &views.mail.reader,
            &views.mail.facts,
            &broken,
            &files_union,
            &views.decide.facts,
            &views.relations.facts,
            &views.secrets,
        )
        .unwrap_err();
        let error = format!("{error:#}");
        assert!(error.contains("read staged Mail text"), "{error}");
    }

    #[test]
    fn account_scoped_uidl_replay_requires_the_same_raw_message() {
        let fixture = Fixture::new();
        let account = id(98);
        let config = add_account(&fixture, account).0;
        let first = pop_publication(
            account,
            config,
            "stable-uidl",
            b"From: a@example.test\r\nTo: sender@example.test\r\nMessage-ID: <first@example.test>\r\nSubject: first\r\n\r\none",
        )
        .unwrap();
        let views = fixture.views();
        let mut first_files = views.files.facts.clone();
        first_files += first.files.facts().clone();
        validate_catalog_union(
            &views.mail.reader,
            &views.mail.facts,
            &first.mail,
            &first_files,
            &views.decide.facts,
            &views.relations.facts,
            &views.secrets,
        )
        .unwrap();
        fixture.publish(files_schema::DEFAULT_SCOPE_ID, first.files.clone());
        fixture.publish(mail_schema::DEFAULT_SCOPE_ID, first.mail.clone());

        let views = fixture.views();
        validate_catalog_union(
            &views.mail.reader,
            &views.mail.facts,
            &first.mail,
            &views.files.facts,
            &views.decide.facts,
            &views.relations.facts,
            &views.secrets,
        )
        .expect("an exact account/UIDL/raw replay is idempotent");

        let conflicting = pop_publication(
            account,
            config,
            "stable-uidl",
            b"From: a@example.test\r\nTo: sender@example.test\r\nMessage-ID: <second@example.test>\r\nSubject: second\r\n\r\ntwo",
        )
        .unwrap();
        let error = validate_catalog_union(
            &views.mail.reader,
            &views.mail.facts,
            &conflicting.mail,
            &views.files.facts,
            &views.decide.facts,
            &views.relations.facts,
            &views.secrets,
        )
        .unwrap_err();
        assert!(format!("{error:#}").contains("UIDL \"stable-uidl\" names different raw messages"));
    }

    #[test]
    fn multipart_draft_rendering_is_byte_deterministic() {
        let draft = MaterializedDraft {
            id: id(80),
            account: id(81),
            envelope_from: "sender@example.test".into(),
            to: vec!["Receiver <receiver@example.test>".into()],
            cc: Vec::new(),
            bcc: Vec::new(),
            subject: "Deterministic multipart".into(),
            body: "same body every time".into(),
            attachments: vec![AttachmentData {
                filename: "bytes.bin".into(),
                media_type: "application/octet-stream".into(),
                bytes: vec![0, 1, 2, 3, 254, 255],
            }],
            in_reply_to: Vec::new(),
            references: Vec::new(),
            created_at: at(4),
        };
        let account = OpenAccount {
            anchor: draft.account,
            config: id(82),
            address: draft.envelope_from.clone(),
            display_name: "Sender".into(),
            pop_endpoint: "pop.example.test:995".into(),
            smtp_endpoint: "smtp.example.test:465".into(),
            username: "sender@example.test".into(),
            password: "unused".into(),
            enabled: true,
        };

        let first = render_draft(&draft, &account).unwrap();
        let second = render_draft(&draft, &account).unwrap();
        assert_eq!(first, second);
        let boundary = format!("boundary=\"=_triblespace_{:x}\"", draft.id);
        assert!(first
            .raw
            .windows(boundary.len())
            .any(|window| window == boundary.as_bytes()));
    }

    #[test]
    fn account_snapshot_superseding_every_fork_head_rejoins_the_dag() {
        let anchor = id(83);
        let credential = id(84);
        let input = |display_name: &str, predecessors: Vec<Id>| AccountConfigInput {
            address: "me@example.test".into(),
            display_name: display_name.into(),
            pop_endpoint: "pop.example.test:995".into(),
            smtp_endpoint: "smtp.example.test:465".into(),
            username: "me@example.test".into(),
            credential,
            enabled: true,
            predecessors,
        };
        let (first, first_id) =
            account_config_fragment(anchor, input("First branch", Vec::new())).unwrap();
        let (second, second_id) =
            account_config_fragment(anchor, input("Second branch", Vec::new())).unwrap();
        let mut facts = first.into_facts();
        facts += second.into_facts();
        assert_eq!(
            account_head(&facts, anchor).unwrap(),
            Head::Forked(vec![first_id, second_id])
        );

        let (joined, joined_id) =
            account_config_fragment(anchor, input("Reconciled", vec![second_id, first_id]))
                .unwrap();
        facts += joined.into_facts();
        assert_eq!(
            account_head(&facts, anchor).unwrap(),
            Head::Unique(joined_id)
        );
    }

    #[test]
    fn operational_account_requires_an_exact_secrets_version() {
        let fixture = Fixture::new();
        let views = fixture.views();
        let missing_secret = id(84);
        let (fragment, _) = account_config_fragment(
            id(83),
            AccountConfigInput {
                address: "me@example.test".into(),
                display_name: "Me".into(),
                pop_endpoint: "pop.example.test:995".into(),
                smtp_endpoint: "smtp.example.test:465".into(),
                username: "me@example.test".into(),
                credential: missing_secret,
                enabled: true,
                predecessors: Vec::new(),
            },
        )
        .unwrap();

        // The local reconstruction used by stopped-world cutover can prove
        // Mail's own shape without conflating collections.
        validate_local_catalog_union(&views.mail.reader, &views.mail.facts, &fragment).unwrap();
        let error = validate_catalog_union(
            &views.mail.reader,
            &views.mail.facts,
            &fragment,
            &views.files.facts,
            &views.decide.facts,
            &views.relations.facts,
            &views.secrets,
        )
        .unwrap_err();
        assert!(format!("{error:#}").contains("unknown Secrets version"));
    }

    #[test]
    fn opening_an_account_requires_utf8_mailbox_secret_bytes() {
        let fixture = Fixture::new();
        let secret = fixture.add_secret("mail/non-utf8", &[0xff, 0xfe], at(4));
        let views = fixture.views();
        let account = id(85);
        let (config, _) = account_config_fragment(
            account,
            AccountConfigInput {
                address: "me@example.test".into(),
                display_name: "Me".into(),
                pop_endpoint: "pop.example.test:995".into(),
                smtp_endpoint: "smtp.example.test:465".into(),
                username: "me@example.test".into(),
                credential: secret,
                enabled: true,
                predecessors: Vec::new(),
            },
        )
        .unwrap();
        validate_catalog_union(
            &views.mail.reader,
            &views.mail.facts,
            &config,
            &views.files.facts,
            &views.decide.facts,
            &views.relations.facts,
            &views.secrets,
        )
        .unwrap();
        fixture.publish(mail_schema::DEFAULT_SCOPE_ID, config);
        let views = fixture.views();
        let error = open_account(
            &views.mail.reader,
            &views.mail.facts,
            &views.secrets,
            account,
            &fixture.signer(),
        )
        .unwrap_err();
        assert!(format!("{error:#}").contains("not UTF-8"));
    }

    #[test]
    fn opening_an_account_uses_the_durable_signer_key() {
        let fixture = Fixture::new();
        let account = id(86);
        add_account(&fixture, account);
        let views = fixture.views();

        let opened = open_account(
            &views.mail.reader,
            &views.mail.facts,
            &views.secrets,
            account,
            &fixture.signer(),
        )
        .unwrap();
        assert_eq!(opened.password, "smtp-secret");

        let outsider = SigningKey::from_bytes(&[99; 32]);
        let error = open_account(
            &views.mail.reader,
            &views.mail.facts,
            &views.secrets,
            account,
            &outsider,
        )
        .unwrap_err();
        assert!(
            format!("{error:#}").contains("no usable wrap for this signing key"),
            "{error:#}"
        );
    }

    #[test]
    fn smtp_acceptance_requires_a_final_positive_reply() {
        assert!(smtp_acceptance_fragment(id(85), 199, "not accepted").is_err());
        assert!(smtp_acceptance_fragment(id(85), 300, "not accepted").is_err());
        assert!(smtp_acceptance_fragment(id(85), 550, "rejected").is_err());
        assert!(smtp_acceptance_fragment(id(85), 250, "queued").is_ok());
    }

    #[test]
    fn collection_roundtrip_enforces_unread_and_exact_outbound_bytes() {
        let fixture = Fixture::new();
        let persona = id(1);
        let account_id = id(2);
        add_person(&fixture, persona);
        let (account_config, credential_id) = add_account(&fixture, account_id);

        let missing_thread = draft_publication(DraftInput {
            nonce: id(93),
            account: account_id,
            envelope_from: "sender@example.test".into(),
            to: vec!["receiver@example.test".into()],
            cc: Vec::new(),
            bcc: Vec::new(),
            subject: "Missing thread anchor".into(),
            body: "must not materialize later and fail".into(),
            attachments: Vec::new(),
            in_reply_to: vec![id(94)],
            references: Vec::new(),
            created_at: at(5),
        })
        .unwrap();
        let views = fixture.views();
        let decide_union = decide::validate_catalog_union(
            &views.decide.reader,
            &views.decide.facts,
            &missing_thread.decide,
        )
        .unwrap();
        let error = validate_catalog_union(
            &views.mail.reader,
            &views.mail.facts,
            &missing_thread.mail,
            &views.files.facts,
            &decide_union,
            &views.relations.facts,
            &views.secrets,
        )
        .unwrap_err();
        assert!(format!("{error:#}").contains("non-resident thread wire"));

        let digest_source = pop_publication(
            account_id,
            account_config,
            "digest-parent",
            b"From: parent@example.test\r\nTo: sender@example.test\r\nSubject: no id\r\n\r\nbody",
        )
        .unwrap();
        let digest_thread = draft_publication(DraftInput {
            nonce: id(96),
            account: account_id,
            envelope_from: "sender@example.test".into(),
            to: vec!["parent@example.test".into()],
            cc: Vec::new(),
            bcc: Vec::new(),
            subject: "Re: no id".into(),
            body: "a digest is local identity, not an RFC thread id".into(),
            attachments: Vec::new(),
            in_reply_to: vec![digest_source.wire],
            references: Vec::new(),
            created_at: at(6),
        })
        .unwrap();
        let views = fixture.views();
        let decide_union = decide::validate_catalog_union(
            &views.decide.reader,
            &views.decide.facts,
            &digest_thread.decide,
        )
        .unwrap();
        let mut digest_mail = digest_source.mail;
        digest_mail += digest_thread.mail;
        let mut digest_files = views.files.facts.clone();
        digest_files += digest_source.files.facts().clone();
        let error = validate_catalog_union(
            &views.mail.reader,
            &views.mail.facts,
            &digest_mail,
            &digest_files,
            &decide_union,
            &views.relations.facts,
            &views.secrets,
        )
        .unwrap_err();
        assert!(format!("{error:#}").contains("digest-only thread wire"));

        let views = fixture.views();
        let wrong_config =
            pop_publication(account_id, id(95), "wrong-config", RAW_INBOUND).unwrap();
        let mut wrong_files = views.files.facts.clone();
        wrong_files += wrong_config.files.facts().clone();
        let error = validate_catalog_union(
            &views.mail.reader,
            &views.mail.facts,
            &wrong_config.mail,
            &wrong_files,
            &views.decide.facts,
            &views.relations.facts,
            &views.secrets,
        )
        .unwrap_err();
        assert!(format!("{error:#}").contains("unknown config"));

        // POP evidence is precomputed, Files is published before Mail, and one
        // immutable multi-scope snapshot is sufficient for preflight.
        let views = fixture.views();
        let incoming =
            pop_publication(account_id, account_config, "UidL-CaSe", RAW_INBOUND).unwrap();
        let mut files_union = views.files.facts.clone();
        files_union += incoming.files.facts().clone();
        validate_catalog_union(
            &views.mail.reader,
            &views.mail.facts,
            &incoming.mail,
            &files_union,
            &views.decide.facts,
            &views.relations.facts,
            &views.secrets,
        )
        .unwrap();
        fixture.publish(files_schema::DEFAULT_SCOPE_ID, incoming.files.clone());
        fixture.publish(mail_schema::DEFAULT_SCOPE_ID, incoming.mail.clone());

        let views = fixture.views();
        validate_catalog(
            &views.mail.reader,
            &views.mail.facts,
            &views.files.facts,
            &views.decide.facts,
            &views.relations.facts,
            &views.secrets,
        )
        .unwrap();
        let inbox = inbox_projection(&views.mail.facts, &views.relations.facts, persona).unwrap();
        assert_eq!(inbox.len(), 1);
        assert!(inbox[0].unread);
        assert!(projection_ids(&views.mail.facts).contains(&incoming.projection));
        let presented =
            projection_view(&views.mail.reader, &views.mail.facts, incoming.projection).unwrap();
        assert_eq!(presented.wire, incoming.wire);
        assert_eq!(
            projection_direction(&views.mail.facts, presented.source).unwrap(),
            ProjectionDirection::Received
        );

        let (read_fragment, _) = read_observation_fragment(incoming.wire, persona);
        validate_catalog_union(
            &views.mail.reader,
            &views.mail.facts,
            &read_fragment,
            &views.files.facts,
            &views.decide.facts,
            &views.relations.facts,
            &views.secrets,
        )
        .unwrap();
        fixture.publish(mail_schema::DEFAULT_SCOPE_ID, read_fragment);

        // A new source observation of the same wire message does not reopen it.
        let views = fixture.views();
        let replay =
            pop_publication(account_id, account_config, "second-uidl", RAW_INBOUND).unwrap();
        validate_catalog_union(
            &views.mail.reader,
            &views.mail.facts,
            &replay.mail,
            &views.files.facts,
            &views.decide.facts,
            &views.relations.facts,
            &views.secrets,
        )
        .unwrap();
        fixture.publish(mail_schema::DEFAULT_SCOPE_ID, replay.mail);
        let views = fixture.views();
        assert!(
            inbox_projection(&views.mail.facts, &views.relations.facts, persona)
                .unwrap()
                .iter()
                .all(|row| !row.unread)
        );

        // Draft and its deterministic Decide genesis are independent signed
        // roots; Decide lands first, then Mail validates against that union.
        let draft = draft_publication(DraftInput {
            nonce: id(4),
            account: account_id,
            envelope_from: "sender@example.test".into(),
            to: vec!["Bob <bob@example.test>".into()],
            cc: Vec::new(),
            bcc: vec!["quiet@example.test".into()],
            subject: "Authorized subject".into(),
            body: "Authorized body".into(),
            attachments: Vec::new(),
            in_reply_to: Vec::new(),
            references: Vec::new(),
            created_at: at(2),
        })
        .unwrap();
        let views = fixture.views();
        let decide_union = decide::validate_catalog_union(
            &views.decide.reader,
            &views.decide.facts,
            &draft.decide,
        )
        .unwrap();
        validate_catalog_union(
            &views.mail.reader,
            &views.mail.facts,
            &draft.mail,
            &views.files.facts,
            &decide_union,
            &views.relations.facts,
            &views.secrets,
        )
        .unwrap();
        fixture.publish(decide_schema::DEFAULT_SCOPE_ID, draft.decide);
        fixture.publish(mail_schema::DEFAULT_SCOPE_ID, draft.mail);

        let views = fixture.views();
        let (resolution, resolution_id) =
            decide::resolution_fragment(draft.decision, "send", None, true, &[], &[], at(3))
                .unwrap();
        decide::validate_catalog_union(&views.decide.reader, &views.decide.facts, &resolution)
            .unwrap();
        fixture.publish(decide_schema::DEFAULT_SCOPE_ID, resolution);

        let views = fixture.views();
        let account = open_account(
            &views.mail.reader,
            &views.mail.facts,
            &views.secrets,
            account_id,
            &fixture.signer(),
        )
        .unwrap();
        assert_eq!(account.password, "smtp-secret");
        let materialized = materialize_draft(
            &views.mail.reader,
            &views.mail.facts,
            &views.files.facts,
            draft.draft,
        )
        .unwrap();
        let rendered = render_draft(&materialized, &account).unwrap();
        let (decision, heads) =
            authorized_send(&views.decide.reader, &views.decide.facts, draft.draft).unwrap();
        assert_eq!(heads, vec![resolution_id]);
        let base_attempt = SendAttemptInput {
            draft: draft.draft,
            config: account.config,
            decision,
            decision_heads: heads,
            raw: rendered.raw.clone(),
            envelope_from: materialized.envelope_from.clone(),
            to: materialized.to.clone(),
            cc: materialized.cc.clone(),
            bcc: materialized.bcc.clone(),
        };

        // A frozen attempt must cite an enabled config whose sender is the
        // draft sender, even if the config itself is otherwise canonical.
        for (address, enabled, needle) in [
            ("sender@example.test", false, "disabled"),
            ("other@example.test", true, "sender differs"),
        ] {
            let (mut config_fragment, config_id) = account_config_fragment(
                account_id,
                AccountConfigInput {
                    address: address.into(),
                    display_name: "Sender".into(),
                    pop_endpoint: "pop.example.test:995".into(),
                    smtp_endpoint: "smtp.example.test:465".into(),
                    username: "sender@example.test".into(),
                    credential: credential_id,
                    enabled,
                    predecessors: vec![account.config],
                },
            )
            .unwrap();
            let (attempt, _) = send_attempt_fragment(SendAttemptInput {
                config: config_id,
                ..base_attempt.clone()
            })
            .unwrap();
            config_fragment += attempt;
            let error = validate_catalog_union(
                &views.mail.reader,
                &views.mail.facts,
                &config_fragment,
                &views.files.facts,
                &views.decide.facts,
                &views.relations.facts,
                &views.secrets,
            )
            .unwrap_err();
            assert!(format!("{error:#}").contains(needle));
        }

        // Substituting the body while preserving the envelope and authorization
        // is rejected before a byte is published or SMTP is touched.
        let mut corrupt = rendered.raw.clone();
        let offset = corrupt
            .windows("Authorized body".len())
            .position(|window| window == b"Authorized body")
            .unwrap();
        corrupt.splice(
            offset..offset + "Authorized body".len(),
            b"Substituted body".iter().copied(),
        );
        let error = prepare_send(
            &views.mail.reader,
            &views.decide.reader,
            &views.mail.facts,
            &views.files.facts,
            &views.decide.facts,
            SendAttemptInput {
                raw: corrupt,
                ..base_attempt.clone()
            },
        )
        .unwrap_err();
        assert!(format!("{error:#}").contains("bytes or envelope"));

        let prepared = prepare_send(
            &views.mail.reader,
            &views.decide.reader,
            &views.mail.facts,
            &views.files.facts,
            &views.decide.facts,
            base_attempt,
        )
        .unwrap();
        let attempt_id = prepared.attempt_id();
        assert!(prepared.outgoing_files().facts().is_empty());

        let events = Rc::new(RefCell::new(Vec::new()));
        let mut smtp = FakeSmtp {
            events: events.clone(),
            fail: false,
        };
        let mut after_attempt = views.mail.facts.clone();
        after_attempt += prepared.attempt_fragment().facts().clone();

        // Acceptance is inseparable from exact outgoing evidence.
        let (receipt_only, _) =
            smtp_acceptance_fragment(attempt_id, 250, "queued without evidence").unwrap();
        let mut malformed_post_effect = prepared.attempt_fragment().clone();
        malformed_post_effect += receipt_only;
        let error = validate_catalog_union(
            &views.mail.reader,
            &views.mail.facts,
            &malformed_post_effect,
            &views.files.facts,
            &views.decide.facts,
            &views.relations.facts,
            &views.secrets,
        )
        .unwrap_err();
        let error = format!("{error:#}");
        assert!(
            error.contains("exactly one outgoing observation"),
            "{error}"
        );

        let mut outgoing_only = prepared.attempt_fragment().clone();
        outgoing_only += prepared.outgoing.mail.clone();
        let error = validate_catalog_union(
            &views.mail.reader,
            &views.mail.facts,
            &outgoing_only,
            &views.files.facts,
            &views.decide.facts,
            &views.relations.facts,
            &views.secrets,
        )
        .unwrap_err();
        let error = format!("{error:#}");
        assert!(error.contains("has no SMTP acceptance"), "{error}");

        submit_once(
            &mut smtp,
            &prepared,
            |fragment| {
                events.borrow_mut().push("publish-attempt");
                fixture.publish(mail_schema::DEFAULT_SCOPE_ID, fragment.clone());
                Ok(())
            },
            |fragment| {
                events.borrow_mut().push("publish-post-effect");
                validate_catalog_union(
                    &views.mail.reader,
                    &after_attempt,
                    fragment,
                    &views.files.facts,
                    &views.decide.facts,
                    &views.relations.facts,
                    &views.secrets,
                )?;
                fixture.publish(mail_schema::DEFAULT_SCOPE_ID, fragment.clone());
                Ok(())
            },
        )
        .unwrap();
        assert_eq!(
            events.borrow().as_slice(),
            ["publish-attempt", "smtp", "publish-post-effect"]
        );
        let views = fixture.views();
        validate_catalog(
            &views.mail.reader,
            &views.mail.facts,
            &views.files.facts,
            &views.decide.facts,
            &views.relations.facts,
            &views.secrets,
        )
        .unwrap();
        assert_eq!(
            acceptances_for_attempt(&views.mail.facts, attempt_id).len(),
            1
        );
    }

    #[test]
    fn send_authorization_is_current_at_effect_time_but_historical_after_publication() {
        let fixture = Fixture::new();
        let account_id = id(90);
        add_account(&fixture, account_id);

        let draft = draft_publication(DraftInput {
            nonce: id(92),
            account: account_id,
            envelope_from: "sender@example.test".into(),
            to: vec!["receiver@example.test".into()],
            cc: Vec::new(),
            bcc: Vec::new(),
            subject: "Snapshot authorization".into(),
            body: "The authorization is historical after the effect starts.".into(),
            attachments: Vec::new(),
            in_reply_to: Vec::new(),
            references: Vec::new(),
            created_at: at(1),
        })
        .unwrap();
        let views = fixture.views();
        let decide_union = decide::validate_catalog_union(
            &views.decide.reader,
            &views.decide.facts,
            &draft.decide,
        )
        .unwrap();
        validate_catalog_union(
            &views.mail.reader,
            &views.mail.facts,
            &draft.mail,
            &views.files.facts,
            &decide_union,
            &views.relations.facts,
            &views.secrets,
        )
        .unwrap();
        fixture.publish(decide_schema::DEFAULT_SCOPE_ID, draft.decide);
        fixture.publish(mail_schema::DEFAULT_SCOPE_ID, draft.mail);

        let (send, send_id) =
            decide::resolution_fragment(draft.decision, "send", None, true, &[], &[], at(2))
                .unwrap();
        fixture.publish(decide_schema::DEFAULT_SCOPE_ID, send);
        let views = fixture.views();
        let account = open_account(
            &views.mail.reader,
            &views.mail.facts,
            &views.secrets,
            account_id,
            &fixture.signer(),
        )
        .unwrap();
        let materialized = materialize_draft(
            &views.mail.reader,
            &views.mail.facts,
            &views.files.facts,
            draft.draft,
        )
        .unwrap();
        let rendered = render_draft(&materialized, &account).unwrap();
        let (decision, heads) =
            authorized_send(&views.decide.reader, &views.decide.facts, draft.draft).unwrap();
        assert_eq!(heads, vec![send_id]);
        let prepared = prepare_send(
            &views.mail.reader,
            &views.decide.reader,
            &views.mail.facts,
            &views.files.facts,
            &views.decide.facts,
            SendAttemptInput {
                draft: draft.draft,
                config: account.config,
                decision,
                decision_heads: heads,
                raw: rendered.raw,
                envelope_from: materialized.envelope_from,
                to: materialized.to,
                cc: materialized.cc,
                bcc: materialized.bcc,
            },
        )
        .unwrap();
        fixture.publish(
            mail_schema::DEFAULT_SCOPE_ID,
            prepared.attempt_fragment().clone(),
        );

        // A concurrent disagreeing resolution makes the current frontier a
        // fork. It prevents a new effect, but it cannot rewrite the evidence
        // of which genuine send head the executor previously observed.
        let (reject, reject_id) =
            decide::resolution_fragment(draft.decision, "reject", None, true, &[], &[], at(3))
                .unwrap();
        fixture.publish(decide_schema::DEFAULT_SCOPE_ID, reject);
        let views = fixture.views();
        assert!(format!(
            "{:#}",
            authorized_send(&views.decide.reader, &views.decide.facts, draft.draft).unwrap_err()
        )
        .contains("divergent heads"));
        validate_catalog(
            &views.mail.reader,
            &views.mail.facts,
            &views.files.facts,
            &views.decide.facts,
            &views.relations.facts,
            &views.secrets,
        )
        .unwrap();

        // Joining that fork as a rejection likewise governs only future
        // effects. The final union cannot reconstruct whether the executor's
        // earlier local frontier was globally complete; that is its affine
        // authority attestation, not a fact derivable after the event.
        let (reject_join, _) = decide::resolution_fragment(
            draft.decision,
            "reject",
            None,
            true,
            &[],
            &[send_id, reject_id],
            at(4),
        )
        .unwrap();
        fixture.publish(decide_schema::DEFAULT_SCOPE_ID, reject_join);
        let views = fixture.views();
        assert!(format!(
            "{:#}",
            authorized_send(&views.decide.reader, &views.decide.facts, draft.draft).unwrap_err()
        )
        .contains("not exact outcome \"send\""));
        validate_catalog(
            &views.mail.reader,
            &views.mail.facts,
            &views.files.facts,
            &views.decide.facts,
            &views.relations.facts,
            &views.secrets,
        )
        .unwrap();
    }

    struct FakeSmtp {
        events: Rc<RefCell<Vec<&'static str>>>,
        fail: bool,
    }

    impl SmtpSubmit for FakeSmtp {
        fn submit(&mut self, _envelope: &SmtpEnvelope, _raw: &[u8]) -> Result<AcceptedReply> {
            self.events.borrow_mut().push("smtp");
            if self.fail {
                bail!("scripted SMTP uncertainty");
            }
            Ok(AcceptedReply {
                code: 250,
                message: "queued".into(),
            })
        }
    }

    struct FakePop {
        events: Rc<RefCell<Vec<&'static str>>>,
        items: Vec<PopItem>,
        messages: HashMap<u32, Vec<u8>>,
        deleted: Vec<u32>,
        quit: bool,
    }

    impl Drop for FakePop {
        fn drop(&mut self) {
            if !self.quit {
                self.events.borrow_mut().push("disconnect");
            }
        }
    }

    impl PopTxn for FakePop {
        fn enumerate_uidls(&mut self) -> Result<Vec<PopItem>> {
            self.events.borrow_mut().push("uidl");
            Ok(self.items.clone())
        }

        fn retrieve_exact(&mut self, session_seq: u32) -> Result<Vec<u8>> {
            self.events.borrow_mut().push("retr");
            Ok(self.messages[&session_seq].clone())
        }

        fn mark_delete(&mut self, session_seq: u32) -> Result<()> {
            self.events.borrow_mut().push("dele");
            self.deleted.push(session_seq);
            Ok(())
        }

        fn quit(mut self) -> Result<()> {
            self.events.borrow_mut().push("quit");
            self.quit = true;
            Ok(())
        }
    }

    fn fake_pop(events: Rc<RefCell<Vec<&'static str>>>) -> FakePop {
        FakePop {
            events,
            items: vec![PopItem {
                session_seq: 7,
                uidl: "Case-Sensitive".into(),
            }],
            messages: HashMap::from([(7, RAW_INBOUND.to_vec())]),
            deleted: Vec::new(),
            quit: false,
        }
    }

    struct ScriptedPopStream {
        reads: Cursor<Vec<u8>>,
        writes: Rc<RefCell<Vec<u8>>>,
    }

    impl Read for ScriptedPopStream {
        fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
            self.reads.read(buffer)
        }
    }

    impl Write for ScriptedPopStream {
        fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
            self.writes.borrow_mut().extend_from_slice(buffer);
            Ok(buffer.len())
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    #[test]
    fn real_pop_session_runs_through_transactional_drain() {
        let mut script =
            b"+OK ready\r\n+OK listing\r\n1 Uidl-Bridge\r\n.\r\n+OK message follows\r\n".to_vec();
        script.extend_from_slice(RAW_INBOUND);
        script.extend_from_slice(b".\r\n+OK deleted\r\n+OK bye\r\n");
        let writes = Rc::new(RefCell::new(Vec::new()));
        let session = crate::mail_pop::PopSession::new(ScriptedPopStream {
            reads: Cursor::new(script),
            writes: writes.clone(),
        })
        .unwrap();
        let mut published = Vec::new();

        drain_pop(session, id(9), id(10), |publication| {
            published.push((publication.wire, publication.observation));
            Ok(())
        })
        .unwrap();

        assert_eq!(published.len(), 1);
        assert_eq!(
            writes.borrow().as_slice(),
            b"UIDL\r\nRETR 1\r\nDELE 1\r\nQUIT\r\n"
        );
    }

    #[test]
    fn pop_publish_precedes_delete_and_failure_disconnects_without_quit() {
        let events = Rc::new(RefCell::new(Vec::new()));
        drain_pop(fake_pop(events.clone()), id(9), id(10), |_| {
            events.borrow_mut().push("publish");
            Ok(())
        })
        .unwrap();
        assert_eq!(
            events.borrow().as_slice(),
            ["uidl", "retr", "publish", "dele", "quit"]
        );

        let events = Rc::new(RefCell::new(Vec::new()));
        let error = drain_pop(fake_pop(events.clone()), id(9), id(10), |_| {
            events.borrow_mut().push("publish-failed");
            bail!("disk full")
        })
        .unwrap_err();
        assert!(format!("{error:#}").contains("disk full"));
        assert_eq!(
            events.borrow().as_slice(),
            ["uidl", "retr", "publish-failed", "disconnect"]
        );
    }

    #[test]
    fn pop_rejects_zero_and_duplicate_session_identities_before_retrieval() {
        let invalid = [
            vec![PopItem {
                session_seq: 0,
                uidl: "zero".into(),
            }],
            vec![
                PopItem {
                    session_seq: 1,
                    uidl: "first".into(),
                },
                PopItem {
                    session_seq: 1,
                    uidl: "second".into(),
                },
            ],
            vec![
                PopItem {
                    session_seq: 1,
                    uidl: "same".into(),
                },
                PopItem {
                    session_seq: 2,
                    uidl: "same".into(),
                },
            ],
        ];
        for items in invalid {
            let events = Rc::new(RefCell::new(Vec::new()));
            let transaction = FakePop {
                events: events.clone(),
                items,
                messages: HashMap::new(),
                deleted: Vec::new(),
                quit: false,
            };
            assert!(drain_pop(transaction, id(9), id(10), |_| Ok(())).is_err());
            assert_eq!(events.borrow().as_slice(), ["uidl", "disconnect"]);
        }
    }
}