boatramp-node 0.48.0

Node assembly for boatramp: the parsed config model (and, incrementally, the config-to-running-node assembly) that the serve binary and library embedders share.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
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
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
//! The **project export/import driver** (`boatramp_core::project_export::ProjectExport`
//! impl) — the cross-crate orchestration that assembles / reads a `BRPROJ` bundle by
//! driving every engine:
//!
//! - **pg** (managed, compute-backed): version-detect via `OperatorSql::query("SHOW
//!   server_version_num")` → [`pg_client_image_for_server_version`] → assemble the
//!   connection from [`operator_target`](crate::managed_sql) + the replica endpoint +
//!   the unsealed credential → `run_ephemeral(pg_dump …)` streaming the dump to a bundle
//!   member (import: `run_ephemeral(pg_restore …)` streaming the member back in via
//!   stdin, after a schema-ledger fingerprint SKEW check).
//! - **control-plane KV**: `deploy.checkpoint()` (durable frontier) then
//!   `kv_dump::export_to_bytes`. Import applies it with `plan_import`/`apply_import`
//!   ONLY for a FULL bundle — a `--data-only` bundle carries app data only (no
//!   identity/RBAC/routing), so its KV slice is NOT restored (a later phase).
//! - **blobs**: `blob_migrate::migrate` of the project's blob prefix into a staging
//!   `FsStorage`, whose files become bundle members (import: the reverse).
//! - **libsql**: the [`snapshot_into`](boatramp_storage::sql_libsql::LibsqlSqlBackends::snapshot_into)
//!   primitive for the explicitly-targeted `(site, name)` databases (full per-site
//!   enumeration is a documented follow-up).
//!
//! Reachability: an external DSN host is used verbatim; a colocated managed DB in
//! `Published` endpoint mode (host-loopback publish, unreachable from a sibling
//! container) is reached at its container **bridge IP** via
//! [`ComputeBackend::replica_direct_host`](boatramp_core::compute::ComputeBackend::replica_direct_host).
//!
//! Phase 1 first cut: **docker backend, pg + libsql + KV + blobs, `--data-only` + full**.
//! mysql and external-URL (non-managed) pg bindings are skipped with a note; the native
//! container backend's `run_ephemeral` is `Unsupported`.
//!
//! ## Atomicity (inc2 chunked + shadow-restore)
//! A FULL **managed, dedicated/Single** pg/mysql/libsql member streams O(chunk) (no whole-member
//! temp) and is applied into a SHADOW — a not-yet-live database/file — then swapped in atomically
//! ONLY after its trailing SHA verifies; any abort (SHA mismatch, truncation, restore error,
//! disconnect) tears the shadow down and leaves live untouched (PER-MEMBER all-or-nothing,
//! default #2).
//!
//! HIGH-1 (Build-2 Security re-review): the pg/mysql dump in a bundle is attacker-crafted, so it is
//! applied by a freshly-minted, per-import EPHEMERAL non-superuser role (pg: `NOSUPERUSER
//! NOCREATEDB NOCREATEROLE`, owns the shadow; mysql: a user granted ONLY on the shadow db, no
//! `SUPER`/`FILE`/`*.*`) with `--no-owner --no-privileges` — NOT the binding's configured user,
//! which on a managed co-located server is the BOOTSTRAP SUPERUSER. A fail-closed probe REFUSES the
//! apply unless the role is provably non-superuser. The superuser/maintenance connection runs ONLY
//! our own trusted DDL (`CREATE ROLE`/`CREATE/ALTER/DROP DATABASE`/`REASSIGN OWNED`), and pre-creates
//! the operator trusted-extension allowlist in the shadow so a legit `CREATE EXTENSION IF NOT EXISTS
//! <ext>` (pgvector) no-ops under the non-superuser apply. Residuals / boundaries: a `--data-only`
//! member and a Shared/external member are NOT chunked, and a MANAGED sidecar apply is REFUSED
//! fail-closed (it would apply as superuser — a least-privilege sidecar apply is the follow-up); an
//! EXTERNAL bring-your-own-URL binding applies with the OPERATOR'S OWN credential against the
//! operator's own database (their trust boundary); a Shared multi-tenant server is refused for
//! chunked shadow-restore (the per-import physical shadow db is a cross-tenant surface deferred to
//! the temp-schema follow-up, default #3 = temp-DB for dedicated/Single). The bundle is NOT
//! whole-bundle atomic (cross-member window); overwriting a populated DB peaks at ~2× its size.
#![cfg(feature = "project-export")]

use std::collections::{BTreeMap, HashMap};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;

use async_trait::async_trait;
use futures::StreamExt;
use futures::io::{AsyncReadExt, AsyncWriteExt};
use sha2::{Digest, Sha256};
use tokio_util::compat::{TokioAsyncReadCompatExt, TokioAsyncWriteCompatExt};

use boatramp_core::Storage;
use boatramp_core::compute::{ComputeBackend, ReplicaPhase};
use boatramp_core::deploy::DeployStore;
use boatramp_core::env::EnvSource;
use boatramp_core::envelope::KeyEnvelope;
use boatramp_core::kv::KvStore;
use boatramp_core::project::ProjectRef;
use boatramp_core::project_export::{
    CloneBlobRef, CloneManifest, CloneSkip, ExportOptions, IdentityChoice, ImportOptions,
    ImportReport, ProjectExport, ProjectExportError,
};
use boatramp_core::sql::SqlValue;
use boatramp_storage::sql_libsql::LibsqlSqlBackends;

use crate::config::ExternalDatabaseConfig;
use crate::managed_sql::{ManagedSqlCredentials, operator_target};
use crate::pg_client::{
    MysqlConnection, PgConnection, mysql_admin_invocation, mysql_restore_invocation,
    mysql_shadow_invocation, mysqlbinlog_capture_invocation, mysqldump_capture_base_invocation,
    mysqldump_invocation, mysqldump_tables_only_invocation, pg_dump_invocation,
    pg_restore_invocation, pg_restore_shadow_invocation, pg_server_major, psql_invocation,
};
use crate::project_bundle::{
    self, IDENTITY_MEMBER_PATH, KV_MEMBER_PATH, MemberKind, MemberSpec, PgMemberInfo, SourceInfo,
};
use boatramp_storage::ExternalSqlKind;
use boatramp_storage::tenant_provision::quote_ident;

type Perr = ProjectExportError;

fn other<E: std::fmt::Display>(e: E) -> Perr {
    Perr::Other(e.to_string())
}

fn now_secs() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/// Bound of the in-flight byte channel bridging the blocking v2 tar reader/writer to the
/// async sink/source. A handful of ~tar-block writes — small, fixed memory; the staging
/// bound (one member on disk) is what the format's streaming guarantee rests on.
const STREAM_BYTE_CHANNEL: usize = 16;

/// The chunk size (bytes) for a `ChunkedTrailer` member — inc2 default #6: a **64 MiB** constant,
/// not operator-tunable. Overridable only in tests (so a chunked round-trip is fast) via
/// [`NodeProjectExport::with_chunk_size`].
pub const DEFAULT_CHUNK_SIZE: usize = 64 * 1024 * 1024;

/// Defense-in-depth per-member import ceiling (inc2 default #6 / the inc1 LOW-1 follow-up): a
/// hostile bundle must not stream unbounded bytes into one member. A generous default (a real
/// member is far smaller), tightenable in tests via [`NodeProjectExport::with_import_caps`].
const DEFAULT_IMPORT_MEMBER_CAP: u64 = 256 * 1024 * 1024 * 1024; // 256 GiB

/// Defense-in-depth whole-bundle import ceiling (inc2 default #6 / inc1 LOW-1): the feeder aborts
/// once the TOTAL bytes streamed from the source exceed this, so a bundle can't stream forever.
const DEFAULT_IMPORT_TOTAL_CAP: u64 = 1024 * 1024 * 1024 * 1024; // 1 TiB

/// Defense-in-depth cap on the number of blob refs a clone MANIFEST may carry before the target's
/// per-ref HEAD fan-out ([`NodeProjectExport::diff_clone_blobs`]) — so a hostile/huge source
/// manifest can neither OOM the diff nor drive an unbounded HEAD storm against the target's bucket.
/// Consistent with (and below) what the 64 MiB manifest-body cap admits (~2M refs).
const MAX_CLONE_MANIFEST_BLOBS: usize = 2_000_000;

/// Max size of a MySQL binlog TRUE-delta member (SQL true-delta). Unlike every other member, this
/// one is read WHOLE INTO MEMORY on both sides (drained into a buffer at export, read into a Vec at
/// restore to pipe into `mysql`), so it carries its own fail-closed RAM bound (LOW-4). A capture
/// whose drained member exceeds this falls back to a full dump (graceful); a restore whose member
/// exceeds it is refused (fail-closed). Generous — a real row-delta since the base is far smaller —
/// but finite, so a crafted/pathological member cannot OOM the node.
const MYSQL_DELTA_MEMBER_MAX: u64 = 2 * 1024 * 1024 * 1024; // 2 GiB

// ---------------------------------------------------------------------------
// Pure helpers (unit-mutation-gated in the merge gate)
// ---------------------------------------------------------------------------

/// Whether a binding `kind` names Postgres.
fn kind_is_postgres(kind: &str) -> bool {
    matches!(
        kind.to_ascii_lowercase().as_str(),
        "postgres" | "postgresql" | "pg"
    )
}

/// Whether a binding `kind` names libsql/SQLite. Completes the kind-classification trio
/// (`postgres`/`mysql`/`libsql`) and is exercised by the `kind_detection` gate; the export loop
/// routes a libsql binding through the per-site snapshot path rather than this classifier, so it
/// has no non-test caller.
#[allow(dead_code)]
fn kind_is_libsql(kind: &str) -> bool {
    matches!(
        kind.to_ascii_lowercase().as_str(),
        "libsql" | "sqlite" | "sqlite3"
    )
}

/// Whether a binding `kind` names MySQL/MariaDB (MariaDB is detected + refused later by
/// the version banner, not the kind string).
fn kind_is_mysql(kind: &str) -> bool {
    matches!(kind.to_ascii_lowercase().as_str(), "mysql" | "mariadb")
}

/// Whether a binding is MANAGED (compute-backed) — i.e. one of OUR co-located managed DB servers
/// whose configured user is a cluster superuser — vs. an EXTERNAL bring-your-own-URL binding (the
/// operator's own database + credential). The untrusted-dump apply must never run as a superuser on
/// a managed binding (HIGH-1).
fn is_managed_binding(cfg: &ExternalDatabaseConfig) -> bool {
    cfg.compute.as_deref().is_some_and(|c| !c.is_empty())
}

/// Parse a `postgres://` / `mysql://` DSN into `(user, password, host, port, database)`
/// for an EXTERNAL (bring-your-own-URL) binding. Best-effort for the standard shape; the
/// password is split on the FIRST `:` so a `:`-bearing password survives. `None` for a
/// shape we don't recognize (the caller then refuses rather than misconnect).
fn parse_sql_url(url: &str) -> Option<(String, String, String, u16, String)> {
    let (scheme, rest) = url.split_once("://")?;
    let default_port = match scheme {
        "postgres" | "postgresql" => 5432,
        "mysql" | "mariadb" => 3306,
        _ => return None,
    };
    let (userinfo, hostpart) = rest.rsplit_once('@')?;
    let (user, password) = match userinfo.split_once(':') {
        Some((u, p)) => (u.to_string(), p.to_string()),
        None => (userinfo.to_string(), String::new()),
    };
    let (hostport, db) = hostpart.split_once('/')?;
    let db = db.split(['?', '&']).next().unwrap_or(db).to_string();
    let (host, port) = match hostport.rsplit_once(':') {
        Some((h, p)) => (h.to_string(), p.parse().ok()?),
        None => (hostport.to_string(), default_port),
    };
    Some((user, password, host, port, db))
}

/// The bundle member path for a Postgres database dump.
fn pg_member_path(db: &str) -> String {
    format!("sql/{db}.pgc")
}

/// Recover the database name from a `sql/<db>.pgc` member path.
fn db_from_pg_member(path: &str) -> Option<&str> {
    path.strip_prefix("sql/")
        .and_then(|s| s.strip_suffix(".pgc"))
}

/// The bundle member path for a Postgres logical-WAL **true-delta** (SQL true-delta program).
fn pgwal_member_path(db: &str) -> String {
    format!("sql/{db}.pgwal")
}

/// Recover the database name from a `sql/<db>.pgwal` true-delta member path.
fn db_from_pgwal_member(path: &str) -> Option<&str> {
    path.strip_prefix("sql/")
        .and_then(|s| s.strip_suffix(".pgwal"))
}

/// The bundle member path for a MySQL database dump.
fn mysql_member_path(db: &str) -> String {
    format!("sql/{db}.sql")
}

/// Recover the database name from a `sql/<db>.sql` member path.
fn db_from_mysql_member(path: &str) -> Option<&str> {
    path.strip_prefix("sql/")
        .and_then(|s| s.strip_suffix(".sql"))
}

/// The bundle member path for a MySQL binlog **true-delta** (SQL true-delta program).
fn mysqlbinlog_member_path(db: &str) -> String {
    format!("sql/{db}.mysqlbinlog")
}

/// Recover the database name from a `sql/<db>.mysqlbinlog` true-delta member path.
fn db_from_mysqlbinlog_member(path: &str) -> Option<&str> {
    path.strip_prefix("sql/")
        .and_then(|s| s.strip_suffix(".mysqlbinlog"))
}

/// The bundle member path for a site's default libsql database.
fn libsql_member_path(project: &str, site: &str) -> String {
    format!("libsql/{project}/{site}/default.sqlite")
}

/// Recover the SITE from a `libsql/<project>/<site>/default.sqlite` member path (the
/// source project segment is discarded — the import re-qualifies with the TARGET
/// project).
fn site_from_libsql_member(path: &str) -> Option<&str> {
    let body = path
        .strip_prefix("libsql/")?
        .strip_suffix("/default.sqlite")?;
    // body = "<project>/<site>"; site is the last segment (project/site carry no `/`).
    Some(body.rsplit_once('/').map(|(_, s)| s).unwrap_or(body))
}

/// The bundle member path for a site's libsql **changeset** true-delta (SQL true-delta program,
/// Stage 4). Sibling of [`libsql_member_path`] with a `.changeset` leaf so a reader tells a true
/// row-delta member from a full `.sqlite` dump.
fn libsql_changeset_member_path(project: &str, site: &str) -> String {
    format!("libsql/{project}/{site}/default.changeset")
}

/// Recover the SITE from a `libsql/<project>/<site>/default.changeset` true-delta member path (the
/// source project segment is discarded — the import re-qualifies with the TARGET project).
fn site_from_libsql_changeset_member(path: &str) -> Option<&str> {
    let body = path
        .strip_prefix("libsql/")?
        .strip_suffix("/default.changeset")?;
    Some(body.rsplit_once('/').map(|(_, s)| s).unwrap_or(body))
}

/// Defense-in-depth project-slug validation at the DRIVER entry (the admin handler
/// already rejects an invalid slug, but a direct driver caller must be guarded too — the
/// `project` string flows into temp paths, libsql `local_path`, the blob prefix, and
/// `ProjectRef::qualified`, so a `..`/`/` would traverse). Mirrors the canonical
/// resource-name validator every other surface uses.
fn check_project_slug(project: &str) -> Result<(), Perr> {
    boatramp_core::project::validate_resource_name("project", project)
        .map_err(|e| Perr::Other(e.to_string()))
}

/// Whether a `--data-only` import must REFUSE (absent `--allow-schema-skew`): it may
/// proceed ONLY when both schema-ledger fingerprints are present AND equal (proven
/// compatible). A mismatch — OR a MISSING fingerprint on either side — cannot prove the
/// target's existing schema matches the data, so it blocks (fail-closed).
fn data_only_skew_blocks(src_fp: Option<&str>, tgt_fp: Option<&str>) -> bool {
    !matches!((src_fp, tgt_fp), (Some(s), Some(t)) if s == t)
}

/// Re-qualify ONE streamed blob member to the TARGET project's scope — the per-blob,
/// forward-pass analogue of the v1 whole-directory rename, and THE tenancy-critical seam of
/// the streaming import. A blob member path is `blobs/hblob/{source}/{site}/{container}/…`;
/// this strips the `blobs/` wrapper and rewrites the leading `hblob/{source}/` segment to
/// `hblob/{target}/`, returning the TARGET-scope storage key `hblob/{target}/…`.
///
/// **Fail-closed.** A member whose key is NOT under `hblob/{source}/` is REFUSED (never
/// silently `put` under a foreign scope), and the key is only ever rebuilt as
/// `hblob/{target}/…` — so every imported object lands in the target project's scope and no
/// source-scope (or other-tenant) key can survive a rename. This mirrors the C1 KV re-key
/// (`rekey_owned_key`) at the blob layer; a leak here shipped a CRITICAL once, so the mapping
/// is explicit and total, not best-effort.
fn target_blob_key(member_path: &str, source: &str, target: &str) -> Result<String, Perr> {
    let src_key = member_path.strip_prefix("blobs/").ok_or_else(|| {
        Perr::Other(format!(
            "blob member path {member_path:?} is missing its 'blobs/' prefix"
        ))
    })?;
    let src_pref = format!("hblob/{source}/");
    let rest = src_key.strip_prefix(&src_pref).ok_or_else(|| {
        Perr::Other(format!(
            "blob member {src_key:?} is not under the source project scope {src_pref:?}; \
             refusing to import a wrong-scope blob (cross-tenant isolation)"
        ))
    })?;
    // Defense-in-depth: the re-keyed REMAINDER must be a clean relative path — no empty segment,
    // no `.`/`..`, no absolute/root component — so a crafted member (`…/../../hblob/victim/…` or an
    // absolute key) can never traverse OUT of `hblob/{target}/` into another tenant's scope or the
    // bucket root. The storage layer also screens keys, but this tenancy-critical seam self-defends
    // rather than relying on it (a leak here shipped a CRITICAL once).
    use std::path::{Component, Path};
    if rest.is_empty() {
        return Err(Perr::Other(format!(
            "blob member {src_key:?} has an empty key under the source scope; refusing"
        )));
    }
    if !Path::new(rest)
        .components()
        .all(|c| matches!(c, Component::Normal(_)))
    {
        return Err(Perr::Other(format!(
            "blob member {src_key:?} has an unsafe path component (absolute or `.`/`..`); \
             refusing to re-key a traversing blob (cross-tenant isolation)"
        )));
    }
    Ok(format!("hblob/{target}/{rest}"))
}

/// The blob-store key prefix covering a project's objects.
///
/// Every blob key is `hblob/{qualified-site}/{container}/{key}` where the qualified site
/// is `ProjectRef::qualified(project, site) = "{project}/{site}"` for EVERY project —
/// including the reserved `default` (`hblob/default/{site}/…`, the v0.31.0 Finding-8
/// two-segment default scope; see `blob_shim`'s `format!("hblob/{qualified_site}/")`).
/// So a project's objects all live under `hblob/{project}/`, with no over-capture (the
/// trailing `/` means `hblob/foo/` never matches a sibling `hblob/foobar/`).
fn blob_project_prefix(project: &str) -> String {
    format!("hblob/{project}/")
}

/// Choose the host a sibling ephemeral client should connect to: in `Published` docker
/// endpoint mode the operator endpoint is a host-loopback publish a sibling cannot
/// route to, so prefer the replica's direct (bridge) host when one was resolved;
/// otherwise (external DSN, `Bridge` mode) the endpoint host is directly reachable.
fn choose_host(endpoint_host: &str, direct_host: Option<&str>, published: bool) -> String {
    match (published, direct_host) {
        (true, Some(h)) if !h.is_empty() => h.to_string(),
        _ => endpoint_host.to_string(),
    }
}

/// The first cell of a single-value query result, as a string.
fn scalar_text(rows: &boatramp_core::sql::SqlRows) -> Option<String> {
    match rows.rows.first().and_then(|r| r.first()) {
        Some(SqlValue::Text(s)) => Some(s.clone()),
        Some(SqlValue::Integer(n)) => Some(n.to_string()),
        _ => None,
    }
}

/// The clear, actionable error for a delta export against a `delta_capture`-enabled db
/// whose server has not actually adopted it yet (PLAN-sql-true-delta Stage 1b).
fn delta_capture_not_restarted_message(db: &str) -> String {
    format!(
        "database {db:?}: delta export refused — `delta_capture` is enabled but the server has \
         not been restarted to adopt it yet (true-delta needs wal_level=logical / binary \
         logging, which only take effect at server start); ensure `delta_capture: true` is set \
         and run `boatramp db restart --db {db}` (or apply with `restart_policy: auto`) before \
         a delta export of this database"
    )
}

/// A stable fingerprint of a schema-ledger query result — a canonical serialization of
/// every row, hashed. Identical input rows (same migrations applied, same content
/// hashes) yield an identical fingerprint on both export (source) and import (target),
/// so a `--data-only` import can detect schema skew.
fn fingerprint_rows(rows: &boatramp_core::sql::SqlRows) -> String {
    let mut hasher = Sha256::new();
    for row in &rows.rows {
        for cell in row {
            let s = match cell {
                SqlValue::Text(s) => s.clone(),
                SqlValue::Integer(n) => n.to_string(),
                other => format!("{other:?}"),
            };
            hasher.update((s.len() as u64).to_le_bytes());
            hasher.update(s.as_bytes());
        }
        hasher.update(b"\x00");
    }
    hex::encode(hasher.finalize())
}

// ---------------------------------------------------------------------------
// The driver
// ---------------------------------------------------------------------------

/// The node's [`ProjectExport`] implementation.
///
/// What the identity export needs to know about the node's secrets envelope — a minimal,
/// NON-secret projection of the node's `EnvelopeSpec` (never the Vault token). Set via
/// [`with_identity_source`](NodeProjectExport::with_identity_source); absent ⇒
/// `--include-identity` is refused (no local KEK to carry).
#[derive(Debug, Clone)]
pub enum IdentityEnvelope {
    /// A local KEK file (raw 32 bytes) — the only kind whose KEK is transportable.
    Local { kek_file: PathBuf },
    /// A Vault/KMS-backed KEK — never extractable, so `--include-identity` is refused.
    Vault,
    /// No secrets envelope — nothing is sealed, nothing to carry.
    None,
}

/// Magic for the identity payload carried INSIDE the transport container.
const IDENTITY_PAYLOAD_MAGIC: &[u8; 6] = b"BRIDP1";

/// Serialize the identity payload: currently just the raw KEK, framed
/// `[magic][u8 version=1][u8 kek_len][kek]` — unambiguous and extensible (a future version
/// may append on-disk sealed key files). The payload is sealed by the AEAD transport
/// container, so this framing only needs to round-trip deterministically.
fn identity_payload_bytes(kek: &[u8]) -> Result<Vec<u8>, Perr> {
    if kek.len() > u8::MAX as usize {
        return Err(Perr::Other("KEK too large for the identity payload".into()));
    }
    let mut v = Vec::with_capacity(IDENTITY_PAYLOAD_MAGIC.len() + 2 + kek.len());
    v.extend_from_slice(IDENTITY_PAYLOAD_MAGIC);
    v.push(1u8);
    v.push(kek.len() as u8);
    v.extend_from_slice(kek);
    Ok(v)
}

/// Parse an [`identity_payload_bytes`] blob back to the raw KEK (import `--identity adopt`).
fn parse_identity_payload(bytes: &[u8]) -> Result<Vec<u8>, Perr> {
    let rest = bytes
        .strip_prefix(IDENTITY_PAYLOAD_MAGIC.as_slice())
        .ok_or_else(|| Perr::Other("identity payload: bad magic".into()))?;
    if rest.len() < 2 {
        return Err(Perr::Other("identity payload: truncated header".into()));
    }
    if rest[0] != 1 {
        return Err(Perr::Other(format!(
            "identity payload: unsupported version {}",
            rest[0]
        )));
    }
    let kek_len = rest[1] as usize;
    let kek = &rest[2..];
    if kek.len() != kek_len {
        return Err(Perr::Other("identity payload: KEK length mismatch".into()));
    }
    Ok(kek.to_vec())
}

/// Install `kek` at `path` as the node's `secrets/kek`, `0600` (owner-only) — the master
/// secret must never be world/group-readable. Used by `--identity adopt`.
async fn write_kek_file(path: &std::path::Path, kek: &[u8]) -> Result<(), Perr> {
    if let Some(parent) = path.parent() {
        tokio::fs::create_dir_all(parent).await.map_err(other)?;
    }
    let path = path.to_path_buf();
    let kek = kek.to_vec();
    tokio::task::spawn_blocking(move || -> std::io::Result<()> {
        #[cfg(unix)]
        {
            use std::io::Write;
            use std::os::unix::fs::OpenOptionsExt;
            // O_EXCL (`create_new`): never clobber or truncate an existing KEK. The adopt caller
            // has already read-and-compared any existing KEK (no-clobber); creating exclusively
            // here closes the check→write TOCTOU window — if a KEK appeared in between, the write
            // fails loudly rather than overwriting the master secret.
            let mut f = std::fs::OpenOptions::new()
                .write(true)
                .create_new(true)
                .mode(0o600)
                .open(&path)?;
            f.write_all(&kek)
        }
        #[cfg(not(unix))]
        {
            std::fs::write(&path, &kek)
        }
    })
    .await
    .map_err(other)?
    .map_err(other)
}

/// Always constructible from the node's always-present deps (deploy + KV + blobs); the
/// engine contexts attach optionally — [`with_managed_pg`](Self::with_managed_pg) for the
/// pg/mysql ephemeral-dump path, [`with_libsql`](Self::with_libsql) for the embedded
/// libsql path — so a libsql-only project (no managed SQL at all) still exports its
/// libsql + KV + blobs.
pub struct NodeProjectExport {
    databases: BTreeMap<String, ExternalDatabaseConfig>,
    deploy: DeployStore,
    kv: Arc<dyn KvStore>,
    blobs: Arc<dyn Storage>,
    /// The LOCAL libsql backend, when the project's `sql` binding is embedded libsql
    /// (not remote sqld). `None` ⇒ no local libsql to snapshot (remote, or no binding).
    /// The driver enumerates the project's sites AUTHORITATIVELY from the deploy store
    /// and snapshots each site's default DB that actually exists on disk.
    libsql: Option<Arc<LibsqlSqlBackends>>,
    /// The compute backend running the ephemeral `pg_dump`/`mysqldump` client. `None` ⇒
    /// no pg/mysql export/import on this node.
    backend: Option<Arc<dyn ComputeBackend>>,
    /// The secrets envelope used to unseal a managed DB credential. `None` with a managed
    /// binding ⇒ that binding can't be dumped (fail-closed per database).
    envelope: Option<Arc<dyn KeyEnvelope>>,
    /// The operator-SQL seam used to version-detect (`SHOW server_version_num` /
    /// `SELECT VERSION()`) + fingerprint the schema ledger. `None` ⇒ no pg/mysql path.
    operator_sql: Option<Arc<dyn boatramp_core::sql::OperatorSql>>,
    /// Host-env source for an EXTERNAL binding's `url_env` lookup. Production is
    /// [`SystemEnv`](boatramp_core::env::SystemEnv); a test injects a map.
    env_source: Arc<dyn EnvSource>,
    published_endpoint: bool,
    /// The secrets-envelope projection for `--include-identity` (local KEK path / Vault /
    /// none). `None` ⇒ identity export is refused. Never holds a secret (no Vault token).
    identity_source: Option<IdentityEnvelope>,
    work_dir: PathBuf,
    connect_timeout_secs: u32,
    /// Operator digest-pin / override for the ephemeral Postgres client image
    /// (`pg_dump`/`pg_restore`/`psql`). `Some` ⇒ used verbatim instead of the version-computed
    /// `pgvector/pgvector:pg{major}` tag — e.g. a `@sha256:`-pinned ref accepted under the
    /// multi-tenant posture. `None` ⇒ the computed tag.
    pg_client_image: Option<String>,
    /// MySQL counterpart — overrides the computed `mysql:<maj.min>` client image.
    mysql_client_image: Option<String>,
    /// The chunk size for a `ChunkedTrailer` member (default [`DEFAULT_CHUNK_SIZE`]; test override).
    chunk_size: usize,
    /// Per-member import byte ceiling (default [`DEFAULT_IMPORT_MEMBER_CAP`]).
    import_member_cap: u64,
    /// Whole-bundle import byte ceiling (default [`DEFAULT_IMPORT_TOTAL_CAP`]).
    import_total_cap: u64,
    /// The operator trusted-extension allowlist (`handlers.bindings.sql.migrate_trusted_extensions`)
    /// the superuser pre-creates in a pg shadow before the NON-superuser apply, so a legit `CREATE
    /// EXTENSION IF NOT EXISTS <ext>` (e.g. pgvector) in an untrusted dump no-ops. A dump naming an
    /// extension NOT on this list fails fail-closed under the non-superuser apply.
    trusted_extensions: Vec<String>,
    /// The configured base directory under which operator-named resumable export/import
    /// directories live (`[serve] resumable_export_dir`). `None` ⇒ the resumable surface is
    /// DISABLED and every resumable call is refused fail-closed. An operator passes only a
    /// relative name under this base; the host confines it (no escape) — the caller never
    /// supplies an absolute node path.
    resumable_base: Option<PathBuf>,
}

impl NodeProjectExport {
    /// Build the driver from the always-present node deps. Attach the pg/mysql context
    /// with [`with_managed_pg`](Self::with_managed_pg) and the libsql backend with
    /// [`with_libsql`](Self::with_libsql). `work_dir` holds staging + bundle temp files.
    pub fn new(
        databases: BTreeMap<String, ExternalDatabaseConfig>,
        deploy: DeployStore,
        kv: Arc<dyn KvStore>,
        blobs: Arc<dyn Storage>,
        work_dir: PathBuf,
    ) -> Self {
        Self {
            databases,
            deploy,
            kv,
            blobs,
            libsql: None,
            backend: None,
            envelope: None,
            operator_sql: None,
            env_source: Arc::new(boatramp_core::env::SystemEnv),
            published_endpoint: true,
            identity_source: None,
            work_dir,
            connect_timeout_secs: 10,
            pg_client_image: None,
            mysql_client_image: None,
            chunk_size: DEFAULT_CHUNK_SIZE,
            import_member_cap: DEFAULT_IMPORT_MEMBER_CAP,
            import_total_cap: DEFAULT_IMPORT_TOTAL_CAP,
            trusted_extensions: Vec::new(),
            resumable_base: None,
        }
    }

    /// Set the operator trusted-extension allowlist (from
    /// `handlers.bindings.sql.migrate_trusted_extensions`) the superuser pre-creates in a pg shadow
    /// before the NON-superuser apply — so a legit `CREATE EXTENSION IF NOT EXISTS <ext>` (pgvector)
    /// in an untrusted dump no-ops instead of failing under the non-superuser apply.
    #[must_use]
    pub fn with_trusted_extensions(mut self, extensions: Vec<String>) -> Self {
        self.trusted_extensions = extensions;
        self
    }

    /// Override the chunk size for `ChunkedTrailer` members (TEST ONLY — production uses the
    /// [`DEFAULT_CHUNK_SIZE`] 64 MiB constant). A small size makes a chunked round-trip test
    /// produce multiple `.part` entries without a large fixture.
    #[must_use]
    pub fn with_chunk_size(mut self, chunk_size: usize) -> Self {
        self.chunk_size = chunk_size.max(1);
        self
    }

    /// Override the import byte ceilings (TEST ONLY — production uses the generous defaults). Lets
    /// a test prove the per-member / total caps reject an over-large bundle cheaply.
    #[must_use]
    pub fn with_import_caps(mut self, member_cap: u64, total_cap: u64) -> Self {
        self.import_member_cap = member_cap;
        self.import_total_cap = total_cap;
        self
    }

    /// Supply an operator override for the ephemeral SQL-client images (the `pg_dump`/`mysqldump`/
    /// `psql` one-shots). Each `Some(ref)` is used VERBATIM in place of the version-computed tag —
    /// so a digest-pinned ref (`pgvector/pgvector:pg16@sha256:<hex>`) can be accepted under the
    /// multi-tenant posture with no rootfs staging. `None` keeps the computed tag.
    #[must_use]
    pub fn with_client_images(
        mut self,
        pg_client_image: Option<String>,
        mysql_client_image: Option<String>,
    ) -> Self {
        self.pg_client_image = pg_client_image;
        self.mysql_client_image = mysql_client_image;
        self
    }

    /// The Postgres client image for `server_version_num`: the operator override
    /// ([`with_client_images`](Self::with_client_images)) used VERBATIM, else the version-computed
    /// `pgvector/pgvector:pg{major}` tag. A verbatim override lets a `@sha256:`-pinned ref be
    /// accepted under the multi-tenant posture; a wrong-major pin fails loud at `pg_dump` time.
    fn pg_image(
        &self,
        server_version_num: &str,
    ) -> Result<String, boatramp_core::compute::VersionMapError> {
        match &self.pg_client_image {
            Some(pinned) => Ok(pinned.clone()),
            None => boatramp_core::compute::pg_client_image_for_server_version(server_version_num),
        }
    }

    /// MySQL counterpart of [`pg_image`](Self::pg_image) — the override verbatim, else the
    /// computed `mysql:<maj.min>` tag.
    fn mysql_image(
        &self,
        version: &str,
    ) -> Result<String, boatramp_core::compute::VersionMapError> {
        match &self.mysql_client_image {
            Some(pinned) => Ok(pinned.clone()),
            None => boatramp_core::compute::mysql_client_image_for_server_version(version),
        }
    }

    /// Replace the host-env source (for an external binding's `url_env`). Tests inject a
    /// map; production keeps [`SystemEnv`](boatramp_core::env::SystemEnv).
    #[must_use]
    pub fn with_env_source(mut self, env_source: Arc<dyn EnvSource>) -> Self {
        self.env_source = env_source;
        self
    }

    /// Attach the pg/mysql ephemeral-dump context: the compute backend that runs the
    /// client container, the secrets envelope (to unseal a managed credential), the
    /// operator-SQL seam (version-detect + schema fingerprint), and whether the backend's
    /// endpoints are host-loopback publishes (so a colocated DB must be reached at its
    /// bridge IP).
    #[must_use]
    pub fn with_managed_pg(
        mut self,
        backend: Arc<dyn ComputeBackend>,
        envelope: Arc<dyn KeyEnvelope>,
        operator_sql: Arc<dyn boatramp_core::sql::OperatorSql>,
        published_endpoint: bool,
    ) -> Self {
        self.backend = Some(backend);
        self.envelope = Some(envelope);
        self.operator_sql = Some(operator_sql);
        self.published_endpoint = published_endpoint;
        self
    }

    /// Attach the LOCAL libsql backend so the driver snapshots each site's embedded DB on
    /// export and places members back on import. Pass `None`-equivalent (don't call this)
    /// for a remote-sqld project (no local file to snapshot).
    #[must_use]
    pub fn with_libsql(mut self, libsql: Arc<LibsqlSqlBackends>) -> Self {
        self.libsql = Some(libsql);
        self
    }

    /// Set the base directory under which operator-named resumable export/import dirs live
    /// (`[serve] resumable_export_dir`). `None`/not-called ⇒ the resumable surface stays
    /// DISABLED (every resumable call refuses, fail-closed). The operator names only a
    /// relative subdir under this base; [`resolve_resumable_dir`](Self::resolve_resumable_dir)
    /// confines it.
    #[must_use]
    pub fn with_resumable_base(mut self, base: Option<PathBuf>) -> Self {
        self.resumable_base = base;
        self
    }

    /// Confine an operator-supplied resumable directory NAME to a path under the configured
    /// [`resumable_base`](Self::resumable_base). The load-bearing control for the resumable
    /// surface: the name reaches the node from an API caller, so an unconfined path would be
    /// arbitrary node read/write. Fail-closed:
    /// - no base configured ⇒ refuse (the surface is disabled);
    /// - empty, absolute, or any non-`Normal` component (`..`, `.`, root/prefix) ⇒ refuse
    ///   (kills lexical traversal + absolute escape);
    /// - after join, canonicalize + assert the result stays under the canonical base ⇒ this
    ///   catches a SYMLINK escape (a symlink in the path resolves out and fails `starts_with`).
    ///
    /// `create` ⇒ create the base + the target dir (export); otherwise the target must exist
    /// (import). Returns the confined, canonicalized absolute path.
    pub(crate) async fn resolve_resumable_dir(
        &self,
        dir_name: &str,
        create: bool,
    ) -> Result<PathBuf, Perr> {
        use std::path::Component;
        let base = self.resumable_base.as_ref().ok_or_else(|| {
            Perr::Other(
                "resumable export/import is not enabled on this node; set \
                 `[serve] resumable_export_dir` to a base directory"
                    .into(),
            )
        })?;
        if dir_name.is_empty() {
            return Err(Perr::Other("resumable directory name is required".into()));
        }
        let rel = Path::new(dir_name);
        if rel.is_absolute() {
            return Err(Perr::Other(
                "resumable directory must be a relative name under the configured base, \
                 not an absolute path"
                    .into(),
            ));
        }
        for comp in rel.components() {
            if !matches!(comp, Component::Normal(_)) {
                return Err(Perr::Other(
                    "resumable directory name must not contain `..`, `.`, or a root/prefix \
                     component"
                        .into(),
                ));
            }
        }
        // The base must exist to canonicalize it (create it on the export path).
        if create {
            tokio::fs::create_dir_all(base).await.map_err(other)?;
        }
        let canon_base = tokio::fs::canonicalize(base).await.map_err(|e| {
            Perr::Other(format!(
                "resumable base {} is not accessible: {e}",
                base.display()
            ))
        })?;
        let joined = canon_base.join(rel);
        if create {
            tokio::fs::create_dir_all(&joined).await.map_err(other)?;
        } else if !tokio::fs::try_exists(&joined).await.map_err(other)? {
            return Err(Perr::Other(format!(
                "resumable directory {dir_name:?} does not exist under the configured base"
            )));
        }
        // Canonicalize the target and REFUSE if it escaped the base (symlink guard).
        let canon = tokio::fs::canonicalize(&joined).await.map_err(other)?;
        if !canon.starts_with(&canon_base) {
            return Err(Perr::Other(
                "resumable directory escapes the configured base (symlink?)".into(),
            ));
        }
        Ok(canon)
    }

    /// Attach the secrets-envelope projection so `--include-identity` can carry the project
    /// KEK (local envelope only). Not called ⇒ `--include-identity` is refused.
    #[must_use]
    pub fn with_identity_source(mut self, source: IdentityEnvelope) -> Self {
        self.identity_source = Some(source);
        self
    }

    /// The compute backend that runs the ephemeral SQL client, or a clear `Unavailable`
    /// error (a node with no docker backend cannot dump/restore pg/mysql).
    fn require_backend(&self) -> Result<&Arc<dyn ComputeBackend>, Perr> {
        self.backend.as_ref().ok_or_else(|| {
            Perr::Unavailable(
                "pg/mysql export/import needs a compute backend to run the client container — \
                 none on this node"
                    .into(),
            )
        })
    }

    /// The operator-SQL seam (version-detect + schema fingerprint), or `Unavailable`.
    fn require_op(&self) -> Result<&Arc<dyn boatramp_core::sql::OperatorSql>, Perr> {
        self.operator_sql.as_ref().ok_or_else(|| {
            Perr::Unavailable(
                "pg/mysql export/import needs the operator-SQL seam (a managed SQL binding) — \
                 not configured on this node"
                    .into(),
            )
        })
    }

    /// Refuse LOUD if `db`'s `delta_capture` opt-in has not actually taken effect on the
    /// LIVE server yet (`wal_level` still not `logical`) — the operator enabled it but has
    /// not restarted the database (PLAN-sql-true-delta Stage 1b's restart primitive). A
    /// connectivity failure checking it is deliberately NOT treated as this condition (it
    /// is left to surface on its own, later in the plan) — this only short-circuits on an
    /// ANSWERED, non-`logical` `wal_level`, so it never masks an unrelated transient error
    /// behind a misleading "not restarted" message.
    async fn assert_pg_delta_capture_live(&self, project: &str, db: &str) -> Result<(), Perr> {
        let op = self.require_op()?;
        if let Ok(rows) = op.query(project, db, "SHOW wal_level").await
            && let Some(level) = scalar_text(&rows)
            && !level.trim().eq_ignore_ascii_case("logical")
        {
            return Err(Perr::Other(delta_capture_not_restarted_message(db)));
        }
        Ok(())
    }

    /// The mysql analogue of [`assert_pg_delta_capture_live`](Self::assert_pg_delta_capture_live):
    /// refuse LOUD if `db`'s `delta_capture` opt-in has not taken effect yet (binary logging
    /// still off, `@@GLOBAL.log_bin` != `1`) because the server has not been restarted.
    async fn assert_mysql_delta_capture_live(&self, project: &str, db: &str) -> Result<(), Perr> {
        let op = self.require_op()?;
        if let Ok(rows) = op.query(project, db, "SELECT @@GLOBAL.log_bin").await
            && let Some(v) = scalar_text(&rows)
            && v.trim() != "1"
        {
            return Err(Perr::Other(delta_capture_not_restarted_message(db)));
        }
        Ok(())
    }

    /// Resolve a SQL database (managed compute-backed OR external bring-your-own-URL) to
    /// its reachable endpoint parts `(host, port, user, password, database)`.
    async fn resolve_endpoint(
        &self,
        project: &str,
        db: &str,
        cfg: &ExternalDatabaseConfig,
    ) -> Result<SqlEndpoint, Perr> {
        if cfg.compute.as_deref().is_some_and(|c| !c.is_empty()) {
            self.resolve_managed_endpoint(project, db, cfg).await
        } else if !cfg.url_env.is_empty() {
            // EXTERNAL: the DSN lives in `url_env`; use its host VERBATIM (the daemon
            // bridge NATs egress to it). The credential comes from the URL, never a sealed
            // store, so no envelope is needed.
            let url = self.env_source.get(&cfg.url_env).ok_or_else(|| {
                Perr::Other(format!(
                    "database {db:?}: external URL env var {} is unset",
                    cfg.url_env
                ))
            })?;
            let (user, password, host, port, database) = parse_sql_url(&url).ok_or_else(|| {
                // Never echo the URL (it carries the credential) — name only the env var.
                Perr::Other(format!(
                    "database {db:?}: external URL in {} is not a parseable \
                     postgres://|mysql:// DSN",
                    cfg.url_env
                ))
            })?;
            Ok(SqlEndpoint {
                host,
                port,
                user,
                password,
                database,
            })
        } else {
            Err(Perr::Other(format!(
                "database {db:?}: neither compute-backed (managed) nor `url_env` (external) — \
                 nothing to dump"
            )))
        }
    }

    /// Resolve a managed compute-backed SQL database to its reachable endpoint parts —
    /// the same derivation the runtime uses (`operator_target` + the healthy replica
    /// endpoint + the unsealed credential), with a colocated `Published` DB reached at its
    /// container bridge IP. Uses the OPERATOR identity (the configured/superuser role); the
    /// untrusted-dump apply NEVER uses this identity — it uses a freshly-minted ephemeral
    /// non-superuser role (see [`PgShadowPlan`]/[`MysqlShadowPlan`]).
    async fn resolve_managed_endpoint(
        &self,
        project: &str,
        db: &str,
        cfg: &ExternalDatabaseConfig,
    ) -> Result<SqlEndpoint, Perr> {
        let backend = self.require_backend()?;
        let envelope = self.envelope.as_ref().ok_or_else(|| {
            Perr::Unavailable(format!(
                "managed database {db:?} needs a [secrets] envelope to unseal its credential — \
                 none on this node"
            ))
        })?;
        let target = operator_target(cfg, project, db).map_err(other)?;
        let states = self
            .deploy
            .list_replica_states(ProjectRef::new(&target.endpoint_project), &target.workload)
            .await
            .map_err(other)?;
        let replica = states
            .into_iter()
            .find(|s| s.phase == ReplicaPhase::Running && s.healthy)
            .ok_or_else(|| {
                Perr::Other(format!(
                    "database {db:?}: no healthy running replica of workload {:?} to dump/restore",
                    target.workload
                ))
            })?;
        let direct = if self.published_endpoint {
            backend.replica_direct_host(&replica.handle).await
        } else {
            None
        };
        let host = choose_host(
            &replica.endpoint.host,
            direct.as_deref(),
            self.published_endpoint,
        );
        let password = ManagedSqlCredentials::new(self.kv.clone(), envelope.clone())
            .password(&target.cred_project, &target.cred_workload)
            .await
            .map_err(Perr::Other)?;
        Ok(SqlEndpoint {
            host,
            port: replica.endpoint.port,
            user: target.user,
            password,
            database: target.database,
        })
    }

    /// Resolve a Postgres database (managed or external) to a `PgConnection` + the
    /// matching client image + the detected `server_version_num`.
    async fn resolve_pg(
        &self,
        project: &str,
        db: &str,
        cfg: &ExternalDatabaseConfig,
    ) -> Result<(PgConnection, String, String), Perr> {
        let op = self.require_op()?;
        let ep = self.resolve_endpoint(project, db, cfg).await?;
        // Version detect via the operator-SQL seam (works for managed + external).
        let banner = op
            .query(project, db, "SHOW server_version_num")
            .await
            .map_err(other)?;
        let server_version_num = scalar_text(&banner).ok_or_else(|| {
            Perr::Other(format!(
                "database {db:?}: empty SHOW server_version_num result"
            ))
        })?;
        let image = self
            .pg_image(&server_version_num)
            .map_err(|e| Perr::Other(format!("database {db:?}: {e}")))?;
        Ok((
            ep.into_pg(self.connect_timeout_secs),
            image,
            server_version_num,
        ))
    }

    /// Resolve a MySQL database (managed or external) to a `MysqlConnection` + the
    /// matching `mysql:<maj.min>` client image + the detected version banner. A MariaDB
    /// banner is REFUSED (distinct dialect — see [`mysql_client_image_for_server_version`]).
    async fn resolve_mysql(
        &self,
        project: &str,
        db: &str,
        cfg: &ExternalDatabaseConfig,
    ) -> Result<(MysqlConnection, String, String), Perr> {
        let op = self.require_op()?;
        let ep = self.resolve_endpoint(project, db, cfg).await?;
        let banner = op
            .query(project, db, "SELECT VERSION()")
            .await
            .map_err(other)?;
        let version = scalar_text(&banner).ok_or_else(|| {
            Perr::Other(format!("database {db:?}: empty SELECT VERSION() result"))
        })?;
        let image = self
            .mysql_image(&version)
            .map_err(|e| Perr::Other(format!("database {db:?}: {e}")))?;
        Ok((ep.into_mysql(self.connect_timeout_secs), image, version))
    }

    /// Best-effort schema-ledger fingerprint of a Postgres database (the applied
    /// migration set + content hashes). `None` if the ledger can't be read (e.g. no
    /// migrations table, or no operator-SQL seam) — the skew check then has nothing to
    /// compare.
    async fn schema_fingerprint(&self, project: &str, db: &str) -> Option<String> {
        let op = self.operator_sql.as_ref()?;
        let sql = "SELECT id, ordinal, content_hash FROM boatramp_migrations.schema_migrations \
                   ORDER BY ordinal, id";
        match op.query(project, db, sql).await {
            Ok(rows) => Some(fingerprint_rows(&rows)),
            Err(_) => None,
        }
    }

    /// Run a SQL client (`pg_dump`/`pg_restore`/`mysqldump`/`mysql`) in an ephemeral
    /// container, streaming `stdin` in (optional) and stdout to `stdout_path`. Returns
    /// the exit code.
    async fn run_sql_client(
        &self,
        image: &str,
        argv: &[String],
        env: &[(String, String)],
        stdin_path: Option<&Path>,
        stdout_path: &Path,
    ) -> Result<i32, Perr> {
        let backend = self.require_backend()?;
        let out = tokio::fs::File::create(stdout_path).await.map_err(other)?;
        let mut sink = out.compat_write();
        let code = if let Some(inp) = stdin_path {
            let f = tokio::fs::File::open(inp).await.map_err(other)?;
            let mut rdr = f.compat();
            backend
                .run_ephemeral(image, argv, env, Some(&mut rdr), &mut sink)
                .await
                .map_err(other)?
        } else {
            backend
                .run_ephemeral(image, argv, env, None, &mut sink)
                .await
                .map_err(other)?
        };
        Ok(code)
    }

    /// Run a SQL client capturing its stdout as a trimmed string (plus the exit code) — for the
    /// trusted-DDL / maintenance statements + probe queries of the inc2 shadow swap (pg `CREATE
    /// DATABASE`/`ALTER … RENAME`/`SELECT rolsuper …`/`SELECT 1 FROM pg_database …`, mysql
    /// `information_schema` table enumeration). The stdout temp lives under `stage_dir` and is
    /// removed after.
    ///
    /// The run is wrapped with [`merge_stderr_argv`] so the client's STDERR — where psql/mysql
    /// write a failed statement's error ("ERROR: database … already exists", "permission denied",
    /// a refused untrusted object) — merges into the captured string; without it `run_ephemeral`
    /// drops stderr on a non-zero exit and a failed DDL surfaces causelessly. A SUCCESSFUL psql/
    /// mysql SELECT or DDL emits nothing on stderr, so the parsed probes are unaffected on success
    /// and only gain the diagnostic on failure. Safe here because stdout is a small parsed result
    /// or discarded — never a dump member (which must NOT merge stderr; see `merge_stderr_argv`).
    async fn run_sql_capture(
        &self,
        image: &str,
        argv: &[String],
        env: &[(String, String)],
        stdin_path: Option<&Path>,
        stage_dir: &Path,
    ) -> Result<(i32, String), Perr> {
        let out = stage_dir.join(format!("cap-{}.out", shadow_suffix()));
        let merged = merge_stderr_argv(argv);
        let code = self
            .run_sql_client(image, &merged, env, stdin_path, &out)
            .await?;
        let s = tokio::fs::read_to_string(&out).await.unwrap_or_default();
        let _ = tokio::fs::remove_file(&out).await;
        Ok((code, s.trim().to_string()))
    }

    /// Like [`run_sql_capture`](Self::run_sql_capture) but WITHOUT the [`merge_stderr_argv`] wrap, so
    /// the captured stdout is PURE command output and the client's stderr can never co-mingle into
    /// it. The one caller whose stdout is a DATA payload — the pg WAL drain, whose stdout is the
    /// hex-encoded `pgoutput` stream (PLAN-sql-true-delta LOW A1) — MUST use this, not the merging
    /// variant (`merge_stderr_argv` is documented must-NOT-wrap-data). On a non-zero exit
    /// `run_ephemeral` drops the container's stderr, so the diagnostic is just the exit code (the
    /// caller fails closed / falls back) — an accepted trade for never corrupting the data stream.
    async fn run_sql_capture_nomerge(
        &self,
        image: &str,
        argv: &[String],
        env: &[(String, String)],
        stdin_path: Option<&Path>,
        stage_dir: &Path,
    ) -> Result<(i32, String), Perr> {
        let out = stage_dir.join(format!("cap-{}.out", shadow_suffix()));
        let code = self
            .run_sql_client(image, argv, env, stdin_path, &out)
            .await?;
        let s = tokio::fs::read_to_string(&out).await.unwrap_or_default();
        let _ = tokio::fs::remove_file(&out).await;
        Ok((code, s.trim().to_string()))
    }
}

/// A SHORT process-unique suffix for a MySQL ephemeral identifier. MySQL caps a USER name at 32
/// chars, and the general `shadow_suffix()` (`<nanos>_<pid>`, ~27 chars) overflows `brexp_apply_` /
/// `brexp_rd_` — so the mysql shadow + binlog-capture ephemeral users use this 16-hex-char suffix
/// instead (`brexp_apply_<16hex>` = 28 chars). Random, so collision-free across concurrent imports;
/// the `brexp_apply_%` / `brexp_rd_%` / `%__shadow_%` sweep LIKE-patterns match it unchanged.
fn mysql_eph_suffix() -> String {
    let mut b = [0u8; 8];
    getrandom::getrandom(&mut b).expect("os rng for mysql ephemeral suffix");
    b.iter().map(|x| format!("{x:02x}")).collect()
}

/// A process-unique shadow suffix (`<nanos>_<pid>`) — same shape libsql's `shadow_path_for` uses,
/// so two imports in the same second never collide and the `*__shadow_*` / `*__old_*` sweep matches.
fn shadow_suffix() -> String {
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    format!("{nanos}_{}", std::process::id())
}

/// Quote a Postgres **string literal** (single-quoted, doubling any embedded `'`) — for the
/// `datname = '<db>'` predicate of our own generated `pg_terminate_backend` / `pg_database`
/// utility SQL (the db name is driver-derived, never a credential or bundle data).
fn pg_lit(s: &str) -> String {
    format!("'{}'", s.replace('\'', "''"))
}

/// POSIX-single-quote each token of a driver-composed argv and join with spaces, so the
/// command can run under `sh -c '… 2>&1'` (merging stderr into the captured sink). Only
/// ever applied to driver-derived flags + identifiers — never a credential (the password
/// rides in the env, e.g. PGPASSWORD), so the single-quoting is defense-in-depth, not a
/// trust boundary. Each embedded `'` is closed, escaped as `'\''`, and reopened.
fn sh_join(argv: &[String]) -> String {
    argv.iter()
        .map(|a| format!("'{}'", a.replace('\'', "'\\''")))
        .collect::<Vec<_>>()
        .join(" ")
}

/// Wrap a driver-composed SQL-client invocation so the container's STDERR merges into the
/// captured stdout sink (`sh -c 'exec … 2>&1'`). `run_ephemeral` keeps only the container's
/// stdout and DROPS stderr on a non-zero exit, so a failed trusted-DDL / maintenance / sidecar
/// restore run otherwise surfaces causelessly ("exited N" with no reason) — the psql / pg_restore
/// / mysql client writes its error text to stderr. Merging lets that text reach the error message.
///
/// MUST NOT be used where stdout is a DATA payload (a `pg_dump`/`mysqldump` whose stdout IS the
/// bundle member, or a chunked producer streaming into the bundle body) — merging stderr would
/// corrupt the member. It is only for runs whose stdout is a small parsed result (a probe) or
/// discarded (a maintenance DDL / a sidecar restore to a throwaway sink): a successful psql/mysql
/// SELECT emits NOTHING on stderr, so a parsed probe is unaffected on success and only GAINS the
/// diagnostic on failure. `exec` keeps the reported exit status the client's own; each token is
/// POSIX single-quoted by [`sh_join`]. The connection password is NOT composed in (it rides in the
/// env — PGPASSWORD/MYSQL_PWD); the only secret that can appear is a we-generate-it SQL literal (the
/// ephemeral role's random password in a `CREATE ROLE … PASSWORD` the maintenance DDL already placed
/// in psql's argv), whose exposure is unchanged by this wrap — it stays argv-resident on the same
/// ephemeral DB-client container, an exposure the trusted-DDL path already accepts.
fn merge_stderr_argv(argv: &[String]) -> Vec<String> {
    vec![
        "sh".to_string(),
        "-c".to_string(),
        format!("exec {} 2>&1", sh_join(argv)),
    ]
}

/// The resolved reachable endpoint of a SQL database (managed or external) — the raw
/// parts the ephemeral client connects with.
struct SqlEndpoint {
    host: String,
    port: u16,
    user: String,
    password: String,
    database: String,
}

impl SqlEndpoint {
    fn into_pg(self, connect_timeout_secs: u32) -> PgConnection {
        PgConnection {
            host: self.host,
            port: self.port,
            user: self.user,
            password: self.password,
            database: self.database,
            connect_timeout_secs,
        }
    }

    fn into_mysql(self, connect_timeout_secs: u32) -> MysqlConnection {
        MysqlConnection {
            host: self.host,
            port: self.port,
            user: self.user,
            password: self.password,
            database: self.database,
            connect_timeout_secs,
        }
    }
}

// ---------------------------------------------------------------------------
// Streaming bridge — the sync `project_bundle` tar reader/writer runs in a
// `spawn_blocking` task and talks to the async driver (which owns `self` and the
// caller's async sink/source) over bounded channels. No `block_on` is nested on a
// runtime thread, so this is deadlock-free on BOTH the current-thread and the
// multi-thread tokio runtime; the channel bounds keep the bundle from ever buffering
// in memory, and each member is staged/restored one at a time (O(largest member)).
// ---------------------------------------------------------------------------

/// A synchronous [`Write`] that forwards each write to an async drain over a bounded
/// channel — the bridge from the blocking v2 tar writer to the caller's async `sink`.
/// A full channel backpressures the blocking writer, so the bundle never buffers in memory.
struct ChannelWriter {
    tx: tokio::sync::mpsc::Sender<Vec<u8>>,
}

impl Write for ChannelWriter {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.tx.blocking_send(buf.to_vec()).map_err(|_| {
            std::io::Error::new(std::io::ErrorKind::BrokenPipe, "export sink closed")
        })?;
        Ok(buf.len())
    }
    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

/// A synchronous [`Read`] fed by an async feeder over a bounded channel — the bridge from
/// the caller's async `src` to the blocking v2 single-pass reader. Bounded memory; `None`
/// from the channel is clean EOF.
struct ChannelReader {
    rx: tokio::sync::mpsc::Receiver<Vec<u8>>,
    buf: Vec<u8>,
    pos: usize,
}

impl ChannelReader {
    fn new(rx: tokio::sync::mpsc::Receiver<Vec<u8>>) -> Self {
        Self {
            rx,
            buf: Vec::new(),
            pos: 0,
        }
    }
}

impl Read for ChannelReader {
    fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> {
        while self.pos >= self.buf.len() {
            match self.rx.blocking_recv() {
                Some(chunk) if !chunk.is_empty() => {
                    self.buf = chunk;
                    self.pos = 0;
                }
                Some(_) => continue, // skip an empty chunk rather than mistaking it for EOF
                None => return Ok(0), // all senders dropped ⇒ EOF
            }
        }
        let n = std::cmp::min(out.len(), self.buf.len() - self.pos);
        out[..n].copy_from_slice(&self.buf[self.pos..self.pos + n]);
        self.pos += n;
        Ok(n)
    }
}

/// An async [`futures::io::AsyncWrite`] that forwards each write into a bounded tokio channel —
/// the bridge from a `run_ephemeral` stdout sink (`pg_dump`/`mysqldump`) straight into a
/// ChunkedTrailer body channel (inc2 Stage C/D), so the SQL dump streams O(chunk) with NO temp.
/// A full channel backpressures the dump via `Poll::Pending`; a closed channel is a broken pipe.
struct AsyncChannelWriter {
    sender: tokio_util::sync::PollSender<Vec<u8>>,
}

impl AsyncChannelWriter {
    fn new(tx: tokio::sync::mpsc::Sender<Vec<u8>>) -> Self {
        Self {
            sender: tokio_util::sync::PollSender::new(tx),
        }
    }
}

impl futures::io::AsyncWrite for AsyncChannelWriter {
    fn poll_write(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
        buf: &[u8],
    ) -> std::task::Poll<std::io::Result<usize>> {
        use std::task::Poll;
        let me = self.get_mut();
        match me.sender.poll_reserve(cx) {
            Poll::Ready(Ok(())) => match me.sender.send_item(buf.to_vec()) {
                Ok(()) => Poll::Ready(Ok(buf.len())),
                Err(_) => Poll::Ready(Err(std::io::Error::new(
                    std::io::ErrorKind::BrokenPipe,
                    "export dump sink closed",
                ))),
            },
            Poll::Ready(Err(_)) => Poll::Ready(Err(std::io::Error::new(
                std::io::ErrorKind::BrokenPipe,
                "export dump sink closed",
            ))),
            Poll::Pending => Poll::Pending,
        }
    }
    fn poll_flush(
        self: std::pin::Pin<&mut Self>,
        _cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<std::io::Result<()>> {
        std::task::Poll::Ready(Ok(()))
    }
    fn poll_close(
        self: std::pin::Pin<&mut Self>,
        _cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<std::io::Result<()>> {
        self.get_mut().sender.close();
        std::task::Poll::Ready(Ok(()))
    }
}

/// An async [`futures::io::AsyncRead`] fed by a bounded tokio channel — the bridge from a
/// ChunkedTrailer member's body channel into a `run_ephemeral` stdin reader (`pg_restore`/`mysql`)
/// on the IMPORT side (inc2 Stage C/D). Bounded memory; a closed channel is clean EOF so the
/// restore client sees stdin half-close and exits.
struct AsyncChannelReader {
    rx: tokio::sync::mpsc::Receiver<Vec<u8>>,
    buf: Vec<u8>,
    pos: usize,
}

impl AsyncChannelReader {
    fn new(rx: tokio::sync::mpsc::Receiver<Vec<u8>>) -> Self {
        Self {
            rx,
            buf: Vec::new(),
            pos: 0,
        }
    }
}

impl futures::io::AsyncRead for AsyncChannelReader {
    fn poll_read(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
        out: &mut [u8],
    ) -> std::task::Poll<std::io::Result<usize>> {
        use std::task::Poll;
        let me = self.get_mut();
        while me.pos >= me.buf.len() {
            match me.rx.poll_recv(cx) {
                Poll::Ready(Some(chunk)) if !chunk.is_empty() => {
                    me.buf = chunk;
                    me.pos = 0;
                }
                Poll::Ready(Some(_)) => continue, // skip an empty chunk, not EOF
                Poll::Ready(None) => return Poll::Ready(Ok(0)), // all senders dropped ⇒ EOF
                Poll::Pending => return Poll::Pending,
            }
        }
        let n = std::cmp::min(out.len(), me.buf.len() - me.pos);
        out[..n].copy_from_slice(&me.buf[me.pos..me.pos + n]);
        me.pos += n;
        Poll::Ready(Ok(n))
    }
}

/// One member staged on disk by the export driver, computed just-in-time by the async stager
/// when the blocking v2 writer requests it. Carries only what the stager's `self`-driven work
/// needs; the big bytes land in a bounded temp the writer deletes right after appending.
enum StageJob {
    /// The passphrase-wrapped identity transport container (already produced at plan time).
    Identity { container: Vec<u8> },
    /// The control-plane KV logical slice — scanned + project-scoped + encoded at stage time.
    Kv { created_at: u64 },
    /// A Postgres `pg_dump` into a staging temp.
    Pg {
        conn: PgConnection,
        image: String,
        data_only: bool,
        /// The detected `SHOW server_version_num` — selects the `pg_dump` comment-handling
        /// strategy (PG17+ `--exclude-extension` vs the blunt `--no-comments`).
        server_version_num: String,
        /// Dump with `--no-publications` — set for a `delta_capture` db, so the ephemeral
        /// `brexp_pub_*` capture publication (which must exist from base time for pgoutput's
        /// historical decode) never lands in the dump and cannot fail the non-superuser shadow
        /// restore (`CREATE PUBLICATION … FOR ALL TABLES` is superuser-only). PLAN-sql-true-delta.
        no_publications: bool,
    },
    /// A MySQL `mysqldump` into a staging temp.
    Mysql {
        conn: MysqlConnection,
        image: String,
        data_only: bool,
    },
    /// A libsql `VACUUM INTO` snapshot of the project-qualified site DB.
    Libsql { qsite: String },
    /// A single blob object, streamed from the source store into a staging temp.
    Blob { key: String },
    /// A control-plane KV **delta** member (`kv.brkvdelta`) — the upserts + tombstones already
    /// computed + encoded at plan time (a DELTA export only).
    KvDelta { bytes: Vec<u8> },
    /// A blob **tombstone** member (`blobs.brtombstones`) — the deleted blob keys already computed
    /// + encoded at plan time (a DELTA export only).
    BlobTombstone { bytes: Vec<u8> },
    /// A Postgres logical-WAL **delta** member (`sql/<db>.pgwal`) — the framed `pgoutput` change
    /// stream drained from the parent base's capture slot, already produced at plan time (an
    /// incremental DELTA export of a managed pg db with `delta_capture`). Replayed onto the
    /// restored base inside the atomic shadow (see `restore_pg_true_delta_in_chain`).
    PgWalDelta { bytes: Vec<u8> },
    /// A MySQL binlog **delta** member (`sql/<db>.mysqlbinlog`) — the framed raw binlog captured
    /// (via `mysqlbinlog --read-from-remote-server --raw`) since the parent base's snapshot GTID,
    /// already produced at plan time (an incremental DELTA export of a managed mysql db with
    /// `delta_capture`). Replayed onto the restored base inside the atomic shadow (see
    /// `restore_mysql_true_delta_in_chain`).
    MysqlBinlogDelta { bytes: Vec<u8> },
    /// A libsql/SQLite **changeset** delta member (`libsql/<project>/<site>/default.changeset`) — the
    /// framed SQLite changeset (session diff of the base snapshot vs the current DB), already
    /// produced at plan time (a DELTA export of a capture-eligible libsql site). Replayed onto the
    /// restored base snapshot inside the atomic shadow (see `restore_libsql_true_delta_in_chain`).
    /// SQL true-delta program, Stage 4.
    LibsqlChangeset { bytes: Vec<u8> },
}

/// The export stager's request: "produce the member at `path`". `chunked` selects a
/// [`StageReply::Chunked`] body stream (ChunkedTrailer framing — O(chunk), no temp) vs a
/// [`StageReply::Sidecar`] staged temp (Sidecar framing).
struct StageReq {
    path: String,
    chunked: bool,
    reply: tokio::sync::oneshot::Sender<StageReply>,
}

/// The stager's reply to a [`StageReq`].
enum StageReply {
    /// A Sidecar member staged whole to this bounded temp (the writer appends then deletes it).
    Sidecar(PathBuf),
    /// A ChunkedTrailer member's body — the writer reads this receiver straight through
    /// `append_member_chunked` (O(chunk)); `poison` is set by the producer task on error so a
    /// premature channel close becomes a loud IO error (never a silently-truncated member).
    Chunked {
        rx: tokio::sync::mpsc::Receiver<Vec<u8>>,
        poison: Arc<std::sync::atomic::AtomicBool>,
    },
    /// Production failed — fail the writer (the specific error is surfaced by the stager).
    Err,
}

/// A started chunked-member body producer: the body-channel receiver, the `poison` flag the
/// producer sets on error, and its `JoinHandle` (awaited by the stager so a producer error fails
/// the export). Returned by [`NodeProjectExport::open_chunked_producer`].
type ChunkedProducer = (
    tokio::sync::mpsc::Receiver<Vec<u8>>,
    Arc<std::sync::atomic::AtomicBool>,
    tokio::task::JoinHandle<Result<(), Perr>>,
);

/// A synchronous [`Read`] over a chunked member's body channel (export) that distinguishes a
/// CLEAN end-of-stream from a PRODUCER FAILURE: on channel close it returns an IO error iff the
/// shared `poison` flag is set (the producer errored), so `append_member_chunked` never writes a
/// valid trailer over a short/incomplete member.
struct ChunkedBodyReader {
    rx: tokio::sync::mpsc::Receiver<Vec<u8>>,
    poison: Arc<std::sync::atomic::AtomicBool>,
    buf: Vec<u8>,
    pos: usize,
}

impl Read for ChunkedBodyReader {
    fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> {
        while self.pos >= self.buf.len() {
            match self.rx.blocking_recv() {
                Some(chunk) if !chunk.is_empty() => {
                    self.buf = chunk;
                    self.pos = 0;
                }
                Some(_) => continue,
                None => {
                    if self.poison.load(std::sync::atomic::Ordering::SeqCst) {
                        return Err(std::io::Error::other("export member producer failed"));
                    }
                    return Ok(0); // clean EOF
                }
            }
        }
        let n = std::cmp::min(out.len(), self.buf.len() - self.pos);
        out[..n].copy_from_slice(&self.buf[self.pos..self.pos + n]);
        self.pos += n;
        Ok(n)
    }
}

/// The import servicer's request, sent by the blocking atomic reader as it streams.
enum ImportMsg {
    /// The bundle head (surfaced before any member) — the source project + data-only flag.
    Head {
        data_only: bool,
        source_project: String,
    },
    /// A Sidecar member staged + size/SHA-verified at `temp`; the servicer restores it then
    /// replies so the reader may advance (one member staged at a time ⇒ O(largest member)).
    Member {
        spec: MemberSpec,
        temp: PathBuf,
        reply: tokio::sync::oneshot::Sender<Result<(), ()>>,
    },
    /// Begin a ChunkedTrailer member: the servicer opens the sink (a libsql shadow, or a staging
    /// temp for a blob/KV member) and drains `body_rx` into it, replying once opened.
    ChunkBegin {
        spec: MemberSpec,
        body_rx: tokio::sync::mpsc::Receiver<Vec<u8>>,
        reply: tokio::sync::oneshot::Sender<Result<(), ()>>,
    },
    /// Finish the in-flight ChunkedTrailer member: `verified` is whether the trailer matched —
    /// COMMIT the sink on true, DROP it on false (the reader then raises the loud mismatch).
    ChunkFinish {
        verified: bool,
        reply: tokio::sync::oneshot::Sender<Result<(), ()>>,
    },
}

/// The blocking atomic reader's [`BundleRestorer`](project_bundle::BundleRestorer) — it bridges the
/// sync reader to the async servicer over the `req` channel (for sidecar members + chunk
/// begin/finish) and a per-member `body` channel (for chunk bytes). It also enforces the
/// per-member import byte CAP (inc2 default #6 / inc1 LOW-1): a sidecar member's staged size and a
/// chunked member's streamed total are both checked against `member_cap`, so one hostile member
/// can't stream unbounded bytes.
struct ImportBridge {
    req_tx: tokio::sync::mpsc::Sender<ImportMsg>,
    /// The in-flight chunked member's body channel (between begin and finish).
    body_tx: Option<tokio::sync::mpsc::Sender<Vec<u8>>>,
    /// Bytes streamed into the in-flight chunked member so far (for the per-member cap).
    chunked_bytes: u64,
    member_cap: u64,
}

impl ImportBridge {
    fn gone() -> project_bundle::BundleError {
        project_bundle::BundleError::MalformedStream("import servicer gone".into())
    }
    fn over_cap(cap: u64) -> project_bundle::BundleError {
        project_bundle::BundleError::MalformedStream(format!(
            "import refused: a member exceeds the per-member byte cap of {cap} bytes"
        ))
    }
}

impl project_bundle::BundleRestorer for ImportBridge {
    fn restore_sidecar(
        &mut self,
        spec: &MemberSpec,
        temp: &std::path::Path,
    ) -> Result<(), project_bundle::BundleError> {
        if let Ok(m) = std::fs::metadata(temp)
            && m.len() > self.member_cap
        {
            return Err(Self::over_cap(self.member_cap));
        }
        let (reply_tx, reply_rx) = tokio::sync::oneshot::channel();
        self.req_tx
            .blocking_send(ImportMsg::Member {
                spec: spec.clone(),
                temp: temp.to_path_buf(),
                reply: reply_tx,
            })
            .map_err(|_| Self::gone())?;
        match reply_rx.blocking_recv() {
            Ok(Ok(())) => Ok(()),
            _ => Err(project_bundle::BundleError::MalformedStream(
                "import restore aborted".into(),
            )),
        }
    }

    fn begin_chunked(&mut self, spec: &MemberSpec) -> Result<(), project_bundle::BundleError> {
        let (body_tx, body_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(STREAM_BYTE_CHANNEL);
        let (reply_tx, reply_rx) = tokio::sync::oneshot::channel();
        self.req_tx
            .blocking_send(ImportMsg::ChunkBegin {
                spec: spec.clone(),
                body_rx,
                reply: reply_tx,
            })
            .map_err(|_| Self::gone())?;
        self.body_tx = Some(body_tx);
        self.chunked_bytes = 0;
        match reply_rx.blocking_recv() {
            Ok(Ok(())) => Ok(()),
            _ => Err(project_bundle::BundleError::MalformedStream(
                "import chunk begin aborted".into(),
            )),
        }
    }

    fn write_chunk(
        &mut self,
        _spec: &MemberSpec,
        buf: &[u8],
    ) -> Result<(), project_bundle::BundleError> {
        self.chunked_bytes = self.chunked_bytes.saturating_add(buf.len() as u64);
        if self.chunked_bytes > self.member_cap {
            return Err(Self::over_cap(self.member_cap));
        }
        match self.body_tx.as_ref() {
            Some(tx) => tx.blocking_send(buf.to_vec()).map_err(|_| {
                project_bundle::BundleError::MalformedStream("chunk sink closed".into())
            }),
            None => Err(project_bundle::BundleError::MalformedStream(
                "write_chunk without begin".into(),
            )),
        }
    }

    fn finish_chunked(
        &mut self,
        _spec: &MemberSpec,
        verified: bool,
    ) -> Result<(), project_bundle::BundleError> {
        // Drop the body channel → EOF to the servicer's drain, THEN ask it to commit/abort.
        self.body_tx = None;
        let (reply_tx, reply_rx) = tokio::sync::oneshot::channel();
        self.req_tx
            .blocking_send(ImportMsg::ChunkFinish {
                verified,
                reply: reply_tx,
            })
            .map_err(|_| Self::gone())?;
        match reply_rx.blocking_recv() {
            Ok(Ok(())) => Ok(()),
            _ => Err(project_bundle::BundleError::MalformedStream(
                "import chunk finish aborted".into(),
            )),
        }
    }
}

/// The servicer's in-flight chunked-member sink, held between `ChunkBegin` and `ChunkFinish`.
enum ChunkState {
    /// A libsql member streaming into an atomic shadow DB (committed-or-dropped at finish).
    Libsql {
        shadow: boatramp_storage::sql_libsql::DumpShadow,
        feed_err: Option<Perr>,
    },
    /// A blob/KV member staged to a bounded temp, then restored via the SAME `restore_member`
    /// (re-key / scope-enforce) as a sidecar member at finish — framing is never a tenancy bypass.
    Staged {
        spec: MemberSpec,
        temp: PathBuf,
        write_err: Option<Perr>,
    },
    /// A Postgres member streaming into a SHADOW database (inc2 Stage C). The restore subprocess
    /// (`pg_restore` as the NON-SUPERUSER owner role) reads the body channel as stdin while it runs;
    /// at finish the shadow is atomically swapped in (verified) or dropped (abort) via trusted DDL.
    Pg {
        plan: Box<PgShadowPlan>,
        restore: tokio::task::JoinHandle<Result<i32, Perr>>,
        out_path: PathBuf,
    },
    /// A MySQL member streaming into a SHADOW database (inc2 Stage D), mirror of [`Pg`](Self::Pg):
    /// `mysql <shadow>` applies the tables-only dump as the non-superuser role; finish swaps via an
    /// atomic `RENAME TABLE` (verified) or drops the shadow (abort).
    Mysql {
        plan: Box<MysqlShadowPlan>,
        restore: tokio::task::JoinHandle<Result<i32, Perr>>,
        out_path: PathBuf,
    },
}

/// The resolved plan for a Postgres atomic shadow-restore (inc2 Stage C).
///
/// THE SECURITY CORE (HIGH-1 fix): the untrusted dump is applied by an EPHEMERAL, per-import
/// `NOSUPERUSER NOCREATEDB NOCREATEROLE` role (`eph_role`), created by the superuser for exactly
/// this import and dropped afterwards — so the confinement holds REGARDLESS of what the binding's
/// configured user is (on a Single/dedicated managed pg that user is the bootstrap SUPERUSER, so
/// relying on `owner_target` would NOT confine). The SUPERUSER / maintenance connection (`maint`,
/// on the `postgres` db) runs ONLY our own trusted `CREATE ROLE`/`CREATE/ALTER/DROP DATABASE`/
/// `REASSIGN OWNED`/`pg_terminate_backend` DDL — never a byte of the bundle's dump. On success the
/// shadow's objects are `REASSIGN OWNED` from the ephemeral role to `owner_user` (the configured
/// role that normally owns the tenant db) before the ephemeral role is dropped.
#[derive(Clone)]
struct PgShadowPlan {
    /// The live (target) database name.
    live_db: String,
    /// The transient shadow database (`<live>__shadow_<suffix>`) the dump restores into.
    shadow_db: String,
    /// The per-process-unique suffix (also names the rename-aside `<live>__old_<suffix>`).
    suffix: String,
    /// The SUPERUSER / maintenance connection (database = `postgres`) for the trusted DDL.
    maint: PgConnection,
    /// The EPHEMERAL non-superuser role name the untrusted dump is applied as.
    eph_role: String,
    /// The ephemeral role's randomly-generated login password.
    eph_password: String,
    /// The configured role that normally owns the tenant db — the shadow's objects are reassigned
    /// to it on a successful swap (so the swapped-in live db has its usual ownership).
    owner_user: String,
    /// The client image (`pg_dump`/`pg_restore`/`psql`).
    image: String,
    /// The operator trusted-extension allowlist the superuser pre-creates in the shadow (so a legit
    /// `CREATE EXTENSION IF NOT EXISTS <ext>` in the dump no-ops under the non-superuser apply).
    trusted_extensions: Vec<String>,
}

impl PgShadowPlan {
    /// The SUPERUSER connection pointed at the SHADOW db (for extension pre-create + `REASSIGN
    /// OWNED`, which must run connected to the db they target).
    fn maint_on_shadow(&self) -> PgConnection {
        let mut c = self.maint.clone();
        c.database = self.shadow_db.clone();
        c
    }
    /// The NON-SUPERUSER apply connection (the ephemeral role) pointed at the shadow db.
    fn apply_conn(&self) -> PgConnection {
        let mut c = self.maint.clone();
        c.user = self.eph_role.clone();
        c.password = self.eph_password.clone();
        c.database = self.shadow_db.clone();
        c
    }
}

/// The resolved plan for a MySQL atomic shadow-restore (inc2 Stage D), mirror of [`PgShadowPlan`]:
/// the untrusted dump is applied by an EPHEMERAL `mysql` user granted ONLY on the shadow db (never
/// `*.*`, `SUPER`, or `FILE`), created + dropped by the superuser around the import.
#[derive(Clone)]
struct MysqlShadowPlan {
    live_db: String,
    shadow_db: String,
    suffix: String,
    /// The SUPERUSER / maintenance connection (no default db) for the trusted DDL + enumeration.
    maint: MysqlConnection,
    /// The EPHEMERAL non-superuser user the untrusted dump is applied as.
    eph_user: String,
    /// The ephemeral user's randomly-generated password.
    eph_password: String,
    image: String,
}

impl MysqlShadowPlan {
    /// The NON-SUPERUSER apply connection (the ephemeral user).
    fn apply_conn(&self) -> MysqlConnection {
        let mut c = self.maint.clone();
        c.user = self.eph_user.clone();
        c.password = self.eph_password.clone();
        c.database = self.shadow_db.clone();
        c
    }
}

/// A random token (32 hex chars) for an ephemeral role's login password — never persisted, never
/// handed to a handler; it exists only for the lifetime of one import's shadow apply.
fn random_token() -> String {
    let mut bytes = [0u8; 16];
    // A failed RNG is fatal to the import, not silently weak.
    getrandom::getrandom(&mut bytes).expect("os rng for ephemeral role password");
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

#[async_trait]
impl ProjectExport for NodeProjectExport {
    async fn export(
        &self,
        project: &str,
        opts: &ExportOptions,
        sink: &mut (dyn futures::io::AsyncWrite + Send + Unpin),
    ) -> Result<(), Perr> {
        // An ordinary export is the clone stream with an EMPTY skip set (the degenerate
        // "send everything, skip nothing" case; the target-driven reader is the superset).
        self.export_clone(project, opts, &CloneSkip::default(), sink)
            .await
    }

    async fn export_clone(
        &self,
        project: &str,
        opts: &ExportOptions,
        skip: &CloneSkip,
        sink: &mut (dyn futures::io::AsyncWrite + Send + Unpin),
    ) -> Result<(), Perr> {
        check_project_slug(project)?;
        // A data-only bundle carries NO control-plane / identity material at all, so the
        // two flags are mutually exclusive — refuse the contradiction rather than silently
        // pick one.
        if opts.data_only && opts.include_identity {
            return Err(Perr::Other(
                "--data-only and --include-identity are mutually exclusive: a data-only \
                 bundle carries application data only (no control-plane KV, no identity)"
                    .into(),
            ));
        }
        let data_only = opts.data_only;
        let created_at = now_secs();
        let session = self.work_dir.join(format!("export-{project}-{created_at}"));
        let stage_dir = session.join("stage");
        tokio::fs::create_dir_all(&stage_dir).await.map_err(other)?;

        // 1. PLAN: enumerate every member up front — version-detect each pg/mysql DB, list the
        //    project's blobs + sites — in the v2 RESTORE order (identity → blobs → pg → mysql
        //    → libsql → KV). The v2 MANIFEST lists these before any member body exists, so the
        //    member SET is decided here; each member's BIG bytes are produced later, one at a
        //    time, by the stager. (A failure here is before the first byte, so the handler can
        //    still turn it into an error status.)
        let (mut specs, mut jobs, source) = self.plan_export(project, opts, created_at).await?;
        // CLONE per-SHA skip: drop the blob members the target already holds (content-matched in
        // ITS OWN scope — see `diff_clone_blobs`). ONLY blob members are skippable; a non-blob
        // skip entry is IGNORED so a skip set can never drop a DB/KV/identity member. Removed from
        // BOTH the spec list (so the MANIFEST omits them) and the stage jobs (so the stager is
        // never asked for them), keeping the stream internally consistent for the inc2 atomic
        // reader — the omitted objects are already present on the target bucket.
        if !skip.skip_member_paths.is_empty() {
            specs.retain(|s| {
                !(s.kind == MemberKind::Blob && skip.skip_member_paths.contains(&s.path))
            });
            jobs.retain(|path, _| specs.iter().any(|s| &s.path == path));
        }

        // 2. STREAM: run the sync v3 writer in a blocking task, bridged to (a) the caller's async
        //    `sink` over a bounded byte channel + drain, and (b) the async stager over a one-slot
        //    request channel. `write_bundle_streaming_v3` dispatches each member by framing: a
        //    Sidecar member is staged → appended → deleted (O(largest-member)); a ChunkedTrailer
        //    member's body is piped STRAIGHT through `append_member_chunked` in `chunk_size` pieces
        //    with NO temp (O(chunk) — the libsql `.dump` + large-blob streaming win over inc1).
        let chunk_size = self.chunk_size;
        let (byte_tx, mut byte_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(STREAM_BYTE_CHANNEL);
        let (stage_tx, mut stage_rx) = tokio::sync::mpsc::channel::<StageReq>(1);
        let writer_out = ChannelWriter { tx: byte_tx };
        let stage_tx_task = stage_tx.clone();
        let specs_for_task = specs.clone();
        let source_for_task = source.clone();
        let write_handle =
            tokio::task::spawn_blocking(move || -> Result<(), project_bundle::BundleError> {
                let request = |path: &str,
                               chunked: bool|
                 -> Result<StageReply, project_bundle::BundleError> {
                    let (reply_tx, reply_rx) = tokio::sync::oneshot::channel();
                    stage_tx_task
                        .blocking_send(StageReq {
                            path: path.to_string(),
                            chunked,
                            reply: reply_tx,
                        })
                        .map_err(|_| {
                            project_bundle::BundleError::MalformedStream(
                                "export stager gone".into(),
                            )
                        })?;
                    reply_rx.blocking_recv().map_err(|_| {
                        project_bundle::BundleError::MalformedStream("export stager dropped".into())
                    })
                };
                project_bundle::write_bundle_streaming_v3(
                    writer_out,
                    created_at,
                    data_only,
                    source_for_task,
                    specs_for_task,
                    chunk_size,
                    // Sidecar: ask the stager to stage the member to a temp.
                    |spec| match request(&spec.path, false)? {
                        StageReply::Sidecar(tmp) => Ok(tmp),
                        _ => Err(project_bundle::BundleError::MalformedStream(
                            "export staging failed".into(),
                        )),
                    },
                    // ChunkedTrailer: ask the stager to START a body producer; read it straight through.
                    |spec| match request(&spec.path, true)? {
                        StageReply::Chunked { rx, poison } => Ok(Box::new(ChunkedBodyReader {
                            rx,
                            poison,
                            buf: Vec::new(),
                            pos: 0,
                        })
                            as Box<dyn Read>),
                        _ => Err(project_bundle::BundleError::MalformedStream(
                            "export chunked member open failed".into(),
                        )),
                    },
                )
            });
        drop(stage_tx); // only the blocking task keeps the request channel alive now

        // Async stager: produce each requested member, using `self`. A Sidecar member is staged to
        // a bounded temp; a ChunkedTrailer member spawns a producer task that streams its body
        // (libsql `.dump` / blob get) into a bounded channel the writer drains. Producer handles
        // are collected and awaited after the writer finishes, so a producer error FAILS the export
        // (and poisons the body stream so no valid trailer is written over a short member).
        let stager = async {
            let mut idx = 0usize;
            let mut producers: Vec<tokio::task::JoinHandle<Result<(), Perr>>> = Vec::new();
            while let Some(req) = stage_rx.recv().await {
                let job = jobs.get(&req.path);
                if req.chunked {
                    match self.open_chunked_producer(job) {
                        Ok((rx, poison, handle)) => {
                            producers.push(handle);
                            let _ = req.reply.send(StageReply::Chunked { rx, poison });
                        }
                        Err(e) => {
                            let _ = req.reply.send(StageReply::Err);
                            return Err::<(), Perr>(e);
                        }
                    }
                } else {
                    let res = match job {
                        Some(job) => self.stage_job(project, job, &stage_dir, idx).await,
                        None => Err(Perr::Other(format!(
                            "export: internal error — no stage job for member {:?}",
                            req.path
                        ))),
                    };
                    idx += 1;
                    match res {
                        Ok(tmp) => {
                            let _ = req.reply.send(StageReply::Sidecar(tmp));
                        }
                        Err(e) => {
                            let _ = req.reply.send(StageReply::Err);
                            return Err::<(), Perr>(e);
                        }
                    }
                }
            }
            // The writer has finished (channel closed) and fully drained every producer; surface
            // any producer error now (a failed dump/blob-get is an export failure).
            for h in producers {
                match h.await {
                    Ok(Ok(())) => {}
                    Ok(Err(e)) => return Err(e),
                    Err(je) => return Err(other(je)),
                }
            }
            Ok(())
        };

        // Async drain: forward the bundle bytes to the caller's sink as they are produced.
        let drain = async {
            while let Some(chunk) = byte_rx.recv().await {
                sink.write_all(&chunk)
                    .await
                    .map_err(|e| Perr::Other(format!("export sink write failed: {e}")))?;
            }
            sink.flush()
                .await
                .map_err(|e| Perr::Other(format!("export sink flush failed: {e}")))?;
            Ok::<(), Perr>(())
        };

        let (stage_res, drain_res, write_res) = tokio::join!(stager, drain, write_handle);
        let _ = tokio::fs::remove_dir_all(&session).await;

        // Error precedence: a staging failure is the most specific cause, a writer/bundle
        // error next, a sink error last.
        stage_res?;
        match write_res {
            Ok(Ok(())) => {}
            Ok(Err(be)) => return Err(other(be)),
            Err(je) => return Err(other(je)),
        }
        drain_res?;
        Ok(())
    }

    async fn import(
        &self,
        project: &str,
        src: &mut (dyn futures::io::AsyncRead + Send + Unpin),
        opts: ImportOptions,
    ) -> Result<ImportReport, Perr> {
        check_project_slug(project)?;

        // MEDIUM-1(a): refuse a clone into a TARGET PROJECT that already holds its own data
        // (owned KV prefixes OR blob scope) unless `overwrite` is set — a clone into a FRESH
        // target is the safe default; replacing a populated project is opt-in. This is distinct
        // from `force` (the store-wide KV commingle override); env-clone creates a fresh target,
        // so this does not break it.
        if !opts.overwrite {
            for prefix in
                boatramp_core::project_export::project_owned_prefixes(ProjectRef::new(project))
            {
                if !self
                    .kv
                    .list_prefix(&prefix)
                    .await
                    .map_err(other)?
                    .is_empty()
                {
                    return Err(Perr::Other(format!(
                        "import refused: target project {project:?} already has control-plane \
                         data under {prefix:?}; pass overwrite=true to replace an existing \
                         project (a clone into a fresh target needs no overwrite)"
                    )));
                }
            }
            if !self
                .blobs
                .list(&blob_project_prefix(project))
                .await
                .map_err(other)?
                .is_empty()
            {
                return Err(Perr::Other(format!(
                    "import refused: target project {project:?} already has blobs; pass \
                     overwrite=true to replace an existing project"
                )));
            }
        }

        let session = self
            .work_dir
            .join(format!("import-{project}-{}", now_secs()));
        let stage_dir = session.join("stage");
        tokio::fs::create_dir_all(&stage_dir).await.map_err(other)?;

        // Bridge: the async feeder pumps the caller's bundle stream into a bounded byte channel →
        // `ChannelReader` → the sync v1/v2/v3 ATOMIC reader (in a blocking task). The `ImportBridge`
        // restorer hands a Sidecar member (staged + size/SHA-VERIFIED at a bounded temp) to the
        // async servicer and BLOCKS until it finishes (verify-then-apply, O(largest member)); a
        // ChunkedTrailer member streams begin/chunk/finish to the servicer, which applies a libsql
        // member into an ATOMIC shadow (committed only on a verified trailer — nothing partial ever
        // reaches live) and stages a blob/KV member to a temp restored via the SAME re-key/enforce
        // as a sidecar member. Reads v1, v2 AND v3 bundles.
        let member_cap = self.import_member_cap;
        let (byte_tx, byte_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(STREAM_BYTE_CHANNEL);
        let (req_tx, mut req_rx) = tokio::sync::mpsc::channel::<ImportMsg>(1);
        let reader = ChannelReader::new(byte_rx);
        let stage_dir_task = stage_dir.clone();
        let req_tx_task = req_tx.clone();
        let read_handle = tokio::task::spawn_blocking(
            move || -> Result<Vec<MemberSpec>, project_bundle::BundleError> {
                let head_tx = req_tx_task.clone();
                let on_head = move |data_only: bool, source: &SourceInfo| {
                    // Surfaced before any member: the servicer needs the source project (to
                    // re-key each member to the TARGET) and the data-only flag.
                    let _ = head_tx.blocking_send(ImportMsg::Head {
                        data_only,
                        source_project: source.project.clone(),
                    });
                };
                let mut bridge = ImportBridge {
                    req_tx: req_tx_task,
                    body_tx: None,
                    chunked_bytes: 0,
                    member_cap,
                };
                project_bundle::read_bundle_streaming_atomic(
                    reader,
                    &stage_dir_task,
                    on_head,
                    &mut bridge,
                )
            },
        );
        drop(req_tx); // only the blocking reader keeps the request channel alive now

        // Async feeder: pump the caller's bundle stream into the blocking reader, enforcing the
        // whole-bundle byte CAP (inc2 default #6 / inc1 LOW-1) so a hostile bundle can't stream
        // forever (memory is already bounded by the channel + one member on disk; this bounds the
        // TOTAL).
        let total_cap = self.import_total_cap;
        let feeder = async {
            let mut buf = vec![0u8; 64 * 1024];
            let mut total: u64 = 0;
            loop {
                let n = src
                    .read(&mut buf)
                    .await
                    .map_err(|e| Perr::Other(format!("import body read failed: {e}")))?;
                if n == 0 {
                    break;
                }
                total = total.saturating_add(n as u64);
                if total > total_cap {
                    return Err(Perr::Other(format!(
                        "import refused: bundle exceeds the total byte cap of {total_cap} bytes"
                    )));
                }
                if byte_tx.send(buf[..n].to_vec()).await.is_err() {
                    break; // the reader stopped (error / early finish) — nothing more to feed
                }
            }
            drop(byte_tx);
            Ok::<(), Perr>(())
        };

        // Async servicer: restore each member using `self`, in arrival (restore) order. A Sidecar
        // member goes through `restore_member`; a ChunkedTrailer member opens a sink on
        // `ChunkBegin` (a libsql shadow, or a staging temp for a blob/KV member), drains its body
        // INLINE, and commits/drops it on `ChunkFinish`.
        let servicer = async {
            let mut report = ImportReport {
                dry_run: !opts.apply,
                ..Default::default()
            };
            let mut data_only = false;
            let mut source_project = String::new();
            let mut saw_identity = false;
            let mut pending_chunk: Option<ChunkState> = None;
            let mut chunk_idx = 0usize;
            while let Some(msg) = req_rx.recv().await {
                match msg {
                    ImportMsg::Head {
                        data_only: d,
                        source_project: s,
                    } => {
                        data_only = d;
                        source_project = s;
                    }
                    ImportMsg::Member { spec, temp, reply } => {
                        let r = self
                            .restore_member(
                                project,
                                data_only,
                                &source_project,
                                &spec,
                                &temp,
                                &opts,
                                &mut report,
                                &mut saw_identity,
                            )
                            .await;
                        match r {
                            Ok(()) => {
                                let _ = reply.send(Ok(()));
                            }
                            Err(e) => {
                                let _ = reply.send(Err(()));
                                return Err::<_, Perr>(e);
                            }
                        }
                    }
                    ImportMsg::ChunkBegin {
                        spec,
                        mut body_rx,
                        reply,
                    } => {
                        // Open the sink for this chunked member by kind, reply so the reader may
                        // stream, then drain the body INLINE into the sink (feeding until EOF).
                        match spec.kind {
                            MemberKind::Libsql => {
                                let site = match site_from_libsql_member(&spec.path) {
                                    Some(s) => s,
                                    None => {
                                        let _ = reply.send(Err(()));
                                        return Err(Perr::Other(format!(
                                            "bad libsql member path {:?}",
                                            spec.path
                                        )));
                                    }
                                };
                                let Some(libsql) = self.libsql.as_ref() else {
                                    let _ = reply.send(Err(()));
                                    return Err(Perr::Unavailable(
                                        "bundle carries a libsql member but this node has no local \
                                         libsql backend to restore it into"
                                            .into(),
                                    ));
                                };
                                let qsite = ProjectRef::new(project).qualified(site);
                                if opts.apply {
                                    match libsql.begin_dump_shadow(&qsite, "", opts.overwrite).await
                                    {
                                        Ok(mut shadow) => {
                                            let _ = reply.send(Ok(()));
                                            let mut feed_err = None;
                                            while let Some(chunk) = body_rx.recv().await {
                                                if feed_err.is_none()
                                                    && let Err(e) = shadow.feed(&chunk).await
                                                {
                                                    feed_err = Some(other(e));
                                                }
                                            }
                                            pending_chunk =
                                                Some(ChunkState::Libsql { shadow, feed_err });
                                        }
                                        Err(e) => {
                                            let _ = reply.send(Err(()));
                                            return Err(other(e));
                                        }
                                    }
                                } else {
                                    // Dry-run: don't open a shadow — just drain + count.
                                    let _ = reply.send(Ok(()));
                                    while body_rx.recv().await.is_some() {}
                                    report.libsql_databases += 1;
                                    pending_chunk = None;
                                }
                            }
                            MemberKind::Blob | MemberKind::Kv => {
                                // Stage the chunk stream to a bounded temp, then restore it via the
                                // SAME `restore_member` (re-key / enforce) as a sidecar member.
                                let temp = stage_dir.join(format!("chunk-{chunk_idx}"));
                                chunk_idx += 1;
                                match tokio::fs::File::create(&temp).await {
                                    Ok(mut f) => {
                                        let _ = reply.send(Ok(()));
                                        use tokio::io::AsyncWriteExt as _;
                                        let mut write_err = None;
                                        while let Some(chunk) = body_rx.recv().await {
                                            if write_err.is_none()
                                                && let Err(e) = f.write_all(&chunk).await
                                            {
                                                write_err = Some(other(e));
                                            }
                                        }
                                        if write_err.is_none()
                                            && let Err(e) = f.flush().await
                                        {
                                            write_err = Some(other(e));
                                        }
                                        drop(f);
                                        pending_chunk = Some(ChunkState::Staged {
                                            spec,
                                            temp,
                                            write_err,
                                        });
                                    }
                                    Err(e) => {
                                        let _ = reply.send(Err(()));
                                        return Err(other(e));
                                    }
                                }
                            }
                            MemberKind::PgDump => {
                                // The UNTRUSTED pg dump → an atomic SHADOW database (inc2 Stage C).
                                // Tenancy: the member path `sql/<db>.pgc` names a BINDING, not a
                                // project; `self.databases.get(db)` + `resolve_pg(project, …)`
                                // resolve the TARGET project's OWN managed db — a pg member can only
                                // ever land in the target's tenant-keyed db, so there is no
                                // cross-tenant surface (no re-key needed; the sidecar PgDump arm
                                // does exactly the same).
                                let db = match db_from_pg_member(&spec.path) {
                                    Some(d) => d.to_string(),
                                    None => {
                                        let _ = reply.send(Err(()));
                                        return Err(Perr::Other(format!(
                                            "bad pg member path {:?}",
                                            spec.path
                                        )));
                                    }
                                };
                                let cfg = match self.databases.get(&db) {
                                    Some(c) => c.clone(),
                                    None => {
                                        let _ = reply.send(Err(()));
                                        return Err(Perr::Other(format!(
                                            "import: no database named {db:?} on this node"
                                        )));
                                    }
                                };
                                if !opts.apply {
                                    // Dry-run: don't touch the server — drain + count.
                                    let _ = reply.send(Ok(()));
                                    while body_rx.recv().await.is_some() {}
                                    report.pg_databases += 1;
                                    pending_chunk = None;
                                } else {
                                    let plan = match self.pg_shadow_plan(project, &db, &cfg).await {
                                        Ok(p) => p,
                                        Err(e) => {
                                            let _ = reply.send(Err(()));
                                            return Err(e);
                                        }
                                    };
                                    // TRUSTED DDL (superuser/maint): mint the ephemeral NON-SUPERUSER
                                    // role + the shadow it owns + pre-create the allowlisted exts.
                                    if let Err(e) = self.pg_create_shadow(&plan, &stage_dir).await {
                                        self.pg_drop_shadow(&plan, &stage_dir).await;
                                        let _ = reply.send(Err(()));
                                        return Err(e);
                                    }
                                    // FAIL-CLOSED: refuse the untrusted apply unless the apply role is
                                    // provably a non-superuser.
                                    if let Err(e) = self
                                        .pg_assert_not_superuser(
                                            &plan.apply_conn(),
                                            &plan.image,
                                            &stage_dir,
                                        )
                                        .await
                                    {
                                        self.pg_drop_shadow(&plan, &stage_dir).await;
                                        let _ = reply.send(Err(()));
                                        return Err(e);
                                    }
                                    let out_path =
                                        stage_dir.join(format!("pgrestore-{chunk_idx}.out"));
                                    chunk_idx += 1;
                                    let restore = match self.spawn_pg_restore(
                                        &plan,
                                        body_rx,
                                        out_path.clone(),
                                    ) {
                                        Ok(h) => h,
                                        Err(e) => {
                                            // Shadow was created — tear it down before failing.
                                            self.pg_drop_shadow(&plan, &stage_dir).await;
                                            let _ = reply.send(Err(()));
                                            return Err(e);
                                        }
                                    };
                                    let _ = reply.send(Ok(()));
                                    pending_chunk = Some(ChunkState::Pg {
                                        plan: Box::new(plan),
                                        restore,
                                        out_path,
                                    });
                                }
                            }
                            MemberKind::MysqlDump => {
                                let db = match db_from_mysql_member(&spec.path) {
                                    Some(d) => d.to_string(),
                                    None => {
                                        let _ = reply.send(Err(()));
                                        return Err(Perr::Other(format!(
                                            "bad mysql member path {:?}",
                                            spec.path
                                        )));
                                    }
                                };
                                let cfg = match self.databases.get(&db) {
                                    Some(c) => c.clone(),
                                    None => {
                                        let _ = reply.send(Err(()));
                                        return Err(Perr::Other(format!(
                                            "import: no database named {db:?} on this node"
                                        )));
                                    }
                                };
                                if !opts.apply {
                                    let _ = reply.send(Ok(()));
                                    while body_rx.recv().await.is_some() {}
                                    report.pg_databases += 1;
                                    pending_chunk = None;
                                } else {
                                    let plan =
                                        match self.mysql_shadow_plan(project, &db, &cfg).await {
                                            Ok(p) => p,
                                            Err(e) => {
                                                let _ = reply.send(Err(()));
                                                return Err(e);
                                            }
                                        };
                                    if let Err(e) =
                                        self.mysql_create_shadow(&plan, &stage_dir).await
                                    {
                                        self.mysql_drop_shadow(&plan, &stage_dir).await;
                                        let _ = reply.send(Err(()));
                                        return Err(e);
                                    }
                                    // FAIL-CLOSED: refuse unless the apply user is least-privilege.
                                    if let Err(e) =
                                        self.mysql_assert_not_superuser(&plan, &stage_dir).await
                                    {
                                        self.mysql_drop_shadow(&plan, &stage_dir).await;
                                        let _ = reply.send(Err(()));
                                        return Err(e);
                                    }
                                    let out_path =
                                        stage_dir.join(format!("myrestore-{chunk_idx}.out"));
                                    chunk_idx += 1;
                                    let restore = match self.spawn_mysql_restore(
                                        &plan,
                                        body_rx,
                                        out_path.clone(),
                                    ) {
                                        Ok(h) => h,
                                        Err(e) => {
                                            self.mysql_drop_shadow(&plan, &stage_dir).await;
                                            let _ = reply.send(Err(()));
                                            return Err(e);
                                        }
                                    };
                                    let _ = reply.send(Ok(()));
                                    pending_chunk = Some(ChunkState::Mysql {
                                        plan: Box::new(plan),
                                        restore,
                                        out_path,
                                    });
                                }
                            }
                            _ => {
                                let _ = reply.send(Err(()));
                                return Err(Perr::Unavailable(format!(
                                    "chunked framing is not wired for member kind {:?}",
                                    spec.kind
                                )));
                            }
                        }
                    }
                    ImportMsg::ChunkFinish { verified, reply } => {
                        let state = pending_chunk.take();
                        let res: Result<(), Perr> = match state {
                            Some(ChunkState::Libsql { shadow, feed_err }) => {
                                if let Some(e) = feed_err {
                                    drop(shadow); // RAII: tear down the shadow
                                    Err(e)
                                } else if !verified {
                                    drop(shadow); // abort: nothing reaches live; reader raises the mismatch
                                    Ok(())
                                } else {
                                    match self
                                        .libsql
                                        .as_ref()
                                        .expect("libsql shadow implies a libsql backend")
                                        .commit_dump_shadow(shadow)
                                        .await
                                    {
                                        Ok(()) => {
                                            report.libsql_databases += 1;
                                            Ok(())
                                        }
                                        Err(e) => Err(other(e)),
                                    }
                                }
                            }
                            Some(ChunkState::Staged {
                                spec,
                                temp,
                                write_err,
                            }) => {
                                let r = if let Some(e) = write_err {
                                    Err(e)
                                } else if !verified {
                                    Ok(()) // abort: drop the temp below; reader raises the mismatch
                                } else {
                                    self.restore_member(
                                        project,
                                        data_only,
                                        &source_project,
                                        &spec,
                                        &temp,
                                        &opts,
                                        &mut report,
                                        &mut saw_identity,
                                    )
                                    .await
                                };
                                let _ = tokio::fs::remove_file(&temp).await;
                                r
                            }
                            Some(ChunkState::Pg {
                                plan,
                                restore,
                                out_path,
                            }) => {
                                // The reader dropped body_tx → stdin EOF; await the restore client.
                                let code = restore.await;
                                let out = tokio::fs::read_to_string(&out_path)
                                    .await
                                    .unwrap_or_default();
                                let _ = tokio::fs::remove_file(&out_path).await;
                                match code {
                                    Ok(Ok(0)) if verified => {
                                        // Restore clean AND trailer matched → atomic swap.
                                        match self.pg_swap_shadow(&plan, &stage_dir).await {
                                            Ok(()) => {
                                                report.pg_databases += 1;
                                                Ok(())
                                            }
                                            Err(e) => {
                                                self.pg_drop_shadow(&plan, &stage_dir).await;
                                                Err(e)
                                            }
                                        }
                                    }
                                    Ok(Ok(0)) => {
                                        // Restore clean but trailer MISMATCH/truncation → abort:
                                        // drop the shadow (live untouched); the reader raises the
                                        // loud SHA/size error.
                                        self.pg_drop_shadow(&plan, &stage_dir).await;
                                        Ok(())
                                    }
                                    Ok(Ok(c)) => {
                                        // Non-zero pg_restore exit — a crafted superuser-only escape
                                        // refused as the non-superuser role lands here (as do other
                                        // restore failures). Drop the shadow; live untouched.
                                        self.pg_drop_shadow(&plan, &stage_dir).await;
                                        Err(Perr::Other(format!(
                                            "pg_restore into shadow {:?} exited {c}; live untouched: {out}",
                                            plan.shadow_db
                                        )))
                                    }
                                    Ok(Err(e)) => {
                                        self.pg_drop_shadow(&plan, &stage_dir).await;
                                        Err(e)
                                    }
                                    Err(je) => {
                                        self.pg_drop_shadow(&plan, &stage_dir).await;
                                        Err(other(je))
                                    }
                                }
                            }
                            Some(ChunkState::Mysql {
                                plan,
                                restore,
                                out_path,
                            }) => {
                                let code = restore.await;
                                let out = tokio::fs::read_to_string(&out_path)
                                    .await
                                    .unwrap_or_default();
                                let _ = tokio::fs::remove_file(&out_path).await;
                                match code {
                                    Ok(Ok(0)) if verified => {
                                        match self.mysql_swap_shadow(&plan, &stage_dir).await {
                                            Ok(()) => {
                                                report.pg_databases += 1;
                                                Ok(())
                                            }
                                            Err(e) => {
                                                self.mysql_drop_shadow(&plan, &stage_dir).await;
                                                Err(e)
                                            }
                                        }
                                    }
                                    Ok(Ok(0)) => {
                                        self.mysql_drop_shadow(&plan, &stage_dir).await;
                                        Ok(())
                                    }
                                    Ok(Ok(c)) => {
                                        self.mysql_drop_shadow(&plan, &stage_dir).await;
                                        Err(Perr::Other(format!(
                                            "mysql restore into shadow {:?} exited {c}; live untouched: {out}",
                                            plan.shadow_db
                                        )))
                                    }
                                    Ok(Err(e)) => {
                                        self.mysql_drop_shadow(&plan, &stage_dir).await;
                                        Err(e)
                                    }
                                    Err(je) => {
                                        self.mysql_drop_shadow(&plan, &stage_dir).await;
                                        Err(other(je))
                                    }
                                }
                            }
                            None => {
                                // A dry-run libsql/pg/mysql chunk (no sink opened) — nothing to commit.
                                Ok(())
                            }
                        };
                        match res {
                            Ok(()) => {
                                let _ = reply.send(Ok(()));
                            }
                            Err(e) => {
                                let _ = reply.send(Err(()));
                                return Err(e);
                            }
                        }
                    }
                }
            }
            // Safety net: if the reader died WITHOUT a ChunkFinish (e.g. a panic / broken req
            // channel) while a pg/mysql shadow was in flight, tear it down so no orphan db remains
            // (the libsql/staged shadows self-clean on Drop; the startup sweep covers a crash).
            match pending_chunk.take() {
                Some(ChunkState::Pg { plan, restore, .. }) => {
                    restore.abort();
                    self.pg_drop_shadow(&plan, &stage_dir).await;
                }
                Some(ChunkState::Mysql { plan, restore, .. }) => {
                    restore.abort();
                    self.mysql_drop_shadow(&plan, &stage_dir).await;
                }
                _ => {}
            }
            Ok((report, data_only, saw_identity))
        };

        let (feed_res, serv_res, read_res) = tokio::join!(feeder, servicer, read_handle);

        // Error precedence: a restore failure is the most specific cause; a bundle-integrity
        // error (SHA / size / order / truncation) next; a body-read error last. On ANY error
        // skip the post-stream steps (fresh-drop etc.) so a half-stream never half-finishes.
        let (mut report, data_only, saw_identity) = match serv_res {
            Ok(v) => v,
            Err(e) => {
                let _ = tokio::fs::remove_dir_all(&session).await;
                return Err(e);
            }
        };
        match read_res {
            Ok(Ok(_specs)) => {}
            Ok(Err(be)) => {
                let _ = tokio::fs::remove_dir_all(&session).await;
                return Err(other(be));
            }
            Err(je) => {
                let _ = tokio::fs::remove_dir_all(&session).await;
                return Err(other(je));
            }
        }
        if let Err(e) = feed_res {
            let _ = tokio::fs::remove_dir_all(&session).await;
            return Err(e);
        }

        // --- post-stream steps (only after a clean, fully-verified pass) ---

        // A `--data-only` bundle carries app data only; record that KV was not restored.
        if data_only {
            report
                .notes
                .push("control-plane KV (identity/RBAC/routing) NOT imported: --data-only".into());
        }

        // `adopt` requires the bundle to carry an identity member. For a FULL bundle this is
        // enforced earlier (at the KV member, before any sealed KV byte is written); this
        // final check also covers a bundle with no KV member (e.g. data-only + adopt).
        if matches!(opts.identity, IdentityChoice::Adopt { .. }) && !saw_identity {
            let _ = tokio::fs::remove_dir_all(&session).await;
            return Err(Perr::Other(
                "--identity adopt requires a bundle exported with --include-identity \
                 (no identity member present); use --identity fresh to import a bundle \
                 without identity"
                    .into(),
            ));
        }

        // --- fresh identity: drop the source sealed-secret keyspace (Ask-4c) ---
        // A `fresh` import of a FULL bundle just restored the SOURCE's KEK-sealed secrets
        // (operator/app + per-tenant), which can never unseal under this node's own
        // (different) KEK. Drop them so the target starts clean and re-provisions — making
        // "zero source-sealed artifacts that unwrap" a POSITIVE absence rather than
        // present-but-inert. Only for a FULL bundle (data-only carries no KV/secrets) and
        // only when applying.
        if matches!(opts.identity, IdentityChoice::Fresh) && !data_only && opts.apply {
            let prefixes =
                boatramp_core::project_export::sealed_secret_prefixes(ProjectRef::new(project));
            let mut dropped = 0usize;
            for prefix in &prefixes {
                for key in self.kv.list_prefix(prefix).await.map_err(other)? {
                    self.kv.delete_checkpointed(&key).await.map_err(other)?;
                    dropped += 1;
                }
            }
            report.notes.push(format!(
                "identity: --fresh dropped {dropped} source-sealed secret key(s); re-provision \
                 secrets + the managed-DB credential on the target"
            ));
        }

        // Operational prerequisites after a FULL control-plane restore — the portable bundle
        // deliberately carries no function/component CODE (deploy artifacts live in blob storage,
        // not this slice), no TLS private keys and no global routing ownership. Surface the
        // follow-up steps so the target is not silently half-restored.
        if !data_only {
            report.notes.push(
                "post-import: re-deploy function/component code (deploy artifacts are not \
                 bundled), re-verify + re-attach the project's domains, and let ACME re-issue TLS \
                 certs (routing + certs are intentionally not carried in a portable bundle)"
                    .into(),
            );
        }

        let _ = tokio::fs::remove_dir_all(&session).await;
        Ok(report)
    }

    async fn export_resumable(
        &self,
        project: &str,
        opts: &ExportOptions,
        dir_name: &str,
    ) -> Result<(), Perr> {
        // Confine the operator-named subdir under the configured base (fail-closed if no
        // base / on any escape), creating it, then run the core member-object export.
        let dir = self.resolve_resumable_dir(dir_name, true).await?;
        self.export_resumable_dir(project, opts, &dir).await
    }

    async fn import_resumable(
        &self,
        project: &str,
        dir_name: &str,
        opts: ImportOptions,
    ) -> Result<ImportReport, Perr> {
        // Confine the operator-named subdir under the configured base; it must already
        // exist (read, not create), then run the core member-object import-as-chain.
        let dir = self.resolve_resumable_dir(dir_name, false).await?;
        self.import_resumable_dir(project, &dir, opts).await
    }

    async fn clone_manifest(
        &self,
        project: &str,
        opts: &ExportOptions,
    ) -> Result<CloneManifest, Perr> {
        self.build_clone_manifest(project, opts).await
    }

    async fn clone_blobs_present(
        &self,
        project: &str,
        source_project: &str,
        blobs: &[CloneBlobRef],
    ) -> Result<CloneSkip, Perr> {
        self.diff_clone_blobs(project, source_project, blobs).await
    }
}

impl NodeProjectExport {
    /// CLONE SOURCE — produce the cheap [`CloneManifest`] for the manifest-first handshake: LIST
    /// the project's own blob objects (member path + size + etag, from a prefix list — never a
    /// body read) for the target's per-SHA diff, plus a light enumeration of the non-blob member
    /// paths (pg/mysql/libsql/kv/identity) the stream will always carry. Blobs are scoped
    /// STRUCTURALLY by the project prefix (`hblob/{project}/`, whose trailing `/` excludes a
    /// sibling-prefix tenant), so no other tenant's object can appear — the manifest is itself a
    /// cross-tenant boundary. Deliberately AVOIDS the engine version-detection `plan_export` does
    /// (no DB round-trip), so the manifest stays cheap and never fails on a down database.
    async fn build_clone_manifest(
        &self,
        project: &str,
        opts: &ExportOptions,
    ) -> Result<CloneManifest, Perr> {
        check_project_slug(project)?;
        if opts.data_only && opts.include_identity {
            return Err(Perr::Other(
                "--data-only and --include-identity are mutually exclusive".into(),
            ));
        }
        let data_only = opts.data_only;

        // Blobs: a metadata-only LIST under the project's OWN scope (`hblob/{project}/`).
        let blob_metas = self
            .blobs
            .list(&blob_project_prefix(project))
            .await
            .map_err(other)?;
        let blobs: Vec<CloneBlobRef> = blob_metas
            .into_iter()
            .map(|m| CloneBlobRef {
                member_path: format!("blobs/{}", m.key),
                size: m.size,
                etag: m.etag,
            })
            .collect();

        // Non-blob members (informational): the member PATHS the stream will carry, derived from
        // config + the stores WITHOUT a version-detect/dump — cheap and never hits the DB.
        let mut non_blob_members: Vec<String> = Vec::new();
        if opts.include_identity {
            non_blob_members.push(project_bundle::IDENTITY_MEMBER_PATH.to_string());
        }
        for (db, cfg) in &self.databases {
            let is_managed = cfg.compute.as_deref().is_some_and(|c| !c.is_empty());
            let dumpable = is_managed || !cfg.url_env.is_empty();
            if kind_is_postgres(&cfg.kind) && dumpable {
                non_blob_members.push(pg_member_path(db));
            } else if kind_is_mysql(&cfg.kind) && dumpable {
                non_blob_members.push(mysql_member_path(db));
            }
        }
        if let Some(libsql) = &self.libsql {
            let sites = self
                .deploy
                .list_sites(ProjectRef::new(project))
                .await
                .map_err(other)?;
            for site in sites {
                let qsite = ProjectRef::new(project).qualified(&site);
                if libsql.local_database_exists(&qsite, "") {
                    non_blob_members.push(libsql_member_path(project, &site));
                }
            }
        }
        if !data_only {
            non_blob_members.push(project_bundle::KV_MEMBER_PATH.to_string());
        }

        Ok(CloneManifest {
            source_project: project.to_string(),
            data_only,
            blobs,
            non_blob_members,
        })
    }

    /// CLONE TARGET — the per-SHA presence DIFF: for each source blob ref, re-key its member path
    /// to THIS target's own scope (`source_project` → `project`, via the SAME [`target_blob_key`]
    /// the restore uses) and check presence in the target's OWN bucket. A ref whose path is NOT
    /// under `hblob/{source_project}/` is REFUSED fail-closed — the diff is confined to the
    /// target's own scope and never trusts a source-declared path to reach a foreign key.
    ///
    /// A blob is marked present (⇒ the source will SKIP it) only on POSITIVE content-identity
    /// evidence: the target already holds an object at the re-keyed key AND either (a) both the
    /// manifest and the target carry an `etag` and they are equal (the strong content hash on
    /// S3/GCS), or (b) no etag is available on either side and the declared sizes match (the
    /// resume case on a fresh target — a present object there was written by a prior attempt of
    /// THIS clone, so same key + same size ⇒ same bytes under the content-addressed-immutable
    /// blob keyspace). Otherwise the blob is pulled and overwritten idempotently.
    ///
    // TODO(project-clone): replace the size-only fallback with a per-object content hash once the
    // at-rest-encryption × content-addressing open question (PLAN §9.1) is resolved — a
    // per-tenant-KEK-encrypted store breaks "same key ⇒ same ciphertext", so the strong-hash path
    // must be mandatory there rather than the size fallback.
    async fn diff_clone_blobs(
        &self,
        project: &str,
        source_project: &str,
        blobs: &[CloneBlobRef],
    ) -> Result<CloneSkip, Perr> {
        check_project_slug(project)?;
        check_project_slug(source_project)?;
        // DoS/OOM guard: a hostile source manifest could list an absurd number of blob refs, each
        // driving a HEAD against the target's own bucket. Cap the COUNT before the fan-out. The
        // 64 MiB manifest-body cap in the server already bounds this transitively (~2M refs max);
        // this is the explicit belt-and-suspenders bound at the driver seam.
        if blobs.len() > MAX_CLONE_MANIFEST_BLOBS {
            return Err(Perr::Other(format!(
                "clone manifest lists {} blob refs, exceeding the maximum of {MAX_CLONE_MANIFEST_BLOBS}; \
                 refusing the diff",
                blobs.len()
            )));
        }
        let mut skip = CloneSkip::default();
        for b in blobs {
            // Re-key to the target's own scope; fail-closed on a foreign/malformed path.
            let target_key = target_blob_key(&b.member_path, source_project, project)?;
            match self.blobs.head(&target_key).await {
                Ok(meta) => {
                    let present = match (&b.etag, &meta.etag) {
                        (Some(src), Some(dst)) => src == dst,
                        _ => match (b.size, meta.size) {
                            (Some(s), Some(d)) => s == d,
                            _ => false,
                        },
                    };
                    if present {
                        skip.skip_member_paths.insert(b.member_path.clone());
                    }
                }
                Err(boatramp_core::StorageError::NotFound(_)) => {} // absent ⇒ pull it
                Err(e) => return Err(other(e)),
            }
        }
        Ok(skip)
    }

    /// Enumerate every bundle member UP FRONT, in the v2 RESTORE order (identity → blobs → pg
    /// → mysql → libsql → KV), returning the ordered [`MemberSpec`] list the v2 MANIFEST
    /// declares, a per-member [`StageJob`] (how to produce each one's bytes later), and the
    /// bundle [`SourceInfo`]. Version-detects each pg/mysql DB (so the manifest can carry its
    /// provenance), lists the project's blobs + sites, and checkpoints the KV frontier for a
    /// full export — all CHEAP relative to the member bodies, which are produced one at a time
    /// by [`stage_job`](Self::stage_job) during the stream.
    async fn plan_export(
        &self,
        project: &str,
        opts: &ExportOptions,
        created_at: u64,
    ) -> Result<(Vec<MemberSpec>, HashMap<String, StageJob>, SourceInfo), Perr> {
        let data_only = opts.data_only;
        let mut ordered: Vec<(MemberSpec, StageJob)> = Vec::new();

        // --- identity transport container (`--include-identity` only) — FIRST (an adopt
        //     import must install the KEK before the KV slice). Local envelope only. ---
        if opts.include_identity {
            let transport_key = opts
                .transport_key
                .as_deref()
                .ok_or_else(|| Perr::Other("--include-identity requires a transport key".into()))?;
            match self.identity_source.as_ref() {
                Some(IdentityEnvelope::Local { kek_file }) => {
                    let kek = tokio::fs::read(kek_file).await.map_err(|e| {
                        Perr::Other(format!("reading KEK {}: {e}", kek_file.display()))
                    })?;
                    let payload = identity_payload_bytes(&kek)?;
                    let container =
                        boatramp_server::envelope::transport_wrap(&payload, transport_key)
                            .map_err(|e| {
                                Perr::Other(format!("wrapping the identity container: {e}"))
                            })?;
                    ordered.push((
                        MemberSpec::sidecar(
                            IDENTITY_MEMBER_PATH.to_string(),
                            MemberKind::Identity,
                            None,
                        ),
                        StageJob::Identity { container },
                    ));
                }
                Some(IdentityEnvelope::Vault) => {
                    return Err(Perr::Other(
                        "--include-identity is not supported for a Vault KEK: the key never \
                         leaves the KMS and cannot be bundled. For a faithful recovery, point \
                         the target node's [secrets.vault] at the same key; otherwise use \
                         --identity fresh."
                            .into(),
                    ));
                }
                Some(IdentityEnvelope::None) | None => {
                    return Err(Perr::Other(
                        "--include-identity requires a local KEK envelope \
                         ([secrets].envelope = \"local\"); none is configured on this node"
                            .into(),
                    ));
                }
            }
        }

        // Checkpoint the durable KV frontier BEFORE we enumerate (full export only), so the
        // KV slice staged later reflects a consistent frontier.
        if !data_only {
            self.deploy.checkpoint().await.map_err(other)?;
        }

        // --- blobs: enumerate the project's objects (metadata only; bodies stream later). A
        //     blob key is `hblob/{project}/…`; the member path wraps it as `blobs/{key}`
        //     (identical to the v1 layout), so the import re-keys the leading project segment
        //     to the TARGET on the way back in. ---
        let blob_metas = self
            .blobs
            .list(&blob_project_prefix(project))
            .await
            .map_err(other)?;
        for meta in blob_metas {
            let member_path = format!("blobs/{}", meta.key);
            // A blob whose KNOWN size exceeds the chunk threshold is framed ChunkedTrailer so the
            // EXPORT streams its body straight through `append_member_chunked` (O(chunk), no
            // whole-object temp — the inc2 win over inc1's stage-the-whole-blob); a small or
            // unknown-size blob stays Sidecar (inc1's staged verify-before-apply, unchanged).
            let spec = if meta.size.is_some_and(|s| s > self.chunk_size as u64) {
                MemberSpec::chunked(member_path, MemberKind::Blob, None)
            } else {
                MemberSpec::sidecar(member_path, MemberKind::Blob, None)
            };
            ordered.push((spec, StageJob::Blob { key: meta.key }));
        }

        // --- per-engine dumps (pg + mysql; managed OR external bring-your-own-URL) ---
        for (db, cfg) in &self.databases {
            let is_managed = cfg.compute.as_deref().is_some_and(|c| !c.is_empty());
            let dumpable = is_managed || !cfg.url_env.is_empty();
            // A MANAGED, DEDICATED/Single pg/mysql FULL dump is framed ChunkedTrailer → the inc2
            // streamed dump + atomic shadow-restore (Stage C/D). A `--data-only` import stays on the
            // inc1 sidecar path (default #1: FULL-restore atomicity only); an EXTERNAL
            // bring-your-own-URL binding stays sidecar (we never CREATE/RENAME/DROP databases on an
            // operator's own server); and a SHARED multi-tenant server stays sidecar (HIGH-1 / #6:
            // the per-import physical shadow db is a cross-tenant surface deferred to the temp-schema
            // follow-up). So: chunked IFF managed AND full AND not-Shared.
            let is_shared = matches!(cfg.tenant, crate::config::TenantIsolation::Shared);
            let chunked = is_managed && !data_only && !is_shared;
            if kind_is_postgres(&cfg.kind) && dumpable {
                let (conn, image, server_version_num) = self.resolve_pg(project, db, cfg).await?;
                let schema_fingerprint = self.schema_fingerprint(project, db).await;
                let pg = Some(PgMemberInfo {
                    server_version_num: server_version_num.clone(),
                    client_image: image.clone(),
                    schema_fingerprint,
                });
                let spec = if chunked {
                    MemberSpec::chunked(pg_member_path(db), MemberKind::PgDump, pg)
                } else {
                    MemberSpec::sidecar(pg_member_path(db), MemberKind::PgDump, pg)
                };
                ordered.push((
                    spec,
                    StageJob::Pg {
                        conn,
                        image,
                        data_only,
                        server_version_num,
                        no_publications: cfg.delta_capture,
                    },
                ));
            } else if kind_is_mysql(&cfg.kind) && dumpable {
                let (conn, image, version) = self.resolve_mysql(project, db, cfg).await?;
                let schema_fingerprint = self.schema_fingerprint(project, db).await;
                let pg = Some(PgMemberInfo {
                    server_version_num: version,
                    client_image: image.clone(),
                    schema_fingerprint,
                });
                let spec = if chunked {
                    MemberSpec::chunked(mysql_member_path(db), MemberKind::MysqlDump, pg)
                } else {
                    MemberSpec::sidecar(mysql_member_path(db), MemberKind::MysqlDump, pg)
                };
                ordered.push((
                    spec,
                    StageJob::Mysql {
                        conn,
                        image,
                        data_only,
                    },
                ));
            }
        }

        // --- libsql snapshots: enumerate the project's sites AUTHORITATIVELY from the deploy
        //     store (never a filesystem walk), one member per site whose embedded default DB
        //     exists on disk. ---
        if let Some(libsql) = &self.libsql {
            let sites = self
                .deploy
                .list_sites(ProjectRef::new(project))
                .await
                .map_err(other)?;
            for site in sites {
                let qsite = ProjectRef::new(project).qualified(&site);
                if !libsql.local_database_exists(&qsite, "") {
                    continue; // a site that never wrote SQL — nothing to snapshot
                }
                ordered.push((
                    // ChunkedTrailer: the libsql member is a streamed `.dump` SQL text (inc2
                    // default #4 — true O(chunk), NOT a staged VACUUM-INTO file), piped straight
                    // through `append_member_chunked`; the import applies it into an atomic shadow.
                    MemberSpec::chunked(
                        libsql_member_path(project, &site),
                        MemberKind::Libsql,
                        None,
                    ),
                    StageJob::Libsql { qsite },
                ));
            }
        }

        // --- control-plane KV slice (FULL export only) — LAST in restore order. A
        //     `--data-only` bundle carries application data ONLY, never the KV slice (RBAC,
        //     routing, personas, sealed secrets), so it is not even staged for data-only. ---
        if !data_only {
            ordered.push((
                MemberSpec::sidecar(KV_MEMBER_PATH.to_string(), MemberKind::Kv, None),
                StageJob::Kv { created_at },
            ));
        }

        let specs: Vec<MemberSpec> = ordered.iter().map(|(s, _)| s.clone()).collect();
        let jobs: HashMap<String, StageJob> =
            ordered.into_iter().map(|(s, j)| (s.path, j)).collect();
        Ok((
            specs,
            jobs,
            SourceInfo {
                project: project.to_string(),
                site: None,
            },
        ))
    }

    /// Start a producer task for a ChunkedTrailer member, returning its body-channel receiver, a
    /// `poison` flag the producer sets on error (so a premature channel close is a loud IO error,
    /// never a silently-truncated member), and its `JoinHandle` (awaited by the stager — a producer
    /// error FAILS the export). The body streams O(chunk): the libsql `.dump` (bounded by one
    /// statement) or the blob get (bounded by one chunk), NEVER staging the whole member to disk.
    fn open_chunked_producer(&self, job: Option<&StageJob>) -> Result<ChunkedProducer, Perr> {
        use std::sync::atomic::Ordering::SeqCst;
        let (body_tx, body_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(STREAM_BYTE_CHANNEL);
        let poison = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let poison2 = poison.clone();
        let handle = match job {
            Some(StageJob::Libsql { qsite }) => {
                let libsql = self.libsql.clone().ok_or_else(|| {
                    Perr::Other("internal: libsql chunked job with no libsql backend".into())
                })?;
                let qsite = qsite.clone();
                tokio::spawn(async move {
                    let r = libsql
                        .dump_database(&qsite, "", &body_tx)
                        .await
                        .map_err(other);
                    if r.is_err() {
                        poison2.store(true, SeqCst);
                    }
                    drop(body_tx); // EOF the reader AFTER the poison store
                    r
                })
            }
            Some(StageJob::Blob { key }) => {
                let blobs = self.blobs.clone();
                let key = key.clone();
                tokio::spawn(async move {
                    let r: Result<(), Perr> = async {
                        let obj = blobs.get(&key).await.map_err(other)?;
                        let mut body = obj.body;
                        while let Some(chunk) = body.next().await {
                            let chunk = chunk.map_err(other)?;
                            body_tx
                                .send(chunk.as_ref().to_vec())
                                .await
                                .map_err(|_| Perr::Other("export blob body sink closed".into()))?;
                        }
                        Ok(())
                    }
                    .await;
                    if r.is_err() {
                        poison2.store(true, SeqCst);
                    }
                    drop(body_tx);
                    r
                })
            }
            Some(StageJob::Pg {
                conn,
                image,
                server_version_num,
                no_publications,
                ..
            }) => {
                // FULL `pg_dump -Fc` stdout → body channel, NO temp (inc2 Stage C). The chunked pg
                // path is FULL-only (default #1), so `data_only` is ignored here (plan_export only
                // frames pg chunked when !data_only).
                let backend = self.require_backend()?.clone();
                let conn = conn.clone();
                let image = image.clone();
                let server_version_num = server_version_num.clone();
                let no_publications = *no_publications;
                // The chunked member is applied into a SHADOW that pre-creates the operator
                // trusted-extension allowlist, so (on PG17+) the dump can `--exclude-extension`
                // exactly those and keep every other object comment (see `pg_dump_invocation`).
                let exclude_extensions = self.trusted_extensions.clone();
                tokio::spawn(async move {
                    let mut sink = AsyncChannelWriter::new(body_tx);
                    let r: Result<(), Perr> = async {
                        let inv = pg_dump_invocation(
                            &conn,
                            false,
                            &server_version_num,
                            &exclude_extensions,
                            no_publications,
                        );
                        let code = backend
                            .run_ephemeral(&image, &inv.argv, &inv.env, None, &mut sink)
                            .await
                            .map_err(other)?;
                        if code != 0 {
                            return Err(Perr::Other(format!("pg_dump exited {code}")));
                        }
                        Ok(())
                    }
                    .await;
                    // Set poison BEFORE closing the sink, so a short/failed dump becomes a loud IO
                    // error at the reader (never a valid trailer over an incomplete member).
                    if r.is_err() {
                        poison2.store(true, SeqCst);
                    }
                    drop(sink); // closes the PollSender → body_rx EOF, after the poison store
                    r
                })
            }
            Some(StageJob::Mysql { conn, image, .. }) => {
                // Tables-only FULL `mysqldump` stdout → body channel, NO temp (inc2 Stage D).
                let backend = self.require_backend()?.clone();
                let conn = conn.clone();
                let image = image.clone();
                tokio::spawn(async move {
                    let mut sink = AsyncChannelWriter::new(body_tx);
                    let r: Result<(), Perr> = async {
                        let inv = mysqldump_tables_only_invocation(&conn);
                        let code = backend
                            .run_ephemeral(&image, &inv.argv, &inv.env, None, &mut sink)
                            .await
                            .map_err(other)?;
                        if code != 0 {
                            return Err(Perr::Other(format!("mysqldump exited {code}")));
                        }
                        Ok(())
                    }
                    .await;
                    if r.is_err() {
                        poison2.store(true, SeqCst);
                    }
                    drop(sink);
                    r
                })
            }
            _ => {
                return Err(Perr::Other(
                    "export: chunked framing is wired only for pg/mysql, libsql + large blobs"
                        .into(),
                ));
            }
        };
        Ok((body_rx, poison, handle))
    }

    /// Produce ONE member's bytes into a bounded staging temp (`stage_dir/m{idx}`), returning
    /// its path. The v2 writer appends the temp then deletes it immediately, so at most one
    /// member is ever staged on disk (the O(largest-member) footprint).
    async fn stage_job(
        &self,
        project: &str,
        job: &StageJob,
        stage_dir: &Path,
        idx: usize,
    ) -> Result<PathBuf, Perr> {
        let tmp = stage_dir.join(format!("m{idx}"));
        match job {
            StageJob::Identity { container } => {
                tokio::fs::write(&tmp, container).await.map_err(other)?;
            }
            StageJob::Kv { created_at } => {
                // Scope the control-plane KV slice to THIS project (C1 cross-tenant isolation):
                // keep ONLY the project's owned keyspace + the site-config bodies it references,
                // dropping every other tenant's material and the global TLS/routing/daemon keys
                // (fail-closed).
                let all = boatramp_core::kv_dump::scan_dumpable(self.kv.as_ref())
                    .await
                    .map_err(other)?;
                let scoped = boatramp_core::project_export::scope_entries_to_project(
                    all,
                    ProjectRef::new(project),
                );
                let kv_bytes = boatramp_core::kv_dump::encode_dump(&scoped, *created_at);
                tokio::fs::write(&tmp, &kv_bytes).await.map_err(other)?;
            }
            StageJob::Pg {
                conn,
                image,
                data_only,
                server_version_num,
                no_publications,
            } => {
                // SIDECAR (data-only, Shared, or external bring-your-own-URL): the restore applies
                // the dump's OWN `CREATE EXTENSION` (we never pre-create extensions on a non-shadow
                // target), so pass an EMPTY exclude list — this keeps the conservative
                // `--no-comments` regardless of server version (see `pg_dump_invocation`).
                let inv =
                    pg_dump_invocation(conn, *data_only, server_version_num, &[], *no_publications);
                let code = self
                    .run_sql_client(image, &inv.argv, &inv.env, None, &tmp)
                    .await?;
                if code != 0 {
                    return Err(Perr::Other(format!("pg_dump exited {code}")));
                }
            }
            StageJob::Mysql {
                conn,
                image,
                data_only,
            } => {
                let inv = mysqldump_invocation(conn, *data_only);
                let code = self
                    .run_sql_client(image, &inv.argv, &inv.env, None, &tmp)
                    .await?;
                if code != 0 {
                    return Err(Perr::Other(format!("mysqldump exited {code}")));
                }
            }
            StageJob::Libsql { qsite } => {
                let libsql = self.libsql.as_ref().ok_or_else(|| {
                    Perr::Other("internal error: libsql stage job with no libsql backend".into())
                })?;
                libsql.snapshot_into(qsite, "", &tmp).await.map_err(other)?;
            }
            StageJob::Blob { key } => {
                // Stream the object from the source store straight into the temp — never
                // buffer the whole object in memory.
                let obj = self.blobs.get(key).await.map_err(other)?;
                let mut body = obj.body;
                let mut f = tokio::fs::File::create(&tmp).await.map_err(other)?;
                use tokio::io::AsyncWriteExt as _;
                while let Some(chunk) = body.next().await {
                    let chunk = chunk.map_err(other)?;
                    f.write_all(chunk.as_ref()).await.map_err(other)?;
                }
                f.flush().await.map_err(other)?;
            }
            StageJob::KvDelta { bytes }
            | StageJob::BlobTombstone { bytes }
            | StageJob::PgWalDelta { bytes }
            | StageJob::MysqlBinlogDelta { bytes }
            | StageJob::LibsqlChangeset { bytes } => {
                // A delta member whose bytes were computed + encoded at plan time (the KV
                // upserts+tombstones / the blob tombstone key list / the drained + framed
                // pgoutput WAL change stream / the framed raw mysql binlog / the framed libsql
                // changeset). Just persist them.
                tokio::fs::write(&tmp, bytes).await.map_err(other)?;
            }
        }
        Ok(tmp)
    }

    /// Restore ONE streamed member (already staged at `temp`) into the TARGET `project`,
    /// routed by `spec.kind`. Mutates `report`; tracks whether an identity member has been
    /// seen (`saw_identity`) so an `adopt` import can be refused before the KV slice is
    /// written if the bundle carries no identity.
    #[allow(clippy::too_many_arguments)]
    async fn restore_member(
        &self,
        project: &str,
        data_only: bool,
        source_project: &str,
        spec: &MemberSpec,
        temp: &Path,
        opts: &ImportOptions,
        report: &mut ImportReport,
        saw_identity: &mut bool,
    ) -> Result<(), Perr> {
        match spec.kind {
            MemberKind::Identity => {
                *saw_identity = true;
                match &opts.identity {
                    IdentityChoice::Adopt { transport_key } => {
                        match self.identity_source.as_ref() {
                            Some(IdentityEnvelope::Local { kek_file }) => {
                                let container = tokio::fs::read(temp).await.map_err(other)?;
                                let payload = boatramp_server::envelope::transport_unwrap(
                                    &container,
                                    transport_key,
                                )
                                .map_err(|e| {
                                    Perr::Other(format!(
                                        "opening the identity container (wrong transport key?): {e}"
                                    ))
                                })?;
                                let kek = parse_identity_payload(&payload)?;
                                // No-clobber: never adopt OVER a different live KEK.
                                match tokio::fs::read(kek_file).await {
                                    Ok(existing) if existing != kek => {
                                        return Err(Perr::Other(format!(
                                            "refusing to adopt: this node already holds a DIFFERENT \
                                         KEK at {} — adopt is for recovery onto a fresh node; use \
                                         --identity fresh to import into a different environment",
                                            kek_file.display()
                                        )));
                                    }
                                    Ok(_) => { /* identical KEK already present — idempotent */ }
                                    Err(_) => {
                                        if opts.apply {
                                            write_kek_file(kek_file, &kek).await?;
                                        }
                                    }
                                }
                                report
                                    .notes
                                    .push("identity: adopted the source KEK (recovery)".into());
                            }
                            Some(IdentityEnvelope::Vault) | Some(IdentityEnvelope::None) | None => {
                                return Err(Perr::Other(
                                "--identity adopt installs a local KEK from the bundle, but this \
                                 node's secrets envelope is not local; for a Vault recovery point \
                                 [secrets.vault] at the same key, or use --identity fresh"
                                    .into(),
                            ));
                            }
                        }
                    }
                    IdentityChoice::Fresh => {
                        report.notes.push(
                            "identity: bundle carries an identity member, but --identity fresh \
                             was selected; the source KEK was NOT installed"
                                .into(),
                        );
                    }
                }
            }
            MemberKind::Blob => {
                // RE-QUALIFY to the TARGET project's scope, FAIL-CLOSED — the tenancy-critical
                // seam. Every imported object lands under `hblob/{project}/`; a wrong-scope
                // member is refused, so no source-scope (or other-tenant) key can survive a
                // rename.
                let target_key = target_blob_key(&spec.path, source_project, project)?;
                report.blobs += 1;
                if opts.apply {
                    // Stream the staged member into the target key via the `Storage::put`
                    // byte-stream path (reuses `FsStorage`'s streaming get) — the whole blob is
                    // never buffered in memory.
                    let staged_dir = temp.parent().ok_or_else(|| {
                        Perr::Other("blob staging temp has no parent directory".into())
                    })?;
                    let staged_name = temp
                        .file_name()
                        .and_then(|n| n.to_str())
                        .ok_or_else(|| Perr::Other("blob staging temp has no file name".into()))?;
                    let staged = boatramp_storage::FsStorage::new(staged_dir);
                    let obj = staged.get(staged_name).await.map_err(other)?;
                    self.blobs
                        .put(
                            &target_key,
                            obj.body,
                            boatramp_core::PutMeta { content_type: None },
                        )
                        .await
                        .map_err(other)?;
                }
            }
            MemberKind::PgDump => {
                let db = db_from_pg_member(&spec.path)
                    .ok_or_else(|| Perr::Other(format!("bad pg member path {:?}", spec.path)))?;
                let cfg = self.databases.get(db).ok_or_else(|| {
                    Perr::Other(format!("import: no database named {db:?} on this node"))
                })?;
                let (conn, image, _ver) = self.resolve_pg(project, db, cfg).await?;
                if data_only {
                    let src_fp = spec.pg.as_ref().and_then(|p| p.schema_fingerprint.clone());
                    let tgt_fp = self.schema_fingerprint(project, db).await;
                    if data_only_skew_blocks(src_fp.as_deref(), tgt_fp.as_deref()) {
                        report.schema_skew.push(db.to_string());
                        if !opts.allow_schema_skew {
                            return Err(Perr::SchemaSkew(vec![db.to_string()]));
                        }
                    }
                }
                if opts.apply {
                    // HIGH-1: a SIDECAR pg member (data-only, or a Shared/dedicated FULL that was not
                    // chunked) is still ATTACKER-CRAFTED. Applying it via `resolve_pg` would connect
                    // as the configured user, which on a MANAGED co-located server is the BOOTSTRAP
                    // SUPERUSER — a crafted archive's `COPY … TO PROGRAM` / `CREATE FUNCTION … LANGUAGE
                    // c` / `CREATE EXTENSION` would then execute = RCE. The chunked FULL path confines
                    // this with an ephemeral non-superuser role + shadow; a least-privilege sidecar
                    // apply (data-only into a live schema) is the follow-up, so until it lands we
                    // REFUSE a managed sidecar apply fail-closed rather than apply as superuser. An
                    // EXTERNAL bring-your-own-URL binding applies with the OPERATOR'S OWN credential
                    // against the OPERATOR'S OWN database (their trust boundary, not our managed
                    // cluster), so it is still applied.
                    //
                    // DO NOT relax this on the reasoning "data-only carries no DDL, so it's safe": the
                    // confinement is NON-SUPERUSER-APPLY, not DDL-inspection. `data_only` here is an
                    // UNTRUSTED MANIFEST FLAG (the bundle is attacker-crafted) — it does NOT constrain
                    // the member's bytes, which the `pg_restore` run executes verbatim. An attacker
                    // sets `data_only: true` and ships a member full of superuser escapes; trusting the
                    // flag to skip the shadow/non-superuser path reintroduces the exact RCE. The only
                    // safe enablement is a real least-privilege sidecar apply (an ephemeral
                    // non-superuser role, as the chunked path mints) — which raises OPEN owner
                    // decisions (its grant surface on LIVE tenant tables, FK/trigger ordering without
                    // superuser, non-atomic partial-apply semantics). Until those are settled, refuse.
                    if is_managed_binding(cfg) {
                        return Err(Perr::Unavailable(format!(
                            "import refused: a MANAGED pg database ({db:?}) can only be restored via \
                             the atomic chunked shadow path (a FULL, dedicated/Single bundle). A \
                             data-only or Shared sidecar restore would apply the untrusted dump as \
                             the bootstrap superuser (RCE risk); a least-privilege sidecar apply is a \
                             pending follow-up. Re-export as a FULL dedicated bundle, or import into \
                             an external (bring-your-own-URL) binding."
                        )));
                    }
                    let inv = pg_restore_invocation(&conn, data_only);
                    // Capture stderr (where pg_restore reports a failed object) into the stdout
                    // sink via `sh -c '… 2>&1'`, so a failed EXTERNAL restore is diagnosable
                    // instead of a causeless "exited N" (run_ephemeral drops stderr on nonzero).
                    let merged = merge_stderr_argv(&inv.argv);
                    let outfile = temp.with_extension("restore.out");
                    let code = self
                        .run_sql_client(&image, &merged, &inv.env, Some(temp), &outfile)
                        .await?;
                    if code != 0 {
                        let diag = tokio::fs::read_to_string(&outfile)
                            .await
                            .unwrap_or_default();
                        let _ = tokio::fs::remove_file(&outfile).await;
                        return Err(Perr::Other(format!(
                            "pg_restore for {db:?} exited {code}: {}",
                            diag.trim()
                        )));
                    }
                    let _ = tokio::fs::remove_file(&outfile).await;
                }
                report.pg_databases += 1;
            }
            MemberKind::MysqlDump => {
                let db = db_from_mysql_member(&spec.path)
                    .ok_or_else(|| Perr::Other(format!("bad mysql member path {:?}", spec.path)))?;
                let cfg = self.databases.get(db).ok_or_else(|| {
                    Perr::Other(format!("import: no database named {db:?} on this node"))
                })?;
                let (conn, image, _ver) = self.resolve_mysql(project, db, cfg).await?;
                if data_only {
                    let src_fp = spec.pg.as_ref().and_then(|p| p.schema_fingerprint.clone());
                    let tgt_fp = self.schema_fingerprint(project, db).await;
                    if data_only_skew_blocks(src_fp.as_deref(), tgt_fp.as_deref()) {
                        report.schema_skew.push(db.to_string());
                        if !opts.allow_schema_skew {
                            return Err(Perr::SchemaSkew(vec![db.to_string()]));
                        }
                    }
                }
                if opts.apply {
                    // HIGH-1 (mirror of the pg sidecar arm): refuse a MANAGED sidecar mysql apply —
                    // it would connect as the bootstrap superuser against our co-located server. An
                    // EXTERNAL binding applies with the operator's own credential (their trust).
                    if is_managed_binding(cfg) {
                        return Err(Perr::Unavailable(format!(
                            "import refused: a MANAGED mysql database ({db:?}) can only be restored \
                             via the atomic chunked shadow path (a FULL, dedicated/Single bundle); a \
                             data-only/Shared sidecar restore would apply the untrusted dump as a \
                             superuser (RCE risk). Re-export as a FULL dedicated bundle, or import \
                             into an external binding."
                        )));
                    }
                    let inv = mysql_restore_invocation(&conn, data_only);
                    // Capture the mysql client's stderr (a failed statement's error) via
                    // `sh -c '… 2>&1'` so a failed EXTERNAL restore is diagnosable, not a
                    // causeless "exited N" (run_ephemeral drops stderr on nonzero).
                    let merged = merge_stderr_argv(&inv.argv);
                    let outfile = temp.with_extension("myrestore.out");
                    let code = self
                        .run_sql_client(&image, &merged, &inv.env, Some(temp), &outfile)
                        .await?;
                    if code != 0 {
                        let diag = tokio::fs::read_to_string(&outfile)
                            .await
                            .unwrap_or_default();
                        let _ = tokio::fs::remove_file(&outfile).await;
                        return Err(Perr::Other(format!(
                            "mysql restore for {db:?} exited {code}: {}",
                            diag.trim()
                        )));
                    }
                    let _ = tokio::fs::remove_file(&outfile).await;
                }
                report.pg_databases += 1;
            }
            MemberKind::Libsql => {
                let Some(libsql) = &self.libsql else {
                    return Err(Perr::Unavailable(
                        "bundle carries libsql members but this node has no local libsql backend \
                         to restore them into"
                            .into(),
                    ));
                };
                let site = site_from_libsql_member(&spec.path).ok_or_else(|| {
                    Perr::Other(format!("bad libsql member path {:?}", spec.path))
                })?;
                let qsite = ProjectRef::new(project).qualified(site);
                if opts.apply {
                    // Sidecar libsql (a v1/v2 VACUUM-INTO member) → atomic shadow+rename,
                    // overwrite-gated. A v3 chunked libsql member takes the streamed-shadow path in
                    // the servicer, never this arm.
                    libsql
                        .restore_snapshot(&qsite, "", temp, opts.overwrite)
                        .await
                        .map_err(other)?;
                }
                report.libsql_databases += 1;
            }
            MemberKind::Kv => {
                if data_only {
                    // A data-only bundle should not carry a KV slice; ignore one if present
                    // (the post-stream note records that KV is not imported for data-only).
                    return Ok(());
                }
                // `adopt` must have installed the source KEK (from an identity member that
                // precedes the KV slice in v2 restore order) BEFORE any sealed KV byte is
                // written — otherwise the sealed secrets could never unseal. Refuse here,
                // fail-closed, if adopt was requested without an identity member.
                if matches!(opts.identity, IdentityChoice::Adopt { .. }) && !*saw_identity {
                    return Err(Perr::Other(
                        "--identity adopt requires a bundle exported with --include-identity \
                         (no identity member present); use --identity fresh to import a bundle \
                         without identity"
                            .into(),
                    ));
                }
                let bytes = tokio::fs::read(temp).await.map_err(other)?;
                let mut decoded = boatramp_core::kv_dump::decode_dump(&bytes).map_err(other)?;
                // Re-qualify the control-plane slice to the TARGET project (matches the blob +
                // libsql re-qualification), so a project-rename import lands every owned key in
                // the target's scope — and the --fresh drop (keyed on the target) removes the
                // right sealed keys rather than nothing.
                boatramp_core::project_export::rekey_entries_to_target(
                    &mut decoded.entries,
                    source_project,
                    project,
                );
                // HIGH-1: SYMMETRIC, FAIL-CLOSED tenancy enforcement on the trust boundary —
                // the mirror of the export-side scope filter. After re-key, EVERY surviving key
                // MUST be under the target's owned prefixes (the one exception is a referenced,
                // content-verified `siteconfig/<hash>`); anything else (another tenant's
                // `project/…`, a global `cert/`/`domain/`/`wildcard/`, a node `daemonconfig/`, a
                // reserved `_cp/`/`_inval/`, or a poisoned siteconfig) ABORTS the import — a
                // crafted bundle must never write node-wide outside the target's scope.
                boatramp_core::project_export::enforce_target_scoped_kv(
                    &decoded.entries,
                    ProjectRef::new(project),
                )
                .map_err(Perr::Other)?;
                if opts.apply {
                    match boatramp_core::kv_dump::apply_import(
                        self.kv.as_ref(),
                        &decoded.entries,
                        opts.force,
                    )
                    .await
                    {
                        Ok(rep) => {
                            report.kv_records = rep.written;
                            report.kv_verified = rep.verified;
                        }
                        Err(boatramp_core::kv_dump::ImportError::Commingle(_)) => {
                            return Err(Perr::Commingle(
                                "control-plane KV import refused a non-empty destination; \
                                 re-run with --force to overlay it"
                                    .into(),
                            ));
                        }
                        Err(e) => return Err(other(e)),
                    }
                } else {
                    let plan = boatramp_core::kv_dump::plan_import(
                        self.kv.as_ref(),
                        &decoded.entries,
                        opts.force,
                    )
                    .await
                    .map_err(other)?;
                    report.kv_records = plan.would_write;
                }
            }
            MemberKind::KvDelta => {
                // The control-plane KV DELTA slice (a delta bundle only): the upserts + tombstones
                // since the base. A data-only bundle carries no KV, so ignore one if present.
                if data_only {
                    return Ok(());
                }
                // adopt must have installed the source KEK before any sealed KV byte is written
                // (same ordering invariant as the full `Kv` arm).
                if matches!(opts.identity, IdentityChoice::Adopt { .. }) && !*saw_identity {
                    return Err(Perr::Other(
                        "--identity adopt requires a bundle exported with --include-identity \
                         (no identity member present); use --identity fresh"
                            .into(),
                    ));
                }
                let bytes = tokio::fs::read(temp).await.map_err(other)?;
                let delta = boatramp_core::project_delta::decode_kv_delta(&bytes).map_err(other)?;

                // UPSERTS: re-key to the TARGET project + the SAME fail-closed tenancy enforcement
                // as a full KV slice (the upserts are attacker-influenceable — a delta crosses the
                // same trust boundary — so they must be target-scoped before any write).
                let mut upserts = delta.upserts;
                boatramp_core::project_export::rekey_entries_to_target(
                    &mut upserts,
                    source_project,
                    project,
                );
                boatramp_core::project_export::enforce_target_scoped_kv(
                    &upserts,
                    ProjectRef::new(project),
                )
                .map_err(Perr::Other)?;

                // TOMBSTONES: a deleted key is equally attacker-influenceable; a tombstone that
                // escaped the target's owned scope would be a CROSS-TENANT DELETE. Re-key each then
                // REFUSE fail-closed any key not under the target's owned prefixes.
                let mut delete_keys = Vec::with_capacity(delta.tombstones.len());
                for k in &delta.tombstones {
                    let rk =
                        boatramp_core::project_export::rekey_owned_key(k, source_project, project);
                    if !boatramp_core::project_export::project_owns_key(
                        &rk,
                        ProjectRef::new(project),
                    ) {
                        return Err(Perr::Other(format!(
                            "control-plane KV delta import refused: tombstone {k:?} is outside the \
                             target project {project}'s owned scope after re-key — a delta must not \
                             delete another tenant's or a global (routing / TLS / daemon) key"
                        )));
                    }
                    delete_keys.push(rk);
                }

                if opts.apply {
                    // A delta OVERLAYS the already-restored base, so the KV dest is non-pristine by
                    // design — force the overlay (the base restore enforced the fresh-target gate).
                    match boatramp_core::kv_dump::apply_import(self.kv.as_ref(), &upserts, true)
                        .await
                    {
                        Ok(rep) => {
                            report.kv_records += rep.written;
                            report.kv_verified += rep.verified;
                        }
                        Err(e) => return Err(other(e)),
                    }
                    for k in &delete_keys {
                        self.kv.delete_checkpointed(k).await.map_err(other)?;
                    }
                } else {
                    report.kv_records += upserts.len();
                }
                report.notes.push(format!(
                    "kv delta: {} upsert(s), {} tombstone(s)",
                    upserts.len(),
                    delete_keys.len()
                ));
            }
            MemberKind::BlobTombstone => {
                // The blob tombstone list (a delta bundle only): blob storage keys deleted since
                // the base. Each key is stored under the SOURCE scope (`hblob/<source>/…`); re-key
                // to the target + REFUSE fail-closed any wrong-scope key (cross-tenant delete),
                // reusing the same `blobs/`-prefixed re-qualify the add path uses.
                let bytes = tokio::fs::read(temp).await.map_err(other)?;
                let keys =
                    boatramp_core::project_delta::decode_blob_tombstones(&bytes).map_err(other)?;
                let mut deleted = 0u64;
                for storage_key in &keys {
                    let target_key =
                        target_blob_key(&format!("blobs/{storage_key}"), source_project, project)?;
                    if opts.apply {
                        self.blobs.delete(&target_key).await.map_err(other)?;
                    }
                    deleted += 1;
                }
                report
                    .notes
                    .push(format!("blob delta: {deleted} tombstone(s)"));
            }
            // SQL TRUE-delta members (the SQL true-delta program, PLAN-sql-true-delta.md). The pg
            // WAL true-delta is REPLAYED onto the restored base inside the atomic shadow by
            // `restore_pg_true_delta_in_chain` (the delta-chain import SKIPS a managed `PgWalDelta`
            // here and hands it to that pass). So this arm is reached ONLY by a path that does not
            // run the shadow pass — a `PgWalDelta` in a non-delta bundle, a non-managed pg binding,
            // or the (unbuilt) mysql binlog / libsql changeset engines — all of which this build
            // cannot faithfully restore, so it refuses loudly (never a silent/partial restore).
            MemberKind::PgWalDelta | MemberKind::MysqlBinlogDelta | MemberKind::LibsqlChangeset => {
                return Err(Perr::Other(format!(
                    "this build cannot restore a SQL true-delta member ({:?}) here — a pg WAL delta \
                     is replayed only via the managed-pg atomic-shadow chain restore; the {} replay \
                     engine is not available on this path (SQL true-delta program)",
                    spec.kind,
                    match spec.kind {
                        MemberKind::PgWalDelta => "Postgres WAL (non-managed/non-chain)",
                        MemberKind::MysqlBinlogDelta => "MySQL binlog",
                        _ => "libsql changeset",
                    }
                )));
            }
        }
        Ok(())
    }

    // -----------------------------------------------------------------------
    // T3 Phase 1 — resumable, chained export (member-object layout)
    //
    // The default export streams a single tar to a forward-only `AsyncWrite` sink, so an
    // interrupted export restarts from scratch. The resumable mode lays the SAME members
    // out as one object per member under a local directory, each written atomically with
    // its size+SHA, so a re-run RESUMES: an already-complete member is skipped (presence +
    // SHA), a partial one is re-produced. Import reads the directory and restores member by
    // member in the MANIFEST's authoritative order, reusing the SAME per-member producers
    // (`stage_job` / `open_chunked_producer`) and restorer (`restore_member`) as the tar
    // path — so the per-project tenancy scoping is byte-for-byte identical and unweakened:
    // the KV slice's `scope_entries_to_project` lives in `stage_job`, and the import
    // re-key / target-scope enforcement lives in `restore_member`. This mode adds NO new
    // data path to a tenant's bytes; it only changes the CONTAINER (a dir of objects).
    //
    // HONEST LIMIT: resume is per-MEMBER, not intra-member — a huge single pg_dump redumps
    // on resume. The win is a many-member export (thousands of blobs, many sites) and
    // surviving a drop BETWEEN members. (An S3-multipart target + byte-range intra-member
    // resume are Phase 2; a delta-onto-a-base export is a separate follow-on program.)

    /// Resumable export to a local directory `dir` (member-object layout). Writes — or, on
    /// resume, reads — an authoritative `MANIFEST`, then one object per member, skipping any
    /// already present + SHA-valid. `dir` is on the NODE's filesystem (a persistent/mounted
    /// path), so a resume actually avoids re-producing the expensive members.
    /// Core resumable export to an ALREADY-CONFINED absolute `dir` (the trait method
    /// [`ProjectExport::export_resumable`] confines an operator-named subdir under the
    /// configured base, then calls this). See the member-object layout + per-member resume
    /// in the body.
    pub async fn export_resumable_dir(
        &self,
        project: &str,
        opts: &ExportOptions,
        dir: &Path,
    ) -> Result<(), Perr> {
        check_project_slug(project)?;
        if opts.data_only && opts.include_identity {
            return Err(Perr::Other(
                "--data-only and --include-identity are mutually exclusive".into(),
            ));
        }
        tokio::fs::create_dir_all(dir).await.map_err(other)?;
        let created_at = now_secs();
        let session = self
            .work_dir
            .join(format!("export-res-{project}-{created_at}"));
        let stage_dir = session.join("stage");
        tokio::fs::create_dir_all(&stage_dir).await.map_err(other)?;

        // PLAN: a FULL export reuses `plan_export`; a DELTA export (`opts.delta`) diffs the
        // current state against the base chain's frontier and emits delta members (KV delta +
        // blob adds/tombstones + SQL full-dump fallback). Both return the ordered member set, the
        // per-member jobs, the source, and — for a delta — the `DeltaInfo` the manifest records.
        let (specs, jobs, source, delta_info) = match &opts.delta {
            None => {
                let (s, j, src) = self.plan_export(project, opts, created_at).await?;
                (s, j, src, None)
            }
            Some(req) => {
                let (s, j, src, di) = self
                    .plan_delta_export(project, opts, req, created_at)
                    .await?;
                (s, j, src, Some(di))
            }
        };

        // The MANIFEST is AUTHORITATIVE. First run: write it. Resume: read it and use ITS
        // member set (members added since are ignored; nothing not in it can be produced) —
        // strict, MANIFEST-wins. Refuse a dir that already holds another project's manifest.
        let manifest_path = dir.join(project_bundle::MANIFEST_PATH);
        let specs = if tokio::fs::try_exists(&manifest_path).await.map_err(other)? {
            let bytes = tokio::fs::read(&manifest_path).await.map_err(other)?;
            let m: project_bundle::StreamManifest = serde_json::from_slice(&bytes)
                .map_err(|e| Perr::Other(format!("read resumable MANIFEST: {e}")))?;
            if m.source.project != source.project {
                return Err(Perr::Other(format!(
                    "resumable export dir holds a MANIFEST for project {:?}, not {:?} — \
                     refusing to mix projects in one dir",
                    m.source.project, source.project
                )));
            }
            m.members
        } else {
            let m = project_bundle::StreamManifest {
                magic: project_bundle::BUNDLE_MAGIC.to_string(),
                format_version: project_bundle::BUNDLE_FORMAT_VERSION_V3,
                created_at,
                data_only: opts.data_only,
                source: source.clone(),
                members: specs.clone(),
                delta: delta_info,
            };
            let bytes = serde_json::to_vec_pretty(&m)
                .map_err(|e| Perr::Other(format!("encode MANIFEST: {e}")))?;
            write_atomic(&manifest_path, &bytes).await?;
            specs
        };

        // SQL true-delta capture (PLAN-sql-true-delta Stage 2): a BASE (full) resumable export of a
        // `delta_capture` managed pg db mints the capture's ephemeral REPLICATION role + the
        // `FOR ALL TABLES` publication NOW (before the slot's consistent point). The pgoutput SLOT
        // itself is created LATER, SNAPSHOT-PINNED, by `produce_pg_capture_base` in the member loop,
        // over a held `replication=database` session across `pg_dump --snapshot` — so the base dump
        // and the slot share one consistent point and the base↔WAL overlap window is CLOSED. A delta
        // export (`opts.delta`) does not create slots; it drains the PARENT's slot (see
        // `plan_delta_export`).
        if opts.delta.is_none() {
            self.pg_capture_base_slots(project, dir, &stage_dir).await;
        }

        // Produce each member that is not already complete.
        for (idx, spec) in specs.iter().enumerate() {
            let obj = dir.join(member_object_name(idx));
            let meta = dir.join(member_meta_name(idx));
            if member_object_valid(&obj, &meta).await? {
                continue; // resume: already produced + SHA-valid.
            }
            // Clear any stale partial before re-producing.
            let _ = tokio::fs::remove_file(&obj).await;
            let _ = tokio::fs::remove_file(dir.join(member_part_name(idx))).await;
            // SQL true-delta (mysql binlog, PLAN-sql-true-delta Stage 3): a BASE (full) resumable
            // export of a capture-eligible managed mysql db dumps it SNAPSHOT-PINNED (`--source-data`,
            // SQL_LOG_BIN stripped) so a later incremental delta can stream the binlog since the
            // base's recorded GTID. Produced specially (staged + stripped) regardless of the spec's
            // framing — in the resumable layout every member is one `m{idx}` object, so framing is
            // irrelevant here. A delta export (`opts.delta`) keeps the normal production (it drains
            // the parent's binlog at plan time, see `plan_delta_export`).
            let capture_base_mysql = opts.delta.is_none()
                && spec.kind == MemberKind::MysqlDump
                && db_from_mysql_member(&spec.path)
                    .and_then(|d| self.databases.get(d))
                    .is_some_and(Self::mysql_capture_eligible);
            // SQL true-delta (pg WAL, PLAN-sql-true-delta Stage 2): a BASE export of a
            // capture-eligible managed pg db dumps it SNAPSHOT-PINNED to its just-created capture
            // slot (close the base↔WAL overlap window) — produced specially regardless of the spec's
            // framing (every resumable member is one `m{idx}` object). A delta export keeps the
            // normal production (it drains the parent's slot at plan time).
            let capture_base_pg = opts.delta.is_none()
                && spec.kind == MemberKind::PgDump
                && db_from_pg_member(&spec.path)
                    .and_then(|d| self.databases.get(d))
                    .is_some_and(Self::pg_capture_eligible);
            let digest = if capture_base_mysql {
                let db = db_from_mysql_member(&spec.path).expect("mysql member path");
                let cfg = self.databases.get(db).expect("capture-eligible db").clone();
                self.produce_mysql_capture_base(project, dir, idx, db, &cfg, &stage_dir)
                    .await?
            } else if capture_base_pg {
                let db = db_from_pg_member(&spec.path).expect("pg member path");
                let cfg = self.databases.get(db).expect("capture-eligible db").clone();
                self.produce_pg_capture_base(project, dir, idx, db, &cfg, &stage_dir)
                    .await?
            } else {
                let job = jobs.get(&spec.path);
                match spec.framing {
                    project_bundle::MemberFraming::Sidecar => {
                        let job = job.ok_or_else(|| {
                            Perr::Other(format!("resumable export: no stage job for {}", spec.path))
                        })?;
                        let tmp = self.stage_job(project, job, &stage_dir, idx).await?;
                        let d = write_member_from_file(dir, idx, &tmp).await?;
                        let _ = tokio::fs::remove_file(&tmp).await;
                        d
                    }
                    project_bundle::MemberFraming::ChunkedTrailer => {
                        let producer = self.open_chunked_producer(job)?;
                        write_member_from_producer(dir, idx, producer).await?
                    }
                }
            };
            let meta_bytes = serde_json::to_vec(&digest)
                .map_err(|e| Perr::Other(format!("encode member meta: {e}")))?;
            write_atomic(&meta, &meta_bytes).await?;
        }

        // SQL true-delta capture (mysql binlog, PLAN-sql-true-delta Stage 3): a BASE export records
        // the snapshot GTID + start binlog of each capture-eligible managed mysql db in
        // `mysql_capture.json` (parsed from the just-produced base member headers), so a later
        // incremental delta can stream the binlog since the base. (The mysql analogue of
        // `pg_capture_base_slots` — but AFTER member production, because the coordinate lives in the
        // base dump itself; there is no long-lived slot to create beforehand.)
        if opts.delta.is_none() {
            self.mysql_capture_base_gtids(project, dir, &specs).await;
        }

        // SQL true-delta capture (libsql changeset, SQL true-delta program, Stage 4): snapshot every
        // local libsql site's DB into `libsql_capture/` + record its sha in `libsql_capture.json`.
        // Run on BOTH base AND delta exports (unlike pg/mysql) so a FIXED base snapshot is always
        // available to diff against (differential, vs the root) AND each delta leaves a fresh snapshot
        // for the next link (incremental). Best-effort: a site that fails to snapshot simply
        // full-dumps at the next delta. Feature-gated — off builds never capture (today's behaviour).
        #[cfg(feature = "sql-delta-libsql")]
        self.libsql_capture_base_snapshots(project, dir).await;

        let _ = tokio::fs::remove_dir_all(&session).await;
        Ok(())
    }

    // -----------------------------------------------------------------------
    // Incremental / delta export (follow-on program; owner-RESOLVED 2026-10-25)
    //
    // A DELTA export reuses the resumable member-object layout + per-member resume, but its
    // member SET is the DIFF against a referenced base: only the KV upserts/tombstones and the
    // changed/new blobs (+ blob tombstones) ride, while the SQL families full-dump as the
    // all-families-consistent fallback (decision 3) until their true-deltas land (decisions 1/2,
    // scaffolded in `boatramp_core::project_delta`). `--mode differential` diffs vs a FIXED base;
    // `--mode incremental` diffs vs the parent (a chain). Restore resolves the chain and applies
    // base → each delta in order (decision 5). The pure diff/replay algebra lives in core; this
    // driver wires it to the live KV scan + blob store + the base chain's member objects.
    // -----------------------------------------------------------------------

    /// Plan a DELTA export: resolve the base/parent chain, replay its frontier (KV key→value +
    /// blob key→{size,sha}), diff the CURRENT state against it, and emit the delta member set — a
    /// KV delta member (upserts + tombstones), the new/changed blobs as full members
    /// (adds-as-full-members), a blob-tombstone member for deletes, and the SQL families as FULL
    /// dumps (the all-families-consistent fallback). Returns the ordered specs, the per-member
    /// jobs, the source, and the `DeltaInfo` the manifest records.
    async fn plan_delta_export(
        &self,
        project: &str,
        opts: &ExportOptions,
        req: &boatramp_core::project_delta::DeltaRequest,
        created_at: u64,
    ) -> Result<
        (
            Vec<MemberSpec>,
            HashMap<String, StageJob>,
            SourceInfo,
            boatramp_core::project_delta::DeltaInfo,
        ),
        Perr,
    > {
        use boatramp_core::project_delta as pd;

        if opts.data_only {
            return Err(Perr::Other(
                "delta export is not supported for a --data-only bundle (a delta carries the \
                 control-plane KV delta, which a data-only bundle excludes)"
                    .into(),
            ));
        }
        if opts.include_identity {
            return Err(Perr::Other(
                "delta export does not carry the identity transport container; include identity \
                 only in the FULL base bundle (import it with --identity adopt), then chain deltas"
                    .into(),
            ));
        }

        // Resolve the base/parent resumable dir (confined under the node base) + walk its chain to
        // the ROOT full bundle. Differential requires a FULL base; incremental may chain a delta.
        let base_dir = self
            .resolve_resumable_dir(&req.base_reference, false)
            .await?;
        let base_manifest = self.read_resumable_manifest(&base_dir).await?;
        if matches!(req.mode, pd::DeltaMode::Differential) && base_manifest.delta.is_some() {
            return Err(Perr::Other(format!(
                "differential delta requires a FULL base bundle, but {:?} is itself a delta — use \
                 --mode incremental to chain onto a delta",
                req.base_reference
            )));
        }
        let chain = self.resolve_chain(&base_dir, &base_manifest).await?;
        if chain[0].1.data_only {
            return Err(Perr::Other(
                "delta export refused: the root base bundle is --data-only; a delta needs a FULL \
                 base (with the control-plane KV slice) to diff against"
                    .into(),
            ));
        }
        if chain[0].1.source.project != project {
            return Err(Perr::Other(format!(
                "delta export refused: the base chain's root is for project {:?}, not {project:?}",
                chain[0].1.source.project
            )));
        }

        // Delta-capture readiness (PLAN-sql-true-delta Stage 1b): `delta_capture` flips a
        // START-ONLY server setting (`wal_level=logical` / `--log-bin`), so an operator who
        // enabled it but has not yet RESTARTED the database (`boatramp db restart`) would
        // otherwise silently get a full-dump delta member for it with no indication why — the
        // capture machinery's own fallback is deliberately non-fatal (true-delta is
        // best-effort). An explicit `delta_capture` opt-in is a stated expectation of a true
        // delta, so refuse LOUD here, up front, rather than let it fall through to that silent
        // fallback. Every capture-eligible db covered by this export is checked; a connectivity
        // failure checking it is NOT this condition (it is left to surface on its own, later).
        for (db, cfg) in &self.databases {
            if Self::pg_capture_eligible(cfg) {
                self.assert_pg_delta_capture_live(project, db).await?;
            } else if Self::mysql_capture_eligible(cfg) {
                self.assert_mysql_delta_capture_live(project, db).await?;
            }
        }

        // Frontier = replay the chain (metadata only): the effective KV + blob state at the base.
        let (kv_frontier, blob_frontier) = self.compute_chain_frontier(&chain).await?;

        // The FULL plan (SQL full-dumps + every blob job + the KV member), then transformed into
        // the delta member set.
        let full_opts = ExportOptions {
            delta: None,
            ..opts.clone()
        };
        let (full_specs, mut full_jobs, source) =
            self.plan_export(project, &full_opts, created_at).await?;

        // --- KV delta: diff the current scoped scan against the frontier ---
        let all_kv = boatramp_core::kv_dump::scan_dumpable(self.kv.as_ref())
            .await
            .map_err(other)?;
        let current_kv = boatramp_core::project_export::scope_entries_to_project(
            all_kv,
            ProjectRef::new(project),
        );
        let base_kv_entries: Vec<boatramp_core::kv::KvDumpEntry> = kv_frontier
            .iter()
            .map(|(k, v)| boatramp_core::kv::KvDumpEntry {
                key: k.clone(),
                value: v.clone(),
                version: 1,
            })
            .collect();
        let kv_delta = pd::compute_kv_delta(&base_kv_entries, &current_kv);
        let kv_delta_bytes = pd::encode_kv_delta(&kv_delta, created_at);

        // --- current blob metadata (sizes) for the cheap diff pre-filter ---
        let current_blob_metas = self
            .blobs
            .list(&blob_project_prefix(project))
            .await
            .map_err(other)?;
        let mut current_sizes: HashMap<String, Option<u64>> = HashMap::new();
        let mut current_keys: std::collections::BTreeSet<String> =
            std::collections::BTreeSet::new();
        for m in &current_blob_metas {
            current_sizes.insert(m.key.clone(), m.size);
            current_keys.insert(m.key.clone());
        }

        // --- SQL true-delta (pg WAL) setup: only an INCREMENTAL delta whose PARENT base recorded a
        // capture slot (in its `pg_capture.json` sidecar) can ship a WAL delta; a differential delta
        // keeps the full-dump fallback (a single advancing slot cannot re-emit the same base→N
        // interval for every differential delta). The drain is a live, slot-advancing operation, so
        // it runs here at plan time and its bytes ride as a `StageJob::PgWalDelta`.
        let parent_capture = if matches!(req.mode, pd::DeltaMode::Incremental) {
            read_pg_capture_sidecar(&base_dir).await
        } else {
            None
        };
        // The mysql analogue (PLAN-sql-true-delta Stage 3): only an INCREMENTAL delta whose PARENT
        // base recorded a snapshot coordinate (in `mysql_capture.json`) can ship a binlog delta.
        let parent_mysql_capture = if matches!(req.mode, pd::DeltaMode::Incremental) {
            read_mysql_capture_sidecar(&base_dir).await
        } else {
            None
        };
        // The libsql analogue (SQL true-delta program, Stage 4). Unlike pg/mysql (a single advancing
        // slot / a one-shot binlog coordinate ⇒ incremental-only), the libsql base is a FIXED FILE
        // snapshot every delta can re-diff, so BOTH modes are eligible: differential diffs each delta
        // vs the root base's stored snapshot; incremental diffs vs the parent's (each export stores a
        // fresh snapshot). Read the capture sidecar from `base_dir` (the fixed base in differential,
        // the parent in incremental) in either mode.
        let parent_libsql_capture = read_libsql_capture_sidecar(&base_dir).await;
        let cap_dir = self
            .work_dir
            .join(format!("delta-capture-{project}-{created_at}"));
        if parent_capture.is_some()
            || parent_mysql_capture.is_some()
            || parent_libsql_capture.is_some()
        {
            tokio::fs::create_dir_all(&cap_dir).await.map_err(other)?;
        }
        let mut any_pg_true_delta = false;
        let mut any_mysql_true_delta = false;
        let mut any_libsql_true_delta = false;

        // --- build the ordered delta member set from the full plan ---
        let mut ordered: Vec<(MemberSpec, StageJob)> = Vec::new();
        for spec in &full_specs {
            match spec.kind {
                MemberKind::Identity => { /* a delta carries no identity (guarded above) */ }
                MemberKind::Kv => {
                    ordered.push((
                        MemberSpec::sidecar(
                            project_bundle::KV_DELTA_MEMBER_PATH.to_string(),
                            MemberKind::KvDelta,
                            None,
                        ),
                        StageJob::KvDelta {
                            bytes: kv_delta_bytes.clone(),
                        },
                    ));
                }
                MemberKind::Blob => {
                    let storage_key = spec
                        .path
                        .strip_prefix("blobs/")
                        .unwrap_or(&spec.path)
                        .to_string();
                    let base_sig = blob_frontier.get(&storage_key);
                    let cur_size = current_sizes.get(&storage_key).copied().flatten();
                    let is_add = match pd::blob_decision_by_size(base_sig, cur_size) {
                        pd::BlobDecision::Add => true,
                        pd::BlobDecision::NeedsContentCheck => match base_sig {
                            // Size matched (or unknown) → content-check: hash the current object.
                            Some(b) => self.blob_sha256(&storage_key).await? != b.sha256,
                            None => true,
                        },
                    };
                    if is_add {
                        // Reuse the full plan's Blob job + spec verbatim (keeps the chunked framing
                        // for a large object) — adds-as-full-members.
                        let job = full_jobs.remove(&spec.path).ok_or_else(|| {
                            Perr::Other(format!(
                                "delta export: no stage job for blob {}",
                                spec.path
                            ))
                        })?;
                        ordered.push((spec.clone(), job));
                    }
                }
                MemberKind::PgDump => {
                    // pg WAL true-delta (PLAN-sql-true-delta Stage 2): if this db is a managed,
                    // capture-eligible binding whose PARENT base recorded a slot, and the schema is
                    // unchanged since the base, DRAIN the slot into a `PgWalDelta` member IN PLACE
                    // OF the full dump. Any miss (not eligible, no parent slot, schema drifted,
                    // slot lost, or the drain fails) FALLS BACK to the full dump — the
                    // all-families-consistent invariant (decision 3) + best-effort true-delta.
                    let db = db_from_pg_member(&spec.path);
                    let wal_member = match (db, parent_capture.as_ref()) {
                        (Some(db), Some(sidecar)) => {
                            self.try_pg_wal_delta(project, db, sidecar, &cap_dir).await
                        }
                        _ => None,
                    };
                    if let Some((bytes, cursor)) = wal_member {
                        any_pg_true_delta = true;
                        let db = db.expect("wal_member implies a parsed db");
                        ordered.push((
                            MemberSpec::sidecar(
                                pgwal_member_path(db),
                                MemberKind::PgWalDelta,
                                None,
                            )
                            .with_sql_cursor(cursor),
                            StageJob::PgWalDelta { bytes },
                        ));
                        // The full dump job for this db is now superseded — drop it.
                        let _ = full_jobs.remove(&spec.path);
                    } else {
                        // SQL full-dump fallback (decision 3): keep the full member verbatim.
                        let job = full_jobs.remove(&spec.path).ok_or_else(|| {
                            Perr::Other(format!("delta export: no stage job for {}", spec.path))
                        })?;
                        ordered.push((spec.clone(), job));
                    }
                }
                MemberKind::MysqlDump => {
                    // mysql binlog true-delta (PLAN-sql-true-delta Stage 3): if this db is a managed,
                    // capture-eligible binding whose PARENT base recorded a snapshot coordinate, and
                    // the schema is unchanged + no DDL in the range, STREAM the binlog since the base
                    // into a `MysqlBinlogDelta` member IN PLACE OF the full dump. Any miss falls back
                    // to the full dump (the all-families-consistent invariant + best-effort delta).
                    let db = db_from_mysql_member(&spec.path);
                    let binlog_member = match (db, parent_mysql_capture.as_ref()) {
                        (Some(db), Some(sidecar)) => {
                            self.try_mysql_binlog_delta(project, db, sidecar, &cap_dir)
                                .await
                        }
                        _ => None,
                    };
                    if let Some((bytes, cursor)) = binlog_member {
                        any_mysql_true_delta = true;
                        let db = db.expect("binlog_member implies a parsed db");
                        ordered.push((
                            MemberSpec::sidecar(
                                mysqlbinlog_member_path(db),
                                MemberKind::MysqlBinlogDelta,
                                None,
                            )
                            .with_sql_cursor(cursor),
                            StageJob::MysqlBinlogDelta { bytes },
                        ));
                        let _ = full_jobs.remove(&spec.path);
                    } else {
                        // SQL full-dump fallback (decision 3): keep the full member verbatim.
                        let job = full_jobs.remove(&spec.path).ok_or_else(|| {
                            Perr::Other(format!("delta export: no stage job for {}", spec.path))
                        })?;
                        ordered.push((spec.clone(), job));
                    }
                }
                MemberKind::Libsql => {
                    // libsql changeset true-delta (SQL true-delta program, Stage 4): if this site's
                    // base recorded a snapshot in the parent's `libsql_capture.json`, and the schema
                    // is unchanged + every table has a PK, DIFF the current DB against that base
                    // snapshot into a `LibsqlChangeset` member IN PLACE OF the full dump. Any miss
                    // (engine not built, no base snapshot, schema drift, diff failure) FALLS BACK to
                    // the full dump — the all-families-consistent invariant + best-effort true-delta.
                    let site = site_from_libsql_member(&spec.path);
                    let cs_member = match (site, parent_libsql_capture.as_ref()) {
                        (Some(site), Some(sidecar)) => match sidecar.sites.get(site) {
                            Some(entry) => {
                                self.try_libsql_changeset_delta(
                                    project, site, entry, &base_dir, &cap_dir,
                                )
                                .await
                            }
                            None => None,
                        },
                        _ => None,
                    };
                    if let Some((bytes, cursor)) = cs_member {
                        any_libsql_true_delta = true;
                        let site = site.expect("cs_member implies a parsed site");
                        ordered.push((
                            MemberSpec::sidecar(
                                libsql_changeset_member_path(project, site),
                                MemberKind::LibsqlChangeset,
                                None,
                            )
                            .with_sql_cursor(cursor),
                            StageJob::LibsqlChangeset { bytes },
                        ));
                        // The full libsql dump for this site is now superseded — drop it.
                        let _ = full_jobs.remove(&spec.path);
                    } else {
                        // SQL full-dump fallback (decision 3): keep the full member verbatim.
                        let job = full_jobs.remove(&spec.path).ok_or_else(|| {
                            Perr::Other(format!("delta export: no stage job for {}", spec.path))
                        })?;
                        ordered.push((spec.clone(), job));
                    }
                }
                MemberKind::KvDelta
                | MemberKind::BlobTombstone
                | MemberKind::PgWalDelta
                | MemberKind::MysqlBinlogDelta
                | MemberKind::LibsqlChangeset => {
                    // plan_export (a FULL plan) never emits delta/true-delta members; unreachable
                    // here. The SQL arm above keeps the full dump (fallback); the per-engine
                    // true-delta capture that would REPLACE a PgDump/MysqlDump/Libsql member with a
                    // PgWalDelta/MysqlBinlogDelta/LibsqlChangeset lands in its own stage.
                }
            }
        }

        // --- blob tombstones: base storage keys gone from the current listing ---
        let base_blob_keys: std::collections::BTreeSet<String> =
            blob_frontier.keys().cloned().collect();
        let tombstones = pd::compute_blob_tombstones(&base_blob_keys, &current_keys);
        if !tombstones.is_empty() {
            ordered.push((
                MemberSpec::sidecar(
                    project_bundle::BLOB_TOMBSTONE_MEMBER_PATH.to_string(),
                    MemberKind::BlobTombstone,
                    None,
                ),
                StageJob::BlobTombstone {
                    bytes: pd::encode_blob_tombstones(&tombstones),
                },
            ));
        }

        // The capture temp dir only held transient psql stdout for the drain — reclaim it.
        let _ = tokio::fs::remove_dir_all(&cap_dir).await;

        let specs: Vec<MemberSpec> = ordered.iter().map(|(s, _)| s.clone()).collect();
        let jobs: HashMap<String, StageJob> =
            ordered.into_iter().map(|(s, j)| (s.path, j)).collect();
        let delta_info = pd::DeltaInfo {
            mode: req.mode,
            base_reference: req.base_reference.clone(),
            base_created_at: base_manifest.created_at,
            // Record a true-delta strategy when at least one SQL member shipped as a true row-delta
            // (so a reader can tell a true row-delta bundle from an all-full-dump fallback); else the
            // all-families full-dump fallback. The per-member `sql_cursor` carries the authoritative
            // per-engine strategy, so when a bundle mixes engines this single hint names pg first.
            sql_strategy: if any_pg_true_delta {
                pd::SqlDeltaKind::PgWalReplay
            } else if any_mysql_true_delta {
                pd::SqlDeltaKind::MysqlBinlogReplay
            } else if any_libsql_true_delta {
                pd::SqlDeltaKind::LibsqlChangeset
            } else {
                pd::SqlDeltaKind::FullDumpFallback
            },
        };
        Ok((specs, jobs, source, delta_info))
    }

    /// Read + parse the `MANIFEST` of a resumable member-object directory.
    async fn read_resumable_manifest(
        &self,
        dir: &Path,
    ) -> Result<project_bundle::StreamManifest, Perr> {
        let manifest_path = dir.join(project_bundle::MANIFEST_PATH);
        let bytes = tokio::fs::read(&manifest_path).await.map_err(|e| {
            Perr::Other(format!(
                "read base/parent MANIFEST at {}: {e}",
                manifest_path.display()
            ))
        })?;
        serde_json::from_slice(&bytes)
            .map_err(|e| Perr::Other(format!("parse base/parent MANIFEST: {e}")))
    }

    /// Resolve a delta CHAIN from `start_dir` (a base or parent) back to the ROOT full bundle,
    /// returning `[root, …, start]` (root first). Walks each manifest's `delta.base_reference`
    /// (confined under the node base), asserting the recorded `base_created_at` matches the
    /// resolved parent — a consistency check that catches a stale or mismatched base (NOT a
    /// cryptographic anti-tamper guarantee: a forged manifest could forge the timestamp too; the
    /// structural defenses are the base-confinement here + the one-source coherence check on
    /// import). Has a cycle/length guard.
    async fn resolve_chain(
        &self,
        start_dir: &Path,
        start_manifest: &project_bundle::StreamManifest,
    ) -> Result<Vec<(PathBuf, project_bundle::StreamManifest)>, Perr> {
        let mut chain = vec![(start_dir.to_path_buf(), start_manifest.clone())];
        let mut guard = 0usize;
        while let Some(di) = chain.last().unwrap().1.delta.clone() {
            guard += 1;
            if guard > 256 {
                return Err(Perr::Other(
                    "delta chain exceeds 256 links (cycle or runaway) — refusing".into(),
                ));
            }
            let parent_dir = self
                .resolve_resumable_dir(&di.base_reference, false)
                .await?;
            let parent_manifest = self.read_resumable_manifest(&parent_dir).await?;
            if parent_manifest.created_at != di.base_created_at {
                return Err(Perr::Other(format!(
                    "delta base mismatch: {:?} records base created_at {} but the resolved base has \
                     {} — refusing a stale or mismatched base",
                    di.base_reference, di.base_created_at, parent_manifest.created_at
                )));
            }
            chain.push((parent_dir, parent_manifest));
        }
        chain.reverse();
        Ok(chain)
    }

    /// Replay a resolved chain `[root, …]` into the effective FRONTIER at its tail: the KV state
    /// (key → value bytes) and the blob state (key → {size, sha256}). Metadata-only — it reads the
    /// root's full KV member + each blob member's recorded `{size,sha}` meta, then applies each
    /// delta's KV upserts/tombstones + blob adds/tombstones in order (the export-side mirror of the
    /// import-side sequential apply).
    async fn compute_chain_frontier(
        &self,
        chain: &[(PathBuf, project_bundle::StreamManifest)],
    ) -> Result<
        (
            BTreeMap<String, Vec<u8>>,
            BTreeMap<String, boatramp_core::project_delta::BlobSig>,
        ),
        Perr,
    > {
        use boatramp_core::project_delta as pd;
        let mut kv: BTreeMap<String, Vec<u8>> = BTreeMap::new();
        let mut blobs: BTreeMap<String, pd::BlobSig> = BTreeMap::new();
        for (dir, m) in chain {
            for (idx, spec) in m.members.iter().enumerate() {
                match spec.kind {
                    MemberKind::Kv => {
                        let bytes = self.read_member_object(dir, idx).await?;
                        let decoded = boatramp_core::kv_dump::decode_dump(&bytes).map_err(other)?;
                        for e in decoded.entries {
                            kv.insert(e.key, e.value);
                        }
                    }
                    MemberKind::KvDelta => {
                        let bytes = self.read_member_object(dir, idx).await?;
                        let delta = pd::decode_kv_delta(&bytes).map_err(other)?;
                        pd::apply_kv_delta_to_frontier(&mut kv, &delta);
                    }
                    MemberKind::Blob => {
                        let storage_key = spec
                            .path
                            .strip_prefix("blobs/")
                            .unwrap_or(&spec.path)
                            .to_string();
                        let meta = self.read_member_meta(dir, idx).await?;
                        blobs.insert(
                            storage_key,
                            pd::BlobSig {
                                size: meta.size,
                                sha256: meta.sha256,
                            },
                        );
                    }
                    MemberKind::BlobTombstone => {
                        let bytes = self.read_member_object(dir, idx).await?;
                        for k in pd::decode_blob_tombstones(&bytes).map_err(other)? {
                            blobs.remove(&k);
                        }
                    }
                    // SQL/libsql/identity do not contribute to the KV/blob frontier.
                    _ => {}
                }
            }
        }
        Ok((kv, blobs))
    }

    /// Read the whole member object `m{idx}` bytes from a resumable dir.
    async fn read_member_object(&self, dir: &Path, idx: usize) -> Result<Vec<u8>, Perr> {
        tokio::fs::read(dir.join(member_object_name(idx)))
            .await
            .map_err(|e| Perr::Other(format!("read member object m{idx:05}: {e}")))
    }

    /// Read + parse the `{size, sha256}` meta sidecar of member `idx`.
    async fn read_member_meta(
        &self,
        dir: &Path,
        idx: usize,
    ) -> Result<project_bundle::MemberMeta, Perr> {
        let bytes = tokio::fs::read(dir.join(member_meta_name(idx)))
            .await
            .map_err(|e| Perr::Other(format!("read member meta m{idx:05}: {e}")))?;
        serde_json::from_slice(&bytes)
            .map_err(|e| Perr::Other(format!("parse member meta m{idx:05}: {e}")))
    }

    /// Stream a blob from the source store and return its lowercase-hex SHA-256 (the authoritative
    /// blob content comparator for the delta diff). Never buffers the whole object.
    async fn blob_sha256(&self, storage_key: &str) -> Result<String, Perr> {
        let obj = self.blobs.get(storage_key).await.map_err(other)?;
        let mut body = obj.body;
        let mut hasher = Sha256::new();
        while let Some(chunk) = body.next().await {
            let chunk = chunk.map_err(other)?;
            hasher.update(chunk.as_ref());
        }
        Ok(hex::encode(hasher.finalize()))
    }

    /// Restore a DELTA member-object directory: resolve the full chain `[root, …, this]` and apply
    /// base → each delta in order (owner decision 5 — sequential apply). The root's KV+blobs are
    /// restored in full; each delta's KV-delta + blob adds/tombstones overlay; the SQL families are
    /// applied ONLY from the NEWEST delta (its full-dump fallback supersedes the base/intermediate
    /// SQL — so a huge DB is restored once, not once per link). Identity members are not applied on
    /// the delta path (a delta clone is `--identity fresh` data movement; adopt-recovery restores
    /// the base bundle directly).
    async fn import_delta_chain(
        &self,
        project: &str,
        this_dir: &Path,
        this_manifest: &project_bundle::StreamManifest,
        opts: &ImportOptions,
    ) -> Result<ImportReport, Perr> {
        let di = this_manifest
            .delta
            .as_ref()
            .ok_or_else(|| Perr::Other("import_delta_chain called on a non-delta bundle".into()))?;
        let base_dir = self
            .resolve_resumable_dir(&di.base_reference, false)
            .await?;
        let base_manifest = self.read_resumable_manifest(&base_dir).await?;
        let mut chain = self.resolve_chain(&base_dir, &base_manifest).await?; // [root … parent]
        chain.push((this_dir.to_path_buf(), this_manifest.clone())); // … this
        if chain[0].1.delta.is_some() {
            return Err(Perr::Other(
                "delta chain does not terminate in a FULL base bundle — refusing".into(),
            ));
        }

        // Chain coherence: every link must share ONE source project. A delta is only meaningful
        // against a base from the same logical source, and `restore_member` re-keys each member
        // from ITS OWN `source.project` → the target — so links that disagree on origin would
        // re-key from different source prefixes and restore an incoherent mix. (The target may
        // still differ from the source: a cross-project clone re-keys the whole coherent chain to
        // `project`. What we forbid is a chain spliced from two different sources.) This defends a
        // resumable chain assembled on an addressable target against a grafted-in foreign base.
        let root_src = &chain[0].1.source;
        if let Some((bad_dir, bad)) = chain
            .iter()
            .find(|(_, m)| m.source.project != root_src.project || m.source.site != root_src.site)
        {
            return Err(Perr::Other(format!(
                "delta import refused: chain link {:?} is for source {:?}/{:?}, but the chain root \
                 is {:?}/{:?} — a delta chain must share one source",
                bad_dir, bad.source.project, bad.source.site, root_src.project, root_src.site
            )));
        }

        // The SAME fresh-target guard as a full resumable import (unless overwrite).
        if !opts.overwrite {
            for prefix in
                boatramp_core::project_export::project_owned_prefixes(ProjectRef::new(project))
            {
                if !self
                    .kv
                    .list_prefix(&prefix)
                    .await
                    .map_err(other)?
                    .is_empty()
                {
                    return Err(Perr::Other(format!(
                        "import refused: target project {project:?} already has control-plane data \
                         under {prefix:?}; pass overwrite=true"
                    )));
                }
            }
            if !self
                .blobs
                .list(&blob_project_prefix(project))
                .await
                .map_err(other)?
                .is_empty()
            {
                return Err(Perr::Other(format!(
                    "import refused: target project {project:?} already has blobs; pass \
                     overwrite=true"
                )));
            }
        }

        let session = self
            .work_dir
            .join(format!("import-delta-{project}-{}", now_secs()));
        tokio::fs::create_dir_all(&session).await.map_err(other)?;

        let mut report = ImportReport::default();
        let mut saw_identity = false;
        let last = chain.len() - 1;
        // Sites whose libsql family is restored by the atomic changeset pass
        // (`restore_libsql_true_delta_in_chain`) AFTER this loop: any site carrying a
        // `LibsqlChangeset` member anywhere in the chain. Their base full `Libsql` member is replayed
        // by that pass too (base snapshot + changesets), so the main loop must SKIP it — exactly as a
        // managed pg/mysql full dump is skipped. A libsql site with NO changeset (pure full-dump
        // fallback) is not here, so it still restores via `restore_member` (newest link). Computed
        // even when the engine feature is off: a bundle built elsewhere may carry changeset members,
        // and the pass below then refuses loudly rather than silently full-dumping the stale base.
        let libsql_changeset_sites: std::collections::BTreeSet<String> = chain
            .iter()
            .flat_map(|(_, m)| m.members.iter())
            .filter(|s| s.kind == MemberKind::LibsqlChangeset)
            .filter_map(|s| site_from_libsql_changeset_member(&s.path).map(str::to_string))
            .collect();
        for (pos, (dir, m)) in chain.iter().enumerate() {
            let is_newest = pos == last;
            for (idx, spec) in m.members.iter().enumerate() {
                let obj = dir.join(member_object_name(idx));
                let meta = dir.join(member_meta_name(idx));
                if !member_object_valid(&obj, &meta).await? {
                    let _ = tokio::fs::remove_dir_all(&session).await;
                    return Err(Perr::Other(format!(
                        "delta restore: chain member {idx} ({}) in {} is missing or fails its SHA",
                        spec.path,
                        dir.display()
                    )));
                }
                // Which members apply at this chain position: the SQL families only from the
                // NEWEST delta (full-dump fallback supersedes the base/intermediate SQL); identity
                // never; KV/blob at every link (base full + each delta's overlay).
                let apply_here = match spec.kind {
                    // Managed pg SQL — a full dump OR a WAL true-delta — is restored by the atomic
                    // shadow pass (`restore_pg_true_delta_in_chain`) AFTER this loop (restore_member
                    // fail-closes on a managed pg member). An EXTERNAL pg full dump still restores
                    // here via restore_member, newest-link only.
                    MemberKind::PgDump => {
                        !db_from_pg_member(&spec.path)
                            .map(|db| self.is_managed_pg(db))
                            .unwrap_or(false)
                            && is_newest
                    }
                    MemberKind::PgWalDelta => false,
                    // Managed mysql SQL — a full dump OR a binlog true-delta — is restored by the
                    // atomic shadow pass (`restore_mysql_true_delta_in_chain`) AFTER this loop
                    // (restore_member fail-closes on a managed mysql member). An EXTERNAL mysql full
                    // dump still restores here via restore_member, newest-link only.
                    MemberKind::MysqlDump => {
                        !db_from_mysql_member(&spec.path)
                            .map(|db| self.is_managed_mysql(db))
                            .unwrap_or(false)
                            && is_newest
                    }
                    MemberKind::MysqlBinlogDelta => false,
                    // A libsql full dump whose site has a changeset in the chain is restored by the
                    // atomic changeset pass (base snapshot + changesets); skip it here. A site with
                    // no changeset still restores its newest full dump via `restore_member`.
                    MemberKind::Libsql => {
                        is_newest
                            && !site_from_libsql_member(&spec.path)
                                .map(|s| libsql_changeset_sites.contains(s))
                                .unwrap_or(false)
                    }
                    // A libsql changeset is replayed only by the atomic changeset pass below.
                    MemberKind::LibsqlChangeset => false,
                    MemberKind::Identity => false,
                    _ => true,
                };
                if !apply_here {
                    continue;
                }
                if let Err(e) = self
                    .restore_member(
                        project,
                        m.data_only,
                        &m.source.project,
                        spec,
                        &obj,
                        opts,
                        &mut report,
                        &mut saw_identity,
                    )
                    .await
                {
                    let _ = tokio::fs::remove_dir_all(&session).await;
                    return Err(e);
                }
            }
        }
        // Managed pg SQL families (full-dump fallback OR WAL true-delta): restore the chain's newest
        // full dump into a fresh atomic shadow, replay each subsequent PgWalDelta onto it as the
        // ephemeral non-superuser role, then swap. Independent of the KV/blob overlay above.
        if let Err(e) = self
            .restore_pg_true_delta_in_chain(project, &chain, opts, &mut report, &session)
            .await
        {
            let _ = tokio::fs::remove_dir_all(&session).await;
            return Err(e);
        }
        // Managed mysql SQL families (full-dump fallback OR binlog true-delta): restore the chain's
        // newest full dump into a fresh atomic shadow, replay each subsequent MysqlBinlogDelta onto
        // it as the ephemeral apply user, then swap. Independent of the KV/blob overlay above.
        if let Err(e) = self
            .restore_mysql_true_delta_in_chain(project, &chain, opts, &mut report, &session)
            .await
        {
            let _ = tokio::fs::remove_dir_all(&session).await;
            return Err(e);
        }
        // libsql changeset true-delta (SQL true-delta program, Stage 4): for each site with a
        // changeset in the chain, copy the base snapshot into a fresh atomic shadow, apply each
        // changeset onto it (confined to the base's own tables, abort-on-conflict), integrity-check,
        // then atomically swap. Independent of the KV/blob overlay above.
        if let Err(e) = self
            .restore_libsql_true_delta_in_chain(
                project,
                &chain,
                &libsql_changeset_sites,
                opts,
                &mut report,
            )
            .await
        {
            let _ = tokio::fs::remove_dir_all(&session).await;
            return Err(e);
        }
        let _ = tokio::fs::remove_dir_all(&session).await;
        report.notes.push(format!(
            "delta restore: applied a {}-link chain ({} base + {} delta(s)) in {} mode",
            chain.len(),
            1,
            chain.len() - 1,
            di.mode.as_flag()
        ));
        Ok(report)
    }

    /// Import a resumable member-object directory (the output of [`export_resumable`]):
    /// restore members in the MANIFEST's authoritative order, reusing [`restore_member`]
    /// per member — identical per-member tenancy re-key/enforce as the streaming import.
    /// Core resumable import from an ALREADY-CONFINED absolute `dir` (the trait method
    /// [`ProjectExport::import_resumable`] confines the operator-named subdir first).
    pub async fn import_resumable_dir(
        &self,
        project: &str,
        dir: &Path,
        opts: ImportOptions,
    ) -> Result<ImportReport, Perr> {
        check_project_slug(project)?;
        let manifest_path = dir.join(project_bundle::MANIFEST_PATH);
        let bytes = tokio::fs::read(&manifest_path)
            .await
            .map_err(|e| Perr::Other(format!("read resumable MANIFEST: {e}")))?;
        let manifest: project_bundle::StreamManifest = serde_json::from_slice(&bytes)
            .map_err(|e| Perr::Other(format!("parse resumable MANIFEST: {e}")))?;

        // A DELTA bundle resolves its base chain and applies base → each delta in order (its own
        // fresh-target guard runs inside). A FULL bundle takes the straight per-member path below.
        if manifest.delta.is_some() {
            return self
                .import_delta_chain(project, dir, &manifest, &opts)
                .await;
        }

        // The same fresh-target guard as the streaming import (unless overwrite).
        if !opts.overwrite {
            for prefix in
                boatramp_core::project_export::project_owned_prefixes(ProjectRef::new(project))
            {
                if !self
                    .kv
                    .list_prefix(&prefix)
                    .await
                    .map_err(other)?
                    .is_empty()
                {
                    return Err(Perr::Other(format!(
                        "import refused: target project {project:?} already has control-plane \
                         data under {prefix:?}; pass overwrite=true"
                    )));
                }
            }
            if !self
                .blobs
                .list(&blob_project_prefix(project))
                .await
                .map_err(other)?
                .is_empty()
            {
                return Err(Perr::Other(format!(
                    "import refused: target project {project:?} already has blobs; pass \
                     overwrite=true"
                )));
            }
        }

        let session = self
            .work_dir
            .join(format!("import-res-{project}-{}", now_secs()));
        tokio::fs::create_dir_all(&session).await.map_err(other)?;

        let mut report = ImportReport::default();
        let mut saw_identity = false;
        for (idx, spec) in manifest.members.iter().enumerate() {
            let obj = dir.join(member_object_name(idx));
            let meta = dir.join(member_meta_name(idx));
            if !member_object_valid(&obj, &meta).await? {
                return Err(Perr::Other(format!(
                    "resumable import: member {idx} ({}) is missing or fails its SHA — the \
                     export directory is incomplete or corrupt",
                    spec.path
                )));
            }
            self.restore_member(
                project,
                manifest.data_only,
                &manifest.source.project,
                spec,
                &obj,
                &opts,
                &mut report,
                &mut saw_identity,
            )
            .await?;
        }
        let _ = tokio::fs::remove_dir_all(&session).await;
        Ok(report)
    }

    // -----------------------------------------------------------------------
    // inc2 Stage C — Postgres atomic shadow-restore
    //
    // THE SECURITY-CRITICAL SPLIT (the pg analogue of Build 1's libsql ATTACH-authorizer fix):
    // a pg dump in a bundle is ATTACKER-CRAFTED (the trailer SHA is integrity, not authenticity),
    // and run as a SUPERUSER a crafted dump can `COPY … TO/FROM PROGRAM/FILE`, `CREATE FUNCTION …
    // LANGUAGE c`, `CREATE EXTENSION`, … = arbitrary code/file execution on the box.
    //
    // HIGH-1 (Build-2 Security re-review): the configured binding user is NOT reliably a
    // non-superuser — on a Single/dedicated managed pg it is the bootstrap SUPERUSER (POSTGRES_USER),
    // and `owner_target` only yields a genuine non-superuser role for `Shared && !default`. So the
    // apply MUST NOT use the configured/owner identity. Instead the superuser creates an EPHEMERAL
    // per-import `NOSUPERUSER NOCREATEDB NOCREATEROLE` role (random password), the shadow is OWNED by
    // it, `pg_restore` applies the untrusted dump CONNECTING AS THAT ephemeral role (so every
    // superuser-only escape FAILS regardless of `cfg.user`), and a fail-closed probe REFUSES the
    // apply if the resolved role is somehow a superuser. The SUPERUSER / maintenance connection
    // (`plan.maint`, on `postgres`) runs ONLY our own trusted DDL — never a byte of the dump — and,
    // before the apply, pre-creates the operator trusted-extension allowlist in the shadow so a legit
    // `CREATE EXTENSION IF NOT EXISTS <ext>` (e.g. pgvector) no-ops under the non-superuser apply.
    // Chunked shadow-restore is for DEDICATED/Single managed servers only; a Shared multi-tenant
    // server is refused here (the per-import physical shadow db is a cross-tenant surface deferred to
    // the temp-schema follow-up).
    // -----------------------------------------------------------------------

    /// Resolve the [`PgShadowPlan`] for a MANAGED, non-Shared pg binding: the superuser/maintenance
    /// connection (on `postgres`), a freshly-minted EPHEMERAL non-superuser apply role + password,
    /// the client image, the shadow name, and the trusted-extension allowlist. External
    /// (bring-your-own-URL) bindings are refused — we must not `CREATE/RENAME/DROP` databases on an
    /// operator's own server — and a Shared multi-tenant server is refused (dedicated/Single only).
    async fn pg_shadow_plan(
        &self,
        project: &str,
        db: &str,
        cfg: &ExternalDatabaseConfig,
    ) -> Result<PgShadowPlan, Perr> {
        if cfg.compute.as_deref().is_none_or(|c| c.is_empty()) {
            return Err(Perr::Unavailable(format!(
                "database {db:?}: the atomic chunked pg shadow-restore is for MANAGED \
                 (compute-backed) databases only; an external bring-your-own-URL binding uses the \
                 sidecar path"
            )));
        }
        if matches!(cfg.tenant, crate::config::TenantIsolation::Shared) {
            return Err(Perr::Unavailable(format!(
                "database {db:?}: the atomic chunked pg shadow-restore is for DEDICATED/Single \
                 managed servers only; a Shared multi-tenant server's per-import physical shadow db \
                 is a cross-tenant surface deferred to the temp-schema follow-up"
            )));
        }
        // Operator identity (configured/superuser) + version-detect → client image. Its endpoint
        // (host/port) + the live tenant db name + the configured owner seed the maintenance conn.
        let (operator_conn, image, _ver) = self.resolve_pg(project, db, cfg).await?;
        let live_db = operator_conn.database.clone();
        let owner_user = operator_conn.user.clone();
        let mut maint = operator_conn;
        // CREATE/ALTER/DROP DATABASE cannot run connected to the tenant db — point at `postgres`.
        maint.database = "postgres".to_string();
        let suffix = shadow_suffix();
        let shadow_db = format!("{live_db}__shadow_{suffix}");
        let eph_role = format!("brexp_apply_{suffix}");
        Ok(PgShadowPlan {
            live_db,
            shadow_db,
            suffix,
            maint,
            eph_role,
            eph_password: random_token(),
            owner_user,
            image,
            trusted_extensions: self.trusted_extensions.clone(),
        })
    }

    /// Fail-closed defense-in-depth probe: confirm the resolved apply identity (`conn`) is NOT a
    /// superuser before any untrusted dump reaches it. Refuses the import loudly otherwise, so the
    /// non-superuser confinement can never be silently absent.
    async fn pg_assert_not_superuser(
        &self,
        conn: &PgConnection,
        image: &str,
        stage_dir: &Path,
    ) -> Result<(), Perr> {
        let inv = psql_invocation(
            conn,
            "SELECT rolsuper FROM pg_roles WHERE rolname = current_user",
        );
        let (code, out) = self
            .run_sql_capture(image, &inv.argv, &inv.env, None, stage_dir)
            .await?;
        if code != 0 {
            return Err(Perr::Other(format!(
                "pg shadow: could not probe the apply role's superuser attribute (exit {code}): {out}"
            )));
        }
        if out.trim() != "f" {
            return Err(Perr::Other(format!(
                "pg shadow REFUSED: the resolved apply role is a SUPERUSER (rolsuper={:?}); an \
                 untrusted bundle dump must only be applied by a non-superuser role",
                out.trim()
            )));
        }
        Ok(())
    }

    /// Run ONE trusted DDL/utility statement through the SUPERUSER / maintenance connection
    /// (`psql -c`). The caller passes a single statement (psql wraps a multi-statement `-c` string
    /// as one implicit transaction, which `CREATE DATABASE`/`ALTER DATABASE … RENAME` forbid).
    async fn pg_run_ddl(
        &self,
        plan: &PgShadowPlan,
        sql: &str,
        stage_dir: &Path,
    ) -> Result<(), Perr> {
        let inv = psql_invocation(&plan.maint, sql);
        let (code, out) = self
            .run_sql_capture(&plan.image, &inv.argv, &inv.env, None, stage_dir)
            .await?;
        if code != 0 {
            return Err(Perr::Other(format!(
                "pg shadow DDL exited {code} ({sql}): {out}"
            )));
        }
        Ok(())
    }

    /// Whether a database `name` exists (via the maintenance connection) — so the swap can skip the
    /// rename-aside when cloning into a target that has no live db yet.
    async fn pg_db_exists(
        &self,
        plan: &PgShadowPlan,
        name: &str,
        stage_dir: &Path,
    ) -> Result<bool, Perr> {
        let sql = format!("SELECT 1 FROM pg_database WHERE datname = {}", pg_lit(name));
        let inv = psql_invocation(&plan.maint, &sql);
        let (code, out) = self
            .run_sql_capture(&plan.image, &inv.argv, &inv.env, None, stage_dir)
            .await?;
        if code != 0 {
            return Err(Perr::Other(format!(
                "pg shadow: could not probe database {name:?} (exit {code}): {out}"
            )));
        }
        Ok(out.trim() == "1")
    }

    /// TRUSTED DDL (superuser): mint the EPHEMERAL non-superuser apply role, create the shadow
    /// database OWNED by it (so the `pg_restore` apply as that role can create objects), and
    /// pre-create the operator trusted-extension allowlist in the shadow (so a legit `CREATE
    /// EXTENSION IF NOT EXISTS <ext>` in the untrusted dump no-ops under the non-superuser apply —
    /// the pgvector wrinkle). The role name + shadow name are per-process unique, so no pre-drop is
    /// needed. A dump that references an extension NOT on the allowlist fails fail-closed under the
    /// non-superuser apply (correct: we never let an untrusted bundle install an arbitrary extension).
    async fn pg_create_shadow(&self, plan: &PgShadowPlan, stage_dir: &Path) -> Result<(), Perr> {
        let role_q = quote_ident(ExternalSqlKind::Postgres, &plan.eph_role);
        let shadow_q = quote_ident(ExternalSqlKind::Postgres, &plan.shadow_db);
        // The random password is a trusted, we-generate-it literal (not a credential that leaks via
        // argv — psql's -c SQL is not a process listing concern on the DB host, and it never reaches
        // a handler); still, quote it as a SQL literal defensively.
        self.pg_run_ddl(
            plan,
            &format!(
                "CREATE ROLE {role_q} LOGIN PASSWORD {} NOSUPERUSER NOCREATEDB NOCREATEROLE \
                 NOREPLICATION NOBYPASSRLS",
                pg_lit(&plan.eph_password)
            ),
            stage_dir,
        )
        .await?;
        self.pg_run_ddl(
            plan,
            &format!("CREATE DATABASE {shadow_q} OWNER {role_q}"),
            stage_dir,
        )
        .await?;
        // Pre-create the allowlisted extensions in the shadow AS THE SUPERUSER, connected to the
        // shadow (extensions are database-local). `IF NOT EXISTS` so a re-run is a no-op. A
        // non-trusted extension (e.g. pgvector — its control file sets no `trusted = true`) can
        // only be installed by a superuser, so the pre-create MUST be the superuser; the untrusted
        // dump's `CREATE EXTENSION IF NOT EXISTS <ext>` then no-ops under the non-superuser apply
        // (the existence check precedes the privilege check, so an already-present extension needs
        // no privilege). The dump's OWNER-only `COMMENT ON EXTENSION <ext>` — which the
        // non-superuser apply could NOT run on this superuser-owned extension — is kept out of the
        // bundle by dumping with `--no-comments` (see `pg_dump_invocation`); the extension's
        // comment is re-set by CREATE EXTENSION regardless, so nothing is lost for the extension.
        // A dump that references an extension NOT on the allowlist fails fail-closed under the
        // non-superuser apply (correct: an untrusted bundle must not install an arbitrary extension).
        if !plan.trusted_extensions.is_empty() {
            let maint_shadow = PgShadowPlan {
                maint: plan.maint_on_shadow(),
                ..plan.clone()
            };
            for ext in &plan.trusted_extensions {
                let ext_q = quote_ident(ExternalSqlKind::Postgres, ext);
                self.pg_run_ddl(
                    &maint_shadow,
                    &format!("CREATE EXTENSION IF NOT EXISTS {ext_q}"),
                    stage_dir,
                )
                .await?;
            }
        }
        Ok(())
    }

    /// Best-effort TEARDOWN of the shadow + ephemeral role (abort / RAII): terminate any lingering
    /// restore connection, `DROP DATABASE IF EXISTS` (which removes the ephemeral-owned objects),
    /// then `DROP ROLE IF EXISTS` the ephemeral role (it owns nothing once the shadow is gone).
    /// Called on EVERY abort path; the startup sweep covers the crash case.
    async fn pg_drop_shadow(&self, plan: &PgShadowPlan, stage_dir: &Path) {
        let shadow_q = quote_ident(ExternalSqlKind::Postgres, &plan.shadow_db);
        let role_q = quote_ident(ExternalSqlKind::Postgres, &plan.eph_role);
        let _ = self
            .pg_run_ddl(
                plan,
                &format!(
                    "SELECT pg_terminate_backend(pid) FROM pg_stat_activity \
                     WHERE datname = {} AND pid <> pg_backend_pid()",
                    pg_lit(&plan.shadow_db)
                ),
                stage_dir,
            )
            .await;
        if let Err(e) = self
            .pg_run_ddl(
                plan,
                &format!("DROP DATABASE IF EXISTS {shadow_q}"),
                stage_dir,
            )
            .await
        {
            tracing::warn!(error = %e, shadow = %plan.shadow_db, "pg shadow drop-on-abort failed; the startup sweep will reclaim it");
        }
        if let Err(e) = self
            .pg_run_ddl(plan, &format!("DROP ROLE IF EXISTS {role_q}"), stage_dir)
            .await
        {
            tracing::warn!(error = %e, role = %plan.eph_role, "pg ephemeral apply-role drop-on-abort failed; the startup sweep will reclaim it");
        }
    }

    /// TRUSTED DDL: atomically swap the verified shadow in for live. Terminate live sessions,
    /// `ALTER DATABASE <live> RENAME TO <live>__old_<suffix>` (skipped if there is no live db yet),
    /// terminate shadow sessions, `ALTER DATABASE <shadow> RENAME TO <live>`, then drop the aside
    /// copy. A sub-ms window exists between the two renames where no `<live>` db is present
    /// (acceptable for an import/clone, not a live cutover). If the shadow→live rename fails after
    /// the aside, the aside is renamed back so live is never lost.
    async fn pg_swap_shadow(&self, plan: &PgShadowPlan, stage_dir: &Path) -> Result<(), Perr> {
        let live_q = quote_ident(ExternalSqlKind::Postgres, &plan.live_db);
        let shadow_q = quote_ident(ExternalSqlKind::Postgres, &plan.shadow_db);
        let role_q = quote_ident(ExternalSqlKind::Postgres, &plan.eph_role);
        let owner_q = quote_ident(ExternalSqlKind::Postgres, &plan.owner_user);
        let old_db = format!("{}__old_{}", plan.live_db, plan.suffix);
        let old_q = quote_ident(ExternalSqlKind::Postgres, &old_db);
        // SWAP-SAFETY INVARIANT (defense in depth; mirror of the mysql guard): never rename live
        // aside + drop the aside without the shadow REPLACEMENT present. pg renames the whole shadow
        // DATABASE in, so the invariant is "the shadow db must EXIST before we touch live" — abort
        // leaving live intact otherwise. (pg's shadow name is per-process random — `<live>__shadow_
        // <nanos>_<pid>` — so it does NOT suffer the mysql true-delta deterministic-name collision
        // race; this guard is cheap insurance, not a fix for a known pg hole.)
        if !self.pg_db_exists(plan, &plan.shadow_db, stage_dir).await? {
            return Err(Perr::Other(format!(
                "pg shadow swap REFUSED: the shadow database {:?} is absent — refusing to rename \
                 live {:?} aside without a replacement. Live left intact.",
                plan.shadow_db, plan.live_db
            )));
        }
        // Reassign the restored objects (owned by the ephemeral role after a `--no-owner` restore)
        // to the configured owner, then re-own the database, so the swapped-in live db has its usual
        // ownership and the ephemeral role can be dropped. REASSIGN OWNED must run connected to the
        // db it targets (the shadow); ALTER DATABASE OWNER runs from the maintenance db.
        let maint_shadow = PgShadowPlan {
            maint: plan.maint_on_shadow(),
            ..plan.clone()
        };
        self.pg_run_ddl(
            &maint_shadow,
            &format!("REASSIGN OWNED BY {role_q} TO {owner_q}"),
            stage_dir,
        )
        .await?;
        self.pg_run_ddl(
            plan,
            &format!("ALTER DATABASE {shadow_q} OWNER TO {owner_q}"),
            stage_dir,
        )
        .await?;
        let live_exists = self.pg_db_exists(plan, &plan.live_db, stage_dir).await?;
        if live_exists {
            self.pg_run_ddl(
                plan,
                &format!(
                    "SELECT pg_terminate_backend(pid) FROM pg_stat_activity \
                     WHERE datname = {} AND pid <> pg_backend_pid()",
                    pg_lit(&plan.live_db)
                ),
                stage_dir,
            )
            .await?;
            self.pg_run_ddl(
                plan,
                &format!("ALTER DATABASE {live_q} RENAME TO {old_q}"),
                stage_dir,
            )
            .await?;
        }
        // Terminate the restore connection to the shadow before renaming it.
        self.pg_run_ddl(
            plan,
            &format!(
                "SELECT pg_terminate_backend(pid) FROM pg_stat_activity \
                 WHERE datname = {} AND pid <> pg_backend_pid()",
                pg_lit(&plan.shadow_db)
            ),
            stage_dir,
        )
        .await?;
        if let Err(e) = self
            .pg_run_ddl(
                plan,
                &format!("ALTER DATABASE {shadow_q} RENAME TO {live_q}"),
                stage_dir,
            )
            .await
        {
            // Roll the aside back to live so a failed swap never loses the original.
            if live_exists {
                let _ = self
                    .pg_run_ddl(
                        plan,
                        &format!("ALTER DATABASE {old_q} RENAME TO {live_q}"),
                        stage_dir,
                    )
                    .await;
            }
            return Err(e);
        }
        if live_exists {
            // The swap succeeded; the aside copy is obsolete (best-effort drop).
            let _ = self
                .pg_run_ddl(
                    plan,
                    &format!(
                        "SELECT pg_terminate_backend(pid) FROM pg_stat_activity \
                         WHERE datname = {} AND pid <> pg_backend_pid()",
                        pg_lit(&old_db)
                    ),
                    stage_dir,
                )
                .await;
            let _ = self
                .pg_run_ddl(plan, &format!("DROP DATABASE IF EXISTS {old_q}"), stage_dir)
                .await;
        }
        // The ephemeral apply role has no objects left (reassigned) — drop it.
        let _ = self
            .pg_run_ddl(plan, &format!("DROP ROLE IF EXISTS {role_q}"), stage_dir)
            .await;
        Ok(())
    }

    /// Spawn the `pg_restore` subprocess that applies the untrusted dump into the shadow, connecting
    /// as the EPHEMERAL NON-SUPERUSER role, reading the chunked member's body channel as stdin (so
    /// the dump streams in O(chunk)). Returns its `JoinHandle` (awaited at `ChunkFinish`).
    fn spawn_pg_restore(
        &self,
        plan: &PgShadowPlan,
        body_rx: tokio::sync::mpsc::Receiver<Vec<u8>>,
        out_path: PathBuf,
    ) -> Result<tokio::task::JoinHandle<Result<i32, Perr>>, Perr> {
        let backend = self.require_backend()?.clone();
        let image = plan.image.clone();
        let inv = pg_restore_shadow_invocation(&plan.apply_conn(), &plan.shadow_db);
        // Run the restore under `sh -c '… 2>&1'` so pg_restore's STDERR — where Postgres
        // reports a refused/failed object — merges into the captured sink that the caller
        // reads for the error message. `run_ephemeral` keeps only the container's stdout
        // and DROPS stderr on a non-zero exit, so without this a failed import (a refused
        // superuser-only escape, or any restore error) surfaces as an empty, causeless
        // "exited N; live untouched: ". Only driver-derived flags + the shadow-db
        // identifier (`[A-Za-z0-9_]`) are composed into the command — never the password,
        // which rides in `inv.env` (PGPASSWORD); each token is POSIX single-quoted, and
        // `exec` keeps the reported exit status pg_restore's own.
        let cmd = format!("exec {} 2>&1", sh_join(&inv.argv));
        let argv = vec!["sh".to_string(), "-c".to_string(), cmd];
        let env = inv.env;
        Ok(tokio::spawn(async move {
            let mut reader = AsyncChannelReader::new(body_rx);
            let out = tokio::fs::File::create(&out_path).await.map_err(other)?;
            let mut sink = out.compat_write();
            backend
                .run_ephemeral(&image, &argv, &env, Some(&mut reader), &mut sink)
                .await
                .map_err(other)
        }))
    }

    // -----------------------------------------------------------------------
    // inc2 Stage D — MySQL atomic shadow-restore (secondary; production is pg). Same
    // non-superuser-apply split: `mysql <shadow>` applies the attacker dump as the owner role;
    // the maintenance connection runs the trusted `CREATE DATABASE` + atomic `RENAME TABLE` swap.
    // -----------------------------------------------------------------------

    /// Resolve the [`MysqlShadowPlan`] for a MANAGED, non-Shared mysql binding (external bindings
    /// stay sidecar; Shared multi-tenant is refused — dedicated/Single only). Mints an EPHEMERAL
    /// apply user + password (HIGH-1: the configured user is the bootstrap superuser on a dedicated
    /// instance, so the apply must NOT use it).
    async fn mysql_shadow_plan(
        &self,
        project: &str,
        db: &str,
        cfg: &ExternalDatabaseConfig,
    ) -> Result<MysqlShadowPlan, Perr> {
        if cfg.compute.as_deref().is_none_or(|c| c.is_empty()) {
            return Err(Perr::Unavailable(format!(
                "database {db:?}: the atomic chunked mysql shadow-restore is for MANAGED \
                 (compute-backed) databases only; an external binding uses the sidecar path"
            )));
        }
        if matches!(cfg.tenant, crate::config::TenantIsolation::Shared) {
            return Err(Perr::Unavailable(format!(
                "database {db:?}: the atomic chunked mysql shadow-restore is for DEDICATED/Single \
                 managed servers only; a Shared multi-tenant server is deferred"
            )));
        }
        let (operator_conn, image, _ver) = self.resolve_mysql(project, db, cfg).await?;
        let live_db = operator_conn.database.clone();
        let maint = operator_conn; // mysql names no default db for the admin SQL
        // A SHORT suffix: `brexp_apply_<suffix>` must fit MySQL's 32-char USER-name cap.
        let suffix = mysql_eph_suffix();
        let shadow_db = format!("{live_db}__shadow_{suffix}");
        let eph_user = format!("brexp_apply_{suffix}");
        Ok(MysqlShadowPlan {
            live_db,
            shadow_db,
            suffix,
            maint,
            eph_user,
            eph_password: random_token(),
            image,
        })
    }

    /// Fail-closed probe: refuse the untrusted mysql apply unless the ephemeral user's grants carry
    /// NO `SUPER`, `FILE`, or `ALL PRIVILEGES ON *.*` — so a crafted dump cannot `INTO OUTFILE` /
    /// `LOAD DATA INFILE` / otherwise escape. Runs as the apply user (`SHOW GRANTS FOR CURRENT_USER`).
    async fn mysql_assert_not_superuser(
        &self,
        plan: &MysqlShadowPlan,
        stage_dir: &Path,
    ) -> Result<(), Perr> {
        let apply = plan.apply_conn();
        let inv = mysql_admin_invocation(&apply);
        let in_path = stage_dir.join(format!("mysql-probe-{}.sql", shadow_suffix()));
        tokio::fs::write(&in_path, "SHOW GRANTS FOR CURRENT_USER();")
            .await
            .map_err(other)?;
        let r = self
            .run_sql_capture(&plan.image, &inv.argv, &inv.env, Some(&in_path), stage_dir)
            .await;
        let _ = tokio::fs::remove_file(&in_path).await;
        let (code, out) = r?;
        if code != 0 {
            return Err(Perr::Other(format!(
                "mysql shadow: could not probe the apply user's grants (exit {code}): {out}"
            )));
        }
        // Refuse SUPER/FILE (global-only escape privileges) or any NON-trivial `*.*` grant. The
        // baseline `GRANT USAGE ON *.* TO …` that every user carries is harmless (USAGE = "no
        // privileges") and must NOT trip the probe. Match the privilege TOKENS (the part BEFORE
        // " ON "), never the whole line — else a db named e.g. `supervisors`/`profiles` in the grant
        // TARGET (`GRANT ALL ON \`profiles\`.* …` → "FILE"/"SUPER" substring) false-refuses a legit
        // restore.
        for line in out.lines() {
            let privs = mysql_grant_privileges(line).to_ascii_uppercase();
            let up = line.to_ascii_uppercase();
            let dangerous_global = up.contains(" ON *.*") && !up.contains("USAGE ON *.*");
            if privs.contains("SUPER") || privs.contains("FILE") || dangerous_global {
                return Err(Perr::Other(format!(
                    "mysql shadow REFUSED: the resolved apply user holds SUPER/FILE/*.* privileges; \
                     an untrusted bundle dump must only be applied by a least-privilege user. \
                     grants: {out}"
                )));
            }
        }
        Ok(())
    }

    /// Run trusted mysql SQL (fed on stdin, no default db) through the maintenance connection,
    /// capturing stdout (for the table enumeration) + the exit code.
    async fn mysql_run_admin(
        &self,
        plan: &MysqlShadowPlan,
        sql: &str,
        stage_dir: &Path,
    ) -> Result<(i32, String), Perr> {
        let inv = mysql_admin_invocation(&plan.maint);
        let in_path = stage_dir.join(format!("mysql-admin-{}.sql", shadow_suffix()));
        tokio::fs::write(&in_path, sql).await.map_err(other)?;
        let r = self
            .run_sql_capture(&plan.image, &inv.argv, &inv.env, Some(&in_path), stage_dir)
            .await;
        let _ = tokio::fs::remove_file(&in_path).await;
        r
    }

    /// List the base tables of a database via `information_schema` (maintenance connection).
    async fn mysql_list_tables(
        &self,
        plan: &MysqlShadowPlan,
        db: &str,
        stage_dir: &Path,
    ) -> Result<Vec<String>, Perr> {
        let sql = format!(
            "SELECT table_name FROM information_schema.tables \
             WHERE table_schema = {} AND table_type = 'BASE TABLE';",
            mysql_lit(db)
        );
        let (code, out) = self.mysql_run_admin(plan, &sql, stage_dir).await?;
        if code != 0 {
            return Err(Perr::Other(format!(
                "mysql shadow: could not list tables of {db:?} (exit {code}): {out}"
            )));
        }
        Ok(out
            .lines()
            .map(|l| l.trim().to_string())
            .filter(|l| !l.is_empty())
            .collect())
    }

    /// Whether a database `name` exists (via `information_schema.schemata`, maintenance connection) —
    /// the mysql analogue of [`pg_db_exists`](Self::pg_db_exists). Used by the true-delta restore's
    /// COLLISION guard: the binlog-delta shadow name is deterministic per db, so a pre-existing one
    /// means a concurrent same-db import is in flight and this import must refuse WITHOUT dropping it.
    async fn mysql_db_exists(
        &self,
        plan: &MysqlShadowPlan,
        name: &str,
        stage_dir: &Path,
    ) -> Result<bool, Perr> {
        let sql = format!(
            "SELECT 1 FROM information_schema.schemata WHERE schema_name = {};",
            mysql_lit(name)
        );
        let (code, out) = self.mysql_run_admin(plan, &sql, stage_dir).await?;
        if code != 0 {
            return Err(Perr::Other(format!(
                "mysql shadow: could not probe database {name:?} (exit {code}): {out}"
            )));
        }
        Ok(out.trim() == "1")
    }

    /// TRUSTED DDL: create the shadow database + mint the EPHEMERAL apply user granted ONLY on the
    /// shadow db (never `*.*`, `SUPER`, or `FILE`), so a crafted dump applied as that user cannot
    /// escape. The ephemeral user is dropped on swap/abort.
    async fn mysql_create_shadow(
        &self,
        plan: &MysqlShadowPlan,
        stage_dir: &Path,
    ) -> Result<(), Perr> {
        let shadow_q = quote_ident(ExternalSqlKind::Mysql, &plan.shadow_db);
        let user_lit = mysql_lit(&plan.eph_user);
        let pw_lit = mysql_lit(&plan.eph_password);
        let (code, out) = self
            .mysql_run_admin(
                plan,
                &format!(
                    "CREATE DATABASE {shadow_q}; \
                     CREATE USER {user_lit}@'%' IDENTIFIED BY {pw_lit}; \
                     GRANT ALL PRIVILEGES ON {shadow_q}.* TO {user_lit}@'%';"
                ),
                stage_dir,
            )
            .await?;
        if code != 0 {
            return Err(Perr::Other(format!(
                "mysql shadow create (db + ephemeral user) exited {code}: {out}"
            )));
        }
        Ok(())
    }

    /// Best-effort shadow + ephemeral-user teardown (abort / RAII).
    async fn mysql_drop_shadow(&self, plan: &MysqlShadowPlan, stage_dir: &Path) {
        let shadow_q = quote_ident(ExternalSqlKind::Mysql, &plan.shadow_db);
        let user_lit = mysql_lit(&plan.eph_user);
        if let Err(e) = self
            .mysql_run_admin(
                plan,
                &format!("DROP DATABASE IF EXISTS {shadow_q}; DROP USER IF EXISTS {user_lit}@'%';"),
                stage_dir,
            )
            .await
        {
            tracing::warn!(error = %e, shadow = %plan.shadow_db, "mysql shadow drop-on-abort failed; the startup sweep will reclaim it");
        }
    }

    /// TRUSTED DDL: atomically swap the verified shadow in for live via ONE `RENAME TABLE` that
    /// moves every live table aside (`<live>.<t>` → `<live>.__old_<suffix>_<t>`) AND every shadow
    /// table in (`<shadow>.<t>` → `<live>.<t>`) — MySQL applies a multi-table `RENAME TABLE`
    /// atomically — then drops the aside tables + the shadow database.
    async fn mysql_swap_shadow(
        &self,
        plan: &MysqlShadowPlan,
        stage_dir: &Path,
    ) -> Result<(), Perr> {
        let live_tables = self
            .mysql_list_tables(plan, &plan.live_db, stage_dir)
            .await?;
        let shadow_tables = self
            .mysql_list_tables(plan, &plan.shadow_db, stage_dir)
            .await?;
        // SWAP-SAFETY INVARIANT: never move live aside + drop the aside without a populated shadow
        // replacement present. An empty shadow while live is non-empty (e.g. a concurrent same-db
        // import dropped this import's populated shadow) would DESTROY tenant data — abort, leaving
        // LIVE INTACT (no RENAME-aside, no DROP). The caller tears down the (bogus/empty) shadow.
        if swap_would_destroy_live(&live_tables, &shadow_tables) {
            return Err(Perr::Other(format!(
                "mysql shadow swap REFUSED: the shadow {:?} is EMPTY while live {:?} has \
                 {} table(s) — swapping would destroy live data (a concurrent same-db import may \
                 have dropped this import's shadow). Live left intact.",
                plan.shadow_db,
                plan.live_db,
                live_tables.len()
            )));
        }
        let liveq = |t: &str| {
            format!(
                "{}.{}",
                quote_ident(ExternalSqlKind::Mysql, &plan.live_db),
                quote_ident(ExternalSqlKind::Mysql, t)
            )
        };
        let shadowq = |t: &str| {
            format!(
                "{}.{}",
                quote_ident(ExternalSqlKind::Mysql, &plan.shadow_db),
                quote_ident(ExternalSqlKind::Mysql, t)
            )
        };
        let aside_name = |t: &str| format!("__old_{}_{t}", plan.suffix);
        let mut moves: Vec<String> = Vec::new();
        for t in &live_tables {
            moves.push(format!("{} TO {}", liveq(t), liveq(&aside_name(t))));
        }
        for t in &shadow_tables {
            moves.push(format!("{} TO {}", shadowq(t), liveq(t)));
        }
        if !moves.is_empty() {
            let (code, out) = self
                .mysql_run_admin(
                    plan,
                    &format!("RENAME TABLE {};", moves.join(", ")),
                    stage_dir,
                )
                .await?;
            if code != 0 {
                return Err(Perr::Other(format!(
                    "mysql shadow swap (RENAME TABLE) exited {code}: {out}"
                )));
            }
        }
        // Drop the aside tables + the now-empty shadow db (best-effort — the swap already landed).
        for t in &live_tables {
            let _ = self
                .mysql_run_admin(
                    plan,
                    &format!("DROP TABLE IF EXISTS {};", liveq(&aside_name(t))),
                    stage_dir,
                )
                .await;
        }
        self.mysql_drop_shadow(plan, stage_dir).await;
        Ok(())
    }

    /// Spawn the `mysql <shadow>` subprocess that applies the untrusted tables-only dump as the
    /// EPHEMERAL least-privilege user, reading the body channel as stdin.
    fn spawn_mysql_restore(
        &self,
        plan: &MysqlShadowPlan,
        body_rx: tokio::sync::mpsc::Receiver<Vec<u8>>,
        out_path: PathBuf,
    ) -> Result<tokio::task::JoinHandle<Result<i32, Perr>>, Perr> {
        let backend = self.require_backend()?.clone();
        let image = plan.image.clone();
        let inv = mysql_shadow_invocation(&plan.apply_conn(), &plan.shadow_db);
        Ok(tokio::spawn(async move {
            let mut reader = AsyncChannelReader::new(body_rx);
            let out = tokio::fs::File::create(&out_path).await.map_err(other)?;
            let mut sink = out.compat_write();
            backend
                .run_ephemeral(&image, &inv.argv, &inv.env, Some(&mut reader), &mut sink)
                .await
                .map_err(other)
        }))
    }

    /// Startup sweep of stale `*__shadow_*` / `*__old_*` databases left by a crash mid-import (the
    /// RAII drop-on-abort only fires in-process). Best-effort per MANAGED pg/mysql binding: a
    /// not-yet-ready or unreachable managed server simply yields no sweep (logged), never a boot
    /// failure. Runs at node startup (no import is in flight yet). Returns the count dropped.
    pub async fn sweep_stale_sql_shadows(&self, project: &str) -> usize {
        let mut dropped = 0usize;
        let session = self.work_dir.join(format!("shadow-sweep-{}", now_secs()));
        if tokio::fs::create_dir_all(&session).await.is_err() {
            return 0;
        }
        // The capture artifacts a PENDING base→delta chain still references (so the orphan sweep
        // never reclaims a slot a legitimately-pending base still needs). §4 orphan sweep.
        let wanted_capture = self.collect_pending_capture_names().await;
        for (db, cfg) in &self.databases {
            if cfg.compute.as_deref().is_none_or(|c| c.is_empty()) {
                continue; // external bindings have no shadow dbs of ours
            }
            if kind_is_postgres(&cfg.kind) {
                if let Ok(plan) = self.pg_shadow_plan(project, db, cfg).await {
                    let sql = "SELECT datname FROM pg_database \
                               WHERE datname LIKE '%\\_\\_shadow\\_%' OR datname LIKE '%\\_\\_old\\_%'";
                    let inv = psql_invocation(&plan.maint, sql);
                    if let Ok((0, out)) = self
                        .run_sql_capture(&plan.image, &inv.argv, &inv.env, None, &session)
                        .await
                    {
                        for name in out.lines().map(str::trim).filter(|l| !l.is_empty()) {
                            let q = quote_ident(ExternalSqlKind::Postgres, name);
                            if self
                                .pg_run_ddl(
                                    &plan,
                                    &format!("DROP DATABASE IF EXISTS {q}"),
                                    &session,
                                )
                                .await
                                .is_ok()
                            {
                                dropped += 1;
                            }
                        }
                    }
                    // Orphan ephemeral apply ROLES (`brexp_apply_%`) left by a crash — drop them
                    // AFTER their shadow dbs are gone (they then own nothing). Each has a random,
                    // never-persisted password and owns nothing, so this is tidiness, not security.
                    let role_sql =
                        "SELECT rolname FROM pg_roles WHERE rolname LIKE 'brexp\\_apply\\_%'";
                    let role_inv = psql_invocation(&plan.maint, role_sql);
                    if let Ok((0, out)) = self
                        .run_sql_capture(&plan.image, &role_inv.argv, &role_inv.env, None, &session)
                        .await
                    {
                        for role in out.lines().map(str::trim).filter(|l| !l.is_empty()) {
                            let q = quote_ident(ExternalSqlKind::Postgres, role);
                            // Best-effort: skips a role that still owns objects (its shadow lingered).
                            if self
                                .pg_run_ddl(&plan, &format!("DROP ROLE IF EXISTS {q}"), &session)
                                .await
                                .is_ok()
                            {
                                dropped += 1;
                            }
                        }
                    }
                    // Orphan pg WAL CAPTURE artifacts (PLAN-sql-true-delta §4): a `brexp_slot_%`
                    // logical slot PINS WAL, so a slot left by an abandoned base→delta chain must be
                    // reclaimed — unless a PENDING base still references it (`wanted_capture`). The
                    // WAL ceiling already bounds the disk; this reclaims the pin promptly. Drop
                    // inactive orphan slots, then their capture roles, then (on the tenant db) their
                    // publications.
                    let slot_sql = "SELECT slot_name FROM pg_replication_slots \
                                    WHERE slot_name LIKE 'brexp\\_slot\\_%' AND NOT active";
                    let slot_inv = psql_invocation(&plan.maint, slot_sql);
                    if let Ok((0, out)) = self
                        .run_sql_capture(&plan.image, &slot_inv.argv, &slot_inv.env, None, &session)
                        .await
                    {
                        for slot in out.lines().map(str::trim).filter(|l| !l.is_empty()) {
                            if wanted_capture.contains(slot) {
                                continue;
                            }
                            if self
                                .pg_run_ddl(
                                    &plan,
                                    &format!("SELECT pg_drop_replication_slot({})", pg_lit(slot)),
                                    &session,
                                )
                                .await
                                .is_ok()
                            {
                                dropped += 1;
                            }
                        }
                    }
                    let crole_sql =
                        "SELECT rolname FROM pg_roles WHERE rolname LIKE 'brexp\\_capture\\_%'";
                    let crole_inv = psql_invocation(&plan.maint, crole_sql);
                    if let Ok((0, out)) = self
                        .run_sql_capture(
                            &plan.image,
                            &crole_inv.argv,
                            &crole_inv.env,
                            None,
                            &session,
                        )
                        .await
                    {
                        for role in out.lines().map(str::trim).filter(|l| !l.is_empty()) {
                            if wanted_capture.contains(role) {
                                continue;
                            }
                            let q = quote_ident(ExternalSqlKind::Postgres, role);
                            if self
                                .pg_run_ddl(&plan, &format!("DROP ROLE IF EXISTS {q}"), &session)
                                .await
                                .is_ok()
                            {
                                dropped += 1;
                            }
                        }
                    }
                    // Publications are per-db — connect to the tenant db to reclaim orphans (tidiness;
                    // a publication pins no WAL on its own).
                    let maint_live = {
                        let mut c = plan.maint.clone();
                        c.database = plan.live_db.clone();
                        c
                    };
                    let pub_sql =
                        "SELECT pubname FROM pg_publication WHERE pubname LIKE 'brexp\\_pub\\_%'";
                    let pub_inv = psql_invocation(&maint_live, pub_sql);
                    if let Ok((0, out)) = self
                        .run_sql_capture(&plan.image, &pub_inv.argv, &pub_inv.env, None, &session)
                        .await
                    {
                        for p in out.lines().map(str::trim).filter(|l| !l.is_empty()) {
                            if wanted_capture.contains(p) {
                                continue;
                            }
                            let q = quote_ident(ExternalSqlKind::Postgres, p);
                            let pdrop = psql_invocation(
                                &maint_live,
                                &format!("DROP PUBLICATION IF EXISTS {q}"),
                            );
                            if let Ok((0, _)) = self
                                .run_sql_capture(
                                    &plan.image,
                                    &pdrop.argv,
                                    &pdrop.env,
                                    None,
                                    &session,
                                )
                                .await
                            {
                                dropped += 1;
                            }
                        }
                    }
                }
            } else if kind_is_mysql(&cfg.kind)
                && let Ok(plan) = self.mysql_shadow_plan(project, db, cfg).await
            {
                let sql = "SELECT schema_name FROM information_schema.schemata \
                           WHERE schema_name LIKE '%\\_\\_shadow\\_%';";
                if let Ok((0, out)) = self.mysql_run_admin(&plan, sql, &session).await {
                    for name in out.lines().map(str::trim).filter(|l| !l.is_empty()) {
                        let q = quote_ident(ExternalSqlKind::Mysql, name);
                        if let Ok((0, _)) = self
                            .mysql_run_admin(
                                &plan,
                                &format!("DROP DATABASE IF EXISTS {q};"),
                                &session,
                            )
                            .await
                        {
                            dropped += 1;
                        }
                    }
                }
                // Orphan ephemeral apply USERS (`brexp_apply_%`) + binlog-capture READER USERS
                // (`brexp_rd_%`) left by a crash — drop them after their shadow dbs are gone
                // (tidiness: each has a random, never-persisted password and only ever held a grant
                // on the now-dropped shadow db, or REPLICATION SLAVE/CLIENT for the read). The reader
                // user pins no server resource (unlike a pg slot), so this is pure tidiness.
                let user_sql = "SELECT user FROM mysql.user \
                                WHERE user LIKE 'brexp\\_apply\\_%' OR user LIKE 'brexp\\_rd\\_%';";
                if let Ok((0, out)) = self.mysql_run_admin(&plan, user_sql, &session).await {
                    for u in out.lines().map(str::trim).filter(|l| !l.is_empty()) {
                        let user_lit = mysql_lit(u);
                        if let Ok((0, _)) = self
                            .mysql_run_admin(
                                &plan,
                                &format!("DROP USER IF EXISTS {user_lit}@'%';"),
                                &session,
                            )
                            .await
                        {
                            dropped += 1;
                        }
                    }
                }
            }
        }
        let _ = tokio::fs::remove_dir_all(&session).await;
        dropped
    }
}

// ===========================================================================================
// pg logical-WAL true-delta: CAPTURE (export) + REPLAY (restore) — PLAN-sql-true-delta Stage 2.
//
// CAPTURE. A managed, dedicated/Single pg db with `delta_capture` sources a row-level delta from
// the server's logical WAL. A BASE (full) resumable export of such a db mints a `FOR ALL TABLES`
// publication + an ephemeral `REPLICATION NOSUPERUSER …` role, then — SNAPSHOT-PINNED — creates a
// `pgoutput` logical replication SLOT over a held `replication=database` session across the base
// `pg_dump --snapshot=<exported snapshot>` (`produce_pg_capture_base`), so the base dump and the
// slot share ONE consistent point and the base↔WAL overlap window is CLOSED (a write committing in
// the old slot-create→dump gap now lands in the WAL ONLY, never also in the dump). Their names + the
// slot's consistent-point LSN + the schema fingerprint are recorded in a `pg_capture.json` sidecar
// beside the resumable member objects. An INCREMENTAL delta export then DRAINS the parent's slot
// (`pg_logical_slot_get_binary_changes` — GET, not peek, so it advances the slot + releases the
// pinned WAL; the drain's hex DATA runs through a NON-merging capture so stderr never co-mingles),
// length-frames each drained message (`pgoutput::frame_message`) into the `PgWalDelta` member, and
// DROPS the slot+publication+role (bounded retention, §4 — also on any drain error). A schema change
// since the base, a lost/missing slot, or `--mode
// differential` all fall back to a full dump for that db.
//
// REPLAY. `restore_pg_true_delta_in_chain` restores the chain's newest FULL dump into the inc2
// atomic shadow, then replays each subsequent `PgWalDelta` onto it — `pgoutput::decode_framed` +
// `pgoutput::render_changes` (injection-safe: identifiers quote_ident'd, values quote_literal'd),
// EXECUTED as the ephemeral NON-superuser owner role (the inc2 HIGH-1 confinement) under
// `standard_conforming_strings = on` + `ON_ERROR_STOP` — before the atomic swap. A render error
// (e.g. `REPLICA IDENTITY NOTHING`) or a replay failure fails the import LOUD (never a partial).
//
// SCOPE: managed dedicated/Single pg only (same as the inc2 shadow path; external + Shared refused).
// Only BASE exports create slots, so an incremental chain WAL-deltas its FIRST delta and full-dumps
// any later link (graceful, consistent). mysql/libsql true-delta are separate later engines.
// ===========================================================================================

/// The capture-sidecar filename written beside a resumable export dir's member objects.
const PG_CAPTURE_SIDECAR: &str = "pg_capture.json";

/// Stale-resumable-base TTL (§4): how long an abandoned-but-resumable BASE export's capture slot is
/// shielded from the startup orphan sweep. A legitimate base→delta chain drains + drops its slot
/// within one base→delta interval; past this age the base is treated as abandoned and the sweep
/// reclaims the slot's WAL pin (the delta that never came falls back to a full dump). Generous (7
/// days) so a deliberate multi-day base→delta workflow still true-deltas; the `max_slot_wal_keep_size`
/// ceiling bounds the disk regardless. Pre-TTL sidecars (no `created_at`) fall back to the file mtime.
const STALE_RESUMABLE_CAPTURE_TTL_SECS: u64 = 7 * 24 * 60 * 60;

/// The `CREATE_REPLICATION_SLOT` **replication-protocol** command that creates `slot` as a pgoutput
/// logical slot AND exports a consistent snapshot (the point the slot's WAL decoding starts from),
/// to be run over a `replication=database` session that stays OPEN across the paired
/// `pg_dump --snapshot`. PG15+ takes the generic option list `(SNAPSHOT 'export')`; PG9.4–14 takes
/// the positional `EXPORT_SNAPSHOT` keyword. `slot` is a driver-derived identifier (never bundle
/// data / a credential), double-quoted for the replication grammar.
fn create_replication_slot_export_sql(slot: &str, server_version_num: &str) -> String {
    let slot_q = format!("\"{}\"", slot.replace('"', "\"\""));
    let opts = match pg_server_major(server_version_num) {
        Some(m) if m >= 15 => "(SNAPSHOT 'export')",
        _ => "EXPORT_SNAPSHOT",
    };
    format!("CREATE_REPLICATION_SLOT {slot_q} LOGICAL pgoutput {opts};")
}

/// One managed-pg db's capture artifacts, recorded in the resumable dir's `pg_capture.json` so a
/// later INCREMENTAL delta (which references this dir as its parent) can drain the slot. Carries
/// only NON-secret names + the base LSN + the base schema fingerprint — never the ephemeral role's
/// password (the superuser mints it fresh at create and resets it fresh at drain, so no credential
/// is ever persisted on disk).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct PgCaptureEntry {
    /// The `pgoutput` logical replication slot name (`brexp_slot_<suffix>`).
    slot: String,
    /// The `FOR ALL TABLES` publication name (`brexp_pub_<suffix>`).
    publication: String,
    /// The ephemeral `REPLICATION NOSUPERUSER …` capture role (`brexp_capture_<suffix>`).
    role: String,
    /// The slot's consistent-point LSN — the point a delta replays FROM. EMPTY until the
    /// SNAPSHOT-PINNED base producer ([`NodeProjectExport::produce_pg_capture_base`]) has created
    /// the slot and read back its `confirmed_flush_lsn`: `pg_begin_capture` only mints the role +
    /// publication, so a sidecar entry with an empty `base_lsn` is a slot that was never
    /// successfully pinned (its delta falls back to a full dump).
    base_lsn: String,
    /// The source schema-ledger fingerprint at capture time. A delta whose current fingerprint
    /// differs MUST fall back to a full dump (logical decoding carries no DDL).
    #[serde(default)]
    schema_fingerprint: Option<String>,
    /// Unix seconds when this capture was begun (the base's slot minted). Used by the startup
    /// orphan sweep's stale-resumable-base TTL (§4): an abandoned-but-resumable base older than
    /// [`STALE_RESUMABLE_CAPTURE_TTL_SECS`] no longer shields its slot from reclamation, so a
    /// forgotten base's WAL pin is freed instead of being held forever. `0` (a pre-TTL sidecar,
    /// absent in the JSON) ⇒ fall back to the sidecar file's mtime for the age.
    #[serde(default)]
    created_at: u64,
}

/// A resumable dir's capture sidecar: per-db capture artifacts keyed by the node's DB binding name.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
struct PgCaptureSidecar {
    dbs: BTreeMap<String, PgCaptureEntry>,
}

/// Read the capture sidecar from a resumable dir (absent/corrupt ⇒ `None`).
async fn read_pg_capture_sidecar(dir: &Path) -> Option<PgCaptureSidecar> {
    let bytes = tokio::fs::read(dir.join(PG_CAPTURE_SIDECAR)).await.ok()?;
    serde_json::from_slice(&bytes).ok()
}

/// The age (seconds) of a resumable dir's capture sidecar FILE, from its mtime — the fallback age
/// for the stale-resumable-base TTL (§4 LOW 4b) when a pre-TTL entry carries no `created_at`. A
/// file we cannot stat / whose mtime is in the future returns `0` (treated as fresh, so the sweep
/// never reclaims a base it cannot age — fail-safe toward retention).
async fn pg_capture_sidecar_age_secs(dir: &Path, now: u64) -> u64 {
    let Ok(meta) = tokio::fs::metadata(dir.join(PG_CAPTURE_SIDECAR)).await else {
        return 0;
    };
    let Ok(modified) = meta.modified() else {
        return 0;
    };
    let mtime_secs = modified
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    now.saturating_sub(mtime_secs)
}

/// Whether a capture sidecar entry still SHIELDS its slot from the startup orphan sweep (§4 LOW 4b):
/// `true` while the base is within the TTL, `false` once it is stale (abandoned-but-resumable) so the
/// sweep may reclaim the slot's WAL pin. The entry's age is its own `created_at` when recorded
/// (`> 0`), else the `file_age_secs` fallback (the sidecar file's mtime, for a pre-TTL entry). Pure
/// so the §4 TTL decision is unit-mutation-gated (flip the comparison and this flags it).
fn capture_entry_shielded(created_at: u64, file_age_secs: u64, now: u64, ttl: u64) -> bool {
    let age = if created_at > 0 {
        now.saturating_sub(created_at)
    } else {
        file_age_secs
    };
    age <= ttl
}

/// Build a capture-role connection by swapping the identity of a superuser connection (same
/// host/port/db; the ephemeral role + its freshly-minted password).
fn capture_role_conn(su: &PgConnection, role: &str, password: &str) -> PgConnection {
    let mut c = su.clone();
    c.user = role.to_string();
    c.password = password.to_string();
    c
}

impl NodeProjectExport {
    /// Whether a db binding is eligible for pg WAL true-delta capture: MANAGED + postgres +
    /// `delta_capture` on + dedicated/Single (NOT external, NOT Shared — the inc2 shadow-path
    /// restriction). A Shared multi-tenant server's cross-tenant publication is out of scope.
    fn pg_capture_eligible(cfg: &ExternalDatabaseConfig) -> bool {
        is_managed_binding(cfg)
            && kind_is_postgres(&cfg.kind)
            && cfg.delta_capture
            && !matches!(cfg.tenant, crate::config::TenantIsolation::Shared)
    }

    /// Whether a configured db is a MANAGED postgres binding (its SQL members take the atomic
    /// shadow true-delta restore path, not `restore_member`).
    fn is_managed_pg(&self, db: &str) -> bool {
        self.databases
            .get(db)
            .map(|c| is_managed_binding(c) && kind_is_postgres(&c.kind))
            .unwrap_or(false)
    }

    /// Run ONE trusted/driver-generated pg statement as `conn` (psql `-tAc`, ON_ERROR_STOP),
    /// returning `(exit_code, trimmed stdout+stderr)`. A thin wrapper over the containerized client.
    async fn pg_capture_sql(
        &self,
        conn: &PgConnection,
        image: &str,
        sql: &str,
        stage_dir: &Path,
    ) -> Result<(i32, String), Perr> {
        let inv = psql_invocation(conn, sql);
        self.run_sql_capture(image, &inv.argv, &inv.env, None, stage_dir)
            .await
    }

    /// Create one managed pg db's NON-slot capture artifacts at BASE time: an ephemeral
    /// `REPLICATION NOSUPERUSER …` role + a `FOR ALL TABLES` publication (both by the SUPERUSER).
    /// The pgoutput logical SLOT is deliberately NOT created here — it is created SNAPSHOT-PINNED by
    /// [`produce_pg_capture_base`] over a held `replication=database` session, so the base dump
    /// (`pg_dump --snapshot=<name>`) and the slot share ONE consistent point and the base↔WAL
    /// overlap window is closed (PLAN-sql-true-delta Stage-2 MEDIUM). Returns a [`PgCaptureEntry`]
    /// whose `base_lsn` is EMPTY (pending — the producer fills it from the slot's
    /// `confirmed_flush_lsn`). Rolls back the role on a publication failure.
    ///
    /// The role is created with a throwaway random password: it is never persisted, and the
    /// snapshot-pinned producer / the drain each RESET it (superuser `ALTER ROLE … PASSWORD`) to a
    /// fresh value just before use — so no capture-role credential ever lands on disk or outlives
    /// the one operation that needs it.
    async fn pg_begin_capture(
        &self,
        project: &str,
        db: &str,
        cfg: &ExternalDatabaseConfig,
        stage_dir: &Path,
    ) -> Result<PgCaptureEntry, Perr> {
        let (su, image, _ver) = self.resolve_pg(project, db, cfg).await?;
        let suffix = shadow_suffix();
        let slot = format!("brexp_slot_{suffix}");
        let publication = format!("brexp_pub_{suffix}");
        let role = format!("brexp_capture_{suffix}");
        let role_pw = random_token();
        let role_q = quote_ident(ExternalSqlKind::Postgres, &role);
        let pub_q = quote_ident(ExternalSqlKind::Postgres, &publication);

        // SUPERUSER: the ephemeral least-privilege REPLICATION role (so the WAL drain + the
        // snapshot-export session are NOT run as the bootstrap superuser — defence in depth), then
        // the publication. The publication MUST exist before the slot's consistent point (the slot
        // is created just after, by the snapshot-pinned producer): pgoutput decodes the WAL against
        // the HISTORICAL catalog snapshot at each change's LSN, so a publication created AFTER a
        // change's LSN is "not visible" there and the drain errors. `FOR ALL TABLES` is
        // superuser-only; a dedicated/Single db is wholly one tenant's, so it is correct here. The
        // base full dump of a delta_capture db is taken with `pg_dump --no-publications` (see
        // `StageJob::Pg.no_publications`) so this capture publication never lands in the dump and
        // cannot fail the non-superuser shadow restore (`CREATE PUBLICATION` is superuser-only).
        let create_role = format!(
            "CREATE ROLE {role_q} LOGIN PASSWORD {} REPLICATION NOSUPERUSER NOCREATEDB \
             NOCREATEROLE NOBYPASSRLS",
            pg_lit(&role_pw)
        );
        let (code, out) = self
            .pg_capture_sql(&su, &image, &create_role, stage_dir)
            .await?;
        if code != 0 {
            return Err(Perr::Other(format!(
                "pg capture: CREATE capture role for {db:?} exited {code}: {out}"
            )));
        }
        let (code, out) = self
            .pg_capture_sql(
                &su,
                &image,
                &format!("CREATE PUBLICATION {pub_q} FOR ALL TABLES"),
                stage_dir,
            )
            .await?;
        if code != 0 {
            let _ = self
                .pg_capture_sql(
                    &su,
                    &image,
                    &format!("DROP ROLE IF EXISTS {role_q}"),
                    stage_dir,
                )
                .await;
            return Err(Perr::Other(format!(
                "pg capture: CREATE PUBLICATION for {db:?} exited {code}: {out}"
            )));
        }

        let schema_fingerprint = self.schema_fingerprint(project, db).await;
        Ok(PgCaptureEntry {
            slot,
            publication,
            role,
            base_lsn: String::new(), // PENDING — produce_pg_capture_base pins + fills it
            schema_fingerprint,
            created_at: now_secs(),
        })
    }

    /// Produce ONE capture-eligible managed-pg db's BASE member object, SNAPSHOT-PINNED to its
    /// capture slot (PLAN-sql-true-delta Stage-2 MEDIUM — close the base↔WAL overlap window). The
    /// slot (`entry.slot`, minted role + publication already created by `pg_begin_capture`) is
    /// created here, inside ONE ephemeral client container, over a `replication=database` session
    /// that is HELD OPEN across the base `pg_dump --snapshot=<exported snapshot>`: the slot's
    /// consistent point and the dump's snapshot are then the SAME, so a write committing in the old
    /// slot-create→dump window lands in the WAL ONLY (never ALSO in the dump), and its replay is a
    /// clean INSERT — not a duplicate-key `ON_ERROR_STOP` abort. On success the sidecar entry's
    /// `base_lsn` is filled from the slot's `confirmed_flush_lsn` (== the consistent point for a
    /// freshly-created, un-consumed slot).
    ///
    /// Robust + best-effort: if the snapshot-pin cannot be established (replication disabled, an old
    /// slot can't be dropped, the session/dump errors) it DROPS any partial slot, REMOVES the db's
    /// sidecar entry (so its future delta falls back to a full dump), and produces a plain
    /// (un-pinned) base dump — the BASE export still succeeds. Idempotent on resume: a pre-existing
    /// slot of this name is dropped and re-pinned so the dump and slot always share one point.
    async fn produce_pg_capture_base(
        &self,
        project: &str,
        dir: &Path,
        idx: usize,
        db: &str,
        cfg: &ExternalDatabaseConfig,
        stage_dir: &Path,
    ) -> Result<project_bundle::MemberMeta, Perr> {
        let (conn, image, server_version_num) = self.resolve_pg(project, db, cfg).await?;
        // The capture artifacts `pg_begin_capture` recorded (role + publication + slot NAME). Absent
        // ⇒ capture never began for this db; fall straight back to a plain base dump.
        let entry = read_pg_capture_sidecar(dir)
            .await
            .and_then(|s| s.dbs.get(db).cloned());
        let staged = stage_dir.join(format!("pgcap-base-{idx}"));

        if let Some(entry) = entry {
            match self
                .pg_snapshot_pinned_dump(
                    &conn,
                    &image,
                    &server_version_num,
                    &entry,
                    &staged,
                    stage_dir,
                )
                .await
            {
                Ok(base_lsn) => {
                    // Record the consistent point so the manifest cursor is the slot's own LSN.
                    self.pg_sidecar_set_base_lsn(dir, db, &base_lsn).await;
                    let meta = write_member_from_file(dir, idx, &staged).await?;
                    let _ = tokio::fs::remove_file(&staged).await;
                    return Ok(meta);
                }
                Err(e) => {
                    tracing::warn!(db = %db, error = %e, "pg delta capture: could not snapshot-pin the base; this db's delta will fall back to a full dump");
                    // Reclaim the (possibly half-created) slot + forget the entry so neither the
                    // orphan sweep nor the ceiling has to, and the future delta cleanly full-dumps.
                    self.pg_drop_capture(project, db, cfg, &entry, stage_dir)
                        .await;
                    self.pg_sidecar_remove_db(dir, db).await;
                }
            }
        }

        // FALLBACK: a plain (un-pinned) base dump — robustness over true-delta (best-effort).
        let _ = tokio::fs::remove_file(&staged).await;
        let exclude_extensions = self.trusted_extensions.clone();
        let inv = pg_dump_invocation(
            &conn,
            false,
            &server_version_num,
            &exclude_extensions,
            cfg.delta_capture,
        );
        let code = self
            .run_sql_client(&image, &inv.argv, &inv.env, None, &staged)
            .await?;
        if code != 0 {
            let _ = tokio::fs::remove_file(&staged).await;
            return Err(Perr::Other(format!(
                "pg capture base fallback dump for {db:?} exited {code}"
            )));
        }
        let meta = write_member_from_file(dir, idx, &staged).await?;
        let _ = tokio::fs::remove_file(&staged).await;
        Ok(meta)
    }

    /// Create `entry.slot` with an EXPORTED SNAPSHOT over a held `replication=database` session and
    /// run `pg_dump --snapshot=<name>` pinned to it, inside ONE ephemeral container, streaming the
    /// `-Fc` archive to `staged`. Returns the slot's consistent-point LSN
    /// (`confirmed_flush_lsn`). The session is the capture role (non-superuser `REPLICATION`); its
    /// password is RESET fresh by the superuser just before use (never persisted). A pre-existing
    /// slot of the name is dropped first (idempotent re-pin on resume).
    async fn pg_snapshot_pinned_dump(
        &self,
        conn: &PgConnection,
        image: &str,
        server_version_num: &str,
        entry: &PgCaptureEntry,
        staged: &Path,
        stage_dir: &Path,
    ) -> Result<String, Perr> {
        let role_q = quote_ident(ExternalSqlKind::Postgres, &entry.role);
        let slot_lit = pg_lit(&entry.slot);
        // SUPERUSER: drop any stale slot of this name (prior incomplete run), so the dump + slot
        // always share one fresh consistent point; never drop one that isn't ours by name.
        let (code, out) = self
            .pg_capture_sql(
                conn,
                image,
                &format!(
                    "SELECT pg_drop_replication_slot({slot_lit}) WHERE EXISTS (SELECT 1 FROM \
                     pg_replication_slots WHERE slot_name = {slot_lit})"
                ),
                stage_dir,
            )
            .await?;
        if code != 0 {
            return Err(Perr::Other(format!(
                "pg capture: drop stale slot {:?} before re-pin exited {code}: {out}",
                entry.slot
            )));
        }
        // SUPERUSER: reset the capture role's password to a fresh, never-persisted value so the
        // held replication session authenticates (mirrors the drain's reset-on-use pattern).
        let role_pw = random_token();
        let (code, out) = self
            .pg_capture_sql(
                conn,
                image,
                &format!("ALTER ROLE {role_q} PASSWORD {}", pg_lit(&role_pw)),
                stage_dir,
            )
            .await?;
        if code != 0 {
            return Err(Perr::Other(format!(
                "pg capture: reset capture-role password exited {code}: {out}"
            )));
        }

        // The pg_dump flags (NON-pinned) the base would normally use: --no-owner/--no-privileges,
        // the extension-comment handling, --no-publications (the capture publication must not land
        // in the dump), -Fc. We append `--snapshot=<exported snapshot>` in the orchestration.
        let exclude_extensions = self.trusted_extensions.clone();
        let dump = pg_dump_invocation(conn, false, server_version_num, &exclude_extensions, true);
        // argv[0] is "pg_dump"; the rest are flags (no credential, no bundle data) — sh-quote them.
        let dump_flags = sh_join(&dump.argv[1..]);
        let slot_cmd = create_replication_slot_export_sql(&entry.slot, server_version_num);

        // ONE container runs BOTH the held snapshot-export session (as the capture role) and the
        // pinned pg_dump (as the tenant conn). The replication session's stdin is a FIFO kept open
        // by fd 9 so psql never hits EOF (which would close the connection + drop the exported
        // snapshot); after the dump we close fd 9 to release it. The capture-role password rides in
        // $BREXP_CAP_PW (env, never argv); the slot name + flags are driver-derived identifiers.
        let script = format!(
            r#"set -u
COORD=$(mktemp) || exit 91
ERRF=$(mktemp) || exit 91
FIFO=$(mktemp -u) || exit 91
mkfifo "$FIFO" || exit 91
# The held replication session's query result → $COORD; its own stdout → /dev/null so NOTHING but
# the foreground pg_dump's `-Fc` archive ever reaches the container stdout (the member sink).
PGPASSWORD="$BREXP_CAP_PW" psql "host=$PGHOST port=$PGPORT user=$BREXP_CAP_ROLE dbname=$PGDATABASE replication=database" -At -F'|' -o "$COORD" <"$FIFO" >/dev/null 2>"$ERRF" &
REPL=$!
exec 9>"$FIFO"
printf '%s\n' {slot_cmd_q} >&9
SNAP=""
i=0
while [ $i -lt 600 ]; do
  SNAP=$(awk -F'|' 'NR==1{{print $3; exit}}' "$COORD" 2>/dev/null)
  [ -n "$SNAP" ] && break
  i=$((i+1)); sleep 0.1
done
if [ -z "$SNAP" ]; then
  echo "brexp: snapshot export failed: $(cat "$ERRF" 2>/dev/null)" >&2
  exec 9>&-; wait "$REPL" 2>/dev/null; exit 92
fi
pg_dump {dump_flags} --snapshot="$SNAP"
RC=$?
exec 9>&-
wait "$REPL" 2>/dev/null
exit $RC
"#,
            slot_cmd_q = sh_join(&[slot_cmd]),
            dump_flags = dump_flags,
        );
        let mut env = conn.env();
        env.push(("BREXP_CAP_ROLE".to_string(), entry.role.clone()));
        env.push(("BREXP_CAP_PW".to_string(), role_pw));
        let argv = vec!["sh".to_string(), "-c".to_string(), script];
        let code = self
            .run_sql_client(image, &argv, &env, None, staged)
            .await?;
        if code != 0 {
            return Err(Perr::Other(format!(
                "pg capture: snapshot-pinned base dump for slot {:?} exited {code} (snapshot export \
                 or pg_dump failed)",
                entry.slot
            )));
        }
        // The slot now exists at its consistent point; read it back as the recorded base cursor.
        // `confirmed_flush_lsn` of a freshly-created, never-consumed logical slot IS the exported
        // snapshot's consistent point (verified live). Empty ⇒ the slot vanished ⇒ treat as failure.
        let (code, lsn) = self
            .pg_capture_sql(
                conn,
                image,
                &format!(
                    "SELECT confirmed_flush_lsn FROM pg_replication_slots WHERE slot_name = {slot_lit}"
                ),
                stage_dir,
            )
            .await?;
        let lsn = lsn.trim().lines().next().unwrap_or("").trim().to_string();
        if code != 0 || lsn.is_empty() {
            return Err(Perr::Other(format!(
                "pg capture: snapshot-pinned slot {:?} has no confirmed_flush_lsn after creation \
                 (exit {code})",
                entry.slot
            )));
        }
        Ok(lsn)
    }

    /// Set `db`'s `base_lsn` in a resumable dir's capture sidecar (the snapshot-pin producer records
    /// the slot's consistent point once the slot is created). No-op if the sidecar/entry is gone.
    async fn pg_sidecar_set_base_lsn(&self, dir: &Path, db: &str, base_lsn: &str) {
        let Some(mut sidecar) = read_pg_capture_sidecar(dir).await else {
            return;
        };
        if let Some(e) = sidecar.dbs.get_mut(db) {
            e.base_lsn = base_lsn.to_string();
            if let Ok(bytes) = serde_json::to_vec_pretty(&sidecar) {
                let _ = write_atomic(&dir.join(PG_CAPTURE_SIDECAR), &bytes).await;
            }
        }
    }

    /// Remove `db`'s entry from a resumable dir's capture sidecar (the snapshot-pin fell back to a
    /// plain dump, so there is no slot to drain — the future delta full-dumps). Deletes the sidecar
    /// file entirely if it becomes empty.
    async fn pg_sidecar_remove_db(&self, dir: &Path, db: &str) {
        let Some(mut sidecar) = read_pg_capture_sidecar(dir).await else {
            return;
        };
        if sidecar.dbs.remove(db).is_some() {
            if sidecar.dbs.is_empty() {
                let _ = tokio::fs::remove_file(dir.join(PG_CAPTURE_SIDECAR)).await;
            } else if let Ok(bytes) = serde_json::to_vec_pretty(&sidecar) {
                let _ = write_atomic(&dir.join(PG_CAPTURE_SIDECAR), &bytes).await;
            }
        }
    }

    /// Drain one managed pg db's capture slot into a framed `pgoutput` byte stream (the `PgWalDelta`
    /// member), then DROP the slot+publication+role (bounded retention, §4). The superuser resets
    /// the capture role's password to a fresh value (so no role credential is persisted), then the
    /// drain runs AS the capture role (non-superuser). Returns `Ok(None)` when the slot is
    /// gone/invalid (reclaimed by the WAL ceiling) — the caller then falls back to a full dump.
    async fn pg_drain_capture(
        &self,
        project: &str,
        db: &str,
        cfg: &ExternalDatabaseConfig,
        entry: &PgCaptureEntry,
        stage_dir: &Path,
    ) -> Result<Option<Vec<u8>>, Perr> {
        let (su, image, _ver) = self.resolve_pg(project, db, cfg).await?;
        let slot_lit = pg_lit(&entry.slot);
        let role_q = quote_ident(ExternalSqlKind::Postgres, &entry.role);

        // Is the slot still present + usable? A slot the WAL ceiling invalidated has wal_status
        // 'lost'; a dropped/absent slot has no row. Either ⇒ no faithful WAL-delta ⇒ full-dump.
        let probe = format!(
            "SELECT coalesce((SELECT wal_status FROM pg_replication_slots WHERE slot_name = \
             {slot_lit}), 'missing')"
        );
        let (code, status) = self.pg_capture_sql(&su, &image, &probe, stage_dir).await?;
        if code != 0 {
            return Err(Perr::Other(format!(
                "pg capture: probe slot {:?} exited {code}: {status}",
                entry.slot
            )));
        }
        let status = status.trim();
        if status == "missing" || status == "lost" {
            self.pg_drop_capture(project, db, cfg, entry, stage_dir)
                .await;
            return Ok(None);
        }

        // Reset the capture role's password (superuser), so no credential is persisted on disk. A
        // failure here leaves the slot pinning WAL, so DROP it before returning (§4 LOW 4a:
        // drop-slot-on-drain-error — reclaim the WAL pin promptly; the delta then full-dumps).
        let role_pw = random_token();
        let (code, out) = self
            .pg_capture_sql(
                &su,
                &image,
                &format!("ALTER ROLE {role_q} PASSWORD {}", pg_lit(&role_pw)),
                stage_dir,
            )
            .await?;
        if code != 0 {
            self.pg_drop_capture(project, db, cfg, entry, stage_dir)
                .await;
            return Err(Perr::Other(format!(
                "pg capture: reset capture-role password for {db:?} exited {code}: {out}"
            )));
        }

        // Drain AS the capture role: GET (not peek) advances the slot + releases its pinned WAL.
        // Each row is one raw pgoutput message; hex-encode it over psql's text output (so a binary
        // stream survives the client cleanly), decode, and length-frame for the delta member. The
        // drain's stdout IS a DATA payload (the hex stream), so it runs through the NON-merging
        // capture (§4 LOW A1) — `merge_stderr_argv` must never wrap a data payload, lest a stderr
        // line co-mingle into the hex. On a non-zero exit stderr is dropped (fail-closed).
        let role_conn = capture_role_conn(&su, &entry.role, &role_pw);
        let drain = format!(
            "SELECT encode(data, 'hex') FROM pg_logical_slot_get_binary_changes({slot_lit}, NULL, \
             NULL, 'proto_version', '1', 'publication_names', {})",
            pg_lit(&entry.publication)
        );
        let drain_inv = psql_invocation(&role_conn, &drain);
        let (code, out) = self
            .run_sql_capture_nomerge(&image, &drain_inv.argv, &drain_inv.env, None, stage_dir)
            .await?;
        if code != 0 {
            // §4 LOW 4a: a drain error on a non-`lost`/non-`missing` path reclaims the slot now
            // (the WAL ceiling would eventually, but promptly is better) — the delta full-dumps.
            self.pg_drop_capture(project, db, cfg, entry, stage_dir)
                .await;
            return Err(Perr::Other(format!(
                "pg capture: drain slot {:?} for {db:?} exited {code}",
                entry.slot
            )));
        }
        let mut framed = Vec::new();
        for line in out.lines() {
            let h = line.trim();
            if h.is_empty() {
                continue;
            }
            let raw = match hex::decode(h) {
                Ok(r) => r,
                Err(e) => {
                    // A non-hex drained row (never expected on a clean drain) ⇒ reclaim the slot
                    // (§4 LOW 4a) and fail closed; the delta falls back to a full dump.
                    self.pg_drop_capture(project, db, cfg, entry, stage_dir)
                        .await;
                    return Err(Perr::Other(format!(
                        "pg capture: a drained row is not valid hex for {db:?}: {e}"
                    )));
                }
            };
            framed.extend_from_slice(&boatramp_core::pgoutput::frame_message(&raw));
        }

        // Bounded retention: the delta is captured ⇒ drop the slot+publication+role now.
        self.pg_drop_capture(project, db, cfg, entry, stage_dir)
            .await;
        Ok(Some(framed))
    }

    /// Best-effort teardown of one db's capture artifacts (slot ⇒ publication ⇒ role), as the
    /// SUPERUSER. Called on drain completion, on abort, and from the startup orphan sweep. The slot
    /// is dropped before the role that owns it.
    async fn pg_drop_capture(
        &self,
        project: &str,
        db: &str,
        cfg: &ExternalDatabaseConfig,
        entry: &PgCaptureEntry,
        stage_dir: &Path,
    ) {
        let Ok((su, image, _ver)) = self.resolve_pg(project, db, cfg).await else {
            return;
        };
        let role_q = quote_ident(ExternalSqlKind::Postgres, &entry.role);
        let pub_q = quote_ident(ExternalSqlKind::Postgres, &entry.publication);
        let slot_lit = pg_lit(&entry.slot);
        // Drop the slot only if it still exists (the SQL-function drain leaves no active backend,
        // so a plain drop succeeds). `WHERE EXISTS` keeps it a no-op if already gone.
        let _ = self
            .pg_capture_sql(
                &su,
                &image,
                &format!(
                    "SELECT pg_drop_replication_slot({slot_lit}) WHERE EXISTS (SELECT 1 FROM \
                     pg_replication_slots WHERE slot_name = {slot_lit})"
                ),
                stage_dir,
            )
            .await;
        let _ = self
            .pg_capture_sql(
                &su,
                &image,
                &format!("DROP PUBLICATION IF EXISTS {pub_q}"),
                stage_dir,
            )
            .await;
        let _ = self
            .pg_capture_sql(
                &su,
                &image,
                &format!("DROP ROLE IF EXISTS {role_q}"),
                stage_dir,
            )
            .await;
    }

    /// Try to produce a pg WAL true-delta member for one db from the PARENT base's capture sidecar.
    /// Returns `Some((framed_pgoutput_bytes, PgLsn cursor))` when a faithful WAL delta is available,
    /// or `None` to signal the caller to keep the full-dump fallback. A capture hiccup (drain error)
    /// is logged + treated as a fallback — the delta export itself never fails for a best-effort
    /// true-delta. Falls back when: the db is not capture-eligible, the parent recorded no slot for
    /// it, the SCHEMA FINGERPRINT changed since the base (logical decoding carries no DDL), or the
    /// slot is gone/lost (reclaimed by the WAL ceiling).
    async fn try_pg_wal_delta(
        &self,
        project: &str,
        db: &str,
        sidecar: &PgCaptureSidecar,
        cap_dir: &Path,
    ) -> Option<(Vec<u8>, boatramp_core::project_delta::SqlMemberCursor)> {
        let cfg = self.databases.get(db)?;
        if !Self::pg_capture_eligible(cfg) {
            return None;
        }
        let entry = sidecar.dbs.get(db)?;
        // PENDING/INCOMPLETE capture: an empty `base_lsn` is a sidecar entry whose slot was never
        // successfully snapshot-pinned (the base producer fell back / crashed before filling it), so
        // there is no reliable slot to drain ⇒ full-dump.
        if entry.base_lsn.is_empty() {
            tracing::info!(db = %db, "pg delta: base capture never completed (no pinned slot) — falling back to a full dump");
            return None;
        }
        // SCHEMA-FINGERPRINT FALLBACK: a DDL change between base and delta cannot be WAL-replayed.
        // Treat None==None as "unchanged"; any difference (incl. one side absent) forces a dump.
        let current_fp = self.schema_fingerprint(project, db).await;
        if current_fp != entry.schema_fingerprint {
            tracing::info!(db = %db, "pg delta: schema fingerprint changed since the base — falling back to a full dump");
            return None;
        }
        match self
            .pg_drain_capture(project, db, cfg, entry, cap_dir)
            .await
        {
            Ok(Some(bytes)) => Some((
                bytes,
                boatramp_core::project_delta::SqlMemberCursor::PgLsn {
                    lsn: entry.base_lsn.clone(),
                },
            )),
            Ok(None) => None, // slot lost/missing ⇒ full-dump fallback
            Err(e) => {
                tracing::warn!(error = %e, db = %db, "pg delta: WAL drain failed — falling back to a full dump");
                None
            }
        }
    }

    /// Collect every capture artifact name (slot / role / publication) a PENDING, NOT-YET-STALE base
    /// still references, by scanning the resumable base for `pg_capture.json` sidecars. The orphan
    /// sweep drops only `brexp_*` artifacts NOT in this set, so a legitimately-pending base→delta
    /// chain's slot is never reclaimed from under it — EXCEPT once the base is older than
    /// [`STALE_RESUMABLE_CAPTURE_TTL_SECS`] (§4 LOW 4b): a stale entry stops shielding its slot, so an
    /// abandoned-but-resumable base's WAL pin is reclaimed rather than held forever. An entry's age is
    /// its recorded `created_at` (falling back to the sidecar file's mtime for a pre-TTL sidecar).
    /// Bounded walk; no resumable base ⇒ empty set.
    async fn collect_pending_capture_names(&self) -> std::collections::HashSet<String> {
        let mut wanted = std::collections::HashSet::new();
        let Some(base) = self.resumable_base.as_ref() else {
            return wanted;
        };
        let now = now_secs();
        let mut stack = vec![base.clone()];
        let mut budget = 4096usize; // bound the walk against a pathological tree
        while let Some(dir) = stack.pop() {
            if budget == 0 {
                break;
            }
            budget -= 1;
            if let Some(sidecar) = read_pg_capture_sidecar(&dir).await {
                // A pre-TTL sidecar (every entry `created_at == 0`) has no per-entry age — fall back
                // to the sidecar FILE's mtime as the base's age, computed once per dir.
                let file_age_secs = pg_capture_sidecar_age_secs(&dir, now).await;
                for e in sidecar.dbs.values() {
                    if !capture_entry_shielded(
                        e.created_at,
                        file_age_secs,
                        now,
                        STALE_RESUMABLE_CAPTURE_TTL_SECS,
                    ) {
                        continue; // stale/abandoned base — stop shielding its slot (§4 LOW 4b)
                    }
                    wanted.insert(e.slot.clone());
                    wanted.insert(e.role.clone());
                    wanted.insert(e.publication.clone());
                }
            }
            if let Ok(mut rd) = tokio::fs::read_dir(&dir).await {
                while let Ok(Some(ent)) = rd.next_entry().await {
                    if ent.file_type().await.map(|t| t.is_dir()).unwrap_or(false) {
                        stack.push(ent.path());
                    }
                }
            }
        }
        wanted
    }

    /// Mint the NON-slot capture artifacts (ephemeral REPLICATION role + `FOR ALL TABLES`
    /// publication) for every capture-eligible pg db covered by a BASE (full) resumable export,
    /// writing a PENDING `pg_capture.json` entry (empty `base_lsn`) per db so the later
    /// snapshot-pinned producer can create the slot + fill the LSN, and so a later incremental delta
    /// can drain it. The publication must exist before the slot's consistent point, so this runs
    /// BEFORE member production (the slot is created SNAPSHOT-PINNED during the base dump, see
    /// [`produce_pg_capture_base`]). Idempotent on resume (skips if a sidecar already exists). Failure
    /// to begin capture for one db is NON-fatal: that db simply has no sidecar entry and its future
    /// delta full-dumps (true-delta is best-effort; the export itself must not fail for it).
    async fn pg_capture_base_slots(&self, project: &str, dir: &Path, stage_dir: &Path) {
        if read_pg_capture_sidecar(dir).await.is_some() {
            return; // resume: role+publication already minted (+ any slot the producer pinned).
        }
        let mut sidecar = PgCaptureSidecar::default();
        for (db, cfg) in &self.databases {
            if !Self::pg_capture_eligible(cfg) {
                continue;
            }
            match self.pg_begin_capture(project, db, cfg, stage_dir).await {
                Ok(entry) => {
                    sidecar.dbs.insert(db.clone(), entry);
                }
                Err(e) => {
                    tracing::warn!(error = %e, db = %db, "pg delta capture: could not create a base slot; this db's delta will fall back to a full dump");
                }
            }
        }
        if !sidecar.dbs.is_empty()
            && let Ok(bytes) = serde_json::to_vec_pretty(&sidecar)
        {
            let _ = write_atomic(&dir.join(PG_CAPTURE_SIDECAR), &bytes).await;
        }
    }

    /// Restore every managed-pg db covered by a resolved delta chain via the atomic shadow: the
    /// newest FULL dump in the chain is restored into a fresh shadow, every subsequent `PgWalDelta`
    /// is REPLAYED onto it as the ephemeral NON-superuser role, then the shadow is atomically
    /// swapped in. A render/replay/restore failure drops the shadow (live untouched) and fails the
    /// import loud. (An external pg db never produces a `PgWalDelta` — capture is managed-only — so
    /// a chain carrying one for a non-managed db is a malformed bundle and is refused.)
    async fn restore_pg_true_delta_in_chain(
        &self,
        project: &str,
        chain: &[(PathBuf, project_bundle::StreamManifest)],
        opts: &ImportOptions,
        report: &mut ImportReport,
        stage_dir: &Path,
    ) -> Result<(), Perr> {
        // Per managed-pg db: the newest FULL dump (base, or a fallback delta) + the WAL deltas AFTER
        // it, in chain order (a newer full dump supersedes earlier WAL).
        struct DbPlan {
            base: Option<(PathBuf, usize)>,
            wal: Vec<(PathBuf, usize)>,
        }
        let mut per_db: BTreeMap<String, DbPlan> = BTreeMap::new();
        for (dir, m) in chain {
            for (idx, spec) in m.members.iter().enumerate() {
                match spec.kind {
                    MemberKind::PgDump => {
                        if let Some(db) =
                            db_from_pg_member(&spec.path).filter(|d| self.is_managed_pg(d))
                        {
                            let e = per_db.entry(db.to_string()).or_insert(DbPlan {
                                base: None,
                                wal: Vec::new(),
                            });
                            e.base = Some((dir.clone(), idx));
                            e.wal.clear();
                        }
                    }
                    MemberKind::PgWalDelta => {
                        if let Some(db) = db_from_pgwal_member(&spec.path) {
                            if !self.is_managed_pg(db) {
                                return Err(Perr::Other(format!(
                                    "pg true-delta restore: a PgWalDelta member {:?} names db {db:?} \
                                     which is not a managed pg binding on this node — malformed bundle",
                                    spec.path
                                )));
                            }
                            per_db
                                .entry(db.to_string())
                                .or_insert(DbPlan {
                                    base: None,
                                    wal: Vec::new(),
                                })
                                .wal
                                .push((dir.clone(), idx));
                        }
                    }
                    _ => {}
                }
            }
        }
        if per_db.is_empty() {
            return Ok(());
        }
        if !opts.apply {
            // Dry-run: account for each db, touch nothing live.
            report.pg_databases += per_db.len();
            return Ok(());
        }
        for (db, plan_db) in per_db {
            let Some((base_dir, base_idx)) = plan_db.base else {
                return Err(Perr::Other(format!(
                    "pg true-delta restore: db {db:?} has WAL delta member(s) but no full base dump \
                     in the chain — cannot replay onto nothing"
                )));
            };
            let cfg = self
                .databases
                .get(&db)
                .ok_or_else(|| {
                    Perr::Other(format!("import: no database named {db:?} on this node"))
                })?
                .clone();
            let plan = self.pg_shadow_plan(project, &db, &cfg).await?;
            if let Err(e) = self.pg_create_shadow(&plan, stage_dir).await {
                self.pg_drop_shadow(&plan, stage_dir).await;
                return Err(e);
            }
            // FAIL-CLOSED: the replay applies UNTRUSTED decoded SQL, so the apply role MUST be a
            // provable non-superuser (inc2 HIGH-1) — the same guard the chunked dump restore uses.
            if let Err(e) = self
                .pg_assert_not_superuser(&plan.apply_conn(), &plan.image, stage_dir)
                .await
            {
                self.pg_drop_shadow(&plan, stage_dir).await;
                return Err(e);
            }
            let base_obj = base_dir.join(member_object_name(base_idx));
            if let Err(e) = self
                .pg_restore_base_into_shadow(&plan, &base_obj, stage_dir)
                .await
            {
                self.pg_drop_shadow(&plan, stage_dir).await;
                return Err(e);
            }
            for (dir, idx) in &plan_db.wal {
                let framed = tokio::fs::read(dir.join(member_object_name(*idx)))
                    .await
                    .map_err(other)?;
                if let Err(e) = self.pg_replay_wal(&plan, &framed, stage_dir).await {
                    self.pg_drop_shadow(&plan, stage_dir).await;
                    return Err(e);
                }
            }
            if let Err(e) = self.pg_swap_shadow(&plan, stage_dir).await {
                self.pg_drop_shadow(&plan, stage_dir).await;
                return Err(e);
            }
            report.pg_databases += 1;
        }
        Ok(())
    }

    /// Stream a base full-dump member object into a freshly-created shadow via `pg_restore` (as the
    /// ephemeral non-superuser role). A non-zero exit drops nothing here (the caller tears the
    /// shadow down) but surfaces the client's error.
    async fn pg_restore_base_into_shadow(
        &self,
        plan: &PgShadowPlan,
        base_obj: &Path,
        stage_dir: &Path,
    ) -> Result<(), Perr> {
        let (tx, rx) = tokio::sync::mpsc::channel::<Vec<u8>>(16);
        let out_path = stage_dir.join(format!("pgwal-base-restore-{}.out", shadow_suffix()));
        let restore = self.spawn_pg_restore(plan, rx, out_path.clone())?;
        // Feed the base dump member object (the raw `pg_dump -Fc` bytes) into the restore's stdin.
        let src = base_obj.to_path_buf();
        let feeder = tokio::spawn(async move {
            use tokio::io::AsyncReadExt;
            let mut f = tokio::fs::File::open(&src).await?;
            let mut buf = vec![0u8; 256 * 1024];
            loop {
                let n = f.read(&mut buf).await?;
                if n == 0 {
                    break;
                }
                if tx.send(buf[..n].to_vec()).await.is_err() {
                    break;
                }
            }
            Ok::<(), std::io::Error>(())
        });
        let code = restore.await;
        let _ = feeder.await;
        let out = tokio::fs::read_to_string(&out_path)
            .await
            .unwrap_or_default();
        let _ = tokio::fs::remove_file(&out_path).await;
        match code {
            Ok(Ok(0)) => Ok(()),
            Ok(Ok(c)) => Err(Perr::Other(format!(
                "pg true-delta base restore into shadow {:?} exited {c}: {out}",
                plan.shadow_db
            ))),
            Ok(Err(e)) => Err(e),
            Err(je) => Err(other(je)),
        }
    }

    /// Decode + render + EXECUTE one `PgWalDelta` member onto the shadow, as the ephemeral
    /// NON-superuser owner role. The decode/render is the UNTRUSTED-delta trust boundary: a value
    /// that cannot be rendered faithfully (e.g. `REPLICA IDENTITY NOTHING`) is a loud error (the
    /// bundle should then have fallen back to a full dump). `standard_conforming_strings = on`
    /// makes `quote_literal`'s single-quote-doubling the only escaping; `ON_ERROR_STOP` aborts the
    /// psql run on the first failed statement (and the caller drops the shadow — live untouched).
    async fn pg_replay_wal(
        &self,
        plan: &PgShadowPlan,
        framed: &[u8],
        stage_dir: &Path,
    ) -> Result<(), Perr> {
        let changes = boatramp_core::pgoutput::decode_framed(framed)
            .map_err(|e| Perr::Other(format!("pg WAL delta: decode failed: {e}")))?;
        let stmts = boatramp_core::pgoutput::render_changes(&changes).map_err(|e| {
            Perr::Other(format!(
                "pg WAL delta: cannot faithfully replay ({e}); such a delta must fall back to a \
                 full dump — refusing a partial restore"
            ))
        })?;
        if stmts.is_empty() {
            return Ok(());
        }
        // The replay script: SCS on (so the rendered literals are the only quoting), then each
        // rendered statement `;`-terminated. `render_changes` emits BEGIN/COMMIT so a source
        // transaction stays atomic on replay; a mid-script failure under ON_ERROR_STOP aborts the
        // run (the caller drops the shadow, so nothing partial reaches live).
        let mut script = String::from("SET standard_conforming_strings = on;\n");
        for s in &stmts {
            script.push_str(s);
            script.push_str(";\n");
        }
        let script_path = stage_dir.join(format!("pgwal-replay-{}.sql", shadow_suffix()));
        tokio::fs::write(&script_path, script.as_bytes())
            .await
            .map_err(other)?;
        let apply = plan.apply_conn();
        // psql reads the replay script from STDIN (so the delta's quoted data never enters argv).
        let argv = vec![
            "psql".to_string(),
            "-v".to_string(),
            "ON_ERROR_STOP=1".to_string(),
        ];
        let r = self
            .run_sql_capture(
                &plan.image,
                &argv,
                &apply.env(),
                Some(&script_path),
                stage_dir,
            )
            .await;
        let _ = tokio::fs::remove_file(&script_path).await;
        let (code, out) = r?;
        if code != 0 {
            return Err(Perr::Other(format!(
                "pg WAL delta replay into shadow {:?} exited {code}: {out}",
                plan.shadow_db
            )));
        }
        Ok(())
    }
}

/// Quote a MySQL **string literal** (single-quoted, doubling embedded `'`) — for our own generated
/// `information_schema` predicates + grant user literals (db/role names are driver-derived).
fn mysql_lit(s: &str) -> String {
    format!("'{}'", s.replace('\'', "''"))
}

// ===========================================================================================
// MySQL binlog true-delta: CAPTURE (export) + REPLAY (restore) — PLAN-sql-true-delta Stage 3.
// (Kept textually separate from the pg engine above to minimize merge conflict; it reuses only the
// shared primitives — the inc2 mysql atomic shadow + the resumable member-object layout.)
//
// CAPTURE. A managed, dedicated/Single mysql db with `delta_capture` (the launch argv carries
// `--log-bin --binlog-format=ROW --gtid-mode=ON …`) sources a row-level delta from the server's
// binlog. Unlike pg (whose slot pins a point BEFORE the base dump, leaving an overlap window), the
// mysql base is SNAPSHOT-PINNED: the BASE (full) resumable export dumps it with
// `mysqldump --source-data=2 --set-gtid-purged=COMMENTED` so the dump header records its OWN
// consistent-snapshot `gtid_executed` + binlog file. The driver STRIPS the privileged
// `SET @@SESSION.SQL_LOG_BIN` toggles mysqldump injects (so the member still restores under the
// least-privilege shadow apply user) and records `{base_gtid, start_log, schema_fingerprint}` in a
// `mysql_capture.json` sidecar — the mysql analogue of `pg_capture.json`. There is NO long-lived
// slot: the server retains the binlog (`binlog_expire_logs_seconds`), so an INCREMENTAL delta mints
// an EPHEMERAL `REPLICATION SLAVE, REPLICATION CLIENT` reader user, streams the binlog since the base
// (`mysqlbinlog --read-from-remote-server --raw` — no server-filesystem access), `tar`s the raw files
// into the `MysqlBinlogDelta` member, then drops the reader user. A schema change since the base
// (fingerprint), a DDL `QUERY_EVENT` in the range, a purged start log, or a drain error all fall back
// to a full dump for that db (best-effort true-delta; the delta bundle is always restorable).
//
// REPLAY. `restore_mysql_true_delta_in_chain` restores the chain's newest FULL dump into the inc2
// atomic mysql shadow, then replays each subsequent `MysqlBinlogDelta` onto it. The raw files are
// decoded LOCALLY (so `--exclude-gtids` + `--rewrite-db` are both allowed, unlike a remote read):
// `mysqlbinlog --skip-gtids --exclude-gtids=<base> --rewrite-db='<live>-><shadow>' --database=<shadow>
// … | mysql <shadow>`, EXECUTED as an EPHEMERAL apply user holding `REPLICATION_APPLIER` +
// `SESSION_VARIABLES_ADMIN` + `ALL ON <shadow>.*` ONLY (NO SUPER/FILE/BINLOG_ADMIN, NO global DML) —
// so a crafted binlog's `BINLOG` row event targeting any table outside the shadow is REFUSED by the
// table-privilege check (validated: the applier privilege does NOT bypass it), and the
// `--rewrite-db`/`--database` pair redirects the source db's events to the shadow + DROPS every
// foreign-db event (defense in depth). Then the atomic `RENAME TABLE` swap. A decode/replay failure
// drops the shadow (live untouched) and fails the import loud.
//
// IMAGE. `mysqlbinlog` ships in the DEBIAN variant of the mysql image, not the (Oracle-Linux) default
// `mysql:<maj.min>` the dump/restore use — so capture + replay run in `mysql:<maj.min>-debian`
// (see `mysql_binlog_image`). SCOPE: managed dedicated/Single mysql only (Shared refused, like pg).
// ===========================================================================================

/// The mysql-capture sidecar filename written beside a resumable export dir's member objects.
const MYSQL_CAPTURE_SIDECAR: &str = "mysql_capture.json";

/// One managed-mysql db's base capture coordinate, recorded in the resumable dir's
/// `mysql_capture.json` so a later INCREMENTAL delta can stream the binlog since the base. Carries
/// only NON-secret coordinates (no credential — the ephemeral reader user is minted fresh at drain
/// with a never-persisted password).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct MysqlCaptureEntry {
    /// The `gtid_executed` at the base dump's consistent snapshot (parsed from its COMMENTED
    /// `SET @@GLOBAL.GTID_PURGED`). The delta's `--exclude-gtids` replays from exactly this point.
    base_gtid: String,
    /// The binlog file at the base snapshot (parsed from the dump's COMMENTED `CHANGE MASTER TO
    /// MASTER_LOG_FILE`). The delta's `mysqlbinlog -R` streams from this file to the current end.
    start_log: String,
    /// The source schema-ledger fingerprint at capture time. A delta whose current fingerprint
    /// differs MUST fall back to a full dump (binlog ROW events carry no faithful cross-DDL replay).
    #[serde(default)]
    schema_fingerprint: Option<String>,
}

/// A resumable dir's mysql-capture sidecar: per-db base coordinates keyed by the node's binding name.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
struct MysqlCaptureSidecar {
    dbs: BTreeMap<String, MysqlCaptureEntry>,
}

/// Read the mysql-capture sidecar from a resumable dir (absent/corrupt ⇒ `None`).
async fn read_mysql_capture_sidecar(dir: &Path) -> Option<MysqlCaptureSidecar> {
    let bytes = tokio::fs::read(dir.join(MYSQL_CAPTURE_SIDECAR))
        .await
        .ok()?;
    serde_json::from_slice(&bytes).ok()
}

/// The `mysqlbinlog`-bearing client image for a resolved `mysql:<maj.min>` dump/restore image: the
/// DEBIAN variant. The Oracle-Linux default `mysql:<maj.min>` ships `mysql`/`mysqldump` but NOT
/// `mysqlbinlog`; the `-debian` variant ships the full client suite. Idempotent (never double-adds).
fn mysql_binlog_image(client_image: &str) -> String {
    if client_image.ends_with("-debian") {
        client_image.to_string()
    } else {
        format!("{client_image}-debian")
    }
}

/// The transient SHADOW database name a mysql binlog true-delta is captured-rewritten to AND restored
/// into. Derived deterministically from the binding's live db so the CAPTURE rewrite target
/// (`mysqlbinlog --rewrite-db='<live>-><this>'`) and the RESTORE shadow are the SAME db — the member
/// is decoded SQL text (not re-rewritable at replay), so the rewrite is baked at capture against this
/// name. The `__shadow_` infix makes the startup `%__shadow_%` sweep reclaim a crashed one.
///
/// NOTE: this is FIXED per db (not per-import), so two concurrent true-delta imports of the SAME db
/// would collide on `CREATE DATABASE` (a clean refusal, never corruption — the restore never drops a
/// pre-existing shadow). Concurrent-import support is a tracked follow-up.
fn mysql_delta_shadow_db(live_db: &str) -> String {
    format!("{live_db}__shadow_brdelta")
}

/// SWAP-SAFETY INVARIANT (data-loss guard): `true` when swapping the shadow in for live would move
/// the LIVE tables aside with NO shadow replacement to put back — i.e. the shadow is EMPTY while
/// live is non-empty. A swap in this state would `RENAME` live aside + `DROP` the aside, DESTROYING
/// tenant data (the same-db import collision race: a colliding import can drop another import's
/// populated shadow, leaving this swap to see an empty shadow). The swap MUST abort here, leaving
/// live intact, rather than empty a tenant's database. (Importing a legitimately-empty database over
/// a non-empty live is also refused by this — an accepted trade for never destroying live data; a
/// genuine "empty the db" is done out of band.)
fn swap_would_destroy_live(live_tables: &[String], shadow_tables: &[String]) -> bool {
    !live_tables.is_empty() && shadow_tables.is_empty()
}

/// Whether a dump line is one of mysqldump's privileged `SQL_LOG_BIN` toggles (emitted by
/// `--source-data`). These need `SESSION_VARIABLES_ADMIN`, which the least-privilege shadow apply
/// user does NOT hold, so the capture-base producer STRIPS them — leaving the COMMENTED GTID/file
/// coordinates (which the sidecar parses) but no executable privileged statement.
fn mysql_line_is_sql_log_bin_toggle(line: &str) -> bool {
    let t = line.trim_start();
    t.starts_with("SET @MYSQLDUMP_TEMP_LOG_BIN") || t.starts_with("SET @@SESSION.SQL_LOG_BIN")
}

/// The PRIVILEGE part of a `SHOW GRANTS` line — everything BEFORE the first " ON " (which separates
/// the privilege list from the grant TARGET, e.g. `GRANT ALL PRIVILEGES ON \`db\`.* TO …`). The
/// confinement probes match dangerous privilege TOKENS against THIS, never the whole line, so a db
/// NAMED after " ON " (e.g. `supervisors`, `filestore`, `profiles` → "SUPER"/"FILE") cannot
/// false-trip the SUPER/FILE/BINLOG_ADMIN substring checks. A backticked target db that itself
/// contains " ON " stays after the first split, so the privilege part is unaffected.
fn mysql_grant_privileges(line: &str) -> &str {
    line.split(" ON ").next().unwrap_or(line)
}

/// Parse the base snapshot coordinate `(base_gtid, start_log)` from a `--source-data=2
/// --set-gtid-purged=COMMENTED` dump header: the COMMENTED `SET @@GLOBAL.GTID_PURGED='+<gtid>'` and
/// the COMMENTED `CHANGE MASTER TO MASTER_LOG_FILE='<file>'`. `None` if either is absent (⇒ the db
/// is not binlog/GTID-enabled as expected, so the delta falls back to a full dump).
fn parse_mysql_base_coord(header: &str) -> Option<(String, String)> {
    let between = |hay: &str, open: &str| -> Option<String> {
        let start = hay.find(open)? + open.len();
        let rest = &hay[start..];
        let end = rest.find('\'')?;
        Some(rest[..end].to_string())
    };
    let gtid = between(header, "GTID_PURGED='")?;
    // The COMMENTED form prefixes the set with a `+` (`'+<gtid>'`); drop it for the raw GTID set.
    let gtid = gtid.trim_start_matches('+').to_string();
    let start_log = between(header, "MASTER_LOG_FILE='")?;
    if gtid.is_empty() || start_log.is_empty() {
        return None;
    }
    Some((gtid, start_log))
}

/// Whether a `mysqlbinlog`-decoded delta carries a DDL `QUERY_EVENT` in the range — in which case the
/// delta MUST fall back to a full dump (binlog ROW events replay DML faithfully, but a schema change
/// between base and delta cannot be row-replayed onto the base). In `binlog_format=ROW`, DML is a
/// `BINLOG '…'` base64 statement (zero bare SQL), so the ONLY bare SQL statements a clean ROW delta
/// emits are the session-context `SET`s + transaction control (`BEGIN`/`COMMIT`/…); ANY other bare
/// statement (a `CREATE`/`ALTER`/`DROP`/`RENAME`/`TRUNCATE`/`GRANT`/…) is a DDL event ⇒ fall back.
fn mysql_binlog_decoded_has_ddl(decoded: &str) -> bool {
    for raw in decoded.lines() {
        let line = raw.trim();
        if line.is_empty()
            || line.starts_with('#') // event header / verbose comment
            || line.starts_with("/*") // conditional-comment-wrapped directive
            || line.starts_with("DELIMITER")
            || line.starts_with("SET ") // session context + GTID_NEXT + PSEUDO_SLAVE_MODE
            || line.starts_with("BINLOG ") // the base64 ROW payload opener
            || line == "'" // BINLOG payload terminators / `'/*!*/;`
            || line.starts_with("'/*")
        {
            continue;
        }
        let up = line.to_ascii_uppercase();
        // Transaction control is not DDL.
        if up.starts_with("BEGIN")
            || up.starts_with("COMMIT")
            || up.starts_with("ROLLBACK")
            || up.starts_with("START TRANSACTION")
            || up.starts_with("SAVEPOINT")
            || up.starts_with("RELEASE SAVEPOINT")
        {
            continue;
        }
        // A base64 payload body line (no SQL keywords, just base64) — treat as continuation.
        if line
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '/' || c == '=')
        {
            continue;
        }
        // Anything else that reaches here is a bare SQL statement ⇒ a DDL event in the range.
        return true;
    }
    false
}

/// Build a reader connection (ephemeral `REPLICATION SLAVE, REPLICATION CLIENT` user) by swapping the
/// identity of the superuser/operator connection (same host/port; fresh user + never-persisted pw).
fn mysql_reader_conn(op: &MysqlConnection, user: &str, password: &str) -> MysqlConnection {
    let mut c = op.clone();
    c.user = user.to_string();
    c.password = password.to_string();
    c
}

impl NodeProjectExport {
    /// Whether a db binding is eligible for mysql binlog true-delta capture: MANAGED + mysql +
    /// `delta_capture` on + dedicated/Single (NOT external, NOT Shared — the inc2 shadow-path
    /// restriction; a Shared multi-tenant server's cross-db binlog is out of scope).
    fn mysql_capture_eligible(cfg: &ExternalDatabaseConfig) -> bool {
        is_managed_binding(cfg)
            && kind_is_mysql(&cfg.kind)
            && cfg.delta_capture
            && !matches!(cfg.tenant, crate::config::TenantIsolation::Shared)
    }

    /// Whether a configured db is a MANAGED mysql binding (its SQL members take the atomic shadow
    /// true-delta restore path, not `restore_member`).
    fn is_managed_mysql(&self, db: &str) -> bool {
        self.databases
            .get(db)
            .map(|c| is_managed_binding(c) && kind_is_mysql(&c.kind))
            .unwrap_or(false)
    }

    /// Run ONE trusted/driver-generated mysql statement on a bare connection (no shadow plan), as
    /// `-N --batch` admin SQL fed on stdin. Used for the ephemeral reader-user lifecycle (which has no
    /// shadow). Returns `(exit_code, trimmed stdout+stderr)`.
    async fn mysql_admin_sql(
        &self,
        conn: &MysqlConnection,
        image: &str,
        sql: &str,
        stage_dir: &Path,
    ) -> Result<(i32, String), Perr> {
        let inv = mysql_admin_invocation(conn);
        let in_path = stage_dir.join(format!("mysql-adm-{}.sql", shadow_suffix()));
        tokio::fs::write(&in_path, sql).await.map_err(other)?;
        let r = self
            .run_sql_capture(image, &inv.argv, &inv.env, Some(&in_path), stage_dir)
            .await;
        let _ = tokio::fs::remove_file(&in_path).await;
        r
    }

    /// Produce ONE capture-eligible managed-mysql db's BASE member object (resumable layout): dump it
    /// `--source-data=2 --set-gtid-purged=COMMENTED` (tables-only, snapshot-pinned) to a staging temp,
    /// STRIP the privileged `SET @@SESSION.SQL_LOG_BIN` toggles so the member restores under the
    /// least-privilege shadow apply user, then write it as `m{idx}` (+ meta). The COMMENTED GTID/file
    /// coordinates survive the strip for `mysql_capture_base_gtids` to parse. Mirrors the generic
    /// Sidecar production (stage → `write_member_from_file`) but with the capture dump + strip.
    async fn produce_mysql_capture_base(
        &self,
        project: &str,
        dir: &Path,
        idx: usize,
        db: &str,
        cfg: &ExternalDatabaseConfig,
        stage_dir: &Path,
    ) -> Result<project_bundle::MemberMeta, Perr> {
        let (conn, image, _ver) = self.resolve_mysql(project, db, cfg).await?;
        let inv = mysqldump_capture_base_invocation(&conn);
        let raw = stage_dir.join(format!("mysqlcap-raw-{idx}"));
        let code = self
            .run_sql_client(&image, &inv.argv, &inv.env, None, &raw)
            .await?;
        if code != 0 {
            let _ = tokio::fs::remove_file(&raw).await;
            return Err(Perr::Other(format!(
                "mysql capture base dump for {db:?} exited {code}"
            )));
        }
        // Strip the privileged SQL_LOG_BIN toggles, streaming line-by-line (header+footer only, but
        // scan the whole file) into the final staged temp.
        let stripped = stage_dir.join(format!("mysqlcap-strip-{idx}"));
        {
            use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
            let rd = tokio::fs::File::open(&raw).await.map_err(other)?;
            let mut lines = tokio::io::BufReader::new(rd).lines();
            let mut wr = tokio::fs::File::create(&stripped).await.map_err(other)?;
            while let Some(line) = lines.next_line().await.map_err(other)? {
                if mysql_line_is_sql_log_bin_toggle(&line) {
                    continue;
                }
                wr.write_all(line.as_bytes()).await.map_err(other)?;
                wr.write_all(b"\n").await.map_err(other)?;
            }
            wr.flush().await.map_err(other)?;
        }
        let _ = tokio::fs::remove_file(&raw).await;
        let meta = write_member_from_file(dir, idx, &stripped).await?;
        let _ = tokio::fs::remove_file(&stripped).await;
        Ok(meta)
    }

    /// Write the `mysql_capture.json` base sidecar from the committed base member objects (post the
    /// resumable member loop, mirror of pg's `pg_capture_base_slots` but READING the produced dumps):
    /// for each capture-eligible managed-mysql db, parse the base GTID + start binlog file from its
    /// `sql/<db>.sql` member header + record the schema fingerprint. Idempotent on resume (skips if a
    /// sidecar already exists). A db whose coordinate can't be parsed simply has no entry (its future
    /// delta full-dumps). Non-fatal throughout — true-delta is best-effort.
    async fn mysql_capture_base_gtids(&self, project: &str, dir: &Path, specs: &[MemberSpec]) {
        if read_mysql_capture_sidecar(dir).await.is_some() {
            return; // resume: coordinates already recorded.
        }
        let mut sidecar = MysqlCaptureSidecar::default();
        for (idx, spec) in specs.iter().enumerate() {
            if spec.kind != MemberKind::MysqlDump {
                continue;
            }
            let Some(db) = db_from_mysql_member(&spec.path) else {
                continue;
            };
            let Some(cfg) = self.databases.get(db) else {
                continue;
            };
            if !Self::mysql_capture_eligible(cfg) {
                continue;
            }
            // Read just the dump header (the COMMENTED coordinates are near the top).
            let obj = dir.join(member_object_name(idx));
            let header = match read_file_prefix(&obj, 16 * 1024).await {
                Ok(h) => h,
                Err(e) => {
                    tracing::warn!(error = %e, db = %db, "mysql delta: could not read base member header; this db's delta will fall back to a full dump");
                    continue;
                }
            };
            let Some((base_gtid, start_log)) = parse_mysql_base_coord(&header) else {
                tracing::warn!(db = %db, "mysql delta: base dump carries no GTID/binlog coordinate (binlog/gtid not enabled?); this db's delta will fall back to a full dump");
                continue;
            };
            let schema_fingerprint = self.schema_fingerprint(project, db).await;
            sidecar.dbs.insert(
                db.to_string(),
                MysqlCaptureEntry {
                    base_gtid,
                    start_log,
                    schema_fingerprint,
                },
            );
        }
        if !sidecar.dbs.is_empty()
            && let Ok(bytes) = serde_json::to_vec_pretty(&sidecar)
        {
            let _ = write_atomic(&dir.join(MYSQL_CAPTURE_SIDECAR), &bytes).await;
        }
    }

    /// Try to produce a mysql binlog true-delta member for one db from the PARENT base's capture
    /// sidecar. Returns `Some((member_tar_bytes, MysqlGtid cursor))` when a faithful binlog delta is
    /// available, or `None` to keep the full-dump fallback. Falls back when: the db is not
    /// capture-eligible, the parent recorded no coordinate, the SCHEMA FINGERPRINT changed since the
    /// base, the range carries a DDL `QUERY_EVENT`, the start binlog was purged, or the drain errors.
    async fn try_mysql_binlog_delta(
        &self,
        project: &str,
        db: &str,
        sidecar: &MysqlCaptureSidecar,
        cap_dir: &Path,
    ) -> Option<(Vec<u8>, boatramp_core::project_delta::SqlMemberCursor)> {
        let cfg = self.databases.get(db)?;
        if !Self::mysql_capture_eligible(cfg) {
            return None;
        }
        let entry = sidecar.dbs.get(db)?;
        // SCHEMA-FINGERPRINT FALLBACK (mirror pg): a DDL change base→delta cannot be row-replayed.
        let current_fp = self.schema_fingerprint(project, db).await;
        if current_fp != entry.schema_fingerprint {
            tracing::info!(db = %db, "mysql delta: schema fingerprint changed since the base — falling back to a full dump");
            return None;
        }
        match self
            .mysql_drain_binlog(project, db, cfg, entry, cap_dir)
            .await
        {
            Ok(Some(bytes)) => Some((
                bytes,
                boatramp_core::project_delta::SqlMemberCursor::MysqlGtid {
                    gtid: entry.base_gtid.clone(),
                },
            )),
            Ok(None) => None, // purged start log / DDL in range ⇒ full-dump fallback
            Err(e) => {
                tracing::warn!(error = %e, db = %db, "mysql delta: binlog drain failed — falling back to a full dump");
                None
            }
        }
    }

    /// Stream one managed-mysql db's binlog since the base into a `tar` of raw binlog files (the
    /// `MysqlBinlogDelta` member). Mints an EPHEMERAL `REPLICATION SLAVE, REPLICATION CLIENT` reader
    /// user (superuser-created, random never-persisted password), runs `mysqlbinlog -R --raw` from the
    /// base's start binlog `--to-last-log` into the container's bounded `/tmp` tmpfs, `tar`s the raw
    /// files to stdout, then DROPS the reader user. Returns `Ok(None)` (full-dump fallback) when the
    /// start binlog is purged (capture exits non-zero) or the range carries a DDL event.
    async fn mysql_drain_binlog(
        &self,
        project: &str,
        db: &str,
        cfg: &ExternalDatabaseConfig,
        entry: &MysqlCaptureEntry,
        stage_dir: &Path,
    ) -> Result<Option<Vec<u8>>, Perr> {
        let (op, image, _ver) = self.resolve_mysql(project, db, cfg).await?;
        let binlog_image = mysql_binlog_image(&image);
        let live_db = cfg.database.clone().unwrap_or_else(|| db.to_string());
        let shadow_db = mysql_delta_shadow_db(&live_db);
        // A SHORT suffix: `brexp_rd_<suffix>` must fit MySQL's 32-char USER-name cap.
        let suffix = mysql_eph_suffix();
        let reader = format!("brexp_rd_{suffix}");
        let reader_pw = random_token();
        let reader_lit = mysql_lit(&reader);

        // SUPERUSER: mint the ephemeral least-privilege reader user (so the binlog stream is NOT read
        // as the bootstrap superuser — defence in depth). REPLICATION SLAVE + CLIENT are exactly what
        // `mysqlbinlog --read-from-remote-server` needs; nothing else.
        let create = format!(
            "CREATE USER {reader_lit}@'%' IDENTIFIED BY {}; \
             GRANT REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO {reader_lit}@'%';",
            mysql_lit(&reader_pw)
        );
        let (code, out) = self
            .mysql_admin_sql(&op, &image, &create, stage_dir)
            .await?;
        if code != 0 {
            return Err(Perr::Other(format!(
                "mysql capture: CREATE reader user for {db:?} exited {code}: {out}"
            )));
        }

        // CAPTURE as the reader user: DB-SCOPED + REWRITTEN + gtid-filtered at capture (NOT --raw),
        // decoding straight to stdout = the member. `--rewrite-db='<live>-><shadow>' --database=
        // <shadow>' make the member contain ONLY the app db's events (retargeted to the shadow) — no
        // `mysql`-schema account DDL / other-tenant rows ever enter the exported member (the
        // disclosure fix). `--skip-gtids --exclude-gtids=<base>` give a clean, overlap-free, directly-
        // replayable stream. STDERR is discarded so a failure (purged start log) is a clean non-zero
        // exit ⇒ full-dump fallback, not a corrupt member.
        let reader_conn = mysql_reader_conn(&op, &reader, &reader_pw);
        let cap = mysqlbinlog_capture_invocation(
            &reader_conn,
            &live_db,
            &shadow_db,
            &entry.base_gtid,
            &entry.start_log,
        );
        let cmd = format!("exec {} 2>/tmp/caperr", sh_join(&cap.argv));
        let argv = vec!["sh".to_string(), "-c".to_string(), cmd];
        let member_path = stage_dir.join(format!("mysqlbinlog-{suffix}.sql"));
        let code = self
            .run_sql_client(&binlog_image, &argv, &cap.env, None, &member_path)
            .await;

        // Drop the ephemeral reader user regardless of capture outcome (bounded retention).
        let drop_sql = format!("DROP USER IF EXISTS {reader_lit}@'%';");
        let _ = self
            .mysql_admin_sql(&op, &image, &drop_sql, stage_dir)
            .await;

        let code = code?;
        if code != 0 {
            // Purged start log / unreachable ⇒ best-effort fallback to a full dump.
            let _ = tokio::fs::remove_file(&member_path).await;
            tracing::info!(db = %db, "mysql delta: binlog capture exited non-zero (start log purged, or server unreachable) — falling back to a full dump");
            return Ok(None);
        }
        // LOW-4 bound (export side): the member is read whole into RAM here + at restore; a delta
        // larger than the cap FALLS BACK to a full dump (graceful) rather than ship an unbounded
        // member. The restore enforces the same cap fail-closed for a crafted/oversized member.
        let member_len = tokio::fs::metadata(&member_path)
            .await
            .map_err(other)?
            .len();
        if member_len > MYSQL_DELTA_MEMBER_MAX {
            let _ = tokio::fs::remove_file(&member_path).await;
            tracing::info!(db = %db, member_len, "mysql delta: binlog delta exceeds the member cap — falling back to a full dump");
            return Ok(None);
        }
        let bytes = tokio::fs::read(&member_path).await.map_err(other)?;
        let _ = tokio::fs::remove_file(&member_path).await;

        // DDL-in-range guard: the member is already decoded (db-scoped) SQL text, so scan it directly
        // and fall back to a full dump if the range carries a DDL statement (a schema change the
        // base→delta row replay cannot faithfully reproduce). The fingerprint check already caught NET
        // schema changes; this catches any app-db DDL even if net-neutral. (`mysql`-schema account DDL
        // is already dropped by `--database=<shadow>`, so it never trips this.)
        let decoded = String::from_utf8_lossy(&bytes);
        if mysql_binlog_decoded_has_ddl(&decoded) {
            tracing::info!(db = %db, "mysql delta: a DDL statement is present in the binlog range — falling back to a full dump");
            return Ok(None);
        }
        Ok(Some(bytes))
    }
}

impl NodeProjectExport {
    /// Restore every managed-mysql db covered by a resolved delta chain via the atomic shadow: the
    /// newest FULL dump in the chain is restored into a fresh shadow, every subsequent
    /// `MysqlBinlogDelta` is REPLAYED onto it as the ephemeral apply user (REPLICATION_APPLIER +
    /// SESSION_VARIABLES_ADMIN + ALL on the shadow ONLY), then the shadow is atomically swapped in.
    /// A render/replay/restore failure drops the shadow (live untouched) and fails the import loud.
    /// (An external mysql db never produces a `MysqlBinlogDelta` — capture is managed-only — so a
    /// chain carrying one for a non-managed db is a malformed bundle and is refused.)
    async fn restore_mysql_true_delta_in_chain(
        &self,
        project: &str,
        chain: &[(PathBuf, project_bundle::StreamManifest)],
        opts: &ImportOptions,
        report: &mut ImportReport,
        stage_dir: &Path,
    ) -> Result<(), Perr> {
        // Per managed-mysql db: the newest FULL dump (base/fallback) + the binlog deltas AFTER it.
        struct DbPlan {
            base: Option<(PathBuf, usize)>,
            binlog: Vec<(PathBuf, usize)>,
        }
        let mut per_db: BTreeMap<String, DbPlan> = BTreeMap::new();
        for (dir, m) in chain {
            for (idx, spec) in m.members.iter().enumerate() {
                match spec.kind {
                    MemberKind::MysqlDump => {
                        if let Some(db) =
                            db_from_mysql_member(&spec.path).filter(|d| self.is_managed_mysql(d))
                        {
                            let e = per_db.entry(db.to_string()).or_insert(DbPlan {
                                base: None,
                                binlog: Vec::new(),
                            });
                            e.base = Some((dir.clone(), idx));
                            e.binlog.clear();
                        }
                    }
                    MemberKind::MysqlBinlogDelta => {
                        if let Some(db) = db_from_mysqlbinlog_member(&spec.path) {
                            if !self.is_managed_mysql(db) {
                                return Err(Perr::Other(format!(
                                    "mysql true-delta restore: a MysqlBinlogDelta member {:?} names \
                                     db {db:?} which is not a managed mysql binding on this node — \
                                     malformed bundle",
                                    spec.path
                                )));
                            }
                            per_db
                                .entry(db.to_string())
                                .or_insert(DbPlan {
                                    base: None,
                                    binlog: Vec::new(),
                                })
                                .binlog
                                .push((dir.clone(), idx));
                        }
                    }
                    _ => {}
                }
            }
        }
        if per_db.is_empty() {
            return Ok(());
        }
        if !opts.apply {
            report.pg_databases += per_db.len();
            return Ok(());
        }
        for (db, plan_db) in per_db {
            let Some((base_dir, base_idx)) = plan_db.base else {
                return Err(Perr::Other(format!(
                    "mysql true-delta restore: db {db:?} has binlog delta member(s) but no full base \
                     dump in the chain — cannot replay onto nothing"
                )));
            };
            let cfg = self
                .databases
                .get(&db)
                .ok_or_else(|| {
                    Perr::Other(format!("import: no database named {db:?} on this node"))
                })?
                .clone();
            let mut plan = self.mysql_shadow_plan(project, &db, &cfg).await?;
            // The delta member's row events were db-REWRITTEN at capture to the deterministic delta
            // shadow name (the member is SQL text, not re-rewritable at replay), so the shadow MUST be
            // exactly that name — override the per-import `__shadow_<hex>` the plan minted. The base
            // tables-only dump restores into any name, so it lands here too; the `RENAME TABLE` swap
            // then moves these tables onto the live db.
            plan.shadow_db = mysql_delta_shadow_db(&plan.live_db);
            // COLLISION guard (data-loss race fix): the delta shadow name is DETERMINISTIC per db,
            // so a pre-existing one means a concurrent same-db import owns it (populated + about to
            // swap). We MUST refuse WITHOUT dropping it — dropping another import's populated shadow
            // would leave ITS swap seeing an empty shadow and destroy live data. Refuse cleanly.
            if self
                .mysql_db_exists(&plan, &plan.shadow_db, stage_dir)
                .await?
            {
                return Err(Perr::Unavailable(format!(
                    "mysql true-delta restore: the delta shadow {:?} already exists — a concurrent \
                     import of db {db:?} is in flight (the binlog-delta shadow name is \
                     deterministic). Retry after it completes.",
                    plan.shadow_db
                )));
            }
            // Now CREATE it (we own it from here). If CREATE fails — including a TOCTOU race where a
            // concurrent import created it between the check above and here — we did NOT create it,
            // so DO NOT drop it (dropping a shadow we don't own is the exact data-loss race): `?`
            // propagates the error WITHOUT a teardown, unlike the drop-on-failure steps below. The
            // ephemeral apply USER is per-import-random, so a create failure is a DB collision, not
            // our user/grant; a startup `%__shadow_%` sweep reclaims any rare half-created leak.
            self.mysql_create_shadow(&plan, stage_dir).await?;
            // The binlog replay needs the apply user to run `BINLOG` row events + the session-context
            // SETs mysqlbinlog emits — grant REPLICATION_APPLIER + SESSION_VARIABLES_ADMIN (on top of
            // the shadow-only ALL). FAIL-CLOSED: then PROVE the apply user is still confined (no
            // SUPER/FILE/BINLOG_ADMIN, no `ALL`/DML on `*.*`), so a crafted binlog cannot escape.
            if let Err(e) = self.mysql_grant_replay(&plan, stage_dir).await {
                self.mysql_drop_shadow(&plan, stage_dir).await;
                return Err(e);
            }
            if let Err(e) = self
                .mysql_assert_replay_user_confined(&plan, stage_dir)
                .await
            {
                self.mysql_drop_shadow(&plan, stage_dir).await;
                return Err(e);
            }
            // Restore the base tables-only dump into the shadow AS the apply user (the inc2 split).
            if let Err(e) = self
                .mysql_restore_base_into_shadow(
                    &plan,
                    &base_dir.join(member_object_name(base_idx)),
                    stage_dir,
                )
                .await
            {
                self.mysql_drop_shadow(&plan, stage_dir).await;
                return Err(e);
            }
            // Replay each `MysqlBinlogDelta` member onto the shadow. The member is db-scoped SQL text
            // (`BINLOG '…'` row events) already rewritten to the shadow at capture, so the replay is a
            // direct `mysql <shadow> < member` as the ephemeral apply user — no `mysqlbinlog` decode,
            // no rewrite, no gtid flags (all baked at capture).
            for (dir, idx) in &plan_db.binlog {
                let member_path = dir.join(member_object_name(*idx));
                // LOW-4: the member is read WHOLE into RAM here (the db-scoped SQL-text member is
                // applied via stdin). Cap it fail-closed so a crafted/oversized member cannot OOM the
                // node (the previous `--raw`-to-tmpfs path bounded this at 64 MiB; the SQL-text path
                // needs its own bound). A legit delta beyond the cap full-dumps at EXPORT instead.
                let member_len = tokio::fs::metadata(&member_path)
                    .await
                    .map_err(other)?
                    .len();
                if member_len > MYSQL_DELTA_MEMBER_MAX {
                    self.mysql_drop_shadow(&plan, stage_dir).await;
                    return Err(Perr::Other(format!(
                        "mysql true-delta restore REFUSED: binlog delta member {} is {member_len} \
                         bytes, over the {MYSQL_DELTA_MEMBER_MAX}-byte cap — refusing to read an \
                         oversized untrusted member into memory",
                        member_path.display()
                    )));
                }
                let member = tokio::fs::read(&member_path).await.map_err(other)?;
                if let Err(e) = self.mysql_replay_binlog(&plan, &member, stage_dir).await {
                    self.mysql_drop_shadow(&plan, stage_dir).await;
                    return Err(e);
                }
            }
            if let Err(e) = self.mysql_swap_shadow(&plan, stage_dir).await {
                self.mysql_drop_shadow(&plan, stage_dir).await;
                return Err(e);
            }
            report.pg_databases += 1;
        }
        Ok(())
    }

    /// Restore a base full-dump member object into the freshly-created shadow via `mysql <shadow>`
    /// (as the ephemeral apply user). The member is the tables-only base dump; a non-zero exit
    /// surfaces the client's error (the caller tears the shadow down).
    async fn mysql_restore_base_into_shadow(
        &self,
        plan: &MysqlShadowPlan,
        base_obj: &Path,
        stage_dir: &Path,
    ) -> Result<(), Perr> {
        let inv = mysql_shadow_invocation(&plan.apply_conn(), &plan.shadow_db);
        let merged = merge_stderr_argv(&inv.argv);
        let out = stage_dir.join(format!("mysqlbase-{}.out", shadow_suffix()));
        let code = self
            .run_sql_client(&plan.image, &merged, &inv.env, Some(base_obj), &out)
            .await?;
        let diag = tokio::fs::read_to_string(&out).await.unwrap_or_default();
        let _ = tokio::fs::remove_file(&out).await;
        if code != 0 {
            return Err(Perr::Other(format!(
                "mysql true-delta base restore into shadow {:?} exited {code}: {}",
                plan.shadow_db,
                diag.trim()
            )));
        }
        Ok(())
    }

    /// TRUSTED DDL: grant the shadow apply user the two dynamic privileges the binlog replay needs —
    /// `REPLICATION_APPLIER` (to execute `BINLOG` row events) and `SESSION_VARIABLES_ADMIN` (to set
    /// the session-context vars mysqlbinlog emits, e.g. `pseudo_slave_mode`/`pseudo_thread_id`).
    /// NEITHER grants table access outside the shadow nor `SUPER`/`FILE`/`BINLOG_ADMIN`, so the apply
    /// stays confined (asserted next). Run by the SUPERUSER / maintenance connection.
    async fn mysql_grant_replay(
        &self,
        plan: &MysqlShadowPlan,
        stage_dir: &Path,
    ) -> Result<(), Perr> {
        let user_lit = mysql_lit(&plan.eph_user);
        let sql =
            format!("GRANT REPLICATION_APPLIER, SESSION_VARIABLES_ADMIN ON *.* TO {user_lit}@'%';");
        let (code, out) = self.mysql_run_admin(plan, &sql, stage_dir).await?;
        if code != 0 {
            return Err(Perr::Other(format!(
                "mysql true-delta: GRANT replay privileges to the apply user exited {code}: {out}"
            )));
        }
        Ok(())
    }

    /// Fail-closed probe: refuse the untrusted binlog replay unless the apply user's grants carry NO
    /// `SUPER`, `FILE`, or `BINLOG_ADMIN`, and NO privilege on `*.*` BEYOND the exact two replay
    /// dynamics (`REPLICATION_APPLIER`, `SESSION_VARIABLES_ADMIN`) plus the harmless `USAGE`. So a
    /// crafted binlog applied as this user cannot escape the shadow (its DML on any table outside the
    /// shadow is refused by the table-privilege check — the applier privilege does NOT bypass it).
    async fn mysql_assert_replay_user_confined(
        &self,
        plan: &MysqlShadowPlan,
        stage_dir: &Path,
    ) -> Result<(), Perr> {
        let apply = plan.apply_conn();
        let inv = mysql_admin_invocation(&apply);
        let in_path = stage_dir.join(format!("mysql-replay-probe-{}.sql", shadow_suffix()));
        tokio::fs::write(&in_path, "SHOW GRANTS FOR CURRENT_USER();")
            .await
            .map_err(other)?;
        let r = self
            .run_sql_capture(&plan.image, &inv.argv, &inv.env, Some(&in_path), stage_dir)
            .await;
        let _ = tokio::fs::remove_file(&in_path).await;
        let (code, out) = r?;
        if code != 0 {
            return Err(Perr::Other(format!(
                "mysql replay: could not probe the apply user's grants (exit {code}): {out}"
            )));
        }
        for line in out.lines() {
            // Match the privilege TOKENS (BEFORE " ON "), never the whole line — else a db named e.g.
            // `supervisors`/`filestore`/`profiles` in the grant TARGET false-refuses a legit restore.
            let privs = mysql_grant_privileges(line).to_ascii_uppercase();
            let up = line.to_ascii_uppercase();
            if privs.contains("SUPER") || privs.contains("FILE") || privs.contains("BINLOG_ADMIN") {
                return Err(Perr::Other(format!(
                    "mysql replay REFUSED: the apply user holds SUPER/FILE/BINLOG_ADMIN; an untrusted \
                     binlog must only be replayed by a least-privilege user. grants: {out}"
                )));
            }
            // A `… ON *.*` grant is allowed ONLY when its PRIVILEGES are exactly the replay dynamics
            // (or USAGE). The db-scoped `ALL ON \`<shadow>\`.*` grant has no " ON *.*" and is fine.
            if up.contains(" ON *.*") {
                let ok = privs.contains("USAGE")
                    || privs.contains("REPLICATION_APPLIER")
                    || privs.contains("SESSION_VARIABLES_ADMIN");
                let has_broad_dml = privs.contains("ALL PRIVILEGES")
                    || privs.contains("INSERT")
                    || privs.contains("UPDATE")
                    || privs.contains("DELETE")
                    || privs.contains("CREATE")
                    || privs.contains("DROP");
                if !ok || has_broad_dml {
                    return Err(Perr::Other(format!(
                        "mysql replay REFUSED: the apply user holds a global `*.*` privilege beyond \
                         the replay dynamics (REPLICATION_APPLIER / SESSION_VARIABLES_ADMIN); an \
                         untrusted binlog must stay confined to the shadow. grants: {out}"
                    )));
                }
            }
        }
        Ok(())
    }

    /// EXECUTE one `MysqlBinlogDelta` member onto the shadow, as the ephemeral apply user. The member
    /// is already-decoded, db-SCOPED SQL text (`BINLOG '…'` row events) rewritten to the shadow AT
    /// CAPTURE, so the replay is a direct `mysql <shadow> < member` — NO `mysqlbinlog`, NO rewrite, NO
    /// gtid flags (all baked at capture). The apply user holds `REPLICATION_APPLIER` (to run the
    /// `BINLOG` events) + `SESSION_VARIABLES_ADMIN` (the session-context SETs) + `ALL ON <shadow>.*`
    /// only, and `--local-infile=0` disables client-side `LOAD DATA LOCAL`. CONFINEMENT: a tampered
    /// member whose events name a db outside the shadow is DENIED by the table-privilege check (the
    /// applier privilege does NOT bypass it — validated), `mysql` errors, and the caller drops the
    /// shadow — nothing partial reaches live. Garbage bytes likewise fail to parse and are refused.
    async fn mysql_replay_binlog(
        &self,
        plan: &MysqlShadowPlan,
        member: &[u8],
        stage_dir: &Path,
    ) -> Result<(), Perr> {
        let apply = plan.apply_conn();
        // `mysql <shadow> --local-infile=0` reading the member SQL text on stdin, as the apply user.
        // `merge_stderr_argv` folds the client's STDERR (a denied/failed statement) into the captured
        // sink so a refusal is diagnosable (run_ephemeral drops stderr on a non-zero exit).
        let inv = mysql_shadow_invocation(&apply, &plan.shadow_db);
        let merged = merge_stderr_argv(&inv.argv);
        let member_path = stage_dir.join(format!("mysqlreplay-{}.sql", shadow_suffix()));
        tokio::fs::write(&member_path, member)
            .await
            .map_err(other)?;
        let out = stage_dir.join(format!("mysqlreplay-{}.out", shadow_suffix()));
        let code = self
            .run_sql_client(&plan.image, &merged, &inv.env, Some(&member_path), &out)
            .await;
        let _ = tokio::fs::remove_file(&member_path).await;
        let diag = tokio::fs::read_to_string(&out).await.unwrap_or_default();
        let _ = tokio::fs::remove_file(&out).await;
        let code = code?;
        if code != 0 {
            return Err(Perr::Other(format!(
                "mysql binlog delta replay into shadow {:?} exited {code}: {}",
                plan.shadow_db,
                diag.trim()
            )));
        }
        Ok(())
    }
}

// ===========================================================================================
// libsql CHANGESET true-delta: CAPTURE (export) + REPLAY (restore) — SQL true-delta program, Stage 4.
// (Textually separate from the pg/mysql engines above to minimize merge conflict; it reuses only the
// resumable member-object layout + the libsql backend's atomic shadow primitives.)
//
// CAPTURE. libsql has no server change stream, so the base is a FIXED FILE: every resumable export
// (base AND delta) snapshots each local libsql site's DB (`snapshot_delta_base` = VACUUM INTO +
// integrity-check) into `libsql_capture/<n>.db` and records its SHA-256 in a `libsql_capture.json`
// sidecar (keyed by SITE) — the libsql analogue of `pg_capture.json`/`mysql_capture.json`. A later
// DELTA export whose base recorded a snapshot diffs the live DB against it with the SQLite session
// engine (`capture_delta_changeset`), shipping the resulting changeset as a `LibsqlChangeset` member
// IN PLACE OF the full dump. A schema change since the base, a PK-less table, a missing/mismatched
// base snapshot, or any diff failure FALLS BACK to a full dump for that site (best-effort true-delta;
// the delta bundle is always a complete point-in-time). BOTH differential (vs the fixed root base)
// and incremental (vs the parent) modes are supported — the base snapshot is a re-diffable file,
// unlike pg's single advancing slot / mysql's one-shot binlog coordinate (incremental-only).
//
// REPLAY. `restore_libsql_true_delta_in_chain` resolves, per site, the newest FULL base `Libsql`
// member (its snapshot + sha from that link's `libsql_capture.json`) + the subsequent `LibsqlChangeset`
// members, and hands them to `restore_delta_changeset_chain`: copy the sha-verified base snapshot
// into a fresh `*.shadow_*`, apply each changeset CONFINED to the base's own tables (abort on any
// conflict / refuse any foreign table), integrity-check, then atomically rename the shadow over live.
// A decode/apply failure drops the shadow (live untouched) and fails the import loud. In-process,
// no Docker — the engine is embedded libsql.
//
// SCOPE: local single-node libsql (the managed default). Feature-gated (`sql-delta-libsql`); an
// off build never captures and REFUSES to restore a changeset member (never a silent full-dump).
// ===========================================================================================

/// The libsql-capture sidecar filename written beside a resumable export dir's member objects.
const LIBSQL_CAPTURE_SIDECAR: &str = "libsql_capture.json";

/// One libsql site's base-snapshot record in `libsql_capture.json`: the snapshot file (RELATIVE to
/// the resumable dir) a later delta diffs against + the restore applies changesets onto, and its
/// SHA-256 (the base cursor — it NAMES the base and lets capture + restore prove same bytes).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct LibsqlCaptureEntry {
    /// The base snapshot path, RELATIVE to the resumable dir (e.g. `libsql_capture/0.db`).
    snapshot_file: String,
    /// The base snapshot's SHA-256 (lowercase hex) — the `LibsqlChangesetBase` cursor value.
    base_sha256: String,
}

/// A resumable dir's libsql-capture sidecar: per-site base snapshots keyed by SITE name.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
struct LibsqlCaptureSidecar {
    sites: BTreeMap<String, LibsqlCaptureEntry>,
}

/// Read the libsql-capture sidecar from a resumable dir (absent/corrupt ⇒ `None`).
async fn read_libsql_capture_sidecar(dir: &Path) -> Option<LibsqlCaptureSidecar> {
    let bytes = tokio::fs::read(dir.join(LIBSQL_CAPTURE_SIDECAR))
        .await
        .ok()?;
    serde_json::from_slice(&bytes).ok()
}

/// CONFINE a base-snapshot path from the (untrusted) `libsql_capture.json` sidecar under `base_dir`
/// before it is read/copied — the `snapshot_file` string travels with the bundle across the import
/// trust boundary, so it is treated exactly like `resolve_resumable_dir` treats an operator-named
/// dir: reject an empty / absolute / `..`-or-`.`-bearing relative path, then canonicalize and assert
/// the result still lives under `base_dir` (defeats a symlink planted in the bundle dir). Returns the
/// confined absolute path or a loud [`Perr`] — never a path that escapes the bundle dir. (Security
/// review Stage 4, Finding 1: an unconfined join enabled `/dev/zero` DoS + out-of-tree file reads.)
#[cfg(any(feature = "sql-delta-libsql", test))]
fn confine_bundle_snapshot(base_dir: &Path, snapshot_file: &str) -> Result<PathBuf, Perr> {
    use std::path::Component;
    let rel = Path::new(snapshot_file);
    if rel.as_os_str().is_empty()
        || rel.is_absolute()
        || rel.components().any(|c| !matches!(c, Component::Normal(_)))
    {
        return Err(Perr::Other(format!(
            "libsql delta: refusing out-of-tree base snapshot path {snapshot_file:?}"
        )));
    }
    let joined = base_dir.join(rel);
    // Resolve symlinks + `.`; the canonical path MUST stay under the canonical base dir.
    let canon_base = std::fs::canonicalize(base_dir).map_err(|e| {
        Perr::Other(format!(
            "libsql delta: canonicalize base dir {}: {e}",
            base_dir.display()
        ))
    })?;
    let canon = std::fs::canonicalize(&joined).map_err(|e| {
        Perr::Other(format!(
            "libsql delta: base snapshot {snapshot_file:?} not found/canonicalize: {e}"
        ))
    })?;
    if !canon.starts_with(&canon_base) {
        return Err(Perr::Other(format!(
            "libsql delta: base snapshot path {snapshot_file:?} escapes the bundle dir (symlink?)"
        )));
    }
    Ok(canon)
}

impl NodeProjectExport {
    /// Snapshot every local libsql site's DB as a delta BASE into `dir/libsql_capture/` and record
    /// each one's sha in `libsql_capture.json`. Best-effort: a site that fails to snapshot is simply
    /// omitted (it full-dumps at the next delta). Enumerates sites AUTHORITATIVELY from the deploy
    /// store (never a filesystem walk), exactly like `plan_export`.
    #[cfg(feature = "sql-delta-libsql")]
    async fn libsql_capture_base_snapshots(&self, project: &str, dir: &Path) {
        let Some(libsql) = &self.libsql else {
            return;
        };
        let sites = match self.deploy.list_sites(ProjectRef::new(project)).await {
            Ok(s) => s,
            Err(e) => {
                tracing::warn!(%project, error = %e, "libsql delta capture: list_sites failed; skipping base snapshots");
                return;
            }
        };
        let mut sidecar = LibsqlCaptureSidecar::default();
        for (i, site) in sites.into_iter().enumerate() {
            let qsite = ProjectRef::new(project).qualified(&site);
            if !libsql.local_database_exists(&qsite, "") {
                continue; // a site that never wrote SQL — nothing to snapshot
            }
            // Opaque per-site filename (the sidecar records the site→file mapping, so the name needs
            // no site-derived escaping).
            let rel = format!("libsql_capture/{i}.db");
            let dest = dir.join(&rel);
            match libsql.snapshot_delta_base(&qsite, "", &dest).await {
                Ok(sha) => {
                    sidecar.sites.insert(
                        site,
                        LibsqlCaptureEntry {
                            snapshot_file: rel,
                            base_sha256: sha,
                        },
                    );
                }
                Err(e) => {
                    tracing::warn!(%project, %site, error = %e, "libsql delta capture: base snapshot failed; this site will full-dump at the next delta");
                }
            }
        }
        if !sidecar.sites.is_empty()
            && let Ok(bytes) = serde_json::to_vec_pretty(&sidecar)
        {
            let _ = write_atomic(&dir.join(LIBSQL_CAPTURE_SIDECAR), &bytes).await;
        }
    }

    /// Try to produce a libsql CHANGESET delta for `site` against the parent base snapshot named by
    /// `entry`. Returns `Some((framed_changeset_bytes, cursor))` on success, or `None` for ANY
    /// fallback (engine not built, no libsql backend, missing/mismatched base, schema drift, PK-less
    /// table, or a diff failure) — the caller then keeps the full dump.
    async fn try_libsql_changeset_delta(
        &self,
        project: &str,
        site: &str,
        entry: &LibsqlCaptureEntry,
        base_dir: &Path,
        cap_dir: &Path,
    ) -> Option<(Vec<u8>, boatramp_core::project_delta::SqlMemberCursor)> {
        // Silence unused-param warnings in an off build (no engine to call).
        let _ = (project, site, entry, base_dir, cap_dir);
        #[cfg(feature = "sql-delta-libsql")]
        {
            use boatramp_storage::sql_libsql_changeset::ChangesetCapture;
            let libsql = self.libsql.as_ref()?;
            let qsite = ProjectRef::new(project).qualified(site);
            if !libsql.local_database_exists(&qsite, "") {
                return None; // site has no live DB now → keep the full-dump member path
            }
            // Confine the sidecar-named base snapshot under base_dir before use (a bad/escaping path
            // → full-dump fallback, never a traversal). Trusted side here (our own export output),
            // but held to the same confinement as the restore side — defense in depth.
            let base_snapshot = match confine_bundle_snapshot(base_dir, &entry.snapshot_file) {
                Ok(p) => p,
                Err(e) => {
                    tracing::warn!(%project, %site, error = %e, "libsql delta: base snapshot path rejected; full-dump fallback");
                    return None;
                }
            };
            match libsql
                .capture_delta_changeset(&qsite, "", &base_snapshot, &entry.base_sha256, cap_dir)
                .await
            {
                Ok(ChangesetCapture::Changeset(cs)) => {
                    let framed = boatramp_core::project_delta::encode_libsql_changeset(&cs);
                    let cursor =
                        boatramp_core::project_delta::SqlMemberCursor::LibsqlChangesetBase {
                            base_sha256: entry.base_sha256.clone(),
                        };
                    Some((framed, cursor))
                }
                Ok(ChangesetCapture::Fallback(reason)) => {
                    tracing::info!(%project, %site, %reason, "libsql delta: full-dump fallback");
                    None
                }
                Err(e) => {
                    tracing::warn!(%project, %site, error = %e, "libsql delta: changeset capture failed; full-dump fallback");
                    None
                }
            }
        }
        #[cfg(not(feature = "sql-delta-libsql"))]
        {
            None
        }
    }

    /// Replay every libsql changeset chain into the atomic shadow. For each site in
    /// `changeset_sites`: resolve the newest FULL base `Libsql` member (a newer full dump supersedes
    /// earlier changesets, like pg/mysql) + its stored base snapshot + the subsequent
    /// `LibsqlChangeset` members in chain order, then `restore_delta_changeset_chain`. A site with no
    /// changeset is restored by the main loop's `restore_member` and never reaches here.
    async fn restore_libsql_true_delta_in_chain(
        &self,
        project: &str,
        chain: &[(PathBuf, project_bundle::StreamManifest)],
        changeset_sites: &std::collections::BTreeSet<String>,
        opts: &ImportOptions,
        report: &mut ImportReport,
    ) -> Result<(), Perr> {
        if changeset_sites.is_empty() {
            return Ok(());
        }
        // Per site: the newest FULL base libsql member (dir) + the changeset members AFTER it.
        struct SitePlan {
            base_dir: Option<PathBuf>,
            changesets: Vec<(PathBuf, usize)>,
        }
        let mut per_site: BTreeMap<String, SitePlan> = BTreeMap::new();
        for (dir, m) in chain {
            for (idx, spec) in m.members.iter().enumerate() {
                match spec.kind {
                    MemberKind::Libsql => {
                        if let Some(site) = site_from_libsql_member(&spec.path)
                            .filter(|s| changeset_sites.contains(*s))
                        {
                            let e = per_site.entry(site.to_string()).or_insert(SitePlan {
                                base_dir: None,
                                changesets: Vec::new(),
                            });
                            e.base_dir = Some(dir.clone());
                            e.changesets.clear();
                        }
                    }
                    MemberKind::LibsqlChangeset => {
                        if let Some(site) = site_from_libsql_changeset_member(&spec.path) {
                            per_site
                                .entry(site.to_string())
                                .or_insert(SitePlan {
                                    base_dir: None,
                                    changesets: Vec::new(),
                                })
                                .changesets
                                .push((dir.clone(), idx));
                        }
                    }
                    _ => {}
                }
            }
        }
        per_site.retain(|_, p| !p.changesets.is_empty());
        if per_site.is_empty() {
            return Ok(());
        }

        #[cfg(not(feature = "sql-delta-libsql"))]
        {
            let _ = (project, opts, report);
            Err(Perr::Unavailable(
                "bundle carries libsql changeset true-delta members but this build lacks the libsql \
                 changeset engine (feature `sql-delta-libsql`) — refusing to restore (never a silent \
                 stale-base full-dump)"
                    .into(),
            ))
        }
        #[cfg(feature = "sql-delta-libsql")]
        {
            let Some(libsql) = self.libsql.clone() else {
                return Err(Perr::Unavailable(
                    "bundle carries libsql changeset members but this node has no local libsql \
                     backend to restore them into"
                        .into(),
                ));
            };
            if !opts.apply {
                report.libsql_databases += per_site.len();
                return Ok(());
            }
            for (site, plan) in per_site {
                let Some(base_dir) = plan.base_dir else {
                    return Err(Perr::Other(format!(
                        "libsql true-delta restore: site {site:?} has changeset member(s) but no full \
                         base libsql member in the chain — cannot replay onto nothing"
                    )));
                };
                // The base snapshot + sha come from the base link's libsql_capture.json sidecar.
                let sidecar = read_libsql_capture_sidecar(&base_dir).await.ok_or_else(|| {
                    Perr::Other(format!(
                        "libsql true-delta restore: base dir {} has no {LIBSQL_CAPTURE_SIDECAR} — \
                         cannot resolve the base snapshot for site {site:?}",
                        base_dir.display()
                    ))
                })?;
                let entry = sidecar.sites.get(&site).ok_or_else(|| {
                    Perr::Other(format!(
                        "libsql true-delta restore: no base snapshot recorded for site {site:?} in \
                         {LIBSQL_CAPTURE_SIDECAR}"
                    ))
                })?;
                // CONFINE the sidecar-named base snapshot under base_dir before reading/copying it
                // (the sidecar is untrusted bundle data) — a bad/escaping path is a hard error, never
                // a traversal / out-of-tree read (Stage 4 security review, Finding 1).
                let base_snapshot = confine_bundle_snapshot(&base_dir, &entry.snapshot_file)?;
                // Decode each changeset member (chain order) into its raw changeset blob.
                let mut changesets: Vec<Vec<u8>> = Vec::with_capacity(plan.changesets.len());
                for (dir, idx) in &plan.changesets {
                    let obj = dir.join(member_object_name(*idx));
                    let bytes = tokio::fs::read(&obj).await.map_err(other)?;
                    let cs = boatramp_core::project_delta::decode_libsql_changeset(&bytes)
                        .map_err(|e| {
                            Perr::Other(format!(
                                "libsql true-delta restore: decode changeset member {}: {e}",
                                obj.display()
                            ))
                        })?;
                    changesets.push(cs);
                }
                let qsite = ProjectRef::new(project).qualified(&site);
                libsql
                    .restore_delta_changeset_chain(
                        &qsite,
                        "",
                        &base_snapshot,
                        &entry.base_sha256,
                        changesets,
                        opts.overwrite,
                    )
                    .await
                    .map_err(other)?;
                report.libsql_databases += 1;
            }
            Ok(())
        }
    }
}

/// Read up to `max` bytes from the start of `path` as a UTF-8 (lossy) string — for parsing a dump's
/// header (the COMMENTED GTID/binlog coordinate) without loading a large member whole.
async fn read_file_prefix(path: &Path, max: usize) -> Result<String, Perr> {
    use tokio::io::AsyncReadExt;
    let mut f = tokio::fs::File::open(path).await.map_err(other)?;
    let mut buf = vec![0u8; max];
    let n = f.read(&mut buf).await.map_err(other)?;
    buf.truncate(n);
    Ok(String::from_utf8_lossy(&buf).into_owned())
}

// --- T3 Phase 1: resumable member-object layout helpers --------------------------------

/// The object filename for member `idx` in a resumable export directory. Zero-padded so a
/// directory listing sorts in member (restore) order.
fn member_object_name(idx: usize) -> String {
    format!("m{idx:05}")
}
/// The per-member `{size, sha256}` sidecar filename (a committed member has both).
fn member_meta_name(idx: usize) -> String {
    format!("m{idx:05}.meta")
}
/// The in-progress partial filename (renamed to the object only once fully written).
fn member_part_name(idx: usize) -> String {
    format!("m{idx:05}.part")
}

/// Write `bytes` to `path` atomically: a sibling `.tmp` then rename (so a crash never
/// leaves a half-written manifest/meta that a resume would trust).
async fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), Perr> {
    let tmp = path.with_extension("writing.tmp");
    tokio::fs::write(&tmp, bytes).await.map_err(other)?;
    tokio::fs::rename(&tmp, path).await.map_err(other)?;
    Ok(())
}

/// Stream-hash a file: its byte length + lowercase-hex SHA-256, read in bounded chunks so a
/// large member never loads whole into memory (preserving the O(chunk) footprint).
async fn sha256_and_size_of_file(path: &Path) -> Result<(u64, String), Perr> {
    use tokio::io::AsyncReadExt;
    let mut f = tokio::fs::File::open(path).await.map_err(other)?;
    let mut hasher = Sha256::new();
    let mut size = 0u64;
    let mut buf = vec![0u8; 64 * 1024];
    loop {
        let n = f.read(&mut buf).await.map_err(other)?;
        if n == 0 {
            break;
        }
        hasher.update(&buf[..n]);
        size += n as u64;
    }
    Ok((size, hex::encode(hasher.finalize())))
}

/// Whether member `obj` is COMPLETE: the object + its `.meta` sidecar both exist and the
/// object's streamed size + SHA-256 match the recorded [`MemberMeta`]. A missing sidecar,
/// an unparsable meta, or any size/SHA mismatch (a truncated/partial object) ⇒ not complete,
/// so the resume re-produces it. This is the per-member resume decision.
async fn member_object_valid(obj: &Path, meta: &Path) -> Result<bool, Perr> {
    if !tokio::fs::try_exists(obj).await.map_err(other)?
        || !tokio::fs::try_exists(meta).await.map_err(other)?
    {
        return Ok(false);
    }
    let meta_bytes = tokio::fs::read(meta).await.map_err(other)?;
    let recorded: project_bundle::MemberMeta = match serde_json::from_slice(&meta_bytes) {
        Ok(m) => m,
        Err(_) => return Ok(false),
    };
    let (size, sha) = sha256_and_size_of_file(obj).await?;
    Ok(size == recorded.size && sha == recorded.sha256)
}

/// Produce member `idx`'s object by copying a staged sidecar temp into `dir`, streaming its
/// bytes through the hasher so no whole-member buffer is held. Writes `m{idx}.part` then
/// renames to `m{idx}`; returns the member's `{size, sha256}`.
async fn write_member_from_file(
    dir: &Path,
    idx: usize,
    src: &Path,
) -> Result<project_bundle::MemberMeta, Perr> {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    let part = dir.join(member_part_name(idx));
    let mut rd = tokio::fs::File::open(src).await.map_err(other)?;
    let mut wr = tokio::fs::File::create(&part).await.map_err(other)?;
    let mut hasher = Sha256::new();
    let mut size = 0u64;
    let mut buf = vec![0u8; 64 * 1024];
    loop {
        let n = rd.read(&mut buf).await.map_err(other)?;
        if n == 0 {
            break;
        }
        wr.write_all(&buf[..n]).await.map_err(other)?;
        hasher.update(&buf[..n]);
        size += n as u64;
    }
    wr.flush().await.map_err(other)?;
    drop(wr);
    tokio::fs::rename(&part, dir.join(member_object_name(idx)))
        .await
        .map_err(other)?;
    Ok(project_bundle::MemberMeta {
        size,
        sha256: hex::encode(hasher.finalize()),
    })
}

/// Produce member `idx`'s object by draining a chunked body producer into `m{idx}.part`,
/// hashing as it goes, then rename to `m{idx}`. Fails LOUD (no rename, no meta) if the
/// producer POISONED (a short/failed dump) or errored, so a partial member can never be
/// recorded as complete.
async fn write_member_from_producer(
    dir: &Path,
    idx: usize,
    producer: ChunkedProducer,
) -> Result<project_bundle::MemberMeta, Perr> {
    use std::sync::atomic::Ordering::SeqCst;
    use tokio::io::AsyncWriteExt;
    let (mut rx, poison, handle) = producer;
    let part = dir.join(member_part_name(idx));
    let mut wr = tokio::fs::File::create(&part).await.map_err(other)?;
    let mut hasher = Sha256::new();
    let mut size = 0u64;
    while let Some(chunk) = rx.recv().await {
        wr.write_all(&chunk).await.map_err(other)?;
        hasher.update(&chunk);
        size += chunk.len() as u64;
    }
    wr.flush().await.map_err(other)?;
    drop(wr);
    // The producer task's own result + the poison flag are the authenticity of the body:
    // a failed/short dump must NOT be committed as a valid member.
    match handle.await {
        Ok(Ok(())) => {}
        Ok(Err(e)) => return Err(e),
        Err(e) => return Err(Perr::Other(format!("export member producer panicked: {e}"))),
    }
    if poison.load(SeqCst) {
        return Err(Perr::Other(format!(
            "export member {idx} producer poisoned (incomplete body) — not committing"
        )));
    }
    tokio::fs::rename(&part, dir.join(member_object_name(idx)))
        .await
        .map_err(other)?;
    Ok(project_bundle::MemberMeta {
        size,
        sha256: hex::encode(hasher.finalize()),
    })
}

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

    #[test]
    fn create_replication_slot_export_sql_is_version_aware_and_quoted() {
        // PG15+ takes the generic option list `(SNAPSHOT 'export')`…
        let pg16 = create_replication_slot_export_sql("brexp_slot_x", "160004");
        assert_eq!(
            pg16,
            "CREATE_REPLICATION_SLOT \"brexp_slot_x\" LOGICAL pgoutput (SNAPSHOT 'export');"
        );
        let pg17 = create_replication_slot_export_sql("brexp_slot_x", "170000");
        assert!(pg17.contains("(SNAPSHOT 'export')"));
        // …PG9.4–14 take the positional EXPORT_SNAPSHOT keyword.
        let pg14 = create_replication_slot_export_sql("brexp_slot_x", "140010");
        assert!(
            pg14.ends_with("LOGICAL pgoutput EXPORT_SNAPSHOT;"),
            "pre-15 must use the positional keyword: {pg14}"
        );
        // An unparseable banner is conservative (treat as old → positional keyword).
        let bad = create_replication_slot_export_sql("brexp_slot_x", "garbage");
        assert!(bad.ends_with("EXPORT_SNAPSHOT;"));
        // The slot name is double-quoted for the replication grammar, embedded `"` doubled.
        let weird = create_replication_slot_export_sql("s\"lot", "160004");
        assert!(
            weird.contains("\"s\"\"lot\""),
            "slot name must be quoted: {weird}"
        );
    }

    #[test]
    fn capture_entry_shielded_applies_the_stale_resumable_ttl() {
        let ttl = STALE_RESUMABLE_CAPTURE_TTL_SECS;
        let now = 1_000_000u64;
        // A FRESH base (created just now) is shielded; one older than the TTL is NOT (§4 LOW 4b).
        assert!(capture_entry_shielded(now - 10, 0, now, ttl));
        assert!(capture_entry_shielded(now - ttl, 0, now, ttl)); // exactly at the TTL still shielded
        assert!(!capture_entry_shielded(now - ttl - 1, 0, now, ttl)); // past the TTL → reclaimable
        // A pre-TTL entry (created_at == 0) falls back to the sidecar FILE age.
        assert!(capture_entry_shielded(0, ttl - 1, now, ttl)); // recent file → shielded
        assert!(!capture_entry_shielded(0, ttl + 1, now, ttl)); // old file → stale
        // A future/garbled created_at never under-ages into staleness (saturating_sub → 0 → shielded).
        assert!(capture_entry_shielded(now + 5, 0, now, ttl));
    }

    /// Drive the streaming export into an in-memory buffer (the v2 bundle bytes) — the
    /// in-process stand-in for the HTTP response the handler wires the sink to.
    async fn export_to_buf(
        drv: &NodeProjectExport,
        project: &str,
        opts: &ExportOptions,
    ) -> Result<Vec<u8>, Perr> {
        let mut sink = futures::io::Cursor::new(Vec::<u8>::new());
        drv.export(project, opts, &mut sink).await?;
        Ok(sink.into_inner())
    }

    /// Read a v2 bundle buffer back into its `data_only` flag + every member (spec + bytes).
    fn read_members(bytes: &[u8]) -> (bool, Vec<(MemberSpec, Vec<u8>)>) {
        let mut data_only = false;
        let mut got: Vec<(MemberSpec, Vec<u8>)> = Vec::new();
        project_bundle::read_bundle_streaming_with_head(
            bytes,
            |d, _s| data_only = d,
            |spec, _sz, body| {
                let mut v = Vec::new();
                body.read_to_end(&mut v)
                    .map_err(project_bundle::BundleError::Io)?;
                got.push((spec.clone(), v));
                Ok(())
            },
        )
        .expect("read back the exported v2 bundle");
        (data_only, got)
    }

    /// Import a bundle buffer through the streaming driver — the in-process stand-in for the
    /// HTTP request body the handler wires the source to.
    async fn import_buf(
        drv: &NodeProjectExport,
        project: &str,
        bytes: &[u8],
        opts: ImportOptions,
    ) -> Result<ImportReport, Perr> {
        let mut src = futures::io::Cursor::new(bytes.to_vec());
        drv.import(project, &mut src, opts).await
    }

    #[test]
    fn kind_detection() {
        assert!(kind_is_postgres("postgres"));
        assert!(kind_is_postgres("PostgreSQL"));
        assert!(kind_is_postgres("pg"));
        assert!(!kind_is_postgres("libsql"));
        assert!(kind_is_libsql("libsql"));
        assert!(kind_is_libsql("sqlite3"));
        assert!(!kind_is_libsql("mysql"));
        assert!(kind_is_mysql("mysql"));
        assert!(kind_is_mysql("MariaDB"));
        assert!(!kind_is_mysql("postgres"));
    }

    #[test]
    fn client_image_override_is_used_verbatim_else_computed() {
        use boatramp_core::Storage;
        use boatramp_core::deploy::DeployStore;
        use boatramp_core::kv::{KvStore, MemoryKv};
        use boatramp_storage::fs::FsStorage;
        use std::collections::BTreeMap;
        use std::sync::Arc;

        let tmp = tempfile::tempdir().unwrap();
        let kv: Arc<dyn KvStore> = Arc::new(MemoryKv::new());
        let blobs: Arc<dyn Storage> = Arc::new(FsStorage::new(tmp.path().join("blobs")));
        let deploy = DeployStore::new(blobs.clone(), kv.clone());
        let drv =
            NodeProjectExport::new(BTreeMap::new(), deploy, kv, blobs, tmp.path().join("work"));

        // No override: delegates to the version computer (and errors on an unmappable version).
        assert_eq!(
            drv.pg_image("160004").unwrap(),
            boatramp_core::compute::pg_client_image_for_server_version("160004").unwrap()
        );
        assert!(drv.pg_image("not-a-number").is_err());

        // Override: used VERBATIM and bypasses the version map entirely — a `@sha256:`-pinned ref
        // is returned even for a version the computer would reject, so the operator's pin reaches
        // `resolve_client_rootfs` (accepted under the multi-tenant posture) unchanged.
        let pinned = drv.with_client_images(
            Some("pgvector/pgvector:pg16@sha256:dead".into()),
            Some("mysql:8.4@sha256:beef".into()),
        );
        assert_eq!(
            pinned.pg_image("not-a-number").unwrap(),
            "pgvector/pgvector:pg16@sha256:dead"
        );
        assert_eq!(
            pinned.mysql_image("not-a-version").unwrap(),
            "mysql:8.4@sha256:beef"
        );
    }

    #[test]
    fn mysql_member_path_round_trips() {
        assert_eq!(mysql_member_path("shop"), "sql/shop.sql");
        assert_eq!(db_from_mysql_member("sql/shop.sql"), Some("shop"));
        // A pg member (`.pgc`) is NOT a mysql member.
        assert_eq!(db_from_mysql_member("sql/app.pgc"), None);
    }

    #[test]
    fn parse_sql_url_handles_pg_and_mysql_dsns() {
        assert_eq!(
            parse_sql_url("postgres://u:p@h:5432/db"),
            Some(("u".into(), "p".into(), "h".into(), 5432, "db".into()))
        );
        assert_eq!(
            parse_sql_url("mysql://svc:pw@10.0.0.6:3306/shop?ssl=true"),
            Some((
                "svc".into(),
                "pw".into(),
                "10.0.0.6".into(),
                3306,
                "shop".into()
            ))
        );
        // Default ports when omitted.
        assert_eq!(
            parse_sql_url("postgres://u:p@h/db").map(|t| t.3),
            Some(5432)
        );
        assert_eq!(parse_sql_url("mysql://u:p@h/db").map(|t| t.3), Some(3306));
        // A ':'-bearing password survives (split on the FIRST ':').
        assert_eq!(
            parse_sql_url("mysql://u:a:b@h:3306/db").map(|t| t.1),
            Some("a:b".into())
        );
        // Unknown scheme / garbage -> None (refuse, don't misconnect).
        assert_eq!(parse_sql_url("redis://h/0"), None);
        assert_eq!(parse_sql_url("not-a-url"), None);
    }

    #[test]
    fn pg_member_path_round_trips() {
        assert_eq!(pg_member_path("app"), "sql/app.pgc");
        assert_eq!(db_from_pg_member("sql/app.pgc"), Some("app"));
        assert_eq!(db_from_pg_member("libsql/x.sqlite"), None);
    }

    #[test]
    fn mysqlbinlog_member_path_round_trips() {
        assert_eq!(mysqlbinlog_member_path("app"), "sql/app.mysqlbinlog");
        assert_eq!(
            db_from_mysqlbinlog_member("sql/app.mysqlbinlog"),
            Some("app")
        );
        // The full-dump and true-delta member paths are distinct namespaces.
        assert_eq!(db_from_mysqlbinlog_member("sql/app.sql"), None);
        assert_eq!(db_from_mysql_member("sql/app.mysqlbinlog"), None);
    }

    #[test]
    fn mysql_binlog_image_appends_debian_once() {
        // mysqlbinlog ships in the DEBIAN variant, not the Oracle-Linux default image.
        assert_eq!(mysql_binlog_image("mysql:8.0"), "mysql:8.0-debian");
        assert_eq!(mysql_binlog_image("mysql:8.4"), "mysql:8.4-debian");
        // Idempotent — never double-adds.
        assert_eq!(mysql_binlog_image("mysql:8.0-debian"), "mysql:8.0-debian");
    }

    #[test]
    fn mysql_sql_log_bin_toggle_detection() {
        // The exact privileged lines `--source-data` injects (stripped from the capture base so the
        // least-privilege shadow user can restore it).
        assert!(mysql_line_is_sql_log_bin_toggle(
            "SET @MYSQLDUMP_TEMP_LOG_BIN = @@SESSION.SQL_LOG_BIN;"
        ));
        assert!(mysql_line_is_sql_log_bin_toggle(
            "SET @@SESSION.SQL_LOG_BIN= 0;"
        ));
        assert!(mysql_line_is_sql_log_bin_toggle(
            "SET @@SESSION.SQL_LOG_BIN = @MYSQLDUMP_TEMP_LOG_BIN;"
        ));
        // A normal dump statement is NOT stripped.
        assert!(!mysql_line_is_sql_log_bin_toggle(
            "INSERT INTO `t` VALUES (1,'a');"
        ));
        assert!(!mysql_line_is_sql_log_bin_toggle(
            "/* SET @@GLOBAL.GTID_PURGED='+uuid:1-9';*/"
        ));
    }

    #[test]
    fn parse_mysql_base_coord_extracts_gtid_and_log_file() {
        let header = "-- Server version\tn8.0.46\n\
            SET @@SESSION.SQL_LOG_BIN= 0;\n\
            /* SET @@GLOBAL.GTID_PURGED='+142694f1-d0bc-11f1:1-9';*/\n\
            -- CHANGE MASTER TO MASTER_LOG_FILE='node-bin.000003', MASTER_LOG_POS=1068;\n\
            DROP TABLE IF EXISTS `t`;\n";
        let (gtid, log) = parse_mysql_base_coord(header).expect("coord parses");
        assert_eq!(gtid, "142694f1-d0bc-11f1:1-9"); // leading '+' stripped
        assert_eq!(log, "node-bin.000003");
        // A dump with no coordinate (binlog/gtid off) ⇒ None ⇒ the delta full-dumps.
        assert_eq!(parse_mysql_base_coord("DROP TABLE IF EXISTS `t`;"), None);
    }

    #[test]
    fn mysql_grant_privileges_splits_before_the_target_db() {
        // The privilege part is everything before the first " ON " — the db NAME in the target must
        // never bleed into a SUPER/FILE/BINLOG_ADMIN substring match (LOW-1).
        let g = |l: &str| mysql_grant_privileges(l).to_ascii_uppercase();
        // A legit least-priv grant on a db whose NAME contains "SUPER"/"FILE"/"PROFILE".
        assert_eq!(
            g("GRANT ALL PRIVILEGES ON `supervisors__shadow_ab`.* TO 'x'@'%'"),
            "GRANT ALL PRIVILEGES"
        );
        assert!(!g("GRANT ALL PRIVILEGES ON `supervisors`.* TO 'x'@'%'").contains("SUPER"));
        assert!(!g("GRANT ALL PRIVILEGES ON `filestore`.* TO 'x'@'%'").contains("FILE"));
        assert!(!g("GRANT ALL PRIVILEGES ON `profiles`.* TO 'x'@'%'").contains("FILE"));
        // A genuinely dangerous privilege IS in the privilege part.
        assert!(g("GRANT SUPER ON *.* TO 'x'@'%'").contains("SUPER"));
        assert!(g("GRANT FILE ON *.* TO 'x'@'%'").contains("FILE"));
        assert!(
            g("GRANT REPLICATION_APPLIER, SESSION_VARIABLES_ADMIN ON *.* TO 'x'@'%'")
                .contains("REPLICATION_APPLIER")
        );
        // The replay dynamics do NOT contain the dangerous tokens.
        let dyn_privs = g("GRANT REPLICATION_APPLIER, SESSION_VARIABLES_ADMIN ON *.* TO 'x'@'%'");
        assert!(
            !dyn_privs.contains("SUPER")
                && !dyn_privs.contains("FILE")
                && !dyn_privs.contains("BINLOG_ADMIN")
        );
    }

    #[test]
    fn mysql_delta_shadow_db_is_deterministic_and_sweepable() {
        assert_eq!(mysql_delta_shadow_db("app"), "app__shadow_brdelta");
        // Carries the `__shadow_` infix so the startup `%__shadow_%` sweep reclaims a crashed one.
        assert!(mysql_delta_shadow_db("tenant_x").contains("__shadow_"));
    }

    #[test]
    fn swap_safety_refuses_empty_shadow_over_nonempty_live() {
        let s = |xs: &[&str]| xs.iter().map(|x| x.to_string()).collect::<Vec<_>>();
        // THE data-loss state: live has tables, shadow is EMPTY → swapping would move live aside +
        // drop it with nothing to put back → DESTROY live. MUST be flagged (the swap aborts).
        assert!(swap_would_destroy_live(&s(&["t", "victim"]), &s(&[])));
        // Safe: a populated shadow replaces live (the normal swap).
        assert!(!swap_would_destroy_live(&s(&["t"]), &s(&["t"])));
        // Safe: live is empty (first import into a fresh db) — nothing to lose.
        assert!(!swap_would_destroy_live(&s(&[]), &s(&["t"])));
        assert!(!swap_would_destroy_live(&s(&[]), &s(&[])));
        // The pre-fix swap built RENAME moves from exactly this (empty-shadow, nonempty-live) state
        // and processed it destructively — the guard above is what the fix adds, so this is not a
        // tautology: a shadow with ANY table is NOT flagged (a partial restore is a separate concern).
        assert!(!swap_would_destroy_live(&s(&["t", "victim"]), &s(&["t"])));
    }

    #[test]
    fn mysql_binlog_ddl_scan_distinguishes_row_dml_from_ddl() {
        // A clean ROW-only delta: comments, session SETs, a BINLOG base64 block, BEGIN/COMMIT.
        let row_only = "/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=1*/;\n\
            # at 197\n\
            SET @@session.sql_mode=1168113696/*!*/;\n\
            BEGIN\n\
            /*!*/;\n\
            BINLOG '\n\
            jnneag8BAAAAegAAAH4AAAA=\n\
            '/*!*/;\n\
            COMMIT\n\
            /*!*/;\n";
        assert!(
            !mysql_binlog_decoded_has_ddl(row_only),
            "a pure ROW/DML delta carries no DDL"
        );
        // A DDL event in the range (statement-logged even in ROW format) ⇒ fall back to a full dump.
        let with_ddl = format!("{row_only}ALTER TABLE `t` ADD COLUMN `c` int\n/*!*/;\n");
        assert!(
            mysql_binlog_decoded_has_ddl(&with_ddl),
            "an ALTER in the range must be detected as DDL"
        );
        let with_create = format!("{row_only}CREATE TABLE `u` (id int)\n/*!*/;\n");
        assert!(mysql_binlog_decoded_has_ddl(&with_create));
    }

    #[test]
    fn check_project_slug_rejects_traversal() {
        assert!(check_project_slug("acme").is_ok());
        assert!(check_project_slug("preview-b").is_ok());
        // A traversing / separator-bearing project is refused (defense-in-depth).
        assert!(check_project_slug("../etc").is_err());
        assert!(check_project_slug("a/b").is_err());
        assert!(check_project_slug("").is_err());
    }

    #[test]
    fn data_only_skew_fails_closed_on_a_missing_fingerprint() {
        // Proven compatible ONLY when both present AND equal.
        assert!(!data_only_skew_blocks(Some("abc"), Some("abc")));
        // Mismatch blocks.
        assert!(data_only_skew_blocks(Some("abc"), Some("xyz")));
        // A MISSING fingerprint on EITHER side blocks (fail-closed) — the security fix.
        assert!(data_only_skew_blocks(None, Some("abc")));
        assert!(data_only_skew_blocks(Some("abc"), None));
        assert!(data_only_skew_blocks(None, None));
    }

    /// Driver-level (in-process, no Docker): a `--data-only` export must NOT stage the
    /// control-plane KV slice, while a FULL export must. Drives the real
    /// `NodeProjectExport::export` with an empty `databases` map (no pg/mysql ⇒ no
    /// ephemeral container) + no libsql, so only the KV/blob orchestration runs. This is
    /// the mutation gate for the Ask-4(a) invariant (a data-only bundle carries no
    /// identity/RBAC/routing/secret bytes).
    #[tokio::test]
    async fn data_only_export_omits_the_control_plane_kv_slice() {
        use boatramp_core::Storage;
        use boatramp_core::deploy::DeployStore;
        use boatramp_core::kv::{KvStore, MemoryKv};
        use boatramp_storage::fs::FsStorage;
        use std::collections::BTreeMap;
        use std::sync::Arc;

        let tmp = tempfile::tempdir().unwrap();
        let kv: Arc<dyn KvStore> = Arc::new(MemoryKv::new());
        // An OWNED control-plane key so the FULL slice is non-trivial — exactly the kind of
        // config/secret byte a data-only bundle must never carry (and that the C1 allowlist
        // scopes INTO a full export, unlike a synthetic non-owned key).
        kv.put("project/acme/config/tenancy", b"{}".to_vec())
            .await
            .unwrap();
        let blobs: Arc<dyn Storage> = Arc::new(FsStorage::new(tmp.path().join("blobs")));
        let deploy = DeployStore::new(blobs.clone(), kv.clone());
        let work = tmp.path().join("work");
        std::fs::create_dir_all(&work).unwrap();
        let drv = NodeProjectExport::new(BTreeMap::new(), deploy, kv.clone(), blobs.clone(), work);

        // FULL export carries the control-plane KV slice...
        let full = export_to_buf(
            &drv,
            "acme",
            &ExportOptions {
                data_only: false,
                ..Default::default()
            },
        )
        .await
        .expect("full export");
        let (full_data_only, full_members) = read_members(&full);
        assert!(!full_data_only, "full manifest is not data-only");
        assert!(
            full_members.iter().any(|(m, _)| m.kind == MemberKind::Kv),
            "a FULL bundle must carry the control-plane KV slice"
        );

        // ...a data-only export must NOT (the Ask-4(a) safety invariant).
        let donly = export_to_buf(
            &drv,
            "acme",
            &ExportOptions {
                data_only: true,
                ..Default::default()
            },
        )
        .await
        .expect("data-only export");
        let (donly_data_only, donly_members) = read_members(&donly);
        assert!(donly_data_only, "data-only manifest flags data_only");
        assert!(
            !donly_members.iter().any(|(m, _)| m.kind == MemberKind::Kv),
            "a data-only bundle must NOT carry the control-plane KV slice (Ask-4a leak)"
        );
    }

    /// Driver-level (in-process): `--include-identity` wraps the KEK into an Identity member
    /// that round-trips under the transport key, and the refusals hold (data-only+identity,
    /// no transport key, a Vault source). Default export carries NO identity member. The
    /// Ask-4(d) gate: identity is excluded by default and only present under the flag.
    #[tokio::test]
    async fn include_identity_wraps_the_kek_and_refusals_hold() {
        use boatramp_core::Storage;
        use boatramp_core::deploy::DeployStore;
        use boatramp_core::kv::{KvStore, MemoryKv};
        use boatramp_storage::fs::FsStorage;
        use std::collections::BTreeMap;
        use std::sync::Arc;

        let tmp = tempfile::tempdir().unwrap();
        let kek = [0x5Au8; 32];
        let kek_file = tmp.path().join("kek");
        std::fs::write(&kek_file, kek).unwrap();

        let mk = |suffix: &str, src: Option<IdentityEnvelope>| {
            let kv: Arc<dyn KvStore> = Arc::new(MemoryKv::new());
            let blobs: Arc<dyn Storage> =
                Arc::new(FsStorage::new(tmp.path().join(format!("b{suffix}"))));
            let deploy = DeployStore::new(blobs.clone(), kv.clone());
            let work = tmp.path().join(format!("w{suffix}"));
            std::fs::create_dir_all(&work).unwrap();
            let mut d = NodeProjectExport::new(BTreeMap::new(), deploy, kv, blobs, work);
            if let Some(s) = src {
                d = d.with_identity_source(s);
            }
            d
        };

        let pass = b"operator-transport-passphrase".to_vec();
        let drv = mk(
            "local",
            Some(IdentityEnvelope::Local {
                kek_file: kek_file.clone(),
            }),
        );

        // include-identity (full) → an Identity member that unwraps to the exact KEK.
        let bundle = export_to_buf(
            &drv,
            "acme",
            &ExportOptions {
                data_only: false,
                include_identity: true,
                transport_key: Some(pass.clone()),
                delta: None,
            },
        )
        .await
        .expect("include-identity export");
        let (_do, members) = read_members(&bundle);
        let (idspec, container) = members
            .iter()
            .find(|(m, _)| m.kind == MemberKind::Identity)
            .expect("identity member present");
        assert_eq!(
            idspec.path, IDENTITY_MEMBER_PATH,
            "identity member at the declared path"
        );
        let payload =
            boatramp_server::envelope::transport_unwrap(container, &pass).expect("unwrap");
        assert_eq!(
            parse_identity_payload(&payload).unwrap(),
            kek,
            "the wrapped KEK round-trips"
        );
        assert!(
            boatramp_server::envelope::transport_unwrap(container, b"wrong").is_err(),
            "wrong transport key cannot open the container"
        );

        // The identity member is FIRST in the v2 restore order (an adopt import installs the
        // KEK before the KV slice).
        assert_eq!(
            members.first().map(|(m, _)| m.kind),
            Some(MemberKind::Identity),
            "identity is the first member in restore order"
        );

        // Default export → NO identity member.
        let plain = export_to_buf(&drv, "acme", &ExportOptions::default())
            .await
            .expect("default export");
        let (_do2, m2) = read_members(&plain);
        assert!(
            !m2.iter().any(|(m, _)| m.kind == MemberKind::Identity),
            "default bundle carries no identity member"
        );

        // Refusals: data-only+identity, missing transport key, and a Vault source.
        assert!(
            export_to_buf(
                &drv,
                "acme",
                &ExportOptions {
                    data_only: true,
                    include_identity: true,
                    transport_key: Some(pass.clone()),
                    delta: None,
                },
            )
            .await
            .is_err(),
            "data-only + include-identity is refused"
        );
        assert!(
            export_to_buf(
                &drv,
                "acme",
                &ExportOptions {
                    data_only: false,
                    include_identity: true,
                    transport_key: None,
                    delta: None,
                },
            )
            .await
            .is_err(),
            "include-identity without a transport key is refused"
        );
        let vault = mk("vault", Some(IdentityEnvelope::Vault));
        assert!(
            export_to_buf(
                &vault,
                "acme",
                &ExportOptions {
                    data_only: false,
                    include_identity: true,
                    transport_key: Some(pass.clone()),
                    delta: None,
                },
            )
            .await
            .is_err(),
            "include-identity on a Vault envelope is refused"
        );
    }

    /// Driver-level (in-process): `adopt` installs the source KEK and keeps the KV slice's
    /// sealed secrets; `fresh` installs no KEK and DROPS the source sealed-secret keyspace;
    /// neither imports `_cp/*`; and `adopt` on a bundle with no identity member is refused.
    /// The Ask-4(b) (never import `_cp/*`) + Ask-4(c) (fresh ⇒ zero source-sealed artifacts)
    /// gate.
    #[tokio::test]
    async fn adopt_installs_kek_and_fresh_drops_source_secrets() {
        use boatramp_core::Storage;
        use boatramp_core::deploy::DeployStore;
        use boatramp_core::kv::{KvStore, MemoryKv};
        use boatramp_storage::fs::FsStorage;
        use std::collections::BTreeMap;
        use std::sync::Arc;

        let tmp = tempfile::tempdir().unwrap();
        let kek = [0x3Cu8; 32];
        let src_kek_file = tmp.path().join("src-kek");
        std::fs::write(&src_kek_file, kek).unwrap();

        // Source: a sealed secret, a per-tenant secret, a reserved `_cp/*` key (must NOT
        // export), and a non-secret control-plane key (routing — kept on fresh).
        let src_kv: Arc<dyn KvStore> = Arc::new(MemoryKv::new());
        for (k, v) in [
            ("project/acme/secret/api-key", &b"sealed"[..]),
            ("project/acme/tenant-secret/t1/token", &b"sealed-t"[..]),
            ("project/acme/email/smtp", &b"sealed-pw"[..]), // H1: email is sealed → dropped on fresh
            ("managed-sql-cred/acme/pg", &b"sealed-cred"[..]), // H1: DB cred → dropped on fresh
            ("_cp/leader", &b"node-1"[..]),
            // A real OWNED, non-secret control-plane key — kept on fresh (and scoped into the
            // export, unlike a synthetic non-owned key which the C1 allowlist would exclude).
            ("project/acme/config/tenancy", &b"{}"[..]),
        ] {
            src_kv.put(k, v.to_vec()).await.unwrap();
        }
        let src_blobs: Arc<dyn Storage> = Arc::new(FsStorage::new(tmp.path().join("src-blobs")));
        let src = NodeProjectExport::new(
            BTreeMap::new(),
            DeployStore::new(src_blobs.clone(), src_kv.clone()),
            src_kv.clone(),
            src_blobs,
            {
                let w = tmp.path().join("src-work");
                std::fs::create_dir_all(&w).unwrap();
                w
            },
        )
        .with_identity_source(IdentityEnvelope::Local {
            kek_file: src_kek_file.clone(),
        });
        let pass = b"transport-pass".to_vec();
        let bundle = export_to_buf(
            &src,
            "acme",
            &ExportOptions {
                data_only: false,
                include_identity: true,
                transport_key: Some(pass.clone()),
                delta: None,
            },
        )
        .await
        .expect("export with identity");

        // Build a fresh target driver (empty KV, a kek_file path that does not yet exist).
        let target = |tag: &str| {
            let kv: Arc<dyn KvStore> = Arc::new(MemoryKv::new());
            let blobs: Arc<dyn Storage> =
                Arc::new(FsStorage::new(tmp.path().join(format!("{tag}-blobs"))));
            let work = tmp.path().join(format!("{tag}-work"));
            std::fs::create_dir_all(&work).unwrap();
            let kek_file = tmp.path().join(format!("{tag}-kek"));
            let drv = NodeProjectExport::new(
                BTreeMap::new(),
                DeployStore::new(blobs.clone(), kv.clone()),
                kv.clone(),
                blobs,
                work,
            )
            .with_identity_source(IdentityEnvelope::Local {
                kek_file: kek_file.clone(),
            });
            (drv, kv, kek_file)
        };

        // --- adopt: installs the KEK, keeps sealed secrets, never writes _cp/* ---
        let (adopt_drv, a_kv, a_kek) = target("a");
        import_buf(
            &adopt_drv,
            "acme",
            &bundle,
            ImportOptions {
                apply: true,
                identity: IdentityChoice::Adopt {
                    transport_key: pass.clone(),
                },
                ..Default::default()
            },
        )
        .await
        .expect("adopt import");
        assert_eq!(
            std::fs::read(&a_kek).unwrap(),
            kek,
            "adopt installed the source KEK"
        );
        assert!(
            a_kv.get("project/acme/secret/api-key")
                .await
                .unwrap()
                .is_some(),
            "adopt keeps the sealed secret (it unseals under the adopted KEK)"
        );
        assert!(
            a_kv.get("project/acme/email/smtp").await.unwrap().is_some()
                && a_kv
                    .get("managed-sql-cred/acme/pg")
                    .await
                    .unwrap()
                    .is_some(),
            "adopt keeps the sealed email profile + managed-DB credential"
        );
        assert!(
            a_kv.get("_cp/leader").await.unwrap().is_none(),
            "import never writes a reserved _cp/* key (Ask-4b)"
        );

        // --- fresh: installs NO KEK, drops the source sealed-secret keyspace ---
        let (fresh_drv, f_kv, f_kek) = target("f");
        import_buf(
            &fresh_drv,
            "acme",
            &bundle,
            ImportOptions {
                apply: true,
                identity: IdentityChoice::Fresh,
                ..Default::default()
            },
        )
        .await
        .expect("fresh import");
        assert!(!f_kek.exists(), "fresh installs no KEK");
        assert!(
            f_kv.get("project/acme/secret/api-key")
                .await
                .unwrap()
                .is_none(),
            "fresh dropped the source sealed secret (Ask-4c)"
        );
        assert!(
            f_kv.get("project/acme/tenant-secret/t1/token")
                .await
                .unwrap()
                .is_none(),
            "fresh dropped the source per-tenant secret (Ask-4c)"
        );
        assert!(
            f_kv.get("project/acme/email/smtp").await.unwrap().is_none(),
            "fresh dropped the source SMTP profile's sealed password (H1)"
        );
        assert!(
            f_kv.get("managed-sql-cred/acme/pg")
                .await
                .unwrap()
                .is_none(),
            "fresh dropped the source managed-DB credential (H1)"
        );
        assert!(
            f_kv.get("project/acme/config/tenancy")
                .await
                .unwrap()
                .is_some(),
            "fresh keeps non-secret, environment-neutral control-plane config (tenancy map)"
        );
        assert!(
            f_kv.get("_cp/leader").await.unwrap().is_none(),
            "import never writes a reserved _cp/* key (Ask-4b)"
        );

        // --- adopt on a bundle WITHOUT an identity member is refused ---
        let plain = export_to_buf(&src, "acme", &ExportOptions::default())
            .await
            .expect("plain export");
        let (no_id_drv, no_id_kv, _f) = target("n");
        assert!(
            import_buf(
                &no_id_drv,
                "acme",
                &plain,
                ImportOptions {
                    apply: true,
                    identity: IdentityChoice::Adopt {
                        transport_key: pass.clone(),
                    },
                    ..Default::default()
                },
            )
            .await
            .is_err(),
            "adopt on a bundle with no identity member is refused"
        );
        // ...and refused BEFORE the sealed KV slice is written (the KV-member guard): no
        // source-sealed secret landed on the target despite the plain bundle carrying one.
        assert!(
            no_id_kv
                .get("project/acme/secret/api-key")
                .await
                .unwrap()
                .is_none(),
            "a refused adopt must not have written the source-sealed KV slice"
        );
    }

    /// A blob LARGER than the chunk size takes the ChunkedTrailer streaming framing and round-trips
    /// byte-identical through export AND import into a re-keyed target scope — the per-member
    /// streaming guarantee (never buffer a whole large blob): export streams the body O(chunk) with
    /// no whole-object temp, import stages the chunk stream to a bounded temp then streams it into
    /// the target store. A small blob stays Sidecar. Round-trip equality over a 5 KB body (≫ the
    /// 16 B test chunk) proves the `.part` framing reassembles the large body exactly.
    #[tokio::test]
    async fn large_blob_round_trips_through_the_chunked_streaming_path() {
        use boatramp_core::Storage;
        use boatramp_core::deploy::DeployStore;
        use boatramp_core::kv::{KvStore, MemoryKv};
        use boatramp_storage::fs::FsStorage;
        use std::collections::BTreeMap;
        use std::sync::Arc;

        let tmp = tempfile::tempdir().unwrap();

        let mk = |tag: &str| {
            let kv: Arc<dyn KvStore> = Arc::new(MemoryKv::new());
            let blobs: Arc<dyn Storage> =
                Arc::new(FsStorage::new(tmp.path().join(format!("{tag}-blobs"))));
            let deploy = DeployStore::new(blobs.clone(), kv.clone());
            let work = tmp.path().join(format!("{tag}-work"));
            std::fs::create_dir_all(&work).unwrap();
            // chunk size 16 B so a modest blob is framed ChunkedTrailer.
            let drv = NodeProjectExport::new(BTreeMap::new(), deploy, kv, blobs.clone(), work)
                .with_chunk_size(16);
            (drv, blobs)
        };

        let (src, src_blobs) = mk("src");

        // A blob much larger than the chunk size (→ ChunkedTrailer) + a tiny one (→ Sidecar);
        // distinct, non-trivial bytes so a wrongly reassembled body is caught.
        let big: Vec<u8> = (0u32..5000).map(|i| (i % 251) as u8).collect();
        let small = b"tiny".to_vec();
        let put = |blobs: Arc<dyn Storage>, key: &'static str, bytes: Vec<u8>| async move {
            let body: boatramp_core::ByteStream =
                futures::stream::once(async move { Ok(bytes::Bytes::from(bytes)) }).boxed();
            blobs
                .put(key, body, boatramp_core::PutMeta { content_type: None })
                .await
                .unwrap();
        };
        put(
            src_blobs.clone(),
            "hblob/acme/web/assets/big.bin",
            big.clone(),
        )
        .await;
        put(
            src_blobs.clone(),
            "hblob/acme/web/assets/small.txt",
            small.clone(),
        )
        .await;

        // data-only export: carries blobs (never gated on data_only) but no KV/identity — keeps the
        // round-trip focused on the blob streaming path.
        let bundle = export_to_buf(
            &src,
            "acme",
            &ExportOptions {
                data_only: true,
                ..Default::default()
            },
        )
        .await
        .expect("export");

        // The bundle is v3 (it carries a chunked member); the v2-only `read_members` helper cannot
        // read it, so parse the MANIFEST (first tar entry) directly to assert the LARGE blob took
        // the ChunkedTrailer streaming framing and the small one stayed Sidecar. The large body's
        // byte-identity is proven by the import round-trip below (which DOES read v3).
        let manifest: project_bundle::StreamManifest = {
            use std::io::Read as _;
            let mut ar = tar::Archive::new(std::io::Cursor::new(&bundle));
            let mut first = ar
                .entries()
                .unwrap()
                .next()
                .expect("manifest entry")
                .unwrap();
            let mut json = String::new();
            first.read_to_string(&mut json).unwrap();
            serde_json::from_str(&json).expect("parse the v3 StreamManifest")
        };
        assert_eq!(
            manifest.format_version,
            project_bundle::BUNDLE_FORMAT_VERSION_V3,
            "a bundle carrying a chunked member is v3"
        );
        let framing = |path: &str| {
            manifest
                .members
                .iter()
                .find(|m| m.path == path)
                .map(|m| m.framing)
        };
        assert_eq!(
            framing("blobs/hblob/acme/web/assets/big.bin"),
            Some(project_bundle::MemberFraming::ChunkedTrailer),
            "a blob larger than the chunk size must take the chunked streaming framing"
        );
        assert_eq!(
            framing("blobs/hblob/acme/web/assets/small.txt"),
            Some(project_bundle::MemberFraming::Sidecar),
            "a small blob stays sidecar"
        );

        // Import into a FRESH target project "acme2": the large blob streams per-member back into
        // the target store under the re-keyed scope, byte-identical.
        let (tgt, tgt_blobs) = mk("tgt");
        let report = import_buf(
            &tgt,
            "acme2",
            &bundle,
            ImportOptions {
                apply: true,
                ..Default::default()
            },
        )
        .await
        .expect("import");
        assert!(
            report.blobs >= 2,
            "both blobs imported (got {})",
            report.blobs
        );

        let got = tgt_blobs
            .get("hblob/acme2/web/assets/big.bin")
            .await
            .expect("the large blob landed under the re-keyed target scope");
        let mut body = got.body;
        let mut buf = Vec::new();
        while let Some(chunk) = body.next().await {
            buf.extend_from_slice(chunk.unwrap().as_ref());
        }
        assert_eq!(
            buf, big,
            "the large blob is byte-identical after a chunked export+import round-trip"
        );
    }

    /// GATE (project-clone, C1 cross-tenant isolation — the 0.32 env-clone-leak class): a
    /// streaming clone of ONE tenant, driven through the REAL source→target stream (manifest →
    /// per-SHA diff → filtered export → inc2 atomic import), lands EXACTLY that tenant's data under
    /// the target scope with ZERO foreign bytes, and leaves the SOURCE byte-unchanged. The fixture
    /// seeds TWO tenants (`acme`, `globex`) sharing ONE blob bucket + ONE KV store — a single-tenant
    /// fixture is structurally blind to a leak (rule 3). This test actually RUNS (not `#[ignore]`d),
    /// wiring the live source→target stream, so a regression that leaked a foreign object or trusted
    /// a source-declared scope fails here (rule 4).
    #[tokio::test]
    async fn clone_isolates_one_tenant_zero_foreign_bytes_source_unchanged() {
        use boatramp_core::Storage;
        use boatramp_core::deploy::DeployStore;
        use boatramp_core::kv::{KvStore, MemoryKv};
        use boatramp_storage::fs::FsStorage;
        use std::collections::BTreeMap;
        use std::sync::Arc;

        let tmp = tempfile::tempdir().unwrap();
        let mk = |tag: &str| {
            let kv: Arc<dyn KvStore> = Arc::new(MemoryKv::new());
            let blobs: Arc<dyn Storage> =
                Arc::new(FsStorage::new(tmp.path().join(format!("{tag}-blobs"))));
            let deploy = DeployStore::new(blobs.clone(), kv.clone());
            let work = tmp.path().join(format!("{tag}-work"));
            std::fs::create_dir_all(&work).unwrap();
            // chunk size 16 B so the (modest) blobs exercise the ChunkedTrailer streaming path too.
            let drv =
                NodeProjectExport::new(BTreeMap::new(), deploy, kv.clone(), blobs.clone(), work)
                    .with_chunk_size(16);
            (drv, kv, blobs)
        };
        let put = |blobs: Arc<dyn Storage>, key: &'static str, bytes: Vec<u8>| async move {
            let body: boatramp_core::ByteStream =
                futures::stream::once(async move { Ok(bytes::Bytes::from(bytes)) }).boxed();
            blobs
                .put(key, body, boatramp_core::PutMeta { content_type: None })
                .await
                .unwrap();
        };
        let read_blob = |blobs: Arc<dyn Storage>, key: String| async move {
            let got = blobs.get(&key).await.ok()?;
            let mut body = got.body;
            let mut buf = Vec::new();
            while let Some(c) = body.next().await {
                buf.extend_from_slice(c.unwrap().as_ref());
            }
            Some(buf)
        };

        // --- SOURCE: two tenants sharing ONE bucket + ONE KV store (the shared keyspace). ---
        let (src, src_kv, src_blobs) = mk("src");
        let acme_bytes: Vec<u8> = (0u32..3000).map(|i| (i % 251) as u8).collect();
        let globex_bytes: Vec<u8> = (0u32..2000).map(|i| ((i * 7) % 251) as u8).collect();
        put(
            src_blobs.clone(),
            "hblob/acme/web/assets/a.bin",
            acme_bytes.clone(),
        )
        .await;
        put(
            src_blobs.clone(),
            "hblob/acme/web/assets/small.txt",
            b"acme-tiny".to_vec(),
        )
        .await;
        put(
            src_blobs.clone(),
            "hblob/globex/web/assets/g.bin",
            globex_bytes.clone(),
        )
        .await;
        // Non-secret, environment-neutral owned KV (survives a `--identity fresh` import) for each.
        src_kv
            .put("project/acme/config/tenancy", b"{\"acme\":1}".to_vec())
            .await
            .unwrap();
        src_kv
            .put("project/globex/config/tenancy", b"{\"globex\":1}".to_vec())
            .await
            .unwrap();

        let opts = ExportOptions::default(); // full bundle (carries the control-plane KV slice)

        // --- TARGET: a fresh, SEPARATE node. Clone acme (same-name) via the live handshake. ---
        let (tgt, tgt_kv, tgt_blobs) = mk("tgt");

        // 1. SOURCE manifest (cheap LIST): must carry ONLY acme's blobs — the manifest is itself a
        //    tenancy boundary (scoped by `hblob/acme/`).
        let manifest = src
            .clone_manifest("acme", &opts)
            .await
            .expect("clone manifest");
        assert_eq!(manifest.source_project, "acme");
        assert_eq!(
            manifest.blobs.len(),
            2,
            "manifest lists exactly acme's two blobs"
        );
        assert!(
            manifest
                .blobs
                .iter()
                .all(|b| b.member_path.starts_with("blobs/hblob/acme/")),
            "NO foreign-tenant object may appear in acme's clone manifest: {:?}",
            manifest.blobs
        );

        // 2. TARGET per-SHA diff: fresh target holds nothing ⇒ an EMPTY skip set (pull everything).
        let skip = tgt
            .clone_blobs_present("acme", &manifest.source_project, &manifest.blobs)
            .await
            .expect("diff");
        assert!(
            skip.skip_member_paths.is_empty(),
            "fresh target skips nothing"
        );

        // 3. SOURCE filtered stream → 4. TARGET inc2 atomic restore (the live source→target stream).
        let mut sink = futures::io::Cursor::new(Vec::<u8>::new());
        src.export_clone("acme", &opts, &skip, &mut sink)
            .await
            .expect("filtered clone export");
        let bundle = sink.into_inner();
        let mut rd = futures::io::Cursor::new(bundle.clone());
        let report = tgt
            .import(
                "acme",
                &mut rd,
                ImportOptions {
                    apply: true,
                    ..Default::default()
                },
            )
            .await
            .expect("clone import");
        assert!(
            report.blobs >= 2,
            "acme's blobs restored (got {})",
            report.blobs
        );

        // --- ASSERT: target holds EXACTLY acme's data under the target scope. ---
        assert_eq!(
            read_blob(tgt_blobs.clone(), "hblob/acme/web/assets/a.bin".into()).await,
            Some(acme_bytes.clone()),
            "acme's blob landed byte-identical under the target scope"
        );
        assert_eq!(
            tgt_kv.get("project/acme/config/tenancy").await.unwrap(),
            Some(b"{\"acme\":1}".to_vec()),
            "acme's owned control-plane KV landed on the target"
        );

        // --- ASSERT: ZERO foreign bytes in the target (the load-bearing isolation gate). ---
        let tgt_keys = tgt_blobs.list("hblob/").await.unwrap();
        assert!(
            tgt_keys.iter().all(|m| m.key.starts_with("hblob/acme/")),
            "NO foreign-tenant object in the target bucket: {:?}",
            tgt_keys.iter().map(|m| &m.key).collect::<Vec<_>>()
        );
        assert!(
            read_blob(tgt_blobs.clone(), "hblob/globex/web/assets/g.bin".into())
                .await
                .is_none(),
            "globex's object must be ABSENT from the target"
        );
        assert!(
            tgt_kv
                .get("project/globex/config/tenancy")
                .await
                .unwrap()
                .is_none(),
            "NO foreign-tenant control-plane KV in the target"
        );
        assert!(
            tgt_kv
                .list_prefix("project/globex/")
                .await
                .unwrap()
                .is_empty(),
            "the target carries no globex keyspace at all"
        );

        // --- ASSERT: the SOURCE is left byte-unchanged (a clone is a read on the source). ---
        assert_eq!(
            read_blob(src_blobs.clone(), "hblob/acme/web/assets/a.bin".into()).await,
            Some(acme_bytes.clone()),
            "source acme blob intact"
        );
        assert_eq!(
            read_blob(src_blobs.clone(), "hblob/globex/web/assets/g.bin".into()).await,
            Some(globex_bytes.clone()),
            "source globex blob intact + untouched by acme's clone"
        );
        assert_eq!(
            src_kv.get("project/globex/config/tenancy").await.unwrap(),
            Some(b"{\"globex\":1}".to_vec()),
            "source globex KV intact"
        );

        // --- RESUME / per-SHA skip: a re-diff against the now-populated target marks acme's blobs
        //     PRESENT ⇒ the source would skip them (O(remaining), not a full re-stream). ---
        let skip2 = tgt
            .clone_blobs_present("acme", &manifest.source_project, &manifest.blobs)
            .await
            .expect("re-diff");
        assert_eq!(
            skip2.skip_member_paths.len(),
            2,
            "a re-run skips both already-present acme blobs: {:?}",
            skip2.skip_member_paths
        );
        // The filtered re-export omits the skipped blob members (nothing left to re-stream), yet a
        // re-import is still correct (idempotent) and leaves the target isolated.
        let mut sink2 = futures::io::Cursor::new(Vec::<u8>::new());
        src.export_clone("acme", &opts, &skip2, &mut sink2)
            .await
            .expect("resumed filtered export");
        let mut rd2 = futures::io::Cursor::new(sink2.into_inner());
        tgt.import(
            "acme",
            &mut rd2,
            ImportOptions {
                apply: true,
                overwrite: true, // the target project already holds its own data
                force: true,     // overlay the now-non-empty control-plane KV destination
                ..Default::default()
            },
        )
        .await
        .expect("resumed import");
        let tgt_keys2 = tgt_blobs.list("hblob/").await.unwrap();
        assert!(
            tgt_keys2.iter().all(|m| m.key.starts_with("hblob/acme/")),
            "a resumed clone still leaks ZERO foreign bytes"
        );

        // --- FAIL-CLOSED: the diff refuses a source-declared ref OUTSIDE the declared source
        //     scope — the target never trusts a crafted manifest to reach a foreign key. ---
        let foreign = vec![CloneBlobRef {
            member_path: "blobs/hblob/globex/web/assets/g.bin".to_string(),
            size: Some(10),
            etag: None,
        }];
        assert!(
            tgt.clone_blobs_present("acme", "acme", &foreign)
                .await
                .is_err(),
            "a ref outside hblob/{{source}}/ must be refused fail-closed"
        );
    }

    /// GATE (project-clone, Security review Part B #5): the CROSS-NAME variant of the tenancy gate —
    /// cloning `preview-a` → `preview-b` exercises the `target_blob_key` + KV re-key END-TO-END
    /// through the live stream (the same-name `acme→acme` case is an identity no-op on the re-key).
    /// A foreign tenant (`other`) shares the source bucket/KV. Asserts the target holds preview-b's
    /// data under the RE-KEYED `hblob/preview-b/` + `project/preview-b/` scopes, byte-identical, with
    /// ZERO `preview-a` or `other` bytes, and the source is byte-unchanged.
    #[tokio::test]
    async fn clone_cross_name_rekeys_end_to_end_zero_foreign_bytes() {
        use boatramp_core::Storage;
        use boatramp_core::deploy::DeployStore;
        use boatramp_core::kv::{KvStore, MemoryKv};
        use boatramp_storage::fs::FsStorage;
        use std::collections::BTreeMap;
        use std::sync::Arc;

        let tmp = tempfile::tempdir().unwrap();
        let mk = |tag: &str| {
            let kv: Arc<dyn KvStore> = Arc::new(MemoryKv::new());
            let blobs: Arc<dyn Storage> =
                Arc::new(FsStorage::new(tmp.path().join(format!("{tag}-blobs"))));
            let deploy = DeployStore::new(blobs.clone(), kv.clone());
            let work = tmp.path().join(format!("{tag}-work"));
            std::fs::create_dir_all(&work).unwrap();
            let drv =
                NodeProjectExport::new(BTreeMap::new(), deploy, kv.clone(), blobs.clone(), work)
                    .with_chunk_size(16);
            (drv, kv, blobs)
        };
        let put = |blobs: Arc<dyn Storage>, key: &'static str, bytes: Vec<u8>| async move {
            let body: boatramp_core::ByteStream =
                futures::stream::once(async move { Ok(bytes::Bytes::from(bytes)) }).boxed();
            blobs
                .put(key, body, boatramp_core::PutMeta { content_type: None })
                .await
                .unwrap();
        };
        let read_blob = |blobs: Arc<dyn Storage>, key: String| async move {
            let got = blobs.get(&key).await.ok()?;
            let mut body = got.body;
            let mut buf = Vec::new();
            while let Some(c) = body.next().await {
                buf.extend_from_slice(c.unwrap().as_ref());
            }
            Some(buf)
        };

        // SOURCE: preview-a (the clone subject) + `other` (a foreign tenant) share one bucket + KV.
        let (src, src_kv, src_blobs) = mk("src");
        let a_bytes: Vec<u8> = (0u32..3000).map(|i| (i % 251) as u8).collect();
        put(
            src_blobs.clone(),
            "hblob/preview-a/web/assets/a.bin",
            a_bytes.clone(),
        )
        .await;
        put(
            src_blobs.clone(),
            "hblob/other/web/assets/o.bin",
            b"foreign".to_vec(),
        )
        .await;
        src_kv
            .put("project/preview-a/config/tenancy", b"{\"a\":1}".to_vec())
            .await
            .unwrap();
        src_kv
            .put("project/other/config/tenancy", b"{\"other\":1}".to_vec())
            .await
            .unwrap();

        let opts = ExportOptions::default();
        let (tgt, tgt_kv, tgt_blobs) = mk("tgt");

        // Clone preview-a → preview-b through the live stream (source_project != target).
        let manifest = src
            .clone_manifest("preview-a", &opts)
            .await
            .expect("manifest");
        assert_eq!(
            manifest.blobs.len(),
            1,
            "manifest lists ONLY preview-a's blob"
        );
        assert!(
            manifest.blobs[0]
                .member_path
                .starts_with("blobs/hblob/preview-a/"),
            "no foreign object in preview-a's manifest"
        );
        let skip = tgt
            .clone_blobs_present("preview-b", &manifest.source_project, &manifest.blobs)
            .await
            .expect("diff");
        assert!(
            skip.skip_member_paths.is_empty(),
            "fresh target skips nothing"
        );
        let mut sink = futures::io::Cursor::new(Vec::<u8>::new());
        src.export_clone("preview-a", &opts, &skip, &mut sink)
            .await
            .expect("filtered export");
        let mut rd = futures::io::Cursor::new(sink.into_inner());
        tgt.import(
            "preview-b",
            &mut rd,
            ImportOptions {
                apply: true,
                ..Default::default()
            },
        )
        .await
        .expect("cross-name clone import");

        // The blob landed under the RE-KEYED target scope (preview-a → preview-b), byte-identical.
        assert_eq!(
            read_blob(tgt_blobs.clone(), "hblob/preview-b/web/assets/a.bin".into()).await,
            Some(a_bytes.clone()),
            "the blob re-keyed to the preview-b scope, byte-identical"
        );
        // The owned KV re-keyed too (project/preview-a/… → project/preview-b/…).
        assert_eq!(
            tgt_kv
                .get("project/preview-b/config/tenancy")
                .await
                .unwrap(),
            Some(b"{\"a\":1}".to_vec()),
            "the owned control-plane KV re-keyed to preview-b"
        );
        // ZERO source-scope or foreign bytes in the target (the load-bearing re-key isolation gate).
        let tgt_keys = tgt_blobs.list("hblob/").await.unwrap();
        assert!(
            tgt_keys
                .iter()
                .all(|m| m.key.starts_with("hblob/preview-b/")),
            "the target bucket holds ONLY preview-b objects: {:?}",
            tgt_keys.iter().map(|m| &m.key).collect::<Vec<_>>()
        );
        assert!(
            tgt_kv
                .list_prefix("project/preview-a/")
                .await
                .unwrap()
                .is_empty(),
            "NO un-re-keyed source-scope KV survives on the target"
        );
        assert!(
            tgt_kv
                .list_prefix("project/other/")
                .await
                .unwrap()
                .is_empty(),
            "NO foreign-tenant KV on the target"
        );
        // The SOURCE is byte-unchanged (a clone reads the source).
        assert_eq!(
            read_blob(src_blobs.clone(), "hblob/preview-a/web/assets/a.bin".into()).await,
            Some(a_bytes),
            "source preview-a blob intact"
        );
        assert_eq!(
            read_blob(src_blobs.clone(), "hblob/other/web/assets/o.bin".into()).await,
            Some(b"foreign".to_vec()),
            "source foreign tenant intact + untouched"
        );
    }

    #[test]
    fn blob_rekey_lands_in_target_scope_and_fails_closed() {
        // Same project → the member's own scope (no rename).
        assert_eq!(
            target_blob_key("blobs/hblob/acme/web/c/obj", "acme", "acme").unwrap(),
            "hblob/acme/web/c/obj"
        );
        // Rename → the object lands under the TARGET project's scope, never the source's.
        let t = target_blob_key("blobs/hblob/preview-a/web/c/obj", "preview-a", "preview-b")
            .expect("rename re-key");
        assert_eq!(t, "hblob/preview-b/web/c/obj");
        assert!(
            !t.contains("preview-a"),
            "NO source-scope segment survives a rename re-key"
        );
        // FAIL-CLOSED (the tenancy-critical mutation): a member NOT under the source project
        // scope is REFUSED, never silently landed in a foreign scope — a sibling-prefix project
        // (`acmecorp` vs `acme`) is not over-captured, and a bare key missing the `blobs/`
        // wrapper is rejected.
        assert!(target_blob_key("blobs/hblob/globex/secret/obj", "acme", "beta").is_err());
        assert!(target_blob_key("blobs/hblob/acmecorp/x", "acme", "beta").is_err());
        assert!(target_blob_key("hblob/acme/x", "acme", "beta").is_err());
        assert!(target_blob_key("blobs/not-hblob/x", "acme", "beta").is_err());

        // Defense-in-depth (Security review Part B #4): the re-keyed REMAINDER must be a clean
        // relative path — a `..`/`.`/absolute/empty component is REFUSED, so a crafted member can
        // never traverse OUT of `hblob/{target}/` into another tenant's scope or the bucket root,
        // even though the key IS under the declared source prefix. Mutation witness: drop the
        // component check in `target_blob_key` and these go from Err → Ok (a traversal escape).
        assert!(
            target_blob_key("blobs/hblob/acme/../globex/obj", "acme", "beta").is_err(),
            "a `..` that climbs out of the acme scope toward globex must be refused"
        );
        assert!(
            target_blob_key("blobs/hblob/acme/a/../../etc/x", "acme", "beta").is_err(),
            "a `..` chain escaping the target scope must be refused"
        );
        assert!(
            target_blob_key("blobs/hblob/acme/./obj", "acme", "beta").is_err(),
            "a `.` component in the remainder must be refused"
        );
        assert!(
            target_blob_key("blobs/hblob/acme/", "acme", "beta").is_err(),
            "an empty remainder (no object key) must be refused"
        );
    }

    /// Security review Part B #2 (OOM/DoS guard): `diff_clone_blobs` REFUSES a manifest whose blob
    /// count exceeds the cap BEFORE the per-ref HEAD fan-out, so a hostile source cannot OOM the
    /// diff or storm the target's bucket with HEADs. A count at/under the cap is accepted.
    #[tokio::test]
    async fn diff_clone_blobs_caps_the_manifest_blob_count() {
        use boatramp_core::Storage;
        use boatramp_core::deploy::DeployStore;
        use boatramp_core::kv::{KvStore, MemoryKv};
        use boatramp_storage::fs::FsStorage;
        use std::collections::BTreeMap;
        use std::sync::Arc;

        let tmp = tempfile::tempdir().unwrap();
        let kv: Arc<dyn KvStore> = Arc::new(MemoryKv::new());
        let blobs: Arc<dyn Storage> = Arc::new(FsStorage::new(tmp.path().join("blobs")));
        let drv = NodeProjectExport::new(
            BTreeMap::new(),
            DeployStore::new(blobs.clone(), kv.clone()),
            kv,
            blobs,
            tmp.path().join("work"),
        );
        // One ref over the cap → refused before any HEAD (the refs point nowhere; a non-capped run
        // would instead HEAD each, but the cap check fires first).
        let over: Vec<CloneBlobRef> = (0..MAX_CLONE_MANIFEST_BLOBS + 1)
            .map(|i| CloneBlobRef {
                member_path: format!("blobs/hblob/acme/web/c/obj-{i}"),
                size: Some(1),
                etag: None,
            })
            .collect();
        let err = drv
            .diff_clone_blobs("acme", "acme", &over)
            .await
            .expect_err("a manifest over the blob-count cap must be refused");
        assert!(
            format!("{err}").contains("exceeding the maximum"),
            "the refusal names the cap: {err}"
        );
        // An empty manifest (well under the cap) is fine and skips nothing.
        let skip = drv
            .diff_clone_blobs("acme", "acme", &[])
            .await
            .expect("an under-cap manifest diffs cleanly");
        assert!(skip.skip_member_paths.is_empty());
    }

    #[test]
    fn libsql_member_path_round_trips_the_site() {
        assert_eq!(
            libsql_member_path("acme", "blog"),
            "libsql/acme/blog/default.sqlite"
        );
        // The SITE is recovered (the source project segment is discarded on import).
        assert_eq!(
            site_from_libsql_member("libsql/acme/blog/default.sqlite"),
            Some("blog")
        );
        assert_eq!(
            site_from_libsql_member("libsql/default/www/default.sqlite"),
            Some("www")
        );
        assert_eq!(site_from_libsql_member("sql/app.pgc"), None);
        assert_eq!(site_from_libsql_member("libsql/bad"), None);
        // The changeset sibling path round-trips too.
        assert_eq!(
            libsql_changeset_member_path("acme", "blog"),
            "libsql/acme/blog/default.changeset"
        );
        assert_eq!(
            site_from_libsql_changeset_member("libsql/acme/blog/default.changeset"),
            Some("blog")
        );
        assert_eq!(
            site_from_libsql_changeset_member("libsql/acme/blog/default.sqlite"),
            None
        );
    }

    /// Stage-4 security review Finding 1: the (untrusted) `libsql_capture.json` `snapshot_file` is
    /// CONFINED under the bundle dir before any read/copy — an absolute path, a `..` traversal, a
    /// `.`-bearing path, or an empty string is REFUSED; a plain relative name that exists resolves to
    /// an in-tree absolute path. (A symlink that escapes is rejected by the canonicalize+starts_with
    /// guard — not exercised here as it needs a filesystem fixture; the component/absolute checks are
    /// the load-bearing lexical guard.)
    #[test]
    fn confine_bundle_snapshot_refuses_out_of_tree_paths() {
        let base = tempfile::tempdir().unwrap();
        let cap = base.path().join("libsql_capture");
        std::fs::create_dir_all(&cap).unwrap();
        std::fs::write(cap.join("0.db"), b"x").unwrap();

        // A legit in-tree relative path resolves under base.
        let ok = confine_bundle_snapshot(base.path(), "libsql_capture/0.db").expect("in-tree ok");
        assert!(ok.starts_with(std::fs::canonicalize(base.path()).unwrap()));

        // Every out-of-tree shape is refused BEFORE any read.
        for bad in [
            "/dev/zero",
            "/etc/passwd",
            "../../../etc/passwd",
            "libsql_capture/../../escape",
            "./libsql_capture/0.db", // a leading `.` is a non-Normal component → refused
            "",
        ] {
            assert!(
                confine_bundle_snapshot(base.path(), bad).is_err(),
                "an out-of-tree snapshot path must be refused: {bad:?}"
            );
        }
    }

    #[test]
    fn blob_prefix_is_two_segment_for_every_project() {
        // Post-0.31.0 (Finding 8): EVERY project's blobs live under `hblob/{project}/`,
        // including the reserved default — NOT the pre-fix bare `hblob/` root.
        assert_eq!(blob_project_prefix("acme"), "hblob/acme/");
        assert_eq!(blob_project_prefix("default"), "hblob/default/");
        // The trailing `/` prevents a sibling-project over-capture: `foo`'s prefix is
        // NOT a prefix of `foobar`'s keys.
        assert!(!blob_project_prefix("foobar").starts_with(&blob_project_prefix("foo")));
    }

    #[test]
    fn choose_host_prefers_bridge_only_under_published() {
        // Published + a resolved bridge IP -> the sibling-reachable bridge IP.
        assert_eq!(
            choose_host("127.0.0.1", Some("172.17.0.3"), true),
            "172.17.0.3"
        );
        // Published but no bridge IP -> fall back to the endpoint host.
        assert_eq!(choose_host("127.0.0.1", None, true), "127.0.0.1");
        // Bridge mode / external DSN -> the endpoint host verbatim (ignore any direct).
        assert_eq!(
            choose_host("db.example.com", Some("172.17.0.3"), false),
            "db.example.com"
        );
    }

    #[test]
    fn fingerprint_is_stable_and_order_sensitive() {
        use boatramp_core::sql::SqlRows;
        let a = SqlRows {
            columns: vec!["id".into()],
            rows: vec![
                vec![SqlValue::Text("m1".into()), SqlValue::Integer(1)],
                vec![SqlValue::Text("m2".into()), SqlValue::Integer(2)],
            ],
        };
        let same = SqlRows {
            columns: vec!["id".into()],
            rows: vec![
                vec![SqlValue::Text("m1".into()), SqlValue::Integer(1)],
                vec![SqlValue::Text("m2".into()), SqlValue::Integer(2)],
            ],
        };
        let different = SqlRows {
            columns: vec!["id".into()],
            rows: vec![vec![SqlValue::Text("m1".into()), SqlValue::Integer(1)]],
        };
        assert_eq!(fingerprint_rows(&a), fingerprint_rows(&same));
        assert_ne!(fingerprint_rows(&a), fingerprint_rows(&different));
    }

    // --- T3 Phase 1: resumable member-object layout + per-member resume decision ---------

    #[tokio::test]
    async fn resumable_member_object_write_and_resume_decision() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();

        // Produce member 0 from a staged sidecar temp, then persist its {size,sha256} meta
        // exactly as `export_resumable` does.
        let src = dir.join("staged-src");
        tokio::fs::write(&src, b"hello-member-zero").await.unwrap();
        let meta = write_member_from_file(dir, 0, &src).await.unwrap();
        assert_eq!(meta.size, b"hello-member-zero".len() as u64);
        write_atomic(
            &dir.join(member_meta_name(0)),
            &serde_json::to_vec(&meta).unwrap(),
        )
        .await
        .unwrap();

        let obj0 = dir.join(member_object_name(0));
        let meta0 = dir.join(member_meta_name(0));
        // Complete + SHA-valid → resume SKIPS it.
        assert!(member_object_valid(&obj0, &meta0).await.unwrap());
        // The `.part` was renamed away (no stray partial).
        assert!(!dir.join(member_part_name(0)).exists());

        // A member never produced → not valid (resume must produce it).
        assert!(
            !member_object_valid(
                &dir.join(member_object_name(1)),
                &dir.join(member_meta_name(1))
            )
            .await
            .unwrap()
        );

        // A TRUNCATED/corrupt object → fails its SHA → not valid → resume re-produces it.
        tokio::fs::write(&obj0, b"trunc").await.unwrap();
        assert!(
            !member_object_valid(&obj0, &meta0).await.unwrap(),
            "a truncated object must fail its recorded SHA and be re-produced on resume"
        );
    }

    #[tokio::test]
    async fn resumable_chunked_member_commits_and_poison_fails_loud() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicBool, Ordering::SeqCst};
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();

        // Happy path: a producer that streams two chunks then returns Ok, poison clear.
        let (tx, rx) = tokio::sync::mpsc::channel::<Vec<u8>>(4);
        let poison = Arc::new(AtomicBool::new(false));
        let h = tokio::spawn(async move {
            tx.send(b"ab".to_vec()).await.unwrap();
            tx.send(b"cd".to_vec()).await.unwrap();
            Ok(())
        });
        let meta = write_member_from_producer(dir, 2, (rx, poison, h))
            .await
            .unwrap();
        assert_eq!(meta.size, 4);
        assert!(dir.join(member_object_name(2)).exists());

        // Poison path: a producer that writes a partial body then POISONS → must fail loud,
        // committing NO object (a partial member can never be recorded complete).
        let (tx, rx) = tokio::sync::mpsc::channel::<Vec<u8>>(4);
        let poison = Arc::new(AtomicBool::new(false));
        let p2 = poison.clone();
        let h = tokio::spawn(async move {
            tx.send(b"partial".to_vec()).await.unwrap();
            p2.store(true, SeqCst);
            Ok(())
        });
        let r = write_member_from_producer(dir, 3, (rx, poison, h)).await;
        assert!(
            r.is_err(),
            "a poisoned (incomplete) producer must fail loud"
        );
        assert!(
            !dir.join(member_object_name(3)).exists(),
            "no member object may be committed when the producer poisoned"
        );
    }

    /// The load-bearing security control for the resumable surface: an operator-named dir is
    /// CONFINED under the configured base. No base ⇒ refused (surface disabled); `..` /
    /// absolute ⇒ refused (traversal); a plain name ⇒ resolved under the base.
    #[tokio::test]
    async fn resumable_dir_is_confined_under_the_configured_base() {
        use boatramp_core::Storage;
        use boatramp_core::deploy::DeployStore;
        use boatramp_core::kv::{KvStore, MemoryKv};
        use boatramp_storage::fs::FsStorage;
        use std::collections::BTreeMap;
        use std::sync::Arc;

        let tmp = tempfile::tempdir().unwrap();
        let mk = |base: Option<PathBuf>| {
            let kv: Arc<dyn KvStore> = Arc::new(MemoryKv::new());
            let blobs: Arc<dyn Storage> = Arc::new(FsStorage::new(tmp.path().join("blobs")));
            let deploy = DeployStore::new(blobs.clone(), kv.clone());
            NodeProjectExport::new(BTreeMap::new(), deploy, kv, blobs, tmp.path().join("work"))
                .with_resumable_base(base)
        };

        // No base configured ⇒ the whole surface is refused (fail-closed).
        assert!(
            mk(None).resolve_resumable_dir("ok", true).await.is_err(),
            "no configured base must refuse the resumable surface"
        );

        let base = tmp.path().join("exports");
        let drv = mk(Some(base.clone()));

        // A plain name resolves to a dir UNDER the canonical base.
        let resolved = drv
            .resolve_resumable_dir("snap1", true)
            .await
            .expect("a plain name is confined + created");
        let canon_base = tokio::fs::canonicalize(&base).await.unwrap();
        assert!(
            resolved.starts_with(&canon_base),
            "resolved {resolved:?} must be under the base {canon_base:?}"
        );

        // Traversal, absolute, and `.`-components are all refused (lexical + absolute escape).
        for bad in ["../escape", "a/../../etc", "/etc/passwd", "", "./x"] {
            assert!(
                drv.resolve_resumable_dir(bad, true).await.is_err(),
                "confinement must refuse {bad:?}"
            );
        }
        // A symlink escaping the base is refused (canonicalize + starts_with guard).
        let outside = tmp.path().join("outside");
        tokio::fs::create_dir_all(&outside).await.unwrap();
        tokio::fs::create_dir_all(&canon_base).await.unwrap();
        #[cfg(unix)]
        {
            let link = base.join("sneaky");
            let _ = std::os::unix::fs::symlink(&outside, &link);
            assert!(
                drv.resolve_resumable_dir("sneaky", false).await.is_err(),
                "a symlink escaping the base must be refused"
            );
        }
    }

    // ---------------------------------------------------------------------------------
    // Incremental / delta export — driver-level round trips (in-process; no Docker/SQL).
    // ---------------------------------------------------------------------------------

    /// Build a delta-capable driver (KV + blob backends, a SHARED resumable base so the base
    /// chain is resolvable on the importing node), returning it plus its kv + blob handles.
    #[cfg(test)]
    fn mk_delta_driver(
        tmp: &std::path::Path,
        shared_base: &std::path::Path,
        tag: &str,
    ) -> (
        NodeProjectExport,
        std::sync::Arc<dyn boatramp_core::kv::KvStore>,
        std::sync::Arc<dyn boatramp_core::Storage>,
    ) {
        use boatramp_core::deploy::DeployStore;
        use boatramp_core::kv::{KvStore, MemoryKv};
        use boatramp_storage::fs::FsStorage;
        use std::collections::BTreeMap;
        use std::sync::Arc;
        let kv: Arc<dyn KvStore> = Arc::new(MemoryKv::new());
        let blobs: Arc<dyn boatramp_core::Storage> =
            Arc::new(FsStorage::new(tmp.join(format!("{tag}-blobs"))));
        let deploy = DeployStore::new(blobs.clone(), kv.clone());
        let work = tmp.join(format!("{tag}-work"));
        std::fs::create_dir_all(&work).unwrap();
        let drv = NodeProjectExport::new(BTreeMap::new(), deploy, kv.clone(), blobs.clone(), work)
            .with_resumable_base(Some(shared_base.to_path_buf()));
        (drv, kv, blobs)
    }

    #[cfg(test)]
    async fn seed_blob(store: &dyn boatramp_core::Storage, key: &str, data: &[u8]) {
        use boatramp_core::{ByteStream, PutMeta, StorageError};
        use bytes::Bytes;
        let data = data.to_vec();
        let stream: ByteStream =
            futures::stream::once(async move { Ok::<Bytes, StorageError>(Bytes::from(data)) })
                .boxed();
        store
            .put(key, stream, PutMeta { content_type: None })
            .await
            .expect("seed blob");
    }

    #[cfg(test)]
    async fn read_blob(store: &dyn boatramp_core::Storage, key: &str) -> Option<Vec<u8>> {
        match store.get(key).await {
            Ok(obj) => {
                let mut body = obj.body;
                let mut buf = Vec::new();
                while let Some(chunk) = body.next().await {
                    buf.extend_from_slice(chunk.ok()?.as_ref());
                }
                Some(buf)
            }
            Err(_) => None,
        }
    }

    /// END-TO-END (decisions 3/4/5): a FULL base + a DIFFERENTIAL delta carrying only the KV
    /// upserts/tombstones + the changed/new blobs (+ a blob tombstone), restored onto a FRESH node
    /// = base reconstructed + the drift applied. Proves base-reference resolution, adds-as-full +
    /// deletes-as-tombstones drift, and the sequential shadow apply, all without SQL/Docker.
    #[tokio::test]
    async fn delta_differential_round_trip_kv_and_blobs() {
        use boatramp_core::project_delta::{DeltaMode, DeltaRequest};
        use boatramp_core::project_export::ProjectExport;

        let tmp = tempfile::tempdir().unwrap();
        let shared_base = tmp.path().join("exports");
        let (src, kv_s, blobs_s) = mk_delta_driver(tmp.path(), &shared_base, "src");

        // Seed the source: two KV config keys + two blobs (all project-owned/scoped).
        kv_s.put("project/acme/config/a", b"one".to_vec())
            .await
            .unwrap();
        kv_s.put("project/acme/config/b", b"two".to_vec())
            .await
            .unwrap();
        seed_blob(blobs_s.as_ref(), "hblob/acme/web/x", b"X-v1").await;
        seed_blob(blobs_s.as_ref(), "hblob/acme/web/y", b"Y-v1").await;

        // FULL base export.
        src.export_resumable("acme", &ExportOptions::default(), "base")
            .await
            .expect("full base export");

        // DRIFT: change b, add c, delete a; change x's bytes, add z, delete y.
        kv_s.put("project/acme/config/b", b"TWO".to_vec())
            .await
            .unwrap();
        kv_s.put("project/acme/config/c", b"new".to_vec())
            .await
            .unwrap();
        kv_s.delete("project/acme/config/a").await.unwrap();
        seed_blob(blobs_s.as_ref(), "hblob/acme/web/x", b"X-v2-longer").await;
        seed_blob(blobs_s.as_ref(), "hblob/acme/web/z", b"Z-v1").await;
        blobs_s.delete("hblob/acme/web/y").await.unwrap();

        // DIFFERENTIAL delta against the fixed base.
        let delta_opts = ExportOptions {
            delta: Some(DeltaRequest {
                mode: DeltaMode::Differential,
                base_reference: "base".to_string(),
            }),
            ..Default::default()
        };
        src.export_resumable("acme", &delta_opts, "d1")
            .await
            .expect("differential delta export");

        // Inspect the delta MANIFEST: it is a delta, names the base, and carries ONLY the drift
        // (a KV-delta member, the two changed/new blobs, a blob-tombstone member — NO full KV
        // member, NO member for the unchanged/deleted blobs).
        let d1_dir = src.resolve_resumable_dir("d1", false).await.unwrap();
        let m = src.read_resumable_manifest(&d1_dir).await.unwrap();
        let di = m.delta.as_ref().expect("delta manifest carries DeltaInfo");
        assert_eq!(di.mode, DeltaMode::Differential);
        assert_eq!(di.base_reference, "base");
        assert_eq!(
            di.sql_strategy,
            boatramp_core::project_delta::SqlDeltaKind::FullDumpFallback
        );
        let kinds: Vec<MemberKind> = m.members.iter().map(|s| s.kind).collect();
        assert!(
            kinds.contains(&MemberKind::KvDelta),
            "a delta carries a KV-delta member"
        );
        assert!(
            kinds.contains(&MemberKind::BlobTombstone),
            "a delta with a deleted blob carries a blob-tombstone member"
        );
        assert!(
            !kinds.contains(&MemberKind::Kv),
            "a delta carries NO full KV member"
        );
        let blob_adds: Vec<&str> = m
            .members
            .iter()
            .filter(|s| s.kind == MemberKind::Blob)
            .map(|s| s.path.as_str())
            .collect();
        assert_eq!(
            blob_adds.len(),
            2,
            "exactly the changed (x) + new (z) blobs ship, got {blob_adds:?}"
        );
        assert!(
            blob_adds
                .iter()
                .all(|p| p.contains("/x") || p.contains("/z"))
        );

        // RESTORE onto a FRESH target node (shares the export base so the chain resolves).
        let (tgt, kv_t, blobs_t) = mk_delta_driver(tmp.path(), &shared_base, "tgt");
        let report = tgt
            .import_resumable(
                "acme",
                "d1",
                ImportOptions {
                    apply: true,
                    ..Default::default()
                },
            )
            .await
            .expect("delta chain restore");
        assert!(
            report.notes.iter().any(|n| n.contains("delta restore")),
            "{:?}",
            report.notes
        );

        // Final KV state = base + delta: a DELETED, b CHANGED, c ADDED.
        assert_eq!(
            kv_t.get("project/acme/config/a").await.unwrap(),
            None,
            "a was tombstoned"
        );
        assert_eq!(
            kv_t.get("project/acme/config/b").await.unwrap().as_deref(),
            Some(b"TWO".as_slice())
        );
        assert_eq!(
            kv_t.get("project/acme/config/c").await.unwrap().as_deref(),
            Some(b"new".as_slice())
        );
        // Final blob state: x CHANGED, z ADDED, y DELETED.
        assert_eq!(
            read_blob(blobs_t.as_ref(), "hblob/acme/web/x")
                .await
                .as_deref(),
            Some(b"X-v2-longer".as_slice())
        );
        assert_eq!(
            read_blob(blobs_t.as_ref(), "hblob/acme/web/z")
                .await
                .as_deref(),
            Some(b"Z-v1".as_slice())
        );
        assert_eq!(
            read_blob(blobs_t.as_ref(), "hblob/acme/web/y").await,
            None,
            "y was tombstoned"
        );
    }

    /// INCREMENTAL chain (decision 4): base ← d1 ← d2, each diffed against its parent, restored as
    /// base + replay(d1, d2). Proves chain resolution (walking parent links to the root) and the
    /// cumulative drift of a multi-link chain.
    #[tokio::test]
    async fn delta_incremental_chain_round_trip() {
        use boatramp_core::project_delta::{DeltaMode, DeltaRequest};
        use boatramp_core::project_export::ProjectExport;

        let tmp = tempfile::tempdir().unwrap();
        let shared_base = tmp.path().join("exports");
        let (src, kv_s, blobs_s) = mk_delta_driver(tmp.path(), &shared_base, "src");

        // Base: k1, k2 + blob p.
        kv_s.put("project/acme/config/k1", b"1".to_vec())
            .await
            .unwrap();
        kv_s.put("project/acme/config/k2", b"2".to_vec())
            .await
            .unwrap();
        seed_blob(blobs_s.as_ref(), "hblob/acme/web/p", b"P1").await;
        src.export_resumable("acme", &ExportOptions::default(), "base")
            .await
            .expect("base");

        // d1 (incremental vs base): change k1, add blob q.
        kv_s.put("project/acme/config/k1", b"1b".to_vec())
            .await
            .unwrap();
        seed_blob(blobs_s.as_ref(), "hblob/acme/web/q", b"Q1").await;
        let inc = |base: &str| ExportOptions {
            delta: Some(DeltaRequest {
                mode: DeltaMode::Incremental,
                base_reference: base.to_string(),
            }),
            ..Default::default()
        };
        src.export_resumable("acme", &inc("base"), "d1")
            .await
            .expect("d1");

        // d2 (incremental vs d1): delete k2, delete blob p, add k3.
        kv_s.delete("project/acme/config/k2").await.unwrap();
        kv_s.put("project/acme/config/k3", b"3".to_vec())
            .await
            .unwrap();
        blobs_s.delete("hblob/acme/web/p").await.unwrap();
        src.export_resumable("acme", &inc("d1"), "d2")
            .await
            .expect("d2");

        // d2's manifest chains onto d1 (its parent), proving the incremental linkage.
        let d2_dir = src.resolve_resumable_dir("d2", false).await.unwrap();
        let m2 = src.read_resumable_manifest(&d2_dir).await.unwrap();
        assert_eq!(m2.delta.as_ref().unwrap().base_reference, "d1");
        assert_eq!(m2.delta.as_ref().unwrap().mode, DeltaMode::Incremental);

        // Restore d2 onto a fresh node = base + d1 + d2 replayed.
        let (tgt, kv_t, blobs_t) = mk_delta_driver(tmp.path(), &shared_base, "tgt");
        tgt.import_resumable(
            "acme",
            "d2",
            ImportOptions {
                apply: true,
                ..Default::default()
            },
        )
        .await
        .expect("incremental chain restore");

        // k1 changed (d1), k2 deleted (d2), k3 added (d2); blob p deleted (d2), q present (d1).
        assert_eq!(
            kv_t.get("project/acme/config/k1").await.unwrap().as_deref(),
            Some(b"1b".as_slice())
        );
        assert_eq!(
            kv_t.get("project/acme/config/k2").await.unwrap(),
            None,
            "k2 tombstoned in d2"
        );
        assert_eq!(
            kv_t.get("project/acme/config/k3").await.unwrap().as_deref(),
            Some(b"3".as_slice())
        );
        assert_eq!(
            read_blob(blobs_t.as_ref(), "hblob/acme/web/p").await,
            None,
            "p tombstoned in d2"
        );
        assert_eq!(
            read_blob(blobs_t.as_ref(), "hblob/acme/web/q")
                .await
                .as_deref(),
            Some(b"Q1".as_slice())
        );
    }

    /// SECURITY (chain coherence): a delta is only valid against a base from the SAME source.
    /// A resumable chain lives on an addressable target, so a base exported from a FOREIGN source
    /// could be grafted under a delta. `import_delta_chain` refuses a chain whose links disagree on
    /// `source.project` — without it, `restore_member` would re-key each link from a different
    /// source prefix and restore an incoherent cross-tenant mix. The mutation that drops this
    /// refusal is exactly the foreign-base-graft it guards.
    #[tokio::test]
    async fn delta_import_refuses_a_chain_with_a_foreign_base_source() {
        use boatramp_core::project_delta::{DeltaMode, DeltaRequest};
        use boatramp_core::project_export::ProjectExport;

        let tmp = tempfile::tempdir().unwrap();
        let shared_base = tmp.path().join("exports");
        let (src, kv_s, blobs_s) = mk_delta_driver(tmp.path(), &shared_base, "src");

        // A valid base + one incremental delta, both for project "acme".
        kv_s.put("project/acme/config/k1", b"1".to_vec())
            .await
            .unwrap();
        seed_blob(blobs_s.as_ref(), "hblob/acme/web/p", b"P1").await;
        src.export_resumable("acme", &ExportOptions::default(), "base")
            .await
            .expect("base");
        kv_s.put("project/acme/config/k1", b"1b".to_vec())
            .await
            .unwrap();
        src.export_resumable(
            "acme",
            &ExportOptions {
                delta: Some(DeltaRequest {
                    mode: DeltaMode::Incremental,
                    base_reference: "base".into(),
                }),
                ..Default::default()
            },
            "d1",
        )
        .await
        .expect("d1");

        // Tamper the ROOT base MANIFEST on disk to claim a FOREIGN source project (simulating a
        // base grafted in from another tenant on the shared addressable target).
        let base_dir = src.resolve_resumable_dir("base", false).await.unwrap();
        let mpath = base_dir.join(project_bundle::MANIFEST_PATH);
        let mut m: project_bundle::StreamManifest =
            serde_json::from_slice(&tokio::fs::read(&mpath).await.unwrap()).unwrap();
        m.source.project = "evil".into();
        tokio::fs::write(&mpath, serde_json::to_vec_pretty(&m).unwrap())
            .await
            .unwrap();

        // Importing d1 now resolves a chain [base(evil), d1(acme)] — mismatched sources → refuse,
        // before any member is applied.
        let (tgt, _kv_t, _blobs_t) = mk_delta_driver(tmp.path(), &shared_base, "tgt");
        let err = tgt
            .import_resumable(
                "acme",
                "d1",
                ImportOptions {
                    apply: true,
                    ..Default::default()
                },
            )
            .await
            .expect_err("a foreign-base chain must be refused");
        let msg = format!("{err}");
        assert!(
            msg.contains("must share one source"),
            "expected a one-source coherence refusal, got: {msg}"
        );
    }

    /// SECURITY (the tenancy-critical delta seam): a KV-delta's tombstone keys are
    /// attacker-influenceable; a tombstone that escapes the target's owned scope would be a
    /// CROSS-TENANT delete. The `KvDelta` restore arm REFUSES it fail-closed. The mutation that
    /// drops this refuse is exactly the cross-tenant-delete bug it guards.
    #[tokio::test]
    async fn delta_restore_refuses_a_cross_tenant_kv_tombstone() {
        use boatramp_core::kv::KvDumpEntry;
        use boatramp_core::project_delta::{self as pd, KvDelta};

        let tmp = tempfile::tempdir().unwrap();
        let shared_base = tmp.path().join("exports");
        let (drv, kv, _blobs) = mk_delta_driver(tmp.path(), &shared_base, "t");
        // A victim key another tenant owns — it must survive a hostile delta aimed at it.
        kv.put("project/globex/secret/x", b"victim".to_vec())
            .await
            .unwrap();

        // A hostile delta: a legit target upsert, but a tombstone pointed at the victim's key.
        let hostile = KvDelta {
            upserts: vec![KvDumpEntry {
                key: "project/acme/config/ok".to_string(),
                value: b"v".to_vec(),
                version: 1,
            }],
            tombstones: vec!["project/globex/secret/x".to_string()],
        };
        let temp = tmp.path().join("hostile.brkvdelta");
        tokio::fs::write(&temp, pd::encode_kv_delta(&hostile, 0))
            .await
            .unwrap();

        let spec = project_bundle::MemberSpec::sidecar(
            project_bundle::KV_DELTA_MEMBER_PATH.to_string(),
            MemberKind::KvDelta,
            None,
        );
        let mut report = ImportReport::default();
        let mut saw = false;
        // Import AS "acme": the tombstone re-keys to itself (globex is not acme's source), lands
        // outside acme's owned scope → REFUSED fail-closed.
        let r = drv
            .restore_member(
                "acme",
                false,
                "acme",
                &spec,
                &temp,
                &ImportOptions {
                    apply: true,
                    ..Default::default()
                },
                &mut report,
                &mut saw,
            )
            .await;
        assert!(r.is_err(), "a cross-tenant tombstone must be refused");
        assert!(
            format!("{}", r.unwrap_err()).contains("outside the target project"),
            "the refusal names the cross-tenant scope violation"
        );
        // The victim's key is UNTOUCHED (fail-closed BEFORE any delete).
        assert_eq!(
            kv.get("project/globex/secret/x").await.unwrap().as_deref(),
            Some(b"victim".as_slice()),
            "a refused delta deletes NOTHING"
        );
    }
}