alkblobs 0.2.2

Content-addressed blob storage: multi-hash put/get/verify store with pluggable backends, transport- and protocol-agnostic
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
//! The ops module's shared test support and the e2e test tree (the
//! `ops-e2e-flows` capstone, the wire-level json/fetch/put handler
//! tests, the fleet renewal forms against the live harness server, and
//! the structural no-side-door audit): the harness machinery lives in
//! `harness.rs`; the unit tests ride their subject modules (`tokens.rs`,
//! `fetch.rs`).

#[cfg(feature = "postgres")]
use std::collections::BTreeSet;
use std::sync::Arc;
#[cfg(feature = "postgres")]
use std::time::Duration;

use alkcall::channels::client::ChannelClient;
use alkcall::channels::reassembly::{MpscRecvStream, MpscSendStream};
use alkcall::core::types::{BiStream, BidiStreamSource, Connection, StreamError};
use alkcall::protocol::wire::ResponseEnvelope;
use alkcall::registry::context::{CompositionAuthority, ScopedPeerEnv};
use parking_lot::Mutex;
use serde_json::{json, Value};
use tokio::io::{AsyncReadExt, AsyncWriteExt};

use super::harness::{
    await_call, bare_context, composer_pair, identity_named, ChannelOpenable, OpsHarness,
    OpsHarnessRegistration, TEST_TIMEOUT,
};
#[cfg(feature = "postgres")]
use crate::facade::Pin;
use crate::hashing::Algorithm;
use crate::keys::Key;
use crate::store::Store;
#[cfg(feature = "postgres")]
use crate::Error;

use super::*;

pub(crate) struct RecordingConverter {
    pub(crate) converted: Mutex<Vec<Key>>,
}

impl RecordingConverter {
    pub(crate) fn captured(&self) -> Vec<Key> {
        self.converted.lock().clone()
    }
}

impl PinConverter for RecordingConverter {
    fn convert(&self, key: &Key) {
        self.converted.lock().push(key.clone());
    }
}

pub(crate) fn key_of(seed: &[u8]) -> Key {
    Key::from(Algorithm::GitBlobSha256.derive(seed, seed.len() as u64))
}

/// The wire digest form's hex for a key: the physical key encoding
/// verbatim (tag-prefixed, ADR-020 §Decision 2) — 42 or 66 lowercase
/// hex chars. The put offer's `key` claim and the response's echoed
/// `key` both read this form (ADR-020 §Decision 4).
pub(crate) fn wire_hex_of(key: &Key) -> String {
    hex::encode(key.as_bytes())
}

/// The wire digest form's hex for a seed's canonical blob-sha-256
/// derivation — the wire-key-hex form the test payload sites present.
pub(crate) fn wire_hex_of_seed(seed: &[u8]) -> String {
    wire_hex_of(&key_of(seed))
}

#[cfg(any(feature = "mem", feature = "sqlite"))]
pub(crate) async fn test_store() -> Arc<Store> {
    #[cfg(feature = "mem")]
    let store = Store::mem_only();
    #[cfg(not(feature = "mem"))]
    let store = {
        let path = std::path::PathBuf::from(format!(
            "/tmp/opencode/alkblobs-ops-foundation-{}-{}.db",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos()
        ));
        Store::kv_only_sqlite(path, 1024, std::time::Duration::ZERO)
            .await
            .unwrap()
    };
    Arc::new(store)
}

// ----------------------------------------------------------------
// blobs/fetch (the binary data plane's consumer side): the verified
// Sub op through the channel halves.
// ----------------------------------------------------------------

#[cfg(any(feature = "mem", feature = "sqlite"))]
fn fetch_openable(ctx: Arc<OpsContext>) -> ChannelOpenable {
    let (spec, establisher, open_handler) = fetch_openables(ctx);
    ChannelOpenable::pump(spec, establisher, open_handler)
}

#[cfg(any(feature = "mem", feature = "sqlite"))]
fn put_openable(ctx: Arc<OpsContext>) -> ChannelOpenable {
    let (spec, establisher, pub_handler) = put_openables(ctx);
    ChannelOpenable::put(spec, establisher, pub_handler)
}

#[cfg(any(feature = "mem", feature = "sqlite"))]
async fn open_fetch(
    client: &ChannelClient,
    namespace: &str,
    digest_hex: &str,
    ranges: Option<Value>,
) -> Result<(u32, Value, MpscSendStream, MpscRecvStream), alkcall::channels::client::ChannelOpenError>
{
    let mut input = json!({ "namespace": namespace, "digest": digest_hex });
    if let Some(ranges) = ranges {
        input["ranges"] = ranges;
    }
    tokio::time::timeout(
        TEST_TIMEOUT,
        client.open_channel_with_reply(FETCH_OP_ID, input, BLOBS_CHANNEL_ALPN),
    )
    .await
    .expect("the open resolves")
}

/// The whole-blob verified round-trip (the op's core criterion):
/// the seeded whole streams byte-exact over the channel and the
/// consumer-side hash-check passes against the carried digest; the
/// ack carries the store path's `{source, len}` shape.
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn fetch_serves_the_verified_whole_and_the_consumer_hash_checks() {
    let store = test_store().await;
    let ctx = Arc::new(OpsContext::new(Arc::clone(&store), OpsConfig::default()));
    let harness = OpsHarness::assemble(vec![]);
    harness.with_token("token:alice", identity_named("alice"));
    harness.grant("alice", "ns-1", &["read"]);
    let client = harness
        .spawn_channel_halves(
            vec![fetch_openable(Arc::clone(&ctx))],
            Some(identity_named("alice")),
        )
        .await;

    let seed: &[u8] = b"the fetched whole blob";
    let (key, _pin) = store
        .put_as(
            Algorithm::GitBlobSha256,
            Some(seed.len() as u64),
            std::io::Cursor::new(seed),
        )
        .await
        .expect("seed put lands");
    let digest_hex = wire_hex_of(&key);

    let (channel_id, reply, send, mut recv) = open_fetch(&client, "ns-1", &digest_hex, None)
        .await
        .expect("the fetch channel establishes");
    assert!(channel_id > 0, "a data channel, not channel 0 itself");
    assert_eq!(
        reply,
        json!({ "channel_id": channel_id, "source": "store", "len": seed.len() }),
        "the store path's ack: source + the expected whole's length"
    );

    let mut received = Vec::new();
    tokio::time::timeout(TEST_TIMEOUT, recv.read_to_end(&mut received))
        .await
        .expect("the stream reads")
        .expect("the stream ends");
    assert_eq!(received, seed, "byte-exact");
    assert_eq!(
        Key::from(Algorithm::GitBlobSha256.derive(&received, received.len() as u64)),
        key,
        "the consumer's whole-blob hash-check passes"
    );
    drop(send);
}

/// The ranged form (criterion: the ADR-006 slice-digest convention,
/// out-of-band, over exactly the returned bytes): the ack carries
/// one slice digest per range in request order — read_range's
/// convention verbatim — and the served concatenation is the
/// ranges' slices; an over-read range clamps (its digest covers
/// exactly the clamped bytes).
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn fetch_serves_ranges_and_the_ack_carries_the_slice_digests() {
    let store = test_store().await;
    let ctx = Arc::new(OpsContext::new(Arc::clone(&store), OpsConfig::default()));
    let harness = OpsHarness::assemble(vec![]);
    harness.with_token("token:alice", identity_named("alice"));
    harness.grant("alice", "ns-1", &["read"]);
    let client = harness
        .spawn_channel_halves(
            vec![fetch_openable(Arc::clone(&ctx))],
            Some(identity_named("alice")),
        )
        .await;

    let seed: Vec<u8> = (0u8..64).collect();
    let (key, _pin) = store
        .put_as(
            Algorithm::GitBlobSha256,
            Some(seed.len() as u64),
            std::io::Cursor::new(seed),
        )
        .await
        .expect("seed put lands");
    let digest_hex = wire_hex_of(&key);

    let (slice0, digest0) = store
        .read_range(&key.as_bytes(), 2, 5)
        .await
        .expect("the store's ranged read");
    let (_, digest1) = store
        .read_range(&key.as_bytes(), 1000, 9999)
        .await
        .expect("the store's past-EOF ranged read");

    let (channel_id, reply, send, mut recv) = open_fetch(
        &client,
        "ns-1",
        &digest_hex,
        Some(json!([{ "offset": 2, "len": 5 }, { "offset": 1000, "len": 9999 }])),
    )
    .await
    .expect("the fetch channel establishes");
    assert_eq!(
        reply,
        json!({
            "channel_id": channel_id,
            "source": "store",
            "slice_digests": [hex::encode(digest0), hex::encode(digest1)]
        }),
        "the ack carries read_range's slice digests, one per range, in request order"
    );

    let mut received = Vec::new();
    tokio::time::timeout(TEST_TIMEOUT, recv.read_to_end(&mut received))
        .await
        .expect("the stream reads")
        .expect("the stream ends");
    let mut expected = slice0;
    expected.extend(
        store
            .read_range(&key.as_bytes(), 1000, 9999)
            .await
            .expect("re-read")
            .0,
    );
    assert_eq!(received, expected, "the concatenation of the served slices");
    drop(send);
}

/// The ranged form's bounds (review-001 S-2), at their gates: an
/// over-count open is the registry's schema `INVALID_INPUT` (the
/// `maxItems` rides the context's `fetch_max_ranges` knob — the small
/// custom config here proves the knob, not a constant, is the home);
/// an over-bytes open — the ingress sums the **requested** lens, the
/// schema cannot — is the establishment `HandlerError` refusal
/// (`channel:open_failed`, the stable domain text), across one item,
/// summed items, and the checked-add overflow arm. A request at the
/// exact byte bound still establishes and byte-verifies end to end.
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn fetch_over_count_rejects_at_the_schema_and_over_bytes_at_the_ingress() {
    let store = test_store().await;
    let config = OpsConfig {
        fetch_max_ranges: 3,
        fetch_max_total_bytes: 16,
        ..OpsConfig::default()
    };
    let ctx = Arc::new(OpsContext::new(Arc::clone(&store), config));
    let harness = OpsHarness::assemble(vec![]);
    harness.with_token("token:alice", identity_named("alice"));
    harness.grant("alice", "ns-1", &["read"]);
    let client = harness
        .spawn_channel_halves(
            vec![fetch_openable(Arc::clone(&ctx))],
            Some(identity_named("alice")),
        )
        .await;

    let (digest_hex, key) = seeded_entry(&store, b"bounded ranged fetch").await;

    let over_count = open_denied(
        &client,
        FETCH_OP_ID,
        json!({
            "namespace": "ns-1",
            "digest": digest_hex.clone(),
            "ranges": [
                { "offset": 0, "len": 1 },
                { "offset": 1, "len": 1 },
                { "offset": 2, "len": 1 },
                { "offset": 3, "len": 1 }
            ]
        }),
    )
    .await;
    assert_eq!(
        error_code(&over_count),
        Some("INVALID_INPUT"),
        "the schema's maxItems (the context's fetch_max_ranges) rejects the over-count \
         open before any handler: {over_count:?}"
    );

    let single_over_bytes = open_denied(
        &client,
        FETCH_OP_ID,
        json!({
            "namespace": "ns-1",
            "digest": digest_hex.clone(),
            "ranges": [{ "offset": 0, "len": 17 }]
        }),
    )
    .await;
    match single_over_bytes.result {
        Err(error) => {
            assert_eq!(error.code, "channel:open_failed", "{error:?}");
            assert!(
                error.message.contains("exceeds the total-bytes bound"),
                "the stable domain text names the bound's shape: {error:?}"
            );
        }
        Ok(_) => panic!("an over-bytes ranged open established: {single_over_bytes:?}"),
    }

    let summed_over_bytes = open_denied(
        &client,
        FETCH_OP_ID,
        json!({
            "namespace": "ns-1",
            "digest": digest_hex.clone(),
            "ranges": [
                { "offset": 0, "len": 6 },
                { "offset": 0, "len": 6 },
                { "offset": 0, "len": 6 }
            ]
        }),
    )
    .await;
    match summed_over_bytes.result {
        Err(error) => {
            assert_eq!(error.code, "channel:open_failed", "{error:?}");
            assert!(
                error.message.contains("exceeds the total-bytes bound"),
                "the schema cannot sum — the ingress does: {error:?}"
            );
        }
        Ok(_) => panic!("summed over-bytes ranged open established: {summed_over_bytes:?}"),
    }

    let overflow_arm = open_denied(
        &client,
        FETCH_OP_ID,
        json!({
            "namespace": "ns-1",
            "digest": digest_hex.clone(),
            "ranges": [
                { "offset": 0, "len": u64::MAX },
                { "offset": 0, "len": u64::MAX }
            ]
        }),
    )
    .await;
    match overflow_arm.result {
        Err(error) => {
            assert_eq!(error.code, "channel:open_failed", "{error:?}");
            assert!(
                error.message.contains("exceeds the total-bytes bound"),
                "the checked-add overflow arm is the same refusal: {error:?}"
            );
        }
        Ok(_) => panic!("an overflow-summed ranged open established: {overflow_arm:?}"),
    }

    // The bound is inclusive: lens summing exactly to the byte bound
    // establishes, and the served concatenation byte-verifies against
    // the store's own ranged reads (the ack digests ride as before).
    let (slice0, digest0) = store
        .read_range(&key.as_bytes(), 0, 8)
        .await
        .expect("the first ranged read");
    let (slice1, digest1) = store
        .read_range(&key.as_bytes(), 8, 8)
        .await
        .expect("the second ranged read");
    let (channel_id, reply, send, mut recv) = open_fetch(
        &client,
        "ns-1",
        &digest_hex,
        Some(json!([{ "offset": 0, "len": 8 }, { "offset": 8, "len": 8 }])),
    )
    .await
    .expect("the bound-exact ranged open establishes");
    assert_eq!(
        reply,
        json!({
            "channel_id": channel_id,
            "source": "store",
            "slice_digests": [hex::encode(digest0), hex::encode(digest1)]
        }),
        "the ack contract is unchanged (the slice digests ride the reply)"
    );
    let mut received = Vec::new();
    tokio::time::timeout(TEST_TIMEOUT, recv.read_to_end(&mut received))
        .await
        .expect("the stream reads")
        .expect("the stream ends");
    let mut expected = slice0;
    expected.extend(slice1);
    assert_eq!(
        received, expected,
        "the bounded ranged request byte-verifies end to end"
    );
    drop(send);
}

/// The fanout seam's consumer side, live-broadcast arm (criterion:
/// a live broadcast tapped — the subscriber receives while the
/// producer runs): the entry never committed, so only the tap could
/// have served; the ack names the path (`source: "fanout"`).
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn fetch_taps_a_live_broadcast_and_serves_while_the_producer_runs() {
    let store = test_store().await;
    let ctx = Arc::new(OpsContext::new(Arc::clone(&store), OpsConfig::default()));
    let harness = OpsHarness::assemble(vec![]);
    harness.with_token("token:alice", identity_named("alice"));
    harness.grant("alice", "ns-1", &["read"]);
    let client = harness
        .spawn_channel_halves(
            vec![fetch_openable(Arc::clone(&ctx))],
            Some(identity_named("alice")),
        )
        .await;

    let seed: Vec<u8> = (0u8..16).collect();
    let key = Key::from(Algorithm::GitBlobSha256.derive(&seed, seed.len() as u64));
    let digest_hex = wire_hex_of(&key);
    let publisher = ctx
        .fanout()
        .begin(&key, SlowSubscriberPolicy::Stall)
        .expect("the broadcast begins");

    let (channel_id, reply, send, mut recv) = open_fetch(&client, "ns-1", &digest_hex, None)
        .await
        .expect("the fetch channel establishes");
    assert_eq!(
        reply,
        json!({ "channel_id": channel_id, "source": "fanout" }),
        "the tapped arm's ack: no length (a live put's tail), the path named"
    );
    assert!(
        !store.has(&key.as_bytes()).await.unwrap(),
        "no commit landed: only the tap could have served"
    );

    publisher.broadcast(Arc::new(seed[..8].to_vec())).await;
    let mut first = vec![0u8; 8];
    tokio::time::timeout(TEST_TIMEOUT, recv.read_exact(&mut first))
        .await
        .expect("the chunk reads")
        .expect("the chunk reads");
    publisher.broadcast(Arc::new(seed[8..].to_vec())).await;
    let mut second = vec![0u8; 8];
    tokio::time::timeout(TEST_TIMEOUT, recv.read_exact(&mut second))
        .await
        .expect("the chunk reads")
        .expect("the chunk reads");
    assert_eq!([first, second].concat(), seed, "the tapped feed, in order");

    publisher.finish();
    let mut rest = Vec::new();
    tokio::time::timeout(TEST_TIMEOUT, recv.read_to_end(&mut rest))
        .await
        .expect("the stream drains")
        .expect("the stream ends");
    assert!(rest.is_empty(), "the broadcast end closes the stream");
    drop(send);
}

/// The late joiner (criterion: a broadcast that ended degrades to
/// the post-commit verified `get` — asserted by which path served):
/// the broadcast begun and ended, the entry committed, the fetch
/// answers from the store path and byte-exact.
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn fetch_late_joiner_after_the_broadcast_end_serves_the_store_path() {
    let store = test_store().await;
    let ctx = Arc::new(OpsContext::new(Arc::clone(&store), OpsConfig::default()));
    let harness = OpsHarness::assemble(vec![]);
    harness.with_token("token:alice", identity_named("alice"));
    harness.grant("alice", "ns-1", &["read"]);
    let client = harness
        .spawn_channel_halves(
            vec![fetch_openable(Arc::clone(&ctx))],
            Some(identity_named("alice")),
        )
        .await;

    let seed: &[u8] = b"the late joiner's bytes";
    let (key, _pin) = store
        .put_as(
            Algorithm::GitBlobSha256,
            Some(seed.len() as u64),
            std::io::Cursor::new(seed),
        )
        .await
        .expect("seed put lands");
    let digest_key = key.clone();

    let publisher = ctx
        .fanout()
        .begin(&digest_key, SlowSubscriberPolicy::Drop)
        .expect("the broadcast begins");
    publisher.broadcast(Arc::new(b"stale feed".to_vec())).await;
    publisher.finish();

    let digest_hex = wire_hex_of(&key);
    let (channel_id, reply, send, mut recv) = open_fetch(&client, "ns-1", &digest_hex, None)
        .await
        .expect("the fetch channel establishes");
    assert_eq!(
        reply,
        json!({ "channel_id": channel_id, "source": "store", "len": seed.len() }),
        "the ended broadcast's late joiner is the store path"
    );

    let mut received = Vec::new();
    tokio::time::timeout(TEST_TIMEOUT, recv.read_to_end(&mut received))
        .await
        .expect("the stream reads")
        .expect("the stream ends");
    assert_eq!(received, seed, "identical bytes under CAS");
    drop(send);
}

/// The miss (criterion: the typed missing-error schema; the have/
/// need diff stays caller-side): an absent digest with no live
/// broadcast refuses establishment — `channel:open_failed` with
/// reason `unknown_resource`, the digest in the refusal's message,
/// the declared [`BLOB_MISSING`] contract on the spec.
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn fetch_miss_refuses_establishment_with_the_typed_missing_shape() {
    let store = test_store().await;
    let ctx = Arc::new(OpsContext::new(Arc::clone(&store), OpsConfig::default()));
    let (spec, _establisher, _pump) = fetch_openables(Arc::clone(&ctx));
    assert!(
        spec.error_schemas
            .iter()
            .any(|error| error.code == BLOB_MISSING),
        "the declared missing-error contract is disclosed on the spec"
    );
    let harness = OpsHarness::assemble(vec![]);
    harness.with_token("token:alice", identity_named("alice"));
    harness.grant("alice", "ns-1", &["read"]);
    let client = harness
        .spawn_channel_halves(
            vec![fetch_openable(Arc::clone(&ctx))],
            Some(identity_named("alice")),
        )
        .await;

    let absent = wire_hex_of(&key_of(b"never landed"));
    let refused = open_fetch(&client, "ns-1", &absent, None).await;
    match refused {
        Err(error) => {
            let call_error = error.call_error().expect("the wire error");
            assert_eq!(call_error.code, "channel:open_failed");
            assert_eq!(
                error.establishment_reason(),
                Some("unknown_resource"),
                "ADR-049's typed vocabulary for the absent resource"
            );
            assert!(
                call_error.message.contains(&absent),
                "the refusal carries the digest: {}",
                call_error.message
            );
        }
        Ok(_) => panic!("the absent digest refused, got a channel"),
    }
}

/// The read gate (criterion: closed-by-default, no read grant on
/// the namespace → denied): the ACL verdict is alkcall's, evaluated
/// at op entry ahead of the establishment phase.
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn fetch_denies_the_ungranted_namespace_closed_by_default() {
    let store = test_store().await;
    let ctx = Arc::new(OpsContext::new(Arc::clone(&store), OpsConfig::default()));
    let harness = OpsHarness::assemble(vec![]);
    harness.with_token("token:stranger", identity_named("stranger"));
    let client = harness
        .spawn_channel_halves(
            vec![fetch_openable(Arc::clone(&ctx))],
            Some(identity_named("stranger")),
        )
        .await;

    let (digest_hex, _) = seeded_entry(&store, b"denied fetch").await;
    let denied = tokio::time::timeout(
        TEST_TIMEOUT,
        client.call_open_op(
            FETCH_OP_ID,
            json!({ "namespace": "ns-unlisted", "digest": digest_hex }),
        ),
    )
    .await
    .expect("the denied open resolves");
    assert_eq!(
        error_code(&denied),
        Some("FORBIDDEN"),
        "closed-by-default: a grant per namespace is the deferred cost"
    );
}

// ----------------------------------------------------------------
// blobs/put (the binary data plane's producer side): the verified
// Sink op through the channel halves — offer/stream/commit, the
// pin hand-over's custody split, and the fanout's producer side.
// ----------------------------------------------------------------

#[cfg(any(feature = "mem", feature = "sqlite"))]
async fn open_put(
    client: &ChannelClient,
    input: Value,
) -> (
    u32,
    MpscSendStream,
    MpscRecvStream,
    alkcall::channels::client::PubOpenReply,
) {
    tokio::time::timeout(
        TEST_TIMEOUT,
        client.open_pub_channel(PUT_OP_ID, input, BLOBS_CHANNEL_ALPN),
    )
    .await
    .expect("the put's open resolves")
    .expect("the put channel opened")
}

/// A store-backed serving session: the context over `store`, the
/// harness carrying `blobs/have` beside it, alice's identity with
/// read+write on `ns-1`, and the channel client serving the put
/// openable. The put tests' common assembly.
#[cfg(any(feature = "mem", feature = "sqlite"))]
async fn put_serving_with(
    store: &Arc<Store>,
    config: OpsConfig,
) -> (Arc<OpsContext>, OpsHarness, ChannelClient) {
    let ctx = Arc::new(OpsContext::new(Arc::clone(store), config));
    let harness = OpsHarness::assemble(vec![have_pair(Arc::clone(&ctx))]);
    harness.with_token("token:alice", identity_named("alice"));
    harness.grant("alice", "ns-1", &["read", "write"]);
    let client = harness
        .spawn_channel_halves(
            vec![put_openable(Arc::clone(&ctx))],
            Some(identity_named("alice")),
        )
        .await;
    (ctx, harness, client)
}

#[cfg(any(feature = "mem", feature = "sqlite"))]
async fn put_serving(store: &Arc<Store>) -> (Arc<OpsContext>, OpsHarness, ChannelClient) {
    put_serving_with(store, OpsConfig::default()).await
}

/// The mandatory-claim round trip (the op's core criterion): the
/// offer ack rides the merged response, the response's `key` echo
/// matches the offered key's wire hex (the byte-exact standard — also
/// the key the store committed under), the stored content is
/// byte-exact, and the minted token renews through
/// have's renewal form — the cross-task contract.
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn put_known_length_round_trips_the_response_and_renews_via_have() {
    let store = test_store().await;
    let (ctx, harness, client) = put_serving(&store).await;

    let seed: &[u8] = b"the known-length put's bytes";
    let key = Key::from(Algorithm::GitBlobSha256.derive(seed, seed.len() as u64));
    // The offer's claim and the have probe ride the wire-key-hex form
    // (ADR-020 §Decision 2); the response echoes the key in the same
    // form (ADR-020 §Decision 4).
    let wire_hex = wire_hex_of(&key);

    let (channel_id, mut send, recv, reply) = open_put(
        &client,
        json!({ "namespace": "ns-1", "key": wire_hex.clone(), "len": seed.len() }),
    )
    .await;
    assert!(channel_id > 0, "a data channel, not channel 0 itself");
    send.write_all(seed).await.expect("the bytes stream");
    drop(send);
    drop(recv);

    let out = tokio::time::timeout(TEST_TIMEOUT, reply.resolve())
        .await
        .expect("the put resolves")
        .expect("the put succeeds");
    let token_hex = out["token"].as_str().expect("the token field").to_owned();
    assert_eq!(
        out,
        json!({
            "channel_id": channel_id,
            "accepted": true,
            "token": token_hex,
            "key": wire_hex,
        }),
        "both response fields always present (ADR-020 §Decision 4); the ack merges beside them"
    );

    assert!(
        store.has(&key.as_bytes()).await.expect("the has probe"),
        "the store committed under the git derivation"
    );
    let (stored_len, stored_blob) = store
        .get(&key.as_bytes())
        .await
        .expect("the read")
        .expect("present");
    assert_eq!(stored_len, seed.len() as u64);
    let mut stored = Vec::new();
    let mut pos = 0u64;
    while pos < stored_len {
        let (slice, _) = stored_blob.read_range(pos, 4096).await.expect("the window");
        stored.extend_from_slice(&slice);
        pos += slice.len() as u64;
    }
    assert_eq!(stored, seed, "byte-exact");

    // The hand-over's non-fleet custody (ADR-010 §4, ADR-012 §2):
    // the registry holds the put's guard — nothing expires.
    let token = PinToken::from_hex(&token_hex).expect("a hex token");
    assert!(ctx.tokens().holds(&token), "the registry took custody");
    assert_eq!(
        store.gc().pin_count(&key),
        1,
        "the registry's guard refcounts the entry"
    );

    // The cross-task contract: the minted token renews via have's
    // renewal form (the call halves serve the JSON plane).
    let call_client = harness.spawn_call_halves();
    let renewed = await_call(call_client.call_with_payload(call_payload(
        "blobs/have",
        json!({ "namespace": "ns-1", "digests": [wire_hex], "token": token_hex }),
        Some("token:alice"),
    )))
    .await;
    assert_eq!(
        renewed.result.expect("the renewal probe"),
        json!({ "present": [true] }),
        "the put-minted token renews"
    );
}

/// The verification-failure shape (criterion: typed error, zero
/// residue on both tiers): a known-length offer whose stream dies
/// short — the large tier's staged form is exercised (the declared
/// length is over the threshold) — the store core rejects
/// `Verification`, the stage file is discarded, and no entry exists
/// on either tier. The offer's claimed key is the claimed-length
/// derivation the tee's pre-EOF cross-check confirms (the content
/// hashes under the claimed preamble), so the VERIFICATION_REFUSED
/// is the facade's own length verdict.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn put_verification_failure_leaves_zero_residue_on_both_tiers() {
    let unique = format!(
        "alkblobs-ops-put-residue-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos()
    );
    let db = std::path::PathBuf::from(format!("/tmp/opencode/{unique}.db"));
    let root = std::path::PathBuf::from(format!("/tmp/opencode/{unique}"));
    let store = Arc::new(
        Store::dual_tier_sqlite_local(db, &root, 1024, std::time::Duration::ZERO)
            .await
            .expect("the dual-tier store constructs"),
    );
    let (_ctx, _harness, client) = put_serving(&store).await;

    let seed: Vec<u8> = (0u8..64).collect();
    let short: &[u8] = &seed[..32];
    // The claimed-length derivation of the short content: the tee's
    // cross-check confirms it, the facade's length verdict (32 < 1024)
    // is what rejects.
    let claimed_key = Key::from(Algorithm::GitBlobSha256.derive(short, 1024));
    let claimed_hex = wire_hex_of(&claimed_key);

    let (_channel_id, mut send, recv, reply) = open_put(
        &client,
        json!({ "namespace": "ns-1", "key": claimed_hex, "len": 1024 }),
    )
    .await;
    send.write_all(short).await.expect("the prefix streams");
    drop(send);
    drop(recv);

    let failed_open = tokio::time::timeout(TEST_TIMEOUT, reply.resolve())
        .await
        .expect("the put resolves")
        .expect_err("a short stream against a known-length offer rejects");
    let failed = failed_open.call_error().expect("the wire error");
    assert_eq!(
        failed.code, VERIFICATION_REFUSED,
        "the offered key's derivation's verification is the typed rejection: {failed:?}"
    );
    let putter_key = claimed_key;
    assert!(
        !store
            .has(&putter_key.as_bytes())
            .await
            .expect("the has probe"),
        "the derived entry never committed"
    );
    let staging = root.join("staging");
    let stage_files = match std::fs::read_dir(&staging) {
        Ok(entries) => entries.count(),
        Err(_not_found) => 0,
    };
    assert_eq!(stage_files, 0, "zero residue on the large tier's staging");
}

/// The offered-claim mismatch (criterion: rejects before commit —
/// the pre-EOF check, the one claim-check moment for every family):
/// the offer carries a key claim the honest stream's derivation under
/// the key's own algorithm contradicts; the response is the typed
/// mismatch (details name the claim and the derived key hex, both the
/// wire form) and neither the claimed key nor the honest content's
/// derived key ever committed.
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn put_known_length_offer_digest_mismatch_rejects_before_commit() {
    let store = test_store().await;
    let (_ctx, _harness, client) = put_serving(&store).await;

    let seed: &[u8] = b"the honest stream's bytes";
    let honest_key = Key::from(Algorithm::GitBlobSha256.derive(seed, seed.len() as u64));
    let claimed_key = Key::from(Algorithm::GitBlobSha256.derive(b"unrelated claim", 16));
    // The details' `derived` echo and the has-probes below read the
    // wire key hex (the tag-prefixed form both details halves carry
    // now).
    let honest_hex = wire_hex_of(&honest_key);
    let claimed_hex = wire_hex_of(&claimed_key);

    let (_channel_id, mut send, recv, reply) = open_put(
        &client,
        json!({ "namespace": "ns-1", "key": claimed_hex, "len": seed.len() }),
    )
    .await;
    send.write_all(seed).await.expect("the bytes stream");
    drop(send);
    drop(recv);

    let rejected_open = tokio::time::timeout(TEST_TIMEOUT, reply.resolve())
        .await
        .expect("the put resolves")
        .expect_err("the mismatched claim rejects");
    let rejected = rejected_open.call_error().expect("the wire error");
    assert_eq!(
        rejected.code, DIGEST_MISMATCH,
        "the offered key is a claim; the derivation under its algorithm is the \
         authority: {rejected:?}"
    );
    assert_eq!(
        rejected
            .details
            .as_ref()
            .and_then(|d| d.get("derived"))
            .and_then(|v| v.as_str()),
        Some(honest_hex.as_str()),
        "the details name the derivation that contradicted the claim"
    );
    for never_committed in [&claimed_key, &honest_key] {
        assert!(
            !store
                .has(&never_committed.as_bytes())
                .await
                .expect("the has probe"),
            "the rejection preceded the facade's commit: {never_committed:?}"
        );
    }
}

/// The custody split's completion (the non-fleet side: the token is
/// the in-process guard's handle): the minted token's embedded
/// confirm converts through the ordered-step primitive — the held
/// guard's release and the converter's registration.
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn put_token_custody_converts_at_the_confirmation() {
    let store = test_store().await;
    let (ctx, _harness, client) = put_serving(&store).await;
    let converted = Arc::new(super::tests::RecordingConverter {
        converted: Mutex::new(Vec::new()),
    });
    ctx.bind_converter("ns-1", converted);
    let seed: &[u8] = b"the custodial put's bytes";
    let key = Key::from(Algorithm::GitBlobSha256.derive(seed, seed.len() as u64));
    let wire_hex = wire_hex_of(&key);

    let (_channel_id, mut send, recv, reply) = open_put(
        &client,
        json!({ "namespace": "ns-1", "key": wire_hex, "len": seed.len() }),
    )
    .await;
    send.write_all(seed).await.expect("the bytes stream");
    drop(send);
    drop(recv);
    let out = tokio::time::timeout(TEST_TIMEOUT, reply.resolve())
        .await
        .expect("the put resolves")
        .expect("the put succeeds");
    let token = PinToken::from_hex(out["token"].as_str().expect("the token")).expect("hex");
    // The response's echoed key (ADR-020 §Decision 4) rides the wire
    // key hex — the same form the offer presented.
    let put_key = out["key"].as_str().expect("the key field").to_owned();
    assert_eq!(
        put_key,
        wire_hex_of(&key),
        "the response echo is the offered key's wire hex"
    );

    assert_eq!(
        store.gc().pin_count(&key),
        1,
        "the registry holds the guard"
    );
    assert!(
        ctx.confirm("ns-1", &token),
        "the embedded converter's registration consumes the held guard"
    );
    assert_eq!(
        store.gc().pin_count(&key),
        0,
        "the conversion released the held guard"
    );
    assert!(
        !ctx.tokens().holds(&token),
        "conversion-confirmed retires the mapping"
    );
}

/// The dedup re-put: a CAS dedup lands no new entry — the re-put's
/// response is `{token, key}` again (the same echoed key), the
/// custodial custody re-mints (fresh guards refcounting the same
/// entry), and every re-put's token renews; the re-put's offered key
/// (the putter re-offering the known one) passes the
/// cross-check by construction.
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn put_dedup_re_put_re_mints_custody_and_both_tokens_renew() {
    let store = test_store().await;
    let (ctx, harness, client) = put_serving(&store).await;
    let seed: &[u8] = b"the re-put's identical bytes";
    let key = Key::from(Algorithm::GitBlobSha256.derive(seed, seed.len() as u64));
    // The offer's re-put claim and the response's echoed `key` ride
    // the wire key hex (ADR-020 §Decision 2/§Decision 4).
    let wire_hex = wire_hex_of(&key);

    let mut tokens = Vec::new();
    for round in 0..3 {
        let offer = json!({ "namespace": "ns-1", "key": wire_hex.clone(), "len": seed.len() });
        let (_channel_id, mut send, recv, reply) = open_put(&client, offer).await;
        send.write_all(seed).await.expect("the bytes stream");
        drop(send);
        drop(recv);
        let out = tokio::time::timeout(TEST_TIMEOUT, reply.resolve())
            .await
            .expect("the re-put resolves")
            .expect("the re-put succeeds");
        assert_eq!(
            out["key"],
            json!(wire_hex),
            "CAS dedup: the same echoed key answers (round {round})"
        );
        let token = PinToken::from_hex(out["token"].as_str().expect("the token")).expect("hex");
        tokens.push(token);
        assert!(
            store
                .stat(&key.as_bytes())
                .await
                .expect("the stat probe")
                .is_some(),
            "the entry exists (round {round})"
        );
    }
    assert_eq!(
        store.gc().pin_count(&key),
        3,
        "each re-put's custody re-mint refcounts the same entry"
    );
    for token in &tokens {
        assert!(
            ctx.tokens().holds(token),
            "each re-put minted its own custody"
        );
    }

    // The renewals answer present (the renewal form rides the
    // minted tokens; ADR-012 §2).
    let call_client = harness.spawn_call_halves();
    for token in &tokens {
        let renewed = await_call(call_client.call_with_payload(call_payload(
            "blobs/have",
            json!({ "namespace": "ns-1", "digests": [wire_hex.clone()], "token": token.to_hex() }),
            Some("token:alice"),
        )))
        .await;
        assert_eq!(
            renewed.result.expect("the renewal probe"),
            json!({ "present": [true] }),
            "the re-put renews the pin's custody form"
        );
    }
}

/// The admission refusal at the wire (ADR-019, the POC-L shape
/// reproduced against a mem store's serving path): with the registry
/// at its cap, the put's stream commits and verifies — and the
/// response is the declared `MINT_REFUSED` error over the
/// **committed** put, the committed key hex in the details (the
/// details field follows the offer's `key` naming), no token issued,
/// no custody taken. Once headroom exists the CAS-idempotent re-put
/// answers `{token, key}` again.
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn put_mint_refused_at_the_registry_cap_answers_committed_with_no_token() {
    let store = test_store().await;
    let config = OpsConfig {
        token_registry_max_entries: 1,
        ..OpsConfig::default()
    };
    let (ctx, _harness, client) = put_serving_with(&store, config).await;
    let converted = Arc::new(RecordingConverter {
        converted: Mutex::new(Vec::new()),
    });
    ctx.bind_converter("ns-1", converted);

    // The loop's prior iteration: a minted, never-confirmed token
    // fills the one-entry registry.
    let loop_key = key_of(b"prior-loop-iteration");
    let pin = store.gc().acquire(&loop_key).await;
    let loop_token = ctx
        .mint_custodial("ns-1", loop_key, pin)
        .expect("the pre-cap mint");
    assert_eq!(ctx.tokens().len(), 1);

    let seed: &[u8] = b"the capped loop's conforming bytes";
    let key = Key::from(Algorithm::GitBlobSha256.derive(seed, seed.len() as u64));
    let wire_hex = wire_hex_of(&key);

    let (_channel_id, mut send, recv, reply) = open_put(
        &client,
        json!({ "namespace": "ns-1", "key": wire_hex.clone(), "len": seed.len() }),
    )
    .await;
    send.write_all(seed).await.expect("the bytes stream");
    drop(send);
    drop(recv);
    let refused = tokio::time::timeout(TEST_TIMEOUT, reply.resolve())
        .await
        .expect("the put resolves")
        .expect_err("the hand-over's mint refuses at the cap");
    let error = refused.call_error().expect("the wire error");
    assert_eq!(
        error.code, MINT_REFUSED,
        "the declared admission refusal: {error:?}"
    );
    assert_eq!(
        error
            .details
            .as_ref()
            .and_then(|d| d.get("key"))
            .and_then(Value::as_str),
        Some(wire_hex.as_str()),
        "the committed key hex rides the refusal (the putter's re-put anchor)"
    );

    // The honest answer's substance: the put committed; no custody
    // was taken; the refusal inserted nothing.
    assert!(
        store.has(&key.as_bytes()).await.expect("the has probe"),
        "the stream committed and verified on this node"
    );
    assert_eq!(
        store.gc().pin_count(&key),
        0,
        "no custody taken — the entry stands unreferenced, sweep eligible"
    );
    assert_eq!(
        ctx.tokens().len(),
        1,
        "the refusal inserted nothing (only the pre-cap mint is registered)"
    );

    // The recovery: headroom restored, the re-put (CAS-idempotent
    // over the committed content) answers {token, key} again.
    assert!(
        ctx.confirm("ns-1", &loop_token),
        "the embedder's confirm retires the loop's entry and frees the headroom"
    );
    let (_channel_id, mut send, recv, reply) = open_put(
        &client,
        json!({ "namespace": "ns-1", "key": wire_hex.clone(), "len": seed.len() }),
    )
    .await;
    send.write_all(seed).await.expect("the bytes stream");
    drop(send);
    drop(recv);
    let re_put = tokio::time::timeout(TEST_TIMEOUT, reply.resolve())
        .await
        .expect("the re-put resolves")
        .expect("the re-put succeeds");
    assert_eq!(re_put["key"], json!(wire_hex), "CAS: the same echoed key");
    assert!(
        re_put["token"].as_str().is_some(),
        "a token answered this time"
    );
}

/// The ACL gate (criterion: closed-by-default, no write grant →
/// denied at op entry, ahead of the establishment phase).
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn put_denies_the_ungranted_namespace_closed_by_default() {
    let store = test_store().await;
    let ctx = Arc::new(OpsContext::new(Arc::clone(&store), OpsConfig::default()));
    let harness = OpsHarness::assemble(vec![]);
    harness.with_token("token:stranger", identity_named("stranger"));
    let client = harness
        .spawn_channel_halves(
            vec![put_openable(Arc::clone(&ctx))],
            Some(identity_named("stranger")),
        )
        .await;

    let denied = tokio::time::timeout(
        TEST_TIMEOUT,
        client.call_open_op(PUT_OP_ID, json!({ "namespace": "ns-unlisted", "key": wire_hex_of_seed(b"the denied offer"), "len": 4 })),
    )
    .await
    .expect("the denied open resolves");
    assert_eq!(
        error_code(&denied),
        Some("FORBIDDEN"),
        "closed-by-default: the write action needs its grant"
    );
}

/// The fanout seam's producer side, live (criterion:
/// serve-while-persisting — a fetch tapping the put's broadcast
/// serves while the put runs): the ack names the tapped path, the
/// feed is a contiguous nonempty suffix of the put's bytes (the tap
/// has no prefix — the A3 shape; the consumer's hash-check on a
/// partial feed is the degrade contract), and the put still
/// resolves `{token, key}` with the commit landed.
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn fetch_taps_the_put_stream_and_serves_while_the_persisting_lands() {
    let store = test_store().await;
    let ctx = Arc::new(OpsContext::new(Arc::clone(&store), OpsConfig::default()));
    let harness = OpsHarness::assemble(vec![]);
    harness.with_token("token:alice", identity_named("alice"));
    harness.grant("alice", "ns-1", &["read", "write"]);
    let client = harness
        .spawn_channel_halves(
            vec![
                put_openable(Arc::clone(&ctx)),
                fetch_openable(Arc::clone(&ctx)),
            ],
            Some(identity_named("alice")),
        )
        .await;

    let seed: Vec<u8> = (0u16..512).map(|i| (i % 251) as u8).collect::<Vec<u8>>();
    let key = Key::from(Algorithm::GitBlobSha256.derive(&seed, seed.len() as u64));
    let wire_hex = wire_hex_of(&key);

    // The putter streams its first bytes and holds: the put's
    // stream reader begins the broadcast (the offered key keys
    // it); the commit cannot land (the stream is still open).
    let (channel_id, mut send, _recv, reply) = open_put(
        &client,
        json!({ "namespace": "ns-1", "key": wire_hex.clone(), "len": seed.len() }),
    )
    .await;
    send.write_all(&seed[..256])
        .await
        .expect("the putter's first bytes stream");

    // The fetch taps the live broadcast. The put's open resolves
    // before its handler runs (the putter streams immediately), so
    // the first establish may race the broadcast's begin — a miss
    // answers unknown_resource (the entry is absent too) and the
    // bounded retry waits for the broadcast the put started; the
    // store path answering instead would mean the put already
    // committed (it cannot: the stream is still open).
    let (_fetch_id, fetch_reply, fetch_send, mut fetch_recv) = {
        let deadline = std::time::Instant::now() + TEST_TIMEOUT;
        loop {
            match open_fetch(&client, "ns-1", &wire_hex, None).await {
                Ok(fetch) => break fetch,
                Err(ref failure) if failure.establishment_reason() == Some("unknown_resource") => {
                    assert!(
                        std::time::Instant::now() < deadline,
                        "the put's broadcast never began"
                    );
                    tokio::time::sleep(std::time::Duration::from_millis(10)).await;
                    continue;
                }
                Err(failure) => {
                    panic!("the fetch establishment failed otherwise: {failure:?}")
                }
            }
        }
    };
    assert_eq!(
        fetch_reply["source"],
        json!("fanout"),
        "the tap: broadcast bytes serve while the put lands"
    );
    assert!(
        fetch_reply["len"].is_null(),
        "a live put's tail ack carries no length"
    );

    // The tap is the putter's coordination point: with the
    // subscriber arm live, the put's remaining bytes flow through
    // the tee's broadcast (Stall — the fetched consumer's reads
    // drive it) and the store arm concurrently.
    send.write_all(&seed[256..])
        .await
        .expect("the rest streams");
    drop(send);

    let drain = tokio::spawn(async move {
        let mut received = Vec::new();
        tokio::time::timeout(TEST_TIMEOUT, fetch_recv.read_to_end(&mut received))
            .await
            .expect("the fetched feed ends")
            .expect("the fetched feed ends");
        received
    });
    let out = tokio::time::timeout(TEST_TIMEOUT, reply.resolve())
        .await
        .expect("the put resolves")
        .expect("the put succeeds");
    assert_eq!(
        out["key"],
        json!(wire_hex),
        "the echoed key, same form the offer presented"
    );
    let received = drain.await.expect("the fetched drain joins");
    assert!(
        !received.is_empty(),
        "the tap caught the put's remaining bytes at least"
    );
    assert_eq!(
        &seed[seed.len() - received.len()..],
        received.as_slice(),
        "the tap's feed is a contiguous in-order suffix (no prefix before the tap)"
    );
    assert!(
        store.has(&key.as_bytes()).await.expect("the has probe"),
        "while the fetch served, the put landed"
    );
    drop(fetch_send);
    let _ = channel_id;
}

/// The kv-only mode's put-time threshold rejection (ADR-012 §6.2,
/// the known-length offer form — the mandatory-claim offer's only
/// form): the over-threshold offer rejects at the put's start.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn put_kv_only_threshold_rejects_the_known_length_offer() {
    let db = std::path::PathBuf::from(format!(
        "/tmp/opencode/alkblobs-ops-put-kvonly-{}-{}.db",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos()
    ));
    let store = Arc::new(
        Store::kv_only_sqlite(db, 128, std::time::Duration::ZERO)
            .await
            .expect("the kv-only store constructs"),
    );
    let (_ctx, _harness, client) = put_serving(&store).await;

    // The over-threshold offer: rejected at the put's start — the
    // facade's put never entered the stream.
    let content = [0u8; 256];
    let key = Key::from(Algorithm::GitBlobSha256.derive(&content, 256));
    let (_channel_id, mut send, recv, reply) = open_put(
        &client,
        json!({
            "namespace": "ns-1",
            "key": wire_hex_of(&key),
            "len": content.len()
        }),
    )
    .await;
    send.write_all(&content[..])
        .await
        .expect("the bytes stream");
    drop(send);
    drop(recv);
    let refused_open = tokio::time::timeout(TEST_TIMEOUT, reply.resolve())
        .await
        .expect("the put resolves")
        .expect_err("the over-threshold known-length offer rejects");
    let refused = refused_open.call_error().expect("the wire error");
    assert_eq!(
        refused.code, PUT_REFUSED,
        "the kv-only put-time rejection: {refused:?}"
    );

    assert!(
        !store.has(&key.as_bytes()).await.expect("the has probe"),
        "nothing committed"
    );
}

// ----------------------------------------------------------------
// The JSON control plane's spec/handler pairs (ops-json-ops): the
// stat/have/delete families through the assembled registry.
// ----------------------------------------------------------------

#[cfg(any(feature = "mem", feature = "sqlite"))]
async fn json_plane(store: Arc<Store>) -> (OpsHarness, Arc<OpsContext>) {
    let ctx = Arc::new(OpsContext::new(store, OpsConfig::default()));
    let harness = OpsHarness::assemble(vec![
        stat_pair(Arc::clone(&ctx)),
        have_pair(Arc::clone(&ctx)),
    ]);
    (harness, ctx)
}

fn call_payload(op: &str, input: Value, auth_token: Option<&str>) -> Value {
    let mut payload = json!({
        "operationId": op,
        "input": input,
    });
    if let Some(token) = auth_token {
        payload["auth_token"] = json!(token);
    }
    payload
}

fn field_str<'a>(envelope: &'a ResponseEnvelope, code_field: &str) -> Option<&'a str> {
    match &envelope.result {
        Err(error) => error
            .details
            .as_ref()
            .and_then(|details| details.get(code_field))
            .and_then(Value::as_str),
        Ok(_) => None,
    }
}

fn error_code(envelope: &ResponseEnvelope) -> Option<&str> {
    match &envelope.result {
        Err(error) => Some(error.code.as_str()),
        Ok(_) => None,
    }
}

/// A seeded store entry alongside its wire digest form: the physical
/// key encoding hex (tag-prefixed, ADR-020 §Decision 2).
#[cfg(any(feature = "mem", feature = "sqlite"))]
async fn seeded_entry(store: &Arc<Store>, seed: &[u8]) -> (String, Key) {
    let len = seed.len() as u64;
    let (key, _pin) = store
        .put_as(
            Algorithm::GitBlobSha256,
            Some(len),
            std::io::Cursor::new(seed),
        )
        .await
        .expect("seed put lands");
    (hex::encode(key.as_bytes()), key)
}

/// `blobs/stat` (criterion: the stat round-trip + the miss shape):
/// a granted identity receives `{len}` for a seeded entry without a
/// content load (the read action's probe-before-offering shape); a
/// miss is the typed `BLOB_MISSING` error (not a `{len: null}`);
/// a malformed digest is rejected at the schema (`INVALID_INPUT`).
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn stat_answers_len_the_miss_is_typed_and_the_digest_ingress_rejects() {
    let store = test_store().await;
    let (harness, _ctx) = json_plane(Arc::clone(&store)).await;
    harness.with_token("token:alice", identity_named("alice"));
    harness.grant("alice", "ns-1", &["read"]);
    let client = harness.spawn_call_halves();

    let (digest_hex, _) = seeded_entry(&store, b"stat round trip").await;

    let answer = await_call(client.call_with_payload(call_payload(
        "blobs/stat",
        json!({ "namespace": "ns-1", "digest": digest_hex }),
        Some("token:alice"),
    )))
    .await;
    assert_eq!(
        answer.result.unwrap(),
        json!({ "len": 15 }),
        "the seeded entry's length answers"
    );

    let absent_probe = wire_hex_of(&key_of(b"missed stat"));
    let missed = await_call(client.call_with_payload(call_payload(
        "blobs/stat",
        json!({ "namespace": "ns-1", "digest": absent_probe.clone() }),
        Some("token:alice"),
    )))
    .await;
    assert_eq!(error_code(&missed), Some(BLOB_MISSING));
    assert_eq!(
        field_str(&missed, "digest").map(str::to_owned),
        Some(absent_probe),
        "the missing-error's details carry the digest"
    );

    let malformed = await_call(client.call_with_payload(call_payload(
        "blobs/stat",
        json!({ "namespace": "ns-1", "digest": "ZZZ-not-hex" }),
        Some("token:alice"),
    )))
    .await;
    assert_eq!(
        error_code(&malformed),
        Some("INVALID_INPUT"),
        "the schema gate rejects a malformed digest before the handler"
    );
}

/// `blobs/have` without the token (criterion: present/absent mixed
/// by index correspondence) and the read gate (closed-by-default):
/// an unlisted namespace's probe denies, the granted identity reads.
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn have_answers_by_index_and_the_unlisted_namespace_denies() {
    let store = test_store().await;
    let (harness, _ctx) = json_plane(Arc::clone(&store)).await;
    harness.with_token("token:alice", identity_named("alice"));
    harness.grant("alice", "ns-1", &["read"]);
    let client = harness.spawn_call_halves();

    let (digest_hex, _) = seeded_entry(&store, b"have probe").await;
    let absent = wire_hex_of(&key_of(b"never put"));

    let mixed = await_call(client.call_with_payload(call_payload(
        "blobs/have",
        json!({ "namespace": "ns-1", "digests": [digest_hex.clone(), absent.clone(), digest_hex.clone()] }),
        Some("token:alice"),
    )))
    .await;
    assert_eq!(
        mixed.result.unwrap(),
        json!({ "present": [true, false, true] }),
        "present[] corresponds to digests[] by index"
    );

    let denied = await_call(client.call_with_payload(call_payload(
        "blobs/have",
        json!({ "namespace": "ns-2-the-unlisted", "digests": [digest_hex.clone()] }),
        Some("token:alice"),
    )))
    .await;
    assert_eq!(
        error_code(&denied),
        Some("FORBIDDEN"),
        "closed-by-default: a grant per namespace is the deferred cost"
    );
}

/// `blobs/have`'s renewal form (criterion: the three answers, the
/// non-fleet arms): a live custodial row renews (`present: true`),
/// an unknown token answers `present: false` (never an error), a
/// mismatched digest answers `present: false`, the gate's case-
/// insensitive token pattern and the ingress's case-insensitive
/// decode agree (an uppercased wire form renews — S-5's case
/// posture), and a malformed token is the schema gate's
/// `INVALID_INPUT` at the wire (S-5's field bound) while the
/// handler's own ingress keeps the unknown-token mapping for calls
/// that ride past the gate. The arity
/// violation is the typed `INVALID_RENEWAL_FORM` — exercised at the
/// handler's ingress (the wire's schema gate would reject first).
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn the_renewal_form_answers_and_the_ingress_rejects_the_arity_violation() {
    let store = test_store().await;
    let (harness, ctx) = json_plane(Arc::clone(&store)).await;
    harness.with_token("token:alice", identity_named("alice"));
    harness.grant("alice", "ns-1", &["read"]);
    let client = harness.spawn_call_halves();

    let (digest_hex, key) = seeded_entry(&store, b"renewal form").await;
    let other = Key::from(Algorithm::GitBlobSha256.derive(b"another entry", 13));
    let pin = store.gc().acquire(&key).await;
    let token = ctx.mint_custodial("ns-1", key.clone(), pin).unwrap();
    let unknown_token = PinToken::generate().unwrap();

    let renewed = await_call(client.call_with_payload(call_payload(
        "blobs/have",
        json!({ "namespace": "ns-1", "digests": [digest_hex.clone()], "token": token.to_hex() }),
        Some("token:alice"),
    )))
    .await;
    assert_eq!(
        renewed.result.unwrap(),
        json!({ "present": [true] }),
        "a live custodial row renews from the held guard (nothing expires)"
    );

    let refused = await_call(client.call_with_payload(call_payload(
        "blobs/have",
        json!({ "namespace": "ns-1", "digests": [wire_hex_of(&other)], "token": token.to_hex() }),
        Some("token:alice"),
    )))
    .await;
    assert_eq!(
        refused.result.unwrap(),
        json!({ "present": [false] }),
        "a digest the token does not bind: the one-token-one-row check, present: false"
    );
    let foreign = await_call(client.call_with_payload(call_payload(
        "blobs/have",
        json!({ "namespace": "ns-1", "digests": [digest_hex.clone()], "token": unknown_token.to_hex() }),
        Some("token:alice"),
    )))
    .await;
    assert_eq!(
        foreign.result.unwrap(),
        json!({ "present": [false] }),
        "a token this node did not mint: the validity-domain refusal, present: false, not an error"
    );

    let uppercased = token.to_hex().to_uppercase();
    let uppercased_wire = await_call(client.call_with_payload(call_payload(
        "blobs/have",
        json!({ "namespace": "ns-1", "digests": [digest_hex.clone()], "token": uppercased }),
        Some("token:alice"),
    )))
    .await;
    assert_eq!(
        uppercased_wire.result.unwrap(),
        json!({ "present": [true] }),
        "the gate's case-insensitive token pattern and the ingress's case-insensitive decode agree (S-5's case posture): an uppercased wire form renews"
    );

    let malformed_token = hex::encode(b"not-a-64-char-canonical-hex-token");
    let malformed_wire = await_call(client.call_with_payload(call_payload(
        "blobs/have",
        json!({ "namespace": "ns-1", "digests": [digest_hex.clone()], "token": malformed_token }),
        Some("token:alice"),
    )))
    .await;
    assert_eq!(
        error_code(&malformed_wire),
        Some("INVALID_INPUT"),
        "the schema gate's S-5 bound rejects the over-length token before any handler contact"
    );

    let (_, handler) = have_pair(Arc::clone(&ctx));
    let malformed = (handler)(
        json!({ "namespace": "ns-1", "digests": [digest_hex.clone()], "token": malformed_token }),
        bare_context(),
    )
    .await;
    assert_eq!(
        malformed.result.unwrap(),
        json!({ "present": [false] }),
        "a malformed token past the gate (direct/composed calls) is the unknown-token form, present: false, never an error"
    );

    let arity_wire = await_call(client.call_with_payload(call_payload(
        "blobs/have",
        json!({ "namespace": "ns-1", "digests": [digest_hex.clone(), "0".repeat(66)], "token": token.to_hex() }),
        Some("token:alice"),
    )))
    .await;
    assert_eq!(
        error_code(&arity_wire),
        Some("INVALID_INPUT"),
        "the schema gate enforces the renewal form's one-digest arity (if/then) at the wire"
    );

    let (_, handler) = have_pair(Arc::clone(&ctx));
    let arity = (handler)(
        json!({ "namespace": "ns-1", "digests": [digest_hex.clone(), "0".repeat(66)], "token": token.to_hex() }),
        bare_context(),
    )
    .await;
    assert_eq!(
        error_code(&arity),
        Some(INVALID_RENEWAL_FORM),
        "the renewal form's one-digest arity is the handler's typed error"
    );

    let invalid = (handler)(
        json!({ "namespace": "ns-1", "digests": ["NOT-DIGEST-HEX"], "token": token.to_hex() }),
        bare_context(),
    )
    .await;
    assert_eq!(
        error_code(&invalid),
        Some(INVALID_DIGEST),
        "the digest ingress rejects, never guesses"
    );
}

/// The renewal's namespace parity (ADR-017 §3), server-less through
/// the wire: a renewal presented under a namespace other than the
/// mint record's answers the validity-domain refusal — `present:
/// false`, never an error, the mapping intact — and a subsequent
/// renew-under-the-minted-namespace succeeds (confirm's refusal
/// discipline is the parity's contrast; the `UnknownToken` mapping is
/// the decided outcome-mapping: a namespace-mismatched renewal is the
/// same "not this token's domain" answer confirm's refusal is).
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn a_wrong_namespace_renewal_answers_the_validity_domain_refusal_and_the_mapping_stays_intact(
) {
    let store = test_store().await;
    let (harness, ctx) = json_plane(Arc::clone(&store)).await;
    harness.with_token("token:alice", identity_named("alice"));
    harness.grant("alice", "ns-1", &["read"]);
    harness.grant("alice", "ns-2", &["read"]);
    let client = harness.spawn_call_halves();

    let (digest_hex, key) = seeded_entry(&store, b"namespace parity").await;
    let pin = store.gc().acquire(&key).await;
    let token = ctx.mint_custodial("ns-1", key.clone(), pin).unwrap();

    let mismatched = await_call(client.call_with_payload(call_payload(
        "blobs/have",
        json!({ "namespace": "ns-2", "digests": [digest_hex.clone()], "token": token.to_hex() }),
        Some("token:alice"),
    )))
    .await;
    assert_eq!(
        mismatched.result.unwrap(),
        json!({ "present": [false] }),
        "a renewal under a namespace the mint record contradicts: present: false, \
         not an error (ADR-017 §3's parity)"
    );

    let parity = await_call(client.call_with_payload(call_payload(
        "blobs/have",
        json!({ "namespace": "ns-1", "digests": [digest_hex.clone()], "token": token.to_hex() }),
        Some("token:alice"),
    )))
    .await;
    assert_eq!(
        parity.result.unwrap(),
        json!({ "present": [true] }),
        "the mapping stayed intact through the parity refusal: the renewal under the \
         minted namespace succeeds"
    );

    assert!(
        ctx.tokens().holds(&token),
        "the mapping survived the parity refusal and the renewal — confirm's refusal \
         discipline rides unmolested (the mapping retires only at a confirmed conversion)"
    );
}

/// `blobs/delete` (criterion: external discovery NOT_FOUND; the
/// internal operator-context composition deletes; the namespace
/// field is audit scoping, not gating — a grantless caller's
/// composed internal call runs under the operator authority):
/// deleted, fail-fast on the absent key, and `GcRefuse` as the
/// typed `GC_REFUSED`.
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn delete_is_external_not_found_and_the_internal_authority_composition_deletes() {
    let store = test_store().await;
    let ctx = Arc::new(OpsContext::new(store, OpsConfig::default()));
    let harness = OpsHarness::assemble_registrations(vec![
        OpsHarnessRegistration::pair(delete_pair(Arc::clone(&ctx)))
            .with_composition_authority(CompositionAuthority::new("blob-operator", [])),
        OpsHarnessRegistration::pair(composer_pair())
            .with_scoped_env(ScopedPeerEnv::new(["blobs/delete"])),
    ]);
    harness.with_token("token:stranger", identity_named("stranger"));
    let client = harness.spawn_call_halves();

    let external = await_call(client.call_with_payload(call_payload(
        "blobs/delete",
        json!({ "namespace": "ns-1", "digests": ["0".repeat(64)] }),
        Some("token:stranger"),
    )))
    .await;
    assert_eq!(
        error_code(&external),
        Some("NOT_FOUND"),
        "an Internal op is not discovered from the wire (the visibility discipline)"
    );

    let (digest_hex, key) = seeded_entry(ctx.store(), b"deleted by the operator").await;

    let composed = await_call(client.call_with_payload(call_payload(
        "blobs/compose-delete",
        json!({ "namespace": "ns-1", "digests": [digest_hex.clone()] }),
        Some("token:stranger"),
    )))
    .await;
    assert_eq!(
        composed.result.unwrap(),
        json!({ "deleted": [digest_hex.clone()] }),
        "the operator-authority composition deletes; the namespace grant is not the gate"
    );
    assert!(
        !ctx.store().has(&key.as_bytes()).await.unwrap_or(true),
        "the entry is gone from the facade after the internal delete"
    );

    let (present_hex, present_key) = seeded_entry(ctx.store(), b"fail fast").await;
    let absent = wire_hex_of(&key_of(b"absent entry"));
    let fail_fast = await_call(client.call_with_payload(call_payload(
        "blobs/compose-delete",
        json!({ "namespace": "ns-1", "digests": [present_hex, absent.clone()] }),
        Some("token:stranger"),
    )))
    .await;
    assert_eq!(
        error_code(&fail_fast),
        Some(BLOB_MISSING),
        "the absent key is the typed missing error"
    );
    assert_eq!(
        field_str(&fail_fast, "digest").map(str::to_owned),
        Some(absent),
        "the missing-error's details carry the failing digest"
    );
    assert!(
        !ctx.store()
            .has(&present_key.as_bytes())
            .await
            .unwrap_or(true),
        "the fail-fast path's preceding digests deleted (nothing atomic was specced)"
    );

    let (pinned_hex, pinned_key) = seeded_entry(ctx.store(), b"protected entry").await;
    let _guard = ctx.store().gc().acquire(&pinned_key).await;
    let refused = await_call(client.call_with_payload(call_payload(
        "blobs/compose-delete",
        json!({ "namespace": "ns-1", "digests": [pinned_hex] }),
        Some("token:stranger"),
    )))
    .await;
    assert_eq!(
        error_code(&refused),
        Some(GC_REFUSED),
        "a protected key's refusal is the typed error"
    );
    assert_eq!(
        field_str(&refused, "digest").map(str::to_owned),
        Some(pinned_hex),
        "the refusal's details carry the protected digest"
    );
}

// ----------------------------------------------------------------
// The wire-key-hex pins (ADR-020 §Decision 2): the schema gate and
// the ingress agree on every input (S-5), bare hex dies, and the
// git-object family's entries are wire-readable end to end.
// ----------------------------------------------------------------

/// The wire form (the physical key encoding, tag-prefixed) round-trips
/// through the ingress to exactly the keys the pool holds, for every
/// registry member — and the same strings pass every op's schema gate.
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn the_wire_key_hex_decodes_to_the_registry_members_the_pool_holds() {
    let store = test_store().await;
    let (harness, ctx) = json_plane(Arc::clone(&store)).await;
    harness.with_token("token:alice", identity_named("alice"));
    harness.grant("alice", "ns-1", &["read", "write"]);
    let client = harness.spawn_call_halves();
    let (_, delete_handler) = delete_pair(Arc::clone(&ctx));

    for algorithm in [
        Algorithm::GitBlobSha256,
        Algorithm::GitBlobSha1,
        Algorithm::GitObjectSha1,
        Algorithm::GitObjectSha256,
    ] {
        let family = matches!(
            algorithm,
            Algorithm::GitObjectSha1 | Algorithm::GitObjectSha256
        );
        let stored: Vec<u8> = if family {
            b"blob 3\0abc".to_vec()
        } else {
            format!("{}-{}", algorithm.byte(), "x").into_bytes()
        };
        let (key, pin) = if family {
            store
                .put_as(
                    algorithm,
                    Some(stored.len() as u64),
                    std::io::Cursor::new(stored.clone()),
                )
                .await
                .expect("the family put lands")
        } else {
            let content = stored.clone();
            store
                .put_as(
                    Algorithm::GitBlobSha256,
                    Some(content.len() as u64),
                    std::io::Cursor::new(content),
                )
                .await
                .expect("the blob put lands")
        };
        drop(pin);
        let key_hex = wire_hex_of(&key);

        // The gate passes the wire form, and the ingress beneath it
        // decodes to the held entry (the S-5 agreement, per member).
        let stat = await_call(client.call_with_payload(call_payload(
            "blobs/stat",
            json!({ "namespace": "ns-1", "digest": key_hex.clone() }),
            Some("token:alice"),
        )))
        .await;
        assert_eq!(
            stat.result.expect("the stat answers"),
            json!({ "len": stored.len() as u64 }),
            "the wire key hex addresses the held entry ({algorithm:?})"
        );

        let have = await_call(client.call_with_payload(call_payload(
            "blobs/have",
            json!({ "namespace": "ns-1", "digests": [key_hex.clone()] }),
            Some("token:alice"),
        )))
        .await;
        assert_eq!(
            have.result.expect("the have answers"),
            json!({ "present": [true] }),
            "the wire key hex haves the held entry ({algorithm:?})"
        );

        let deleted = (delete_handler)(
            json!({ "namespace": "ns-1", "digests": [key_hex.clone()] }),
            bare_context(),
        )
        .await;
        assert_eq!(
            deleted.result.expect("the delete answers"),
            json!({ "deleted": [key_hex] }),
            "the wire key hex deletes the held entry ({algorithm:?})"
        );
        assert!(
            !store.has(&key.as_bytes()).await.expect("the has probe"),
            "the delete landed ({algorithm:?})"
        );
    }
}

/// The bare-hex death and the gate/ingress agreement (S-5, pinned):
/// the gate's pattern is the physical encoding's widths and charset —
/// everything the ingress accepts the gate passes, and every
/// gate-passing string has exactly one ingress verdict (the
/// rejects-never-guesses decoder: the tag validated, the digest
/// length checked per tag, never inferred). The battery carries the
/// old schema's shapes too: **bare 40/64-hex digest strings now die
/// at the gate** (`INVALID_INPUT`, the old implicit default-family
/// reads gone), while tag-validation shapes the loose gate cannot see
/// (an unknown tag; a tag/width mismatch — a 42-char string whose tag
/// declares a 33-byte key) reject at the ingress (`INVALID_DIGEST`).
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn bare_hex_dies_and_the_gate_and_ingress_agree_on_every_input() {
    let store = test_store().await;
    let (harness, ctx) = json_plane(Arc::clone(&store)).await;
    harness.with_token("token:alice", identity_named("alice"));
    harness.grant("alice", "ns-1", &["read"]);
    let client = harness.spawn_call_halves();
    let (_, stat_handler) = stat_pair(Arc::clone(&ctx));

    let keys: Vec<Key> = vec![
        key_of(b"the s5 battery's seed"),
        Key::from(Algorithm::GitBlobSha1.derive(b"blob 3\0abc", 10)),
        Key::from(Algorithm::GitObjectSha1.derive(b"blob 3\0abc", 10)),
        Key::from(Algorithm::GitObjectSha256.derive(b"blob 3\0abc", 10)),
    ];
    for key in &keys {
        assert!(matches!(
            key.algorithm(),
            Algorithm::GitBlobSha256
                | Algorithm::GitBlobSha1
                | Algorithm::GitObjectSha1
                | Algorithm::GitObjectSha256
        ));
    }
    let gate_passing: Vec<String> = keys.iter().map(wire_hex_of).collect();

    let gate_rejects: Vec<String> = vec![
        "a".repeat(40),
        "a".repeat(64),
        "a".repeat(41),
        "a".repeat(43),
        "a".repeat(65),
        "a".repeat(67),
        "g".repeat(66),
        "ZZZ-not-hex".to_owned(),
        wire_hex_of(&keys[0]).to_uppercase(),
    ];

    let ingress_rejects: Vec<String> = vec![
        format!("05{}", "a".repeat(40)),
        format!("01{}", "a".repeat(40)),
        format!("02{}", "b".repeat(64)),
        format!("04{}", "a".repeat(40)),
        format!("03{}", "b".repeat(64)),
    ];

    for digest in gate_rejects {
        let wire = await_call(client.call_with_payload(call_payload(
            "blobs/stat",
            json!({ "namespace": "ns-1", "digest": digest }),
            Some("token:alice"),
        )))
        .await;
        assert_eq!(
            error_code(&wire),
            Some("INVALID_INPUT"),
            "the gate rejects: {digest}"
        );
        let direct = (stat_handler)(
            json!({ "namespace": "ns-1", "digest": digest }),
            bare_context(),
        )
        .await;
        assert_eq!(
            error_code(&direct),
            Some(INVALID_DIGEST),
            "the ingress rejects what the gate rejected: {digest}"
        );
    }

    for digest in &ingress_rejects {
        assert!(
            super::wire::digest_ingress(digest).is_err(),
            "the ingress rejects its battery member: {digest}"
        );
        let wire = await_call(client.call_with_payload(call_payload(
            "blobs/stat",
            json!({ "namespace": "ns-1", "digest": digest }),
            Some("token:alice"),
        )))
        .await;
        assert_eq!(
            error_code(&wire),
            Some(INVALID_DIGEST),
            "the loose gate passes, the ingress validates the tag: {digest}"
        );
    }

    // Every ingress acceptance is a gate pass, and the decode is the
    // key itself (never a default-family guess): per member, the
    // ingress reproduces the constructed key exactly.
    for (digest, decoded) in gate_passing.iter().zip(&keys) {
        let wire = await_call(client.call_with_payload(call_payload(
            "blobs/stat",
            json!({ "namespace": "ns-1", "digest": digest }),
            Some("token:alice"),
        )))
        .await;
        assert_ne!(
            error_code(&wire),
            Some("INVALID_INPUT"),
            "the gate passes the wire-key-hex form ({digest})"
        );
        assert_ne!(
            error_code(&wire),
            Some(INVALID_DIGEST),
            "the gate-passing string is not ingress-rejected ({digest})"
        );
        assert_eq!(
            error_code(&wire),
            Some(BLOB_MISSING),
            "the battery's entries are unseeded: the miss shape answers"
        );
        assert_eq!(
            super::wire::digest_ingress(digest).ok(),
            Some(decoded.clone()),
            "the gate-passing string decodes to its key ({digest})",
        );
    }
}

/// The family gap closed end to end (review-003's F-1, the family
/// half; ADR-020 §Decision 9's pinning test, re-homed from POC-X's
/// `tests/ops_gap.rs`): a facade-published git-object entry is
/// stat-able, have-servable, and fetchable over the ops surface in
/// its own key hex — the ranged fetch returns the stored bytes, the
/// slice digests verifying — and a wire-offered family put lands
/// under its own oid (the tee hasher opens under the claimed key's
/// algorithm, the store arm routes `put_as`, the response echoes the
/// git oid key), then serves over stat/fetch. Both sha-1 and sha-256
/// family members ride the path — the cross-family vector's lesson:
/// same digest bytes, different tags, so one member's passing says
/// nothing about the other's ingress; the tag prefix is the address's
/// family identity (ADR-020 §Decision 1's invariant: the addressable
/// classes of the facade and of the wire are the same set).
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn a_facade_published_family_entry_is_wire_readable_end_to_end() {
    let store = test_store().await;
    let ctx = Arc::new(OpsContext::new(Arc::clone(&store), OpsConfig::default()));
    let harness = OpsHarness::assemble(vec![
        stat_pair(Arc::clone(&ctx)),
        have_pair(Arc::clone(&ctx)),
    ]);
    harness.with_token("token:alice", identity_named("alice"));
    harness.grant("alice", "ns-1", &["read", "write"]);
    let client = harness.spawn_call_halves();
    let channel_client = harness
        .spawn_channel_halves(
            vec![
                fetch_openable(Arc::clone(&ctx)),
                put_openable(Arc::clone(&ctx)),
            ],
            Some(identity_named("alice")),
        )
        .await;

    let loose: &[u8] = b"tree 20\0the loose object's body";
    let honest: Vec<u8> = (0u8..24).collect();

    for algorithm in [Algorithm::GitObjectSha1, Algorithm::GitObjectSha256] {
        let tag = format!("{:02x}", algorithm.byte());

        let (key, _family_pin) = store
            .put_as(
                algorithm,
                Some(loose.len() as u64),
                std::io::Cursor::new(loose.to_vec()),
            )
            .await
            .expect("the family put lands");
        let key_hex = wire_hex_of(&key);
        assert_eq!(
            &key_hex[..2],
            tag,
            "the family member's tag byte rides the wire form ({algorithm:?})"
        );
        assert_eq!(
            key_hex.len(),
            2 * (1 + key.digest().bytes().len()),
            "the wire form's width is the physical encoding's: the tag byte + the git oid \
             ({algorithm:?})"
        );
        assert_eq!(
            algorithm.derive(loose, loose.len() as u64).bytes(),
            key.digest().bytes(),
            "the landed digest is byte-identical to git's oid derivation ({algorithm:?})"
        );

        let stat = await_call(client.call_with_payload(call_payload(
            "blobs/stat",
            json!({ "namespace": "ns-1", "digest": key_hex.clone() }),
            Some("token:alice"),
        )))
        .await;
        assert_eq!(
            stat.result.expect("the family stat answers"),
            json!({ "len": loose.len() }),
            "ADR-018 §Decision 3's stat semantic: the stored preimage's length ({algorithm:?})"
        );

        let have = await_call(client.call_with_payload(call_payload(
            "blobs/have",
            json!({ "namespace": "ns-1", "digests": [key_hex.clone()] }),
            Some("token:alice"),
        )))
        .await;
        assert_eq!(
            have.result.expect("the family have answers"),
            json!({ "present": [true] }),
            "the family entry haves present in its own key hex ({algorithm:?})"
        );

        let (slice0, digest0) = store
            .read_range(&key.as_bytes(), 0, 8)
            .await
            .expect("the first ranged read");
        let (slice1, digest1) = store
            .read_range(&key.as_bytes(), 8, loose.len() as u64 - 8)
            .await
            .expect("the second ranged read");
        let (channel_id, reply, send, mut recv) = open_fetch(
            &channel_client,
            "ns-1",
            &key_hex,
            Some(json!([
                { "offset": 0, "len": 8 },
                { "offset": 8, "len": loose.len() as u64 - 8 }
            ])),
        )
        .await
        .expect("the family entry fetches through the standard channel op");
        assert_eq!(
            reply,
            json!({
                "channel_id": channel_id,
                "source": "store",
                "slice_digests": [hex::encode(digest0), hex::encode(digest1)]
            }),
            "the ranged fetch's ack carries the verifying slice digests ({algorithm:?})"
        );
        let mut received = Vec::new();
        tokio::time::timeout(TEST_TIMEOUT, recv.read_to_end(&mut received))
            .await
            .expect("the stream reads")
            .expect("the stream ends");
        drop(send);
        assert_eq!(
            received,
            [slice0, slice1].concat(),
            "the ranged fetch returns the stored bytes ({algorithm:?})"
        );
        assert_eq!(
            received, loose,
            "the family entry serves byte-exact ({algorithm:?})"
        );
        assert_eq!(
            algorithm.derive(&received, received.len() as u64).bytes(),
            key.digest().bytes(),
            "the family's own derivation verifies the served bytes ({algorithm:?})"
        );

        // The write side of the pinning test (ADR-020 §Decision 4): a
        // wire-offered family put lands under its own oid — the tee
        // hashes under the claimed key's algorithm (identity-family:
        // the preimage verbatim, the len only checked against the
        // stream), the store arm routes `put_as`, the hand-over mints,
        // and the response echoes the key in the vocabulary it
        // offered.
        let family_key = Key::from(algorithm.derive(&honest, honest.len() as u64));
        let claimed = wire_hex_of(&family_key);
        assert_eq!(
            &claimed[..2],
            tag,
            "the wire-offered family put's key hex carries the family tag ({algorithm:?})"
        );
        let (_channel_id, mut send, recv, reply) = open_put(
            &channel_client,
            json!({ "namespace": "ns-1", "key": claimed.clone(), "len": honest.len() }),
        )
        .await;
        send.write_all(&honest).await.expect("the bytes stream");
        drop(send);
        drop(recv);
        let out = tokio::time::timeout(TEST_TIMEOUT, reply.resolve())
            .await
            .expect("the put resolves")
            .expect("the wire-offered family put lands under its own oid");
        assert_eq!(
            out["key"],
            json!(claimed),
            "the response echoes the git oid key the offer carried ({algorithm:?})"
        );
        assert!(
            store
                .has(&family_key.as_bytes())
                .await
                .expect("the has probe"),
            "the entry committed under the family's own oid ({algorithm:?})"
        );
        assert_eq!(
            store.gc().pin_count(&family_key),
            1,
            "the hand-over's custody refcounts the landed family entry ({algorithm:?})"
        );
        let token =
            PinToken::from_hex(out["token"].as_str().expect("the token field")).expect("hex");
        assert!(
            ctx.tokens().holds(&token),
            "the landed family put minted its custody ({algorithm:?})"
        );

        // The landed entry serves over the wire: a stat naming the git
        // oid key answers ADR-018 §Decision 3's semantic, and a whole
        // fetch streams the stored preimage byte-exact.
        let landed_stat = await_call(client.call_with_payload(call_payload(
            "blobs/stat",
            json!({ "namespace": "ns-1", "digest": claimed.clone() }),
            Some("token:alice"),
        )))
        .await;
        assert_eq!(
            landed_stat.result.expect("the landed entry's stat answers"),
            json!({ "len": honest.len() }),
            "the landed family entry stats in its own oid hex ({algorithm:?})"
        );
        let (landed_channel, ack, send, mut recv) =
            open_fetch(&channel_client, "ns-1", &claimed, None)
                .await
                .expect("the landed entry fetches through the standard channel op");
        assert_eq!(
            ack,
            json!({ "channel_id": landed_channel, "source": "store", "len": honest.len() }),
            "the landed family entry serves from the store path ({algorithm:?})"
        );
        let mut streamed = Vec::new();
        tokio::time::timeout(TEST_TIMEOUT, recv.read_to_end(&mut streamed))
            .await
            .expect("the stream reads")
            .expect("the stream ends");
        drop(send);
        assert_eq!(
            streamed, honest,
            "the landed family entry serves byte-exact ({algorithm:?})"
        );
        assert_eq!(
            algorithm.derive(&streamed, streamed.len() as u64).bytes(),
            family_key.digest().bytes(),
            "the landed entry's served bytes verify under the family's own derivation \
             ({algorithm:?})"
        );
    }
}

// ----------------------------------------------------------------
// The renewal form's fleet arms (the foundation's noted fleet
// forms) — against the live harness server (the fleet column's
// SKIP posture adapted in-crate): env-driven DSN, skipping cleanly
// server-less, acceptance green against the server.
// ----------------------------------------------------------------

/// The harness-server DSN (`ALKBLOBS_PG_HOST/PORT/USER/PASSWORD/DB`
/// — the alkstore convention; host gated, the rest defaulting to
/// the harness server's values). `None` → the caller skips.
#[cfg(feature = "postgres")]
async fn fleet_dsn() -> Option<String> {
    let host = std::env::var("ALKBLOBS_PG_HOST")
        .ok()
        .filter(|v| !v.is_empty())?;
    let port = std::env::var("ALKBLOBS_PG_PORT")
        .ok()
        .filter(|v| !v.is_empty())
        .unwrap_or_else(|| "15432".to_owned());
    let user = std::env::var("ALKBLOBS_PG_USER")
        .ok()
        .filter(|v| !v.is_empty())
        .unwrap_or_else(|| "postgres".to_owned());
    let password = std::env::var("ALKBLOBS_PG_PASSWORD")
        .ok()
        .filter(|v| !v.is_empty())
        .unwrap_or_else(|| "poc".to_owned());
    let db = std::env::var("ALKBLOBS_PG_DB")
        .ok()
        .filter(|v| !v.is_empty())
        .unwrap_or_else(|| "blobs".to_owned());
    let dsn = format!("host={host} port={port} user={user} password={password} dbname={db}");
    match tokio::time::timeout(std::time::Duration::from_secs(3), async {
        let (client, connection) = tokio_postgres::connect(&dsn, tokio_postgres::NoTls)
            .await
            .map_err(|e| Error::Io(format!("postgres harness: {e}")))?;
        tokio::spawn(async move {
            let _ = connection.await;
        });
        Ok::<tokio_postgres::Client, Error>(client)
    })
    .await
    {
        Ok(Ok(_)) => Some(dsn),
        Ok(Err(e)) => {
            eprintln!("skipping (harness server unreachable): {e}");
            None
        }
        Err(_) => {
            eprintln!("skipping (harness server unreachable: connect timeout)");
            None
        }
    }
}

/// The pin-row instrument (the fleet column's medium-oracle
/// pattern, the have handler's renewal arm's observation): one
/// independent connection reads the schema's
/// `gc_pins(key, owner, expiry)` — the durable pin state — for one
/// key (`(owner, expiry)` per row; nanos are absolute wall time).
#[cfg(feature = "postgres")]
async fn fleet_pin_row(
    dsn: &str,
    schema: &str,
    key: &[u8],
) -> Result<Option<(Vec<u8>, i64)>, Error> {
    let (client, connection) = tokio_postgres::connect(dsn, tokio_postgres::NoTls)
        .await
        .map_err(|e| Error::Io(format!("postgres harness: {e}")))?;
    tokio::spawn(async move {
        let _ = connection.await;
    });
    let sql = format!(
        "SELECT owner, expiry FROM \"{}\".gc_pins WHERE key = $1",
        schema.replace('"', "\"\"")
    );
    let row = client
        .query_opt(&sql, &[&key])
        .await
        .map_err(|e| Error::Io(format!("postgres harness: {e}")))?;
    Ok(row.map(|row| {
        let owner: Vec<u8> = row.get(0);
        let expiry: i64 = row.get(1);
        (owner, expiry)
    }))
}

#[cfg(feature = "postgres")]
async fn fleet_schema_drop(dsn: &str, schema: &str) {
    if let Ok((admin, connection)) = tokio_postgres::connect(dsn, tokio_postgres::NoTls).await {
        tokio::spawn(async move {
            let _ = connection.await;
        });
        let sql = format!(
            "DROP SCHEMA IF EXISTS \"{}\" CASCADE",
            schema.replace('"', "\"\"")
        );
        let _ = admin.batch_execute(&sql).await;
    }
}

/// Two fleet-declared dual-tier stores over one freshly minted
/// schema (the fleet column's factory pattern, the have handler's
/// renewal arm's shape): the serving instance A mints the token,
/// the peer B plays the foreign mint — each with its own
/// store-instance id (the pin rows compose by owner) and the short
/// test pin TTL (the expiry horizon's observable cadence).
/// Returns the two stores; the caller owns the temp root and the
/// schema's teardown.
#[cfg(feature = "postgres")]
async fn open_fleet_pair(
    dsn: &str,
    schema: &str,
    root_a: &std::path::Path,
    root_b: &std::path::Path,
) -> Result<(Store, Store), Error> {
    let ttl = PAIR_TTL;
    let opts = |schema: &str| crate::PgOpts {
        schema: schema.to_owned(),
        ..crate::PgOpts::default()
    };
    let store_a = crate::Store::dual_tier_postgres_local_fleet(
        dsn,
        opts(schema),
        root_a.to_path_buf(),
        1024,
        std::time::Duration::ZERO,
        ttl,
        crate::FleetSharedMedia::asserted(),
    )
    .await?;
    let store_b = crate::Store::dual_tier_postgres_local_fleet(
        dsn,
        opts(schema),
        root_b.to_path_buf(),
        1024,
        std::time::Duration::ZERO,
        ttl,
        crate::FleetSharedMedia::asserted(),
    )
    .await?;
    Ok((store_a, store_b))
}

/// The have handler's renewal form against a **live fleet store**
/// (the foundation's noted fleet forms; ADR-012 §2's renew duty on
/// the wire): the namespace parity fires first (ADR-017 §3 — a
/// renewal under a namespace the mint record contradicts answers
/// `present: false`, not an error, and the mapping stays intact for
/// the correct-namespace renewal); the fleet token renews the live
/// row (`present: true` — the row's expiry moves, observed by the
/// independent connection's `gc_pins` read); a putter pausing past
/// the TTL answers `present: false` and **no renewal occurs** (the
/// expiry frozen at the last renewal — the never-resurrect
/// discipline, ADR-008 §2); a peer's foreign mint answers
/// `present: false`, not an error — the validity domain is the
/// minting node (ADR-012 §2). The custodial-mint-is-refused-under-
/// fleet arm rides the same contexts.
#[cfg(feature = "postgres")]
#[tokio::test]
async fn the_fleet_renewal_form_renews_the_live_row_and_never_resurrects_the_expired_one() {
    let Some(dsn) = fleet_dsn().await else {
        eprintln!(
            "skipping (no postgres harness server): set ALKBLOBS_PG_HOST/PORT/USER/PASSWORD/DB"
        );
        return;
    };
    let schema = format!(
        "alkblobs_ops_have_renewal_{}_{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos()
    );
    let root = std::env::temp_dir().join(format!(
        "alkblobs-ops-fleet-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos()
    ));
    std::fs::create_dir_all(&root).expect("the temp root created");

    let (store_a, store_b) = open_fleet_pair(&dsn, &schema, &root.join("a"), &root.join("b"))
        .await
        .expect("the fleet pair constructs against the harness server");
    let store_a = Arc::new(store_a);
    let store_b = Arc::new(store_b);
    let ctx = Arc::new(OpsContext::new(Arc::clone(&store_a), OpsConfig::default()));
    let peer = Arc::new(OpsContext::new(Arc::clone(&store_b), OpsConfig::default()));

    let harness = OpsHarness::assemble(vec![have_pair(Arc::clone(&ctx))]);
    harness.with_token("token:alice", identity_named("alice"));
    harness.grant("alice", "ns-1", &["read"]);
    harness.grant("alice", "ns-2", &["read"]);
    let client = harness.spawn_call_halves();

    let seed: &[u8] = b"fleet renewal";
    let (key, pin_guard) = store_a
        .put_as(
            Algorithm::GitBlobSha256,
            Some(seed.len() as u64),
            std::io::Cursor::new(seed),
        )
        .await
        .expect("the fleet put commits the pin row");
    // The guard's drop at response completion is the put handler's
    // own act (ADR-010 §4) — from here the pin row's expiry is the
    // protection, and the TTL/3 renewal duty has stopped.
    drop(pin_guard);
    let digest_hex = wire_hex_of(&key);
    let owner = ctx
        .fleet_owner()
        .expect("the fleet-declared store's instance id");
    let token = ctx
        .mint_fleet("ns-1", key.clone(), &owner)
        .expect("the fleet mint over the serving instance");
    let minted_expiry = fleet_pin_row(&dsn, &schema, &key.as_bytes())
        .await
        .expect("the row instrument")
        .expect("the put's pin row");

    let custodial_refused: Pin = store_b.gc().acquire(&key).await;
    assert!(
        peer.mint_custodial("ns-1", key.clone(), custodial_refused)
            .is_err(),
        "the custodial mint is refused on a fleet-declared store (the row is the protection)"
    );

    // The namespace parity (ADR-017 §3) on the live fleet form: the
    // minted fleet token presented under a different namespace answers
    // present: false — the validity-domain refusal, not an error — and
    // the minted mapping stays intact for the correct-namespace renewal
    // that follows (the row's expiry moves only on that renewal).
    let parity = await_call(client.call_with_payload(call_payload(
        "blobs/have",
        json!({ "namespace": "ns-2", "digests": [digest_hex.clone()], "token": token.to_hex() }),
        Some("token:alice"),
    )))
    .await;
    assert_eq!(
        parity.result.expect("the parity probe answers"),
        json!({ "present": [false] }),
        "a renewal under a namespace the mint record contradicts: present: false, \
         not an error (ADR-017 §3)"
    );

    let renewed = await_call(client.call_with_payload(call_payload(
        "blobs/have",
        json!({ "namespace": "ns-1", "digests": [digest_hex.clone()], "token": token.to_hex() }),
        Some("token:alice"),
    )))
    .await;
    assert_eq!(
        renewed.result.expect("the renewal probe answers"),
        json!({ "present": [true] }),
        "the live row renews on the wire (the parity refusal retired nothing)"
    );
    let renewed_expiry = fleet_pin_row(&dsn, &schema, &key.as_bytes())
        .await
        .expect("the row instrument")
        .expect("the row");
    assert!(
        renewed_expiry.1 > minted_expiry.1,
        "the renewal moved the row's expiry forward (minted {}, renewed {})",
        minted_expiry.1,
        renewed_expiry.1
    );
    assert_eq!(
        renewed_expiry.0, owner,
        "the renewed row is the minting instance's"
    );

    let foreign = await_call(client.call_with_payload(call_payload(
        "blobs/have",
        json!({ "namespace": "ns-1", "digests": [digest_hex.clone()], "token": PinToken::generate().expect("the CSPRNG minted").to_hex() }),
        Some("token:alice"),
    )))
    .await;
    assert_eq!(
        foreign.result.expect("the renewal probe answers"),
        json!({ "present": [false] }),
        "a token this node did not mint: the validity-domain refusal, present: false, not an error"
    );

    tokio::time::sleep(EXPIRY_HORIZON).await;
    let expired = await_call(client.call_with_payload(call_payload(
        "blobs/have",
        json!({ "namespace": "ns-1", "digests": [digest_hex.clone()], "token": token.to_hex() }),
        Some("token:alice"),
    )))
    .await;
    assert_eq!(
        expired.result.expect("the renewal probe answers"),
        json!({ "present": [false] }),
        "a putter paused past the TTL: the row expired, present: false, no renewal"
    );
    let expired_expiry = fleet_pin_row(&dsn, &schema, &key.as_bytes())
        .await
        .expect("the row instrument");
    assert!(
        expired_expiry.is_none() || expired_expiry.map(|row| row.1) == Some(renewed_expiry.1),
        "the expired probe renewed nothing: the row's expiry froze at the last renewal, \
         and the row is gone only when a sweep's maintenance step reaped it"
    );

    fleet_schema_drop(&dsn, &schema).await;
    let _ = std::fs::remove_dir_all(&root);
    let _ = (store_a, store_b, ctx, peer);
}

/// The fleet put through the wire (the hand-over's fleet arm,
/// ADR-010 §4 + ops-surface.md's hand-over contract, on a live
/// fleet pair): the put commits the pin row, the response is
/// `{token, key}`, the guard dropped at the response (pin_count
/// 0 — the row is the signal), the token renews via the renewal
/// form (the row's expiry moves), and the dedup re-put renews the
/// row again through the joint tx's upsert of `(key, owner)`.
#[cfg(feature = "postgres")]
#[tokio::test]
async fn put_fleet_round_trip_hands_the_row_over_and_the_re_put_renews_it() {
    let Some(dsn) = fleet_dsn().await else {
        eprintln!(
            "skipping (no postgres harness server): set ALKBLOBS_PG_HOST/PORT/USER/PASSWORD/DB"
        );
        return;
    };
    let unique = format!(
        "{}_{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos()
    );
    let schema = format!("alkblobs_ops_put_fleet_{unique}");
    let root = std::env::temp_dir().join(format!("alkblobs-ops-fleet-put-{unique}"));
    std::fs::create_dir_all(&root).expect("the temp root created");

    let (store, _peer_store) = open_fleet_pair(&dsn, &schema, &root.join("a"), &root.join("b"))
        .await
        .expect("the fleet pair constructs against the harness server");
    let serving = Arc::new(store);
    let ctx = Arc::new(OpsContext::new(Arc::clone(&serving), OpsConfig::default()));
    let harness = OpsHarness::assemble(vec![have_pair(Arc::clone(&ctx))]);
    harness.with_token("token:alice", identity_named("alice"));
    harness.grant("alice", "ns-1", &["read", "write"]);
    let client = harness
        .spawn_channel_halves(
            vec![put_openable(Arc::clone(&ctx))],
            Some(identity_named("alice")),
        )
        .await;
    let call_client = harness.spawn_call_halves();

    let seed: &[u8] = b"the fleet put's bytes";
    let key = Key::from(Algorithm::GitBlobSha256.derive(seed, seed.len() as u64));
    let wire_hex = wire_hex_of(&key);

    // The first put: the row commits (the joint entry+pin tx), the
    // response carries both fields, and the guard drops at the
    // response — pin_count 0 is the row-is-the-signal observable.
    let (_channel_id, mut send, recv, reply) = open_put(
        &client,
        json!({ "namespace": "ns-1", "key": wire_hex.clone(), "len": seed.len() }),
    )
    .await;
    send.write_all(seed).await.expect("the bytes stream");
    drop(send);
    drop(recv);
    let out = tokio::time::timeout(TEST_TIMEOUT, reply.resolve())
        .await
        .expect("the put resolves")
        .expect("the put succeeds");
    assert_eq!(out["key"], json!(wire_hex), "the echoed key");
    let token = PinToken::from_hex(out["token"].as_str().expect("the token field")).expect("hex");
    assert_eq!(
        serving.gc().pin_count(&key),
        0,
        "the guard dropped at the response: the row's expiry is the only protection"
    );
    let row_put = fleet_pin_row(&dsn, &schema, &key.as_bytes())
        .await
        .expect("the row instrument")
        .expect("the put's pin row");
    assert_eq!(
        row_put.0,
        ctx.fleet_owner().expect("the serving instance's id"),
        "the row's owner is the serving instance"
    );

    // The token renews via the wire's renewal form; the row's
    // expiry moves (the putter's TTL/3 cadence, ADR-012 §2).
    let renewed = await_call(call_client.call_with_payload(call_payload(
        "blobs/have",
        json!({ "namespace": "ns-1", "digests": [wire_hex.clone()], "token": token.to_hex() }),
        Some("token:alice"),
    )))
    .await;
    assert_eq!(
        renewed.result.expect("the renewal probe answers"),
        json!({ "present": [true] }),
        "the put-minted fleet token renews"
    );
    let row_renewed = fleet_pin_row(&dsn, &schema, &key.as_bytes())
        .await
        .expect("the row instrument")
        .expect("the row");
    assert!(
        row_renewed.1 > row_put.1,
        "the renewal moved the row's expiry forward"
    );

    // The dedup re-put (CAS): the joint tx's upsert of (key, owner)
    // is the re-put's renewal form — the row's expiry moves again,
    // a fresh token mints, the putter's first token still maps.
    let (_channel_id, mut send, recv, reply) = open_put(
        &client,
        json!({ "namespace": "ns-1", "key": wire_hex.clone(), "len": seed.len() }),
    )
    .await;
    send.write_all(seed).await.expect("the bytes stream");
    drop(send);
    drop(recv);
    let out = tokio::time::timeout(TEST_TIMEOUT, reply.resolve())
        .await
        .expect("the re-put resolves")
        .expect("the re-put succeeds");
    assert_eq!(
        out["key"],
        json!(wire_hex),
        "CAS dedup: the same echoed key answers"
    );
    let re_token =
        PinToken::from_hex(out["token"].as_str().expect("the token field")).expect("hex");
    assert_ne!(re_token, token, "each hand-over mints its own token");
    assert!(ctx.tokens().holds(&re_token));
    assert!(
        ctx.tokens().holds(&token),
        "the first mapping outlives the re-put"
    );
    let row_after = fleet_pin_row(&dsn, &schema, &key.as_bytes())
        .await
        .expect("the row instrument")
        .expect("the row");
    assert!(
        row_after.1 > row_renewed.1,
        "the re-put's joint-tx upsert renewed the row"
    );

    fleet_schema_drop(&dsn, &schema).await;
    let _ = std::fs::remove_dir_all(&root);
    let _ = (serving, _peer_store, ctx, harness, client, call_client);
}

// ----------------------------------------------------------------
// The ops-e2e-flows capstone: the full lifecycle flows the
// handler tests exercise only in pieces, proven as a whole on
// the wire through this harness.
// ----------------------------------------------------------------

#[cfg(feature = "postgres")]
const EXPIRY_HORIZON: Duration = Duration::from_millis(3000);

/// The fleet pair's short test pin TTL — the widened load-tolerance
/// posture (the original 900 ms collapsed under a loaded-but-
/// unsaturated harness server: a starved cadence tick lands near the
/// expiry and keeps the row briefly alive past a tight horizon; every
/// waiting assertion now polls within its generous window instead,
/// and the TTL + horizon pair leaves the tick whole cadences of
/// margin).
#[cfg(feature = "postgres")]
const PAIR_TTL: Duration = Duration::from_millis(2000);

/// A set-backed liveness source (the rows fixtures' shape, the
/// flows edition): the store consults the same set the converter
/// registers into — the conversion hand-over's landing surface.
#[cfg(feature = "postgres")]
struct FlowLiveSet {
    live: Mutex<BTreeSet<Key>>,
}

#[cfg(feature = "postgres")]
impl Default for FlowLiveSet {
    fn default() -> FlowLiveSet {
        FlowLiveSet {
            live: Mutex::new(BTreeSet::new()),
        }
    }
}

#[cfg(feature = "postgres")]
impl FlowLiveSet {
    fn contains(&self, key: &Key) -> bool {
        self.live.lock().contains(key)
    }
}

#[cfg(feature = "postgres")]
impl crate::facade::LivenessSource for FlowLiveSet {
    fn live_keys(&self) -> Vec<Key> {
        self.live.lock().iter().cloned().collect()
    }
}

/// The namespace binding's converter in the hand-over flow's shape:
/// the registration act puts the digest into the embedder's
/// liveness registry (the registered source the protection hands
/// to).
#[cfg(feature = "postgres")]
struct HandoverConverter {
    live: Arc<FlowLiveSet>,
}

#[cfg(feature = "postgres")]
impl PinConverter for HandoverConverter {
    fn convert(&self, key: &Key) {
        self.live.live.lock().insert(key.clone());
    }
}

#[cfg(all(feature = "postgres", feature = "pg-lo"))]
async fn harness_table_count(dsn: &str, schema: &str, table: &str) -> usize {
    let (client, connection) = tokio_postgres::connect(dsn, tokio_postgres::NoTls)
        .await
        .expect("the instrument's connection");
    tokio::spawn(async move {
        let _ = connection.await;
    });
    let sql = format!(
        "SELECT count(*) FROM \"{}\".\"{}\"",
        schema.replace('"', "\"\""),
        table.replace('"', "\"\"")
    );
    let row = client.query_one(&sql, &[]).await.expect("the count");
    let count: i64 = row.get(0);
    count as usize
}

#[cfg(feature = "postgres")]
async fn renewal_answer(
    call_client: &alkcall::protocol::connection::CallConnection,
    namespace: &str,
    digest_hex: &str,
    token: &PinToken,
) -> Value {
    await_call(call_client.call_with_payload(call_payload(
        "blobs/have",
        json!({
            "namespace": namespace,
            "digests": [digest_hex],
            "token": token.to_hex()
        }),
        Some("token:alice"),
    )))
    .await
    .result
    .expect("the renewal probe answers")
}

#[cfg(any(feature = "mem", feature = "sqlite"))]
async fn open_denied(client: &ChannelClient, op: &str, input: Value) -> ResponseEnvelope {
    tokio::time::timeout(TEST_TIMEOUT, client.call_open_op(op, input))
        .await
        .expect("the open resolves")
}

#[cfg(any(feature = "mem", feature = "sqlite"))]
async fn have_call(
    call_client: &alkcall::protocol::connection::CallConnection,
    auth: &str,
    digests: &[String],
    token: Option<&PinToken>,
) -> Vec<bool> {
    let mut input = json!({ "namespace": "ns-1", "digests": digests });
    if let Some(token) = token {
        input["token"] = json!(token.to_hex());
    }
    let answer =
        await_call(call_client.call_with_payload(call_payload("blobs/have", input, Some(auth))))
            .await;
    match answer.result {
        Ok(out) => out["present"]
            .as_array()
            .expect("present[]")
            .iter()
            .map(|value| value.as_bool().expect("a bool"))
            .collect(),
        Err(error) => panic!("the have probe answers, got {error:?}"),
    }
}

/// The have/need flow, end to end: seed the store via the facade,
/// diff from the client side (the need announcement is the fetch
/// miss — the wire carries only concrete fetch requests), fetch
/// exactly the absent set after the putter fills it, re-diff to
/// all-present. The renewal-cadence boundary rides along (the test
/// plays the embedder's cadence explicitly, ADR-013 §1).
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn the_have_need_flow_diffs_caller_side_and_fetches_exactly_the_need_set() {
    let store = test_store().await;
    let ctx = Arc::new(OpsContext::new(Arc::clone(&store), OpsConfig::default()));
    let harness = OpsHarness::assemble(vec![
        stat_pair(Arc::clone(&ctx)),
        have_pair(Arc::clone(&ctx)),
    ]);
    harness.with_token("token:alice", identity_named("alice"));
    harness.grant("alice", "ns-1", &["read", "write"]);
    let fetch_client = harness
        .spawn_channel_halves(
            vec![
                fetch_openable(Arc::clone(&ctx)),
                put_openable(Arc::clone(&ctx)),
            ],
            Some(identity_named("alice")),
        )
        .await;
    let call_client = harness.spawn_call_halves();

    let (d1_hex, _) = seeded_entry(&store, b"have/need seed one").await;
    let (d2_hex, _) = seeded_entry(&store, b"have/need seed two").await;
    let d3_seed: Vec<u8> = (0u8..32).collect();
    let d3_hex = wire_hex_of_seed(&d3_seed);
    let manifest = vec![d1_hex.clone(), d2_hex.clone(), d3_hex.clone()];

    let round_one = have_call(&call_client, "token:alice", &manifest, None).await;
    assert_eq!(
        round_one,
        vec![true, true, false],
        "the diff is caller-side: the wire answered the digests' presence, \
         the need set fell out of it"
    );
    let need_hex = manifest[2].clone();

    let announcement = open_fetch(&fetch_client, "ns-1", &need_hex, None).await;
    match announcement {
        Err(error) => {
            assert_eq!(
                error.establishment_reason(),
                Some("unknown_resource"),
                "the need announcement is the fetch miss: the wire carried a concrete \
                 fetch request and the absent digest refused"
            );
        }
        Ok(_) => panic!("the absent digest refused, got a channel"),
    }
    let no_need_op = await_call(call_client.call_with_payload(call_payload(
        "blobs/need",
        json!({ "namespace": "ns-1", "digests": manifest }),
        Some("token:alice"),
    )))
    .await;
    assert_eq!(
        error_code(&no_need_op),
        Some("NOT_FOUND"),
        "no need op exists: the diff is caller-side, the wire carries only concrete \
         fetch requests"
    );

    let (_channel_id, mut send, recv, reply) = open_put(
        &fetch_client,
        json!({ "namespace": "ns-1", "key": need_hex.clone(), "len": d3_seed.len() }),
    )
    .await;
    send.write_all(&d3_seed).await.expect("the bytes stream");
    drop(send);
    drop(recv);
    let out = tokio::time::timeout(TEST_TIMEOUT, reply.resolve())
        .await
        .expect("the put resolves")
        .expect("the put succeeds");
    // The response echoes the key in the manifest's own wire form.
    assert_eq!(out["key"], json!(need_hex), "the put filled the need");
    let putter_token = PinToken::from_hex(out["token"].as_str().expect("the token")).expect("hex");
    let renewal = have_call(
        &call_client,
        "token:alice",
        std::slice::from_ref(&need_hex),
        Some(&putter_token),
    )
    .await;
    assert_eq!(renewal, vec![true], "the putter's cadence rode the renewal form (the test drives renewal explicitly — no in-crate renewal worker exists, ADR-013 §1)");

    let round_two = have_call(&call_client, "token:alice", &manifest, None).await;
    assert_eq!(
        round_two,
        vec![true, true, true],
        "re-diffed after the fill"
    );

    let (channel_id, ack, send, mut recv) = open_fetch(&fetch_client, "ns-1", &need_hex, None)
        .await
        .expect("the need-set fetch establishes");
    assert_eq!(
        ack,
        json!({"channel_id": channel_id, "source": "store", "len": d3_seed.len()}),
        "the wire carried a concrete fetch request for exactly the need set"
    );
    let mut received = Vec::new();
    tokio::time::timeout(TEST_TIMEOUT, recv.read_to_end(&mut received))
        .await
        .expect("the stream reads")
        .expect("the stream ends");
    assert_eq!(received, d3_seed, "byte-exact");
    assert_eq!(
        Key::from(Algorithm::GitBlobSha256.derive(&received, received.len() as u64)),
        super::wire::digest_ingress(&need_hex).expect("the wire form decodes"),
        "the consumer's whole-blob hash-check passed"
    );
    drop(send);
}

/// The fleet token lifecycle's success half, end to end against the
/// harness server (env-driven, skipping cleanly server-less): the
/// wire put mints over the committed row, the renewal form renews
/// before expiry (the row's expiry observed moving), the
/// embedder's registration confirms and the row's protection hands
/// to the registered liveness source (the namespace binding's
/// converter), and the row expires naturally — the entry survives
/// on the registered source's protection.
#[cfg(feature = "postgres")]
#[tokio::test]
async fn the_fleet_token_lifecycle_hands_over_to_the_registered_liveness_source() {
    let Some(dsn) = fleet_dsn().await else {
        eprintln!(
            "skipping (no postgres harness server): set ALKBLOBS_PG_HOST/PORT/USER/PASSWORD/DB"
        );
        return;
    };
    let unique = format!(
        "{}_{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos()
    );
    let schema = format!("alkblobs_flows_fleet_success_{unique}");
    let root = std::env::temp_dir().join(format!("alkblobs-flows-fleet-success-{unique}"));
    std::fs::create_dir_all(&root).expect("the temp root created");

    let (store, _peer) = open_fleet_pair(&dsn, &schema, &root.join("a"), &root.join("b"))
        .await
        .expect("the fleet pair constructs against the harness server");
    let serving = Arc::new(store);
    let ctx = Arc::new(OpsContext::new(Arc::clone(&serving), OpsConfig::default()));

    let live = Arc::new(FlowLiveSet::default());
    let _registration = serving
        .register_liveness_source(crate::facade::LivenessRegistration::InProcess(
            Arc::clone(&live) as Arc<dyn crate::facade::LivenessSource>,
        ))
        .expect("the embedder's liveness registration");
    let converter = Arc::new(HandoverConverter {
        live: Arc::clone(&live),
    });
    ctx.bind_converter("ns-1", converter as Arc<dyn PinConverter>);

    let harness = OpsHarness::assemble(vec![have_pair(Arc::clone(&ctx))]);
    harness.with_token("token:alice", identity_named("alice"));
    harness.grant("alice", "ns-1", &["read", "write"]);
    let client = harness
        .spawn_channel_halves(
            vec![put_openable(Arc::clone(&ctx))],
            Some(identity_named("alice")),
        )
        .await;
    let call_client = harness.spawn_call_halves();

    let seed: &[u8] = b"the fleet lifecycle put";
    let key = Key::from(Algorithm::GitBlobSha256.derive(seed, seed.len() as u64));
    let wire_hex = wire_hex_of(&key);

    let (_channel_id, mut send, recv, reply) = open_put(
        &client,
        json!({ "namespace": "ns-1", "key": wire_hex.clone(), "len": seed.len() }),
    )
    .await;
    send.write_all(seed).await.expect("the bytes stream");
    drop(send);
    drop(recv);
    let out = tokio::time::timeout(TEST_TIMEOUT, reply.resolve())
        .await
        .expect("the put resolves")
        .expect("the put succeeds");
    assert_eq!(out["key"], json!(wire_hex));
    let token = PinToken::from_hex(out["token"].as_str().expect("the token field")).expect("hex");

    let owner = ctx.fleet_owner().expect("the serving instance's id");
    let row_minted = fleet_pin_row(&dsn, &schema, &key.as_bytes())
        .await
        .expect("the row instrument")
        .expect("the put's pin row");
    assert_eq!(
        row_minted.0, owner,
        "the row's owner is the serving instance"
    );
    assert_eq!(
        serving.gc().pin_count(&key),
        0,
        "the guard dropped at the response: the row's expiry is the protection"
    );

    assert_eq!(
        renewal_answer(&call_client, "ns-1", &wire_hex, &token).await,
        json!({ "present": [true] }),
        "renewed before expiry"
    );
    let row_renewed_1 = fleet_pin_row(&dsn, &schema, &key.as_bytes())
        .await
        .expect("the row instrument")
        .expect("the row");
    assert!(
        row_renewed_1.1 > row_minted.1,
        "the renewal moved the row's expiry forward"
    );
    assert_eq!(
        renewal_answer(&call_client, "ns-1", &wire_hex, &token).await,
        json!({ "present": [true] })
    );
    let row_renewed_2 = fleet_pin_row(&dsn, &schema, &key.as_bytes())
        .await
        .expect("the row instrument")
        .expect("the row");
    assert!(
        row_renewed_2.1 > row_renewed_1.1,
        "the cadence moved the expiry again (the test plays the embedder's TTL/3 role)"
    );

    assert!(
        ctx.confirm("ns-1", &token),
        "the embedder's registration confirms: the namespace binding's converter ran"
    );
    assert!(
        !ctx.tokens().holds(&token),
        "conversion-confirmed retires the mapping"
    );
    assert!(
        live.contains(&key),
        "the converter registered the key into the embedder's liveness registry"
    );
    assert_eq!(
        renewal_answer(&call_client, "ns-1", &wire_hex, &token).await,
        json!({ "present": [false] }),
        "the row's protection handed to the registered source: the token is spent, \
         the probe answers present: false, never an error"
    );
    assert!(
        serving.has(&key.as_bytes()).await.expect("the has probe"),
        "the entry stands after the registration confirms"
    );

    tokio::time::sleep(EXPIRY_HORIZON).await;
    let staged = serving.sweep().await.expect("sweeps are never errors");
    assert_eq!(staged.aborted, None);
    let row_after_staging = fleet_pin_row(&dsn, &schema, &key.as_bytes())
        .await
        .expect("the row instrument");
    assert!(
        row_after_staging.is_none(),
        "the expired row reaped by the sweep's maintenance step"
    );
    let executed = serving.sweep().await.expect("sweeps are never errors");
    assert_eq!(
        (executed.deleted, executed.aborted),
        (0, None),
        "the registered source's protection held: nothing deleted"
    );
    assert!(
        serving.has(&key.as_bytes()).await.expect("the has probe"),
        "the entry survives on the registered liveness source"
    );
    assert!(live.contains(&key), "the source carried the key throughout");

    fleet_schema_drop(&dsn, &schema).await;
    let _ = std::fs::remove_dir_all(&root);
    let _ = (
        serving,
        ctx,
        harness,
        client,
        call_client,
        _peer,
        _registration,
    );
}

/// The fleet token lifecycle's failure half against the harness
/// server: pause past TTL → the renewal probe answers
/// `present: false` → the sweeper reaps the row and the sweep
/// deletes the unprotected entry → the re-put backstop (the
/// digest re-offered; CAS makes the re-put idempotent) recovers
/// byte-identically. The race resolves to a re-put, never to
/// silent loss (ADR-010 §4's expiry semantics verbatim, on the
/// wire).
#[cfg(feature = "postgres")]
#[tokio::test]
async fn the_paused_fleet_token_expires_reaps_and_the_reput_backstop_never_loses_silently() {
    let Some(dsn) = fleet_dsn().await else {
        eprintln!(
            "skipping (no postgres harness server): set ALKBLOBS_PG_HOST/PORT/USER/PASSWORD/DB"
        );
        return;
    };
    let unique = format!(
        "{}_{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos()
    );
    let schema = format!("alkblobs_flows_fleet_failure_{unique}");
    let root = std::env::temp_dir().join(format!("alkblobs-flows-fleet-failure-{unique}"));
    std::fs::create_dir_all(&root).expect("the temp root created");

    let (store, _peer) = open_fleet_pair(&dsn, &schema, &root.join("a"), &root.join("b"))
        .await
        .expect("the fleet pair constructs against the harness server");
    let serving = Arc::new(store);
    let ctx = Arc::new(OpsContext::new(Arc::clone(&serving), OpsConfig::default()));
    let _registration = serving
        .register_liveness_source(crate::facade::LivenessRegistration::InProcess(Arc::new(
            FlowLiveSet::default(),
        )
            as Arc<dyn crate::facade::LivenessSource>))
        .expect("the embedder's liveness registration");

    let harness = OpsHarness::assemble(vec![have_pair(Arc::clone(&ctx))]);
    harness.with_token("token:alice", identity_named("alice"));
    harness.grant("alice", "ns-1", &["read", "write"]);
    let client = harness
        .spawn_channel_halves(
            vec![
                put_openable(Arc::clone(&ctx)),
                fetch_openable(Arc::clone(&ctx)),
            ],
            Some(identity_named("alice")),
        )
        .await;
    let call_client = harness.spawn_call_halves();

    let seed: Vec<u8> = (0u8..48).map(|i| i % 31).collect();
    let key = Key::from(Algorithm::GitBlobSha256.derive(&seed, seed.len() as u64));
    let wire_hex = wire_hex_of(&key);

    let (_channel_id, mut send, recv, reply) = open_put(
        &client,
        json!({ "namespace": "ns-1", "key": wire_hex.clone(), "len": seed.len() }),
    )
    .await;
    send.write_all(&seed).await.expect("the bytes stream");
    drop(send);
    drop(recv);
    let out = tokio::time::timeout(TEST_TIMEOUT, reply.resolve())
        .await
        .expect("the put resolves")
        .expect("the put succeeds");
    let token = PinToken::from_hex(out["token"].as_str().expect("the token field")).expect("hex");
    let row_put = fleet_pin_row(&dsn, &schema, &key.as_bytes())
        .await
        .expect("the row instrument")
        .expect("the put's pin row");

    // The putter's pause past TTL — the load-tolerance posture: the
    // wait polls the **row instrument** until the expiry is past
    // instead of sampling once at a fixed wall time (a starved
    // harness server stretches everything; a poll on the have probe
    // itself would feed the row it watches — every present: true
    // answer is a renewal). Then the single have call asserts the
    // expired answer.
    let pause_deadline = std::time::Instant::now() + Duration::from_secs(10);
    loop {
        let row = fleet_pin_row(&dsn, &schema, &key.as_bytes())
            .await
            .expect("the row instrument")
            .expect("the row stands until a sweep's maintenance reaps it");
        if row.1 <= crate::pg_common::time_to_nanos(std::time::SystemTime::now()) {
            break;
        }
        assert!(
            std::time::Instant::now() < pause_deadline,
            "the putter's pause past TTL: the row's expiry is past"
        );
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
    let expired = await_call(call_client.call_with_payload(call_payload(
        "blobs/have",
        json!({ "namespace": "ns-1", "digests": [wire_hex.clone()], "token": token.to_hex() }),
        Some("token:alice"),
    )))
    .await;
    assert_eq!(
        expired.result.expect("the renewal probe answers"),
        json!({ "present": [false] }),
        "the putter paused past TTL: present: false, no renewal occurred"
    );
    let row_after_probe = fleet_pin_row(&dsn, &schema, &key.as_bytes())
        .await
        .expect("the row instrument");
    assert_eq!(
        row_after_probe.map(|row| row.1),
        Some(row_put.1),
        "the expired probe renewed nothing: the row's expiry froze at the last write"
    );

    let staged = serving.sweep().await.expect("sweeps are never errors");
    assert_eq!(staged.aborted, None);
    assert_eq!(
        staged.candidates_staged, 1,
        "the unprotected entry staged for the delete window"
    );
    assert!(
        fleet_pin_row(&dsn, &schema, &key.as_bytes())
            .await
            .expect("the row instrument")
            .is_none(),
        "the sweeper reaped the expired row (the maintenance step)"
    );
    let executed = serving.sweep().await.expect("sweeps are never errors");
    assert_eq!(
        (executed.deleted, executed.aborted),
        (1, None),
        "the execution deleted the unprotected entry exactly once"
    );
    assert!(
        !serving.has(&key.as_bytes()).await.expect("the has probe"),
        "the entry did not survive the sweep"
    );

    let (_channel_id, mut send, recv, reply) = open_put(
        &client,
        json!({ "namespace": "ns-1", "key": wire_hex.clone(), "len": seed.len() }),
    )
    .await;
    send.write_all(&seed).await.expect("the bytes stream");
    drop(send);
    drop(recv);
    let out = tokio::time::timeout(TEST_TIMEOUT, reply.resolve())
        .await
        .expect("the re-put resolves")
        .expect("the re-put succeeds");
    assert_eq!(
        out["key"],
        json!(wire_hex),
        "CAS dedup: the re-offered key recovered the same address"
    );
    let re_token =
        PinToken::from_hex(out["token"].as_str().expect("the token field")).expect("hex");
    let row_recovered = fleet_pin_row(&dsn, &schema, &key.as_bytes())
        .await
        .expect("the row instrument")
        .expect("the re-put's pin row");
    assert_eq!(
        row_recovered.0,
        ctx.fleet_owner().expect("the serving instance's id"),
        "the recovery restored the pool's own protection"
    );
    let mut renewal;
    let renew_deadline = std::time::Instant::now() + Duration::from_millis(1500);
    loop {
        renewal = await_call(call_client.call_with_payload(call_payload(
            "blobs/have",
            json!({ "namespace": "ns-1", "digests": [wire_hex.clone()], "token": re_token.to_hex() }),
            Some("token:alice"),
        )))
        .await
        .result
        .expect("the renewal probe answers");
        if renewal == json!({ "present": [true] }) {
            break;
        }
        assert!(
            std::time::Instant::now() < renew_deadline,
            "the recovery's token renews (the closed-degradation fold on a transient \
             harness error re-asks within the TTL cadence before it counts)"
        );
        tokio::time::sleep(Duration::from_millis(250)).await;
    }
    assert_eq!(
        renewal,
        json!({ "present": [true] }),
        "the recovery's token renews (the closed-degradation fold on a transient \
         harness error re-asks within the TTL cadence before it counts)"
    );

    let (channel_id, ack, send, mut recv) = open_fetch(&client, "ns-1", &wire_hex, None)
        .await
        .expect("the recovered entry fetches");
    assert_eq!(
        ack,
        json!({ "channel_id": channel_id, "source": "store", "len": seed.len() }),
        "the recovered entry serves: never a silent loss"
    );
    let mut received = Vec::new();
    tokio::time::timeout(TEST_TIMEOUT, recv.read_to_end(&mut received))
        .await
        .expect("the stream reads")
        .expect("the stream ends");
    assert_eq!(received, seed, "the recovery is byte-identical");
    drop(send);

    fleet_schema_drop(&dsn, &schema).await;
    let _ = std::fs::remove_dir_all(&root);
    let _ = (
        serving,
        ctx,
        harness,
        client,
        call_client,
        _peer,
        _registration,
    );
}

/// The foreign-token refusal: a token minted by node A presented to
/// node B (a second fleet instance's ops module over the same pool)
/// answers `present: false`, not an error — the validity domain is
/// the minting node (ADR-012 §2); B's own mint over the same pool
/// renews.
#[cfg(feature = "postgres")]
#[tokio::test]
async fn the_foreign_token_refusal_is_present_false_not_an_error() {
    let Some(dsn) = fleet_dsn().await else {
        eprintln!(
            "skipping (no postgres harness server): set ALKBLOBS_PG_HOST/PORT/USER/PASSWORD/DB"
        );
        return;
    };
    let unique = format!(
        "{}_{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos()
    );
    let schema = format!("alkblobs_flows_foreign_token_{unique}");
    let root = std::env::temp_dir().join(format!("alkblobs-flows-foreign-token-{unique}"));
    std::fs::create_dir_all(&root).expect("the temp root created");

    let (store_a, store_b) = open_fleet_pair(&dsn, &schema, &root.join("a"), &root.join("b"))
        .await
        .expect("the fleet pair constructs against the harness server");
    let node_a = Arc::new(store_a);
    let node_b = Arc::new(store_b);
    let ctx_a = Arc::new(OpsContext::new(Arc::clone(&node_a), OpsConfig::default()));
    let ctx_b = Arc::new(OpsContext::new(Arc::clone(&node_b), OpsConfig::default()));

    let harness_a = OpsHarness::assemble(vec![have_pair(Arc::clone(&ctx_a))]);
    harness_a.with_token("token:peer", identity_named("peer"));
    harness_a.grant("peer", "ns-1", &["read"]);
    let call_a = harness_a.spawn_call_halves();
    let harness_b = OpsHarness::assemble(vec![have_pair(Arc::clone(&ctx_b))]);
    harness_b.with_token("token:peer", identity_named("peer"));
    harness_b.grant("peer", "ns-1", &["read"]);
    let call_b = harness_b.spawn_call_halves();

    let seed: &[u8] = b"the foreign token's entry";
    let (key, _pin) = node_a
        .put_as(
            Algorithm::GitBlobSha256,
            Some(seed.len() as u64),
            std::io::Cursor::new(seed),
        )
        .await
        .expect("the put commits the pin row");
    let digest_hex = wire_hex_of(&key);
    let owner_a = ctx_a.fleet_owner().expect("node A's instance id");
    let token_a = ctx_a
        .mint_fleet("ns-1", key.clone(), &owner_a)
        .expect("node A mints over its own row");
    drop(_pin);

    let (_, pin_b) = node_b
        .put_as(
            Algorithm::GitBlobSha256,
            Some(seed.len() as u64),
            std::io::Cursor::new(seed),
        )
        .await
        .expect("node B's re-put composes its own pin row");
    let owner_b = ctx_b.fleet_owner().expect("node B's instance id");
    let token_b = ctx_b
        .mint_fleet("ns-1", key.clone(), &owner_b)
        .expect("node B mints over its own row");
    drop(pin_b);

    let foreign = await_call(call_b.call_with_payload(call_payload(
        "blobs/have",
        json!({ "namespace": "ns-1", "digests": [digest_hex.clone()], "token": token_a.to_hex() }),
        Some("token:peer"),
    )))
    .await;
    assert_eq!(
        foreign.result.expect("the renewal probe answers"),
        json!({ "present": [false] }),
        "a token minted by node A presented to node B: present: false, not an error \
         (the validity domain is the minting node, ADR-012 §2)"
    );
    let reverse = await_call(call_a.call_with_payload(call_payload(
        "blobs/have",
        json!({ "namespace": "ns-1", "digests": [digest_hex.clone()], "token": token_b.to_hex() }),
        Some("token:peer"),
    )))
    .await;
    assert_eq!(
        reverse.result.expect("the renewal probe answers"),
        json!({ "present": [false] }),
        "the refusal is symmetric: B's token is foreign to A"
    );
    let own = await_call(call_b.call_with_payload(call_payload(
        "blobs/have",
        json!({ "namespace": "ns-1", "digests": [digest_hex.clone()], "token": token_b.to_hex() }),
        Some("token:peer"),
    )))
    .await;
    assert_eq!(
        own.result.expect("the renewal probe answers"),
        json!({ "present": [true] }),
        "node B's own mint over the same pool renews"
    );

    fleet_schema_drop(&dsn, &schema).await;
    let _ = std::fs::remove_dir_all(&root);
    let _ = (node_a, node_b, ctx_a, ctx_b, harness_a, harness_b, call_a);
}

/// The non-fleet token lifecycle, server-less: the wire put
/// custodially mints (the registry holds the guard), have-present
/// answers from the custody, the embedder's registration confirms
/// and the guard converts (the namespace binding's converter), and
/// the token retires — with the entry standing after conversion.
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn the_non_fleet_lifecycle_custody_confirmation_conversion_and_retirement() {
    let store = test_store().await;
    let ctx = Arc::new(OpsContext::new(Arc::clone(&store), OpsConfig::default()));
    let harness = OpsHarness::assemble(vec![have_pair(Arc::clone(&ctx))]);
    harness.with_token("token:alice", identity_named("alice"));
    harness.grant("alice", "ns-1", &["read", "write"]);
    let client = harness
        .spawn_channel_halves(
            vec![put_openable(Arc::clone(&ctx))],
            Some(identity_named("alice")),
        )
        .await;
    let call_client = harness.spawn_call_halves();

    let seed: &[u8] = b"the non-fleet lifecycle put";
    let key = Key::from(Algorithm::GitBlobSha256.derive(seed, seed.len() as u64));
    let key_hex = wire_hex_of(&key);
    let (_channel_id, mut send, recv, reply) = open_put(
        &client,
        json!({ "namespace": "ns-1", "key": key_hex.clone(), "len": seed.len() }),
    )
    .await;
    send.write_all(seed).await.expect("the bytes stream");
    drop(send);
    drop(recv);
    let out = tokio::time::timeout(TEST_TIMEOUT, reply.resolve())
        .await
        .expect("the put resolves")
        .expect("the put succeeds");
    let echoed_key = out["key"].as_str().expect("the key field").to_owned();
    let token = PinToken::from_hex(out["token"].as_str().expect("the token field")).expect("hex");
    assert_eq!(
        echoed_key, key_hex,
        "the put response's key echo is the offered key's wire hex"
    );

    assert_eq!(
        store.gc().pin_count(&key),
        1,
        "the registry holds the guard (the custodial form)"
    );
    assert_eq!(
        have_call(
            &call_client,
            "token:alice",
            std::slice::from_ref(&key_hex),
            Some(&token)
        )
        .await,
        vec![true],
        "have-present answers from the custody (nothing expires)"
    );

    let converted = Arc::new(super::tests::RecordingConverter {
        converted: Mutex::new(Vec::new()),
    });
    ctx.bind_converter("ns-1", converted.clone());
    assert!(
        ctx.confirm("ns-1", &token),
        "the embedder's registration confirms: the guard converts through the \
         ordered-step primitive"
    );
    assert_eq!(
        store.gc().pin_count(&key),
        0,
        "the conversion consumed the held guard"
    );
    assert!(
        !ctx.tokens().holds(&token),
        "conversion-confirmed retires the mapping"
    );
    assert_eq!(
        converted.captured(),
        vec![key.clone()],
        "the converter received the digest"
    );
    assert_eq!(
        have_call(
            &call_client,
            "token:alice",
            std::slice::from_ref(&key_hex),
            Some(&token)
        )
        .await,
        vec![false],
        "the retired token's probe answers present: false, never an error"
    );
    assert_eq!(
        have_call(
            &call_client,
            "token:alice",
            std::slice::from_ref(&key_hex),
            None
        )
        .await,
        vec![true],
        "the pure probe answers: the entry stands on the registered source's \
         protection (the hand-over contract's have-present observable)"
    );
}

/// The ACL matrix, end to end: closed-by-default (the unlisted
/// namespace denies read AND write); the read/write split (the
/// read-granted identity fetches/stats/haves but cannot put; the
/// write-granted identity puts and neither it nor a peer granted
/// elsewhere can fetch); delete only under the internal authority
/// context.
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn the_acl_matrix_closed_by_default_the_read_write_split_and_internal_only_delete() {
    let store = test_store().await;
    let ctx = Arc::new(OpsContext::new(Arc::clone(&store), OpsConfig::default()));
    let harness = OpsHarness::assemble_registrations(vec![
        OpsHarnessRegistration::pair(stat_pair(Arc::clone(&ctx))),
        OpsHarnessRegistration::pair(have_pair(Arc::clone(&ctx))),
        OpsHarnessRegistration::pair(delete_pair(Arc::clone(&ctx)))
            .with_composition_authority(CompositionAuthority::new("blob-operator", [])),
        OpsHarnessRegistration::pair(composer_pair())
            .with_scoped_env(ScopedPeerEnv::new(["blobs/delete"])),
    ]);
    for (token, id) in [
        ("token:reader", "reader"),
        ("token:writer", "writer"),
        ("token:other", "other"),
        ("token:stranger", "stranger"),
    ] {
        harness.with_token(token, identity_named(id));
    }
    harness.grant("reader", "ns-1", &["read"]);
    harness.grant("writer", "ns-1", &["write"]);
    harness.grant("other", "ns-2", &["read"]);
    let call_client = harness.spawn_call_halves();
    let reader_client = harness
        .spawn_channel_halves(
            vec![
                put_openable(Arc::clone(&ctx)),
                fetch_openable(Arc::clone(&ctx)),
            ],
            Some(identity_named("reader")),
        )
        .await;
    let writer_client = harness
        .spawn_channel_halves(
            vec![
                put_openable(Arc::clone(&ctx)),
                fetch_openable(Arc::clone(&ctx)),
            ],
            Some(identity_named("writer")),
        )
        .await;
    let stranger_client = harness
        .spawn_channel_halves(
            vec![
                put_openable(Arc::clone(&ctx)),
                fetch_openable(Arc::clone(&ctx)),
            ],
            Some(identity_named("stranger")),
        )
        .await;
    let other_client = harness
        .spawn_channel_halves(
            vec![fetch_openable(Arc::clone(&ctx))],
            Some(identity_named("other")),
        )
        .await;

    let seed: &[u8] = b"the ACL matrix's entry";
    let (key, _seed_pin) = store
        .put_as(
            Algorithm::GitBlobSha256,
            Some(seed.len() as u64),
            std::io::Cursor::new(seed),
        )
        .await
        .expect("seed put lands");
    let digest_hex = wire_hex_of(&key);

    assert_eq!(
        error_code(
            &await_call(call_client.call_with_payload(call_payload(
                "blobs/stat",
                json!({ "namespace": "ns-unlisted", "digest": digest_hex.clone() }),
                Some("token:stranger"),
            )))
            .await
        ),
        Some("FORBIDDEN"),
        "closed-by-default: the unlisted namespace denies read (stat)"
    );
    assert_eq!(
        error_code(
            &await_call(call_client.call_with_payload(call_payload(
                "blobs/have",
                json!({ "namespace": "ns-unlisted", "digests": [digest_hex.clone()] }),
                Some("token:stranger"),
            )))
            .await
        ),
        Some("FORBIDDEN"),
        "closed-by-default: the unlisted namespace denies read (have)"
    );
    assert_eq!(
        error_code(
            &open_denied(
                &stranger_client,
                FETCH_OP_ID,
                json!({ "namespace": "ns-unlisted", "digest": digest_hex.clone() }),
            )
            .await
        ),
        Some("FORBIDDEN"),
        "closed-by-default: the unlisted namespace denies read (fetch)"
    );
    assert_eq!(
        error_code(
            &open_denied(
                &stranger_client,
                PUT_OP_ID,
                json!({ "namespace": "ns-unlisted", "key": wire_hex_of(&key), "len": 4 }),
            )
            .await
        ),
        Some("FORBIDDEN"),
        "closed-by-default: the unlisted namespace denies write"
    );

    let stat = await_call(call_client.call_with_payload(call_payload(
        "blobs/stat",
        json!({ "namespace": "ns-1", "digest": digest_hex.clone() }),
        Some("token:reader"),
    )))
    .await;
    assert_eq!(
        stat.result.unwrap(),
        json!({ "len": seed.len() }),
        "the read-granted identity stats"
    );
    assert_eq!(
        have_call(
            &call_client,
            "token:reader",
            std::slice::from_ref(&digest_hex),
            None
        )
        .await,
        vec![true],
        "the read-granted identity haves"
    );
    let (_channel_id, ack, send, mut recv) = open_fetch(&reader_client, "ns-1", &digest_hex, None)
        .await
        .expect("the read-granted identity fetches");
    assert_eq!(ack["source"], json!("store"));
    let mut received = Vec::new();
    tokio::time::timeout(TEST_TIMEOUT, recv.read_to_end(&mut received))
        .await
        .expect("the stream reads")
        .expect("the stream ends");
    assert_eq!(received, seed, "the read-granted fetch is byte-exact");
    assert_eq!(
        Key::from(Algorithm::GitBlobSha256.derive(&received, received.len() as u64)),
        key,
        "the consumer's whole-blob hash-check passed"
    );
    drop(send);
    assert_eq!(
        error_code(
            &open_denied(
                &reader_client,
                PUT_OP_ID,
                json!({ "namespace": "ns-1", "len": 4 }),
            )
            .await
        ),
        Some("FORBIDDEN"),
        "the read grant is not the write grant: the read-granted identity cannot put"
    );

    let writer_seed: &[u8] = b"the write-granted put";
    let writer_key =
        Key::from(Algorithm::GitBlobSha256.derive(writer_seed, writer_seed.len() as u64));
    let (_channel_id, mut send, recv, reply) = open_put(
        &writer_client,
        json!({ "namespace": "ns-1", "key": wire_hex_of(&writer_key), "len": writer_seed.len() }),
    )
    .await;
    send.write_all(writer_seed).await.expect("the bytes stream");
    drop(send);
    drop(recv);
    let out = tokio::time::timeout(TEST_TIMEOUT, reply.resolve())
        .await
        .expect("the put resolves")
        .expect("the write-granted identity puts");
    assert_eq!(out["key"], json!(wire_hex_of(&writer_key)));
    assert_eq!(
        error_code(
            &open_denied(
                &writer_client,
                FETCH_OP_ID,
                json!({ "namespace": "ns-1", "digest": digest_hex.clone() }),
            )
            .await
        ),
        Some("FORBIDDEN"),
        "the write grant is not the read grant: the write-granted identity cannot fetch"
    );
    assert_eq!(
        error_code(
            &open_denied(
                &other_client,
                FETCH_OP_ID,
                json!({ "namespace": "ns-1", "digest": digest_hex.clone() }),
            )
            .await
        ),
        Some("FORBIDDEN"),
        "a read-only peer of another namespace cannot fetch this namespace: grants \
         are per-namespace (closed-by-default)"
    );

    let external = await_call(call_client.call_with_payload(call_payload(
        "blobs/delete",
        json!({ "namespace": "ns-1", "digests": [digest_hex.clone()] }),
        Some("token:stranger"),
    )))
    .await;
    assert_eq!(
        error_code(&external),
        Some("NOT_FOUND"),
        "delete is not callable from the wire (the internal visibility)"
    );
    let (victim_hex, victim_key) = seeded_entry(&store, b"the deleted entry").await;
    let composed = await_call(call_client.call_with_payload(call_payload(
        "blobs/compose-delete",
        json!({ "namespace": "ns-1", "digests": [victim_hex.clone()] }),
        Some("token:stranger"),
    )))
    .await;
    assert_eq!(
        composed.result.unwrap(),
        json!({ "deleted": [victim_hex.clone()] }),
        "delete ran under the internal authority context only"
    );
    assert!(
        !store.has(&victim_key.as_bytes()).await.unwrap_or(true),
        "the internal delete removed the entry"
    );
}

/// The re-routing posture's serving half (ADR-008 §3): a large
/// (pg-lo) entry served through `blobs/fetch` from the storage
/// node's dual-tier fleet store — the standard channel op, no
/// fleet-specific op (the module supports the shape without
/// change). Env-driven, skipping cleanly server-less.
#[cfg(all(feature = "postgres", feature = "pg-lo"))]
#[tokio::test]
async fn the_rerouting_serving_half_serves_a_large_entry_through_the_standard_fetch() {
    let Some(dsn) = fleet_dsn().await else {
        eprintln!(
            "skipping (no postgres harness server): set ALKBLOBS_PG_HOST/PORT/USER/PASSWORD/DB"
        );
        return;
    };
    let unique = format!(
        "{}_{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos()
    );
    let kv_schema = format!("alkblobs_flows_rerouting_kv_{unique}");
    let lo_schema = format!("alkblobs_flows_rerouting_lo_{unique}");
    let opts = |schema: String| crate::PgOpts {
        schema,
        ..crate::PgOpts::default()
    };
    let storage = Arc::new(
        crate::Store::dual_tier_postgres_pglo_fleet(
            &dsn,
            opts(kv_schema.clone()),
            &dsn,
            opts(lo_schema.clone()),
            1024,
            std::time::Duration::ZERO,
            PAIR_TTL,
        )
        .await
        .expect("the consolidation fleet store constructs against the harness server"),
    );
    let ctx = Arc::new(OpsContext::new(Arc::clone(&storage), OpsConfig::default()));
    let harness = OpsHarness::assemble(vec![]);
    harness.with_token("token:alice", identity_named("alice"));
    harness.grant("alice", "ns-1", &["read"]);
    let client = harness
        .spawn_channel_halves(
            vec![fetch_openable(Arc::clone(&ctx))],
            Some(identity_named("alice")),
        )
        .await;

    let large: Vec<u8> = (0u32..4096).map(|i| (i % 251) as u8).collect();
    let (key, pin) = storage
        .put_as(
            Algorithm::GitBlobSha256,
            Some(large.len() as u64),
            std::io::Cursor::new(large.as_slice()),
        )
        .await
        .expect("the large put publishes");
    drop(pin);
    let digest_hex = wire_hex_of(&key);

    let kv_rows = harness_table_count(&dsn, &kv_schema, "blobs").await;
    let lo_rows = harness_table_count(&dsn, &lo_schema, "lo_entries").await;
    assert_eq!(
        (kv_rows, lo_rows),
        (0, 1),
        "the over-threshold entry landed on the pg-lo tier (kv 0 rows, large 1): \
         the re-routing storage node's dual-tier shape"
    );

    assert_eq!(FETCH_OP_ID, "channels/blobs/sub");
    assert_eq!(BLOBS_CHANNEL_ALPN, "alk/blobs");
    let (channel_id, ack, send, mut recv) = open_fetch(&client, "ns-1", &digest_hex, None)
        .await
        .expect("the large entry fetches through the standard channel op");
    assert_eq!(
        ack,
        json!({ "channel_id": channel_id, "source": "store", "len": large.len() }),
        "the ack names the store path and the expected whole"
    );
    let mut received = Vec::new();
    tokio::time::timeout(TEST_TIMEOUT, recv.read_to_end(&mut received))
        .await
        .expect("the stream reads")
        .expect("the stream ends");
    assert_eq!(received, large, "the pg-lo entry served byte-exact");
    assert_eq!(
        Key::from(Algorithm::GitBlobSha256.derive(&received, received.len() as u64)),
        key,
        "the consumer's whole-blob hash-check passed"
    );
    drop(send);

    tokio::time::sleep(EXPIRY_HORIZON).await;
    storage
        .delete(&key.as_bytes())
        .await
        .expect("the serving node's operator delete past the row's expiry");
    assert!(
        !storage.has(&key.as_bytes()).await.expect("the has probe"),
        "the post-serving cleanup removed the entry"
    );
    assert_eq!(
        harness_table_count(&dsn, &lo_schema, "lo_entries").await,
        0,
        "zero LO residue on the shared harness database (delete is one tx: \
         lo_unlink + companion-row delete)"
    );

    fleet_schema_drop(&dsn, &kv_schema).await;
    fleet_schema_drop(&dsn, &lo_schema).await;
    let _ = (ctx, harness, client);
}

// ----------------------------------------------------------------
// D-2's malformed-payload sweep (review-001 — the op handlers' error
// arms): the wire schema gate over every op, the post-schema handler
// ingress family, the establishers' form checks, the fetch pump's
// silent-return arms, the put's torn-stream settle, and the
// store-core failures the ops error family surfaces.
// ----------------------------------------------------------------

/// A one-shot `BidiStreamSource` for the direct pump invocations: the
/// canned accept result (a pre-wired stream pair, taken once, or the
/// closed shape) answers immediately, bypassing the channel wrapper —
/// the pump's silent-return arms are exercisable without the full
/// wire.
struct PumpSource {
    accept: parking_lot::Mutex<Option<BiStream>>,
}

impl PumpSource {
    fn closed() -> PumpSource {
        PumpSource {
            accept: parking_lot::Mutex::new(None),
        }
    }

    fn with(server: BiStream) -> PumpSource {
        PumpSource {
            accept: parking_lot::Mutex::new(Some(server)),
        }
    }
}

#[async_trait::async_trait]
impl BidiStreamSource for PumpSource {
    async fn accept_bi(&self) -> Result<BiStream, StreamError> {
        match self.accept.lock().take() {
            Some(stream) => Ok(stream),
            None => Err(StreamError::StreamClosed),
        }
    }

    async fn open_bi(&self) -> Result<BiStream, StreamError> {
        Err(StreamError::StreamClosed)
    }

    fn remote_addr(&self) -> Option<std::net::SocketAddr> {
        None
    }

    fn close(&self, _code: u32, _reason: &str) {}
}

fn pump_conn(server: BiStream) -> Connection {
    Connection::from_source(
        PumpSource::with(server),
        BLOBS_CHANNEL_ALPN.as_bytes().to_vec(),
    )
}

/// A dummy [`Connection`] for direct handler invocations whose input
/// the handler rejects before any data-plane touch (an unconnected end
/// never matters — the guard rejects first).
fn put_conn() -> Connection {
    let (_, server_end) = tokio::io::duplex(4096);
    Connection::from_bidi(server_end, BLOBS_CHANNEL_ALPN.as_bytes().to_vec(), None)
}

/// A pre-wired duplex pair for direct pump invocations: the server
/// half rides into the pump's [`Connection`], the client end stays
/// with the test — dropping the whole client end tears the pump's
/// writes with `BrokenPipe` immediately (the mid-service
/// silent-return shapes; a half-dropped end would only fill the
/// buffer, so the whole end goes).
fn pump_stream_pair() -> (BiStream, tokio::io::DuplexStream) {
    let (client_end, server_end) = tokio::io::duplex(1024 * 1024);
    let (server_read, server_write) = tokio::io::split(server_end);
    (BiStream::from_joined(server_read, server_write), client_end)
}

#[cfg(feature = "mem")]
#[cfg(unix)]
fn chmod_000(path: &std::path::Path) {
    use std::os::unix::fs::PermissionsExt;
    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o000)).expect("chmod 000");
}

#[cfg(feature = "mem")]
#[cfg(unix)]
fn chmod_755(path: &std::path::Path) {
    use std::os::unix::fs::PermissionsExt;
    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).expect("chmod 755");
}

/// The wire schema gate is the first rejection for every op: each of
/// the five ops driven with malformed/missing/over-bound payloads
/// answers `INVALID_INPUT` before any handler or store contact (the
/// sweep over `blobs/stat`, `blobs/have`, `blobs/fetch`, `blobs/put`,
/// and `blobs/delete` — whose external discovery is the NOT_FOUND
/// visibility form and whose internal composition still validates).
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn the_malformed_payload_wire_sweep_rejects_every_op_at_the_schema_gate() {
    let store = test_store().await;
    let ctx = Arc::new(OpsContext::new(Arc::clone(&store), OpsConfig::default()));
    let harness = OpsHarness::assemble_registrations(vec![
        OpsHarnessRegistration::pair(stat_pair(Arc::clone(&ctx))),
        OpsHarnessRegistration::pair(have_pair(Arc::clone(&ctx))),
        OpsHarnessRegistration::pair(delete_pair(Arc::clone(&ctx)))
            .with_composition_authority(CompositionAuthority::new("blob-operator", [])),
        OpsHarnessRegistration::pair(composer_pair())
            .with_scoped_env(ScopedPeerEnv::new(["blobs/delete"])),
    ]);
    harness.with_token("token:alice", identity_named("alice"));
    harness.grant("alice", "ns-1", &["read", "write"]);
    let call_client = harness.spawn_call_halves();
    let channel_client = harness
        .spawn_channel_halves(
            vec![
                put_openable(Arc::clone(&ctx)),
                fetch_openable(Arc::clone(&ctx)),
            ],
            Some(identity_named("alice")),
        )
        .await;

    let digest_hex = wire_hex_of_seed(b"any-payload");

    let mut invalids: Vec<(&str, Value)> = Vec::new();
    for payload in [
        json!({ "digest": digest_hex.clone() }),
        json!({ "namespace": "ns-1" }),
        json!({ "namespace": "ns-1", "digest": 42 }),
        json!({ "namespace": "ns-1", "digest": "G".repeat(64) }),
        json!({ "namespace": "ns-1", "digest": "a".repeat(65) }),
        // Bare hex dies at the gate too (ADR-020 §Decision 2): the
        // implicit default-family readings of the old schema are gone.
        json!({ "namespace": "ns-1", "digest": "a".repeat(40) }),
        json!({ "namespace": "ns-1", "digest": "a".repeat(64) }),
        json!({ "namespace": "ns-1", "digest": digest_hex.clone(), "extra": true }),
    ] {
        invalids.push(("blobs/stat", payload));
    }
    for payload in [
        json!({ "namespace": "ns-1" }),
        json!({ "namespace": "ns-1", "digests": digest_hex.clone() }),
        json!({ "namespace": "ns-1", "digests": [42] }),
        json!({ "namespace": "ns-1", "digests": ["G".repeat(64)] }),
        json!({ "namespace": "ns-1", "digests": ["a".repeat(64)] }),
        json!({ "namespace": "ns-1", "digests": [], "token": "x".repeat(64) }),
        json!({ "namespace": "ns-1", "digests": [digest_hex.clone(), digest_hex.clone()], "token": "x".repeat(64) }),
        json!({ "namespace": "ns-1", "digests": [digest_hex.clone()], "unexpected": 1 }),
        // S-5's token field bound: the renewal form's `token` carries
        // `maxLength` + the hex pattern — an over-length or non-hex
        // token is the schema gate's `INVALID_INPUT`, never the
        // handler's ingress (whose decode stays bounded by the 64-char
        // length-first guard).
        json!({ "namespace": "ns-1", "digests": [digest_hex.clone()], "token": "a".repeat(65) }),
        json!({ "namespace": "ns-1", "digests": [digest_hex.clone()], "token": "G".repeat(64) }),
    ] {
        invalids.push(("blobs/have", payload));
    }
    for payload in [
        json!({ "namespace": "" }),
        json!({ "namespace": "ns-1", "digests": "no-array" }),
        json!({ "namespace": "ns-1", "digests": [42] }),
        json!({ "namespace": "ns-1", "digests": ["G".repeat(64)] }),
        json!({ "namespace": "ns-1", "digests": [digest_hex.clone()], "surprise": 1 }),
    ] {
        invalids.push(("blobs/compose-delete", payload));
    }

    for (op, payload) in invalids {
        let answered = await_call(call_client.call_with_payload(call_payload(
            op,
            payload.clone(),
            Some("token:alice"),
        )))
        .await;
        assert_eq!(
            error_code(&answered),
            Some("INVALID_INPUT"),
            "{op} rejected the malformed payload at the schema gate: {payload} -> {answered:?}"
        );
    }

    // The op-entry order: the ACL verdict denies the empty namespace
    // before the schema gate answers — closed-by-default runs first
    // (the same op with a well-formed but ungranted namespace).
    let acl_first = await_call(call_client.call_with_payload(call_payload(
        "blobs/stat",
        json!({ "namespace": "", "digest": digest_hex.clone() }),
        Some("token:alice"),
    )))
    .await;
    assert_eq!(
        error_code(&acl_first),
        Some("FORBIDDEN"),
        "the op-entry ACL denies the ungranted namespace ahead of the schema gate"
    );

    for payload in [
        json!({ "namespace": "ns-1" }),
        json!({ "namespace": "ns-1", "digest": "G".repeat(64) }),
        json!({ "namespace": "ns-1", "digest": digest_hex.clone(), "ranges": "no-array" }),
        json!({ "namespace": "ns-1", "digest": digest_hex.clone(), "ranges": [] }),
        json!({ "namespace": "ns-1", "digest": digest_hex.clone(), "ranges": [{ "offset": 0 }] }),
        json!({ "namespace": "ns-1", "digest": digest_hex.clone(), "ranges": [{ "offset": -1, "len": 4 }] }),
        json!({ "namespace": "ns-1", "digest": digest_hex.clone(), "ranges": [{ "offset": 0, "len": 4, "surprise": 1 }] }),
        // S-2's count bound: the schema's `maxItems` rides the context's
        // `fetch_max_ranges` knob (the default 256) — an over-count open
        // is the registry's `INVALID_INPUT`, never a handler.
        json!({ "namespace": "ns-1", "digest": digest_hex.clone(), "ranges": std::iter::repeat_n(json!({ "offset": 0, "len": 1 }), 257).collect::<Vec<_>>() }),
    ] {
        let answered = open_denied(&channel_client, FETCH_OP_ID, payload.clone()).await;
        assert_eq!(
            error_code(&answered),
            Some("INVALID_INPUT"),
            "fetch rejected the malformed open payload: {payload}"
        );
    }

    for payload in [
        // The mandatory claims (ADR-020 §Decision 3): a missing key and
        // a missing len are schema rejects now.
        json!({ "namespace": "ns-1", "len": 4 }),
        json!({ "namespace": "ns-1", "key": digest_hex.clone() }),
        json!({ "namespace": "ns-1", "key": "G".repeat(64), "len": 4 }),
        json!({ "namespace": "ns-1", "key": digest_hex.clone(), "len": "four" }),
        json!({ "namespace": "ns-1", "key": digest_hex.clone(), "len": -1 }),
        json!({ "namespace": "ns-1", "key": digest_hex.clone(), "len": 4, "surprise": 1 }),
        // The bare-hex death rides the put claim too (ADR-020 §Decision
        // 2): a bare 40/64-hex oid offer — the wave-13 wire form — is
        // the schema gate's reject, never a default-family read.
        json!({ "namespace": "ns-1", "key": "a".repeat(40), "len": 4 }),
        json!({ "namespace": "ns-1", "key": "b".repeat(64), "len": 4 }),
    ] {
        let answered = open_denied(&channel_client, PUT_OP_ID, payload.clone()).await;
        assert_eq!(
            error_code(&answered),
            Some("INVALID_INPUT"),
            "put rejected the malformed offer: {payload}"
        );
    }

    let external = await_call(call_client.call_with_payload(call_payload(
        "blobs/delete",
        json!({ "digests": "not even shaped" }),
        Some("token:alice"),
    )))
    .await;
    assert_eq!(
        error_code(&external),
        Some("NOT_FOUND"),
        "the internal visibility verdict precedes validation on the wire"
    );
}

/// The handlers' post-schema ingress family (the "unreachable
/// post-validation" guards are load-bearing for direct and composed
/// calls that bypass the wire): a handler invoked with a schema-passing
/// shape the ingress cannot parse answers the wire-invalid-input form;
/// a malformed digest field answers the declared `INVALID_DIGEST`
/// rejects-never-guesses ingress.
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn the_handler_ingress_sweep_rejects_the_post_schema_shapes() {
    let store = test_store().await;
    let ctx = Arc::new(OpsContext::new(Arc::clone(&store), OpsConfig::default()));

    let (_, stat_handler) = stat_pair(Arc::clone(&ctx));
    let (_, have_handler) = have_pair(Arc::clone(&ctx));
    let (_, delete_handler) = delete_pair(Arc::clone(&ctx));

    for (handler, payload, expected) in [
        (
            &stat_handler,
            json!({}),
            "input failed input_schema validation",
        ),
        (
            &stat_handler,
            json!({ "namespace": "ns-1", "digest": "ZZZ-not-hex" }),
            "the digest is not tag-prefixed key hex",
        ),
        (
            &have_handler,
            json!({}),
            "input failed input_schema validation",
        ),
        (
            &have_handler,
            json!({ "namespace": "ns-1", "digests": ["ZZZ-not-hex"] }),
            "the digest is not tag-prefixed key hex",
        ),
        (
            &delete_handler,
            json!({}),
            "input failed input_schema validation",
        ),
        (
            &delete_handler,
            json!({ "namespace": "ns-1", "digests": ["ZZZ-not-hex"] }),
            "the digest is not tag-prefixed key hex",
        ),
        (
            // A gate-passing width the physical encoding rejects: all
            // hex, 42 chars, but the tag byte declares a 21-byte key
            // over 20 digest bytes — never a guess.
            &stat_handler,
            json!({ "namespace": "ns-1", "digest": format!("01{}", "a".repeat(40)) }),
            "the digest is not tag-prefixed key hex",
        ),
        (
            // An unknown registry byte at the 42-char width: the tag
            // is the validation, the length never a family guess.
            &delete_handler,
            json!({ "namespace": "ns-1", "digests": [format!("05{}", "a".repeat(40))] }),
            "the digest is not tag-prefixed key hex",
        ),
    ] {
        let answered = (handler)(payload.clone(), bare_context()).await;
        match answered.result {
            Err(error) => {
                assert!(
                    error.code == "INVALID_INPUT" || error.code == INVALID_DIGEST,
                    "the ingress swept {payload}: {error:?}"
                );
                assert!(
                    error.message.contains(expected),
                    "the ingress names its reason against {payload}: {error:?}"
                );
            }
            Ok(out) => panic!("the ingress swept {payload}, got {out:?}"),
        }
    }

    // The store-error family's ingest-side complement: have's pure
    // probe folds engine failures into `present: false` — the probes
    // stay probes (ADR-008's discipline) — asserted here against a
    // probe the store never answers (the keys are absent either way).
    let (_, handler) = have_pair(Arc::clone(&ctx));
    let probed = (handler)(
        json!({ "namespace": "ns-1", "digests": [wire_hex_of_seed(b"never")] }),
        bare_context(),
    )
    .await;
    assert_eq!(
        probed.result.unwrap(),
        json!({ "present": [false] }),
        "the pure probe's fold-by-design form"
    );
}

/// The store-core failures are the ops error family's internal form:
/// a large tier whose tree cannot answer (the local tier's committed
/// shard made unreadable — real media produces exactly this failure
/// class) surfaces through the wire as `INTERNAL`, naming the stage —
/// never as a `None`/`false`/missing shape (the probes' error
/// discipline is distinct from the probes' miss discipline).
/// Establishment-side the same failure refuses with reason
/// `handler_error` — never serve unverifiable bytes. Review-001 S-4:
/// every message is the stable domain text — no store-core `Display`
/// detail (path, engine form, os-error fragment) rides the wire on
/// any driven arm. (The have op is excluded by construction: its
/// pure probe folds engine failures to `present: false` —
/// ADR-008's probes-stay-probes discipline — so a store failure
/// there never synthesizes a wire message.)
#[cfg(feature = "mem")]
#[cfg(unix)]
#[tokio::test]
async fn the_store_cores_failures_surface_through_the_ops_error_family() {
    let unique = format!(
        "alkblobs-ops-d2-broken-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos()
    );
    let root = std::env::temp_dir().join(&unique);
    std::fs::create_dir_all(&root).expect("the broken-tree root");
    let store = Arc::new(
        Store::dual_tier_mem_local(&root, 8)
            .await
            .expect("the mem+local dual tier constructs"),
    );
    let content: Vec<u8> = (0..64u32).map(|i| (i % 173) as u8).collect();
    let (key, _pin) = store
        .put_as(
            Algorithm::GitBlobSha256,
            Some(content.len() as u64),
            std::io::Cursor::new(content.as_slice()),
        )
        .await
        .expect("the large put lands on the local tier");
    let key_hex = hex::encode(key.as_bytes());
    let shard2 = root.join(&key_hex[..2]).join(&key_hex[2..4]);
    chmod_000(&shard2);

    let ctx = Arc::new(OpsContext::new(Arc::clone(&store), OpsConfig::default()));
    let harness = OpsHarness::assemble_registrations(vec![
        OpsHarnessRegistration::pair(stat_pair(Arc::clone(&ctx))),
        OpsHarnessRegistration::pair(delete_pair(Arc::clone(&ctx)))
            .with_composition_authority(CompositionAuthority::new("blob-operator", [])),
        OpsHarnessRegistration::pair(composer_pair())
            .with_scoped_env(ScopedPeerEnv::new(["blobs/delete"])),
    ]);
    harness.with_token("token:alice", identity_named("alice"));
    harness.grant("alice", "ns-1", &["read", "write"]);
    let call_client = harness.spawn_call_halves();
    let channel_client = harness
        .spawn_channel_halves(
            vec![fetch_openable(Arc::clone(&ctx))],
            Some(identity_named("alice")),
        )
        .await;
    let digest_hex = wire_hex_of(&key);

    let stat = await_call(call_client.call_with_payload(call_payload(
        "blobs/stat",
        json!({ "namespace": "ns-1", "digest": digest_hex.clone() }),
        Some("token:alice"),
    )))
    .await;
    match stat.result {
        Err(error) => {
            assert_eq!(error.code, "INTERNAL", "{error:?}");
            assert_eq!(
                error.message, "the store core failed at stat",
                "the stable domain text: the stage is named, the store core's Display \
                 detail is not (review-001 S-4): {error:?}"
            );
            assert!(
                !error.message.contains('/')
                    && !error.message.contains("io:")
                    && !error.message.contains("Permission"),
                "no path, engine-form, or os-error fragment rides the wire: {error:?}"
            );
        }
        Ok(out) => panic!("the unreadable shard surfaced a stat answer: {out:?}"),
    }

    let deleted = await_call(call_client.call_with_payload(call_payload(
        "blobs/compose-delete",
        json!({ "namespace": "ns-1", "digests": [digest_hex.clone()] }),
        Some("token:alice"),
    )))
    .await;
    match deleted.result {
        Err(error) => {
            assert_eq!(error.code, "INTERNAL", "{error:?}");
            assert_eq!(
                error.message, "the store core failed at delete",
                "the stable domain text: the stage is named, the store core's Display \
                 detail is not (review-001 S-4): {error:?}"
            );
            assert!(
                !error.message.contains('/')
                    && !error.message.contains("io:")
                    && !error.message.contains("Permission"),
                "no path, engine-form, or os-error fragment rides the wire: {error:?}"
            );
        }
        Ok(out) => panic!("the unreadable shard surfaced a delete answer: {out:?}"),
    }

    for (input, stage) in [
        (
            json!({ "namespace": "ns-1", "digest": digest_hex.clone() }),
            "the verified read",
        ),
        (
            json!({ "namespace": "ns-1", "digest": digest_hex.clone(),
                    "ranges": [{ "offset": 0, "len": 4 }] }),
            "the ranged read",
        ),
    ] {
        let refused = tokio::time::timeout(
            TEST_TIMEOUT,
            channel_client.call_open_op(FETCH_OP_ID, input.clone()),
        )
        .await
        .expect("the refused open resolves");
        match refused.result {
            Err(error) => {
                assert_eq!(error.code, "channel:open_failed", "{error:?}");
                let handler_message = error.message.clone();
                assert!(
                    handler_message.contains(stage),
                    "the failed consult names its stage: {error:?} (wanted {stage})"
                );
                assert!(
                    handler_message.contains("the store core failed at")
                        && !handler_message.contains('/')
                        && !handler_message.contains("io:")
                        && !handler_message.contains("Permission"),
                    "the stable domain text: no store-core detail rides the refusal \
                     (review-001 S-4): {error:?}"
                );
            }
            Ok(open) => panic!("the unreadable shard served an open: {open:?} ({stage})"),
        }
    }

    chmod_755(&shard2);
    let _ = std::fs::remove_dir_all(&root);
    let _ = (store, ctx, harness, call_client, channel_client, _pin);
}

/// The establishers' post-schema form checks (the ingest guards the
/// wire gate makes unreachable, driven directly): a malformed digest
/// claim or range shape refuses establishment as a `HandlerError`
/// naming the field, and the put establisher's mandatory `key` claim
/// (missing or undecodable) refuses the same way — rejects, never
/// guesses, even where the wire
/// schema would have rejected first.
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn the_establisher_ingress_rejects_the_post_schema_offer_shapes() {
    let store = test_store().await;
    let ctx = Arc::new(OpsContext::new(Arc::clone(&store), OpsConfig::default()));
    let auth = super::harness::auth_for(None, BLOBS_CHANNEL_ALPN.as_bytes());

    let (_, put_establisher, _) = put_openables(Arc::clone(&ctx));
    let (_, fetch_establisher, _) = fetch_openables(Arc::clone(&ctx));

    // The mandatory key claim (ADR-020 §Decision 3): a missing claim
    // and an undecodable claim both refuse establishment; bare hex
    // dies at the ingress too (ADR-020 §Decision 2).
    for input in [
        json!({ "namespace": "ns-1" }),
        json!({ "namespace": "ns-1", "key": "ZZZ-not-hex" }),
        json!({ "namespace": "ns-1", "key": hex::encode(key_of(b"ok-digest").digest().bytes()) }),
    ] {
        let refused = match put_establisher(input.clone(), auth.clone()).await {
            Err(refused) => refused,
            Ok(_) => panic!("the put establisher's key ingress did not sweep {input}"),
        };
        assert!(
            matches!(
                refused,
                alkcall::channels::operations::EstablishmentError::HandlerError { .. }
            ),
            "the put establisher's key ingress swept {input}: {refused:?}"
        );
    }

    let ok_key = wire_hex_of_seed(b"ok-digest");
    let ack = &put_establisher(
        json!({ "namespace": "ns-1", "key": ok_key.clone() }),
        auth.clone(),
    )
    .await
    .expect("the offer ack rides establishment on the gate-passing key");
    assert!(
        ack.reply_fields()
            .expect("the reply fields")
            .contains_key("accepted"),
        "the offer ack's accepted reply field rides establishment"
    );

    for input in [
        json!({ "digest": "ZZZ-not-hex" }),
        // Bare hex dies at the ingress too (ADR-020 §Decision 2): the
        // old default-family readings are gone from the handlers.
        json!({ "digest": hex::encode(key_of(b"ok-digest").digest().bytes()) }),
        json!({ "digest": ok_key, "ranges": "not-an-array" }),
        json!({ "digest": ok_key, "ranges": [{ "offset": 0 }] }),
    ] {
        let refused = match fetch_establisher(input.clone(), auth.clone()).await {
            Err(refused) => refused,
            Ok(_) => panic!("the fetch establisher's ingest guards swept {input}"),
        };
        assert!(
            matches!(
                refused,
                alkcall::channels::operations::EstablishmentError::HandlerError { .. }
            ),
            "the fetch establisher's ingest guards swept {input}: {refused:?}"
        );
    }

    // S-2's total-bytes bound at the default config (64 MiB): the
    // stable domain text names the bound and the knob's value — no
    // raw payload value rides the message.
    let over_bytes = match fetch_establisher(
        json!({
            "digest": ok_key,
            "ranges": [{ "offset": 0, "len": u64::MAX }, { "offset": 0, "len": u64::MAX }]
        }),
        auth.clone(),
    )
    .await
    {
        Err(refused) => refused,
        Ok(_) => panic!("the over-bytes request was not refused at the ingress"),
    };
    assert!(
        matches!(
            &over_bytes,
            alkcall::channels::operations::EstablishmentError::HandlerError { message }
                if message.contains("exceeds the total-bytes bound")
                    && (message.contains("the limit is 67108864 bytes")
                        || message.contains("the limit of 67108864 bytes"))
                    && !message.contains("offset")
        ),
        "the over-bytes refusal is the stable text at the default bound: {over_bytes:?}"
    );
}

/// The fetch pump's silent-return arms (R-02's lifetime discipline —
/// the handler task tracks the data plane): a pump whose channel never
/// opened, whose plan fails to downcast or unwrap, or whose stream
/// dies mid-service returns without panic — the three named arms plus
/// the mid-service write-failure forms per serving path, each ending
/// the pump alone.
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn the_fetch_pump_silent_return_arms_end_the_pump_without_serving() {
    let store = test_store().await;
    let ctx = Arc::new(OpsContext::new(Arc::clone(&store), OpsConfig::default()));
    let auth = super::harness::auth_for(None, BLOBS_CHANNEL_ALPN.as_bytes());
    let hex_of = |seed: &[u8]| wire_hex_of_seed(seed);

    // The channel never opened: the pump accepts nothing.
    let (_, _, pump) = fetch_openables(Arc::clone(&ctx));
    let conn =
        Connection::from_source(PumpSource::closed(), BLOBS_CHANNEL_ALPN.as_bytes().to_vec());
    let closed = (pump)(json!({}), None, conn, auth.clone());
    tokio::time::timeout(TEST_TIMEOUT, closed)
        .await
        .expect("the never-opened pump resolved")
        .expect("the never-opened pump returned clean");

    // A plan of the wrong type: the downcast refuses — the pump owns
    // its plan type and nothing else serves through it.
    let (_, _, pump) = fetch_openables(Arc::clone(&ctx));
    let (server, _client) = pump_stream_pair();
    let conn = pump_conn(server);
    let downcast_refused = (pump)(
        json!({}),
        Some(Arc::new(0u8) as alkcall::channels::operations::ChannelPlan),
        conn,
        auth.clone(),
    );
    tokio::time::timeout(TEST_TIMEOUT, downcast_refused)
        .await
        .expect("the misplanned pump resolved")
        .expect("the misplanned pump returned clean");

    let big: Vec<u8> = (0..256u32 * 4096).map(|i| (i % 251) as u8).collect();
    let (key, _pin) = store
        .put_as(
            Algorithm::GitBlobSha256,
            Some(big.len() as u64),
            std::io::Cursor::new(big.as_slice()),
        )
        .await
        .expect("the big entry put");
    let digest_hex = hex_of(&big);

    // A whole-form plan held by another owner: the unwrap refuses —
    // the plan is the establisher's one-shot hand-over, never shared.
    let (_, _, pump) = fetch_openables(Arc::clone(&ctx));
    let whole = fetch_establish_whole(&ctx, &digest_hex, &auth).await;
    let plan = whole.plan.expect("the whole form's plan");
    let held = Arc::clone(&plan);
    let (server, _client) = pump_stream_pair();
    let conn = pump_conn(server);
    let unwrap_refused = (pump)(json!({}), Some(plan), conn, auth.clone());
    tokio::time::timeout(TEST_TIMEOUT, unwrap_refused)
        .await
        .expect("the held-plan pump resolved")
        .expect("the held-plan pump returned clean");
    drop(held);

    // The whole form's service dying at the first write (the
    // consumer's read half gone): the pump returns, the stream torn.
    let (_, _, pump) = fetch_openables(Arc::clone(&ctx));
    let whole = fetch_establish_whole(&ctx, &digest_hex, &auth).await;
    let plan = whole.plan.expect("the whole form's plan");
    let (server, client) = pump_stream_pair();
    drop(client);
    let conn = pump_conn(server);
    let torn_whole = (pump)(json!({}), Some(plan), conn, auth.clone());
    tokio::time::timeout(TEST_TIMEOUT, torn_whole)
        .await
        .expect("the torn whole pump resolved")
        .expect("the torn whole pump returned clean");

    // The ranged form: the slices pump against a torn consumer.
    let (_, fetch_establisher, pump) = fetch_openables(Arc::clone(&ctx));
    let ranged = fetch_establisher(
        json!({
            "digest": digest_hex.clone(),
            "ranges": [{ "offset": 0, "len": big.len() as u64 }, { "offset": 4, "len": 8 }]
        }),
        auth.clone(),
    )
    .await
    .expect("the ranged establishment");
    let plan = ranged.plan.expect("the ranged form's plan");
    let (server, client) = pump_stream_pair();
    drop(client);
    let conn = pump_conn(server);
    let torn_ranged = (pump)(json!({}), Some(plan), conn, auth.clone());
    tokio::time::timeout(TEST_TIMEOUT, torn_ranged)
        .await
        .expect("the torn ranged pump resolved")
        .expect("the torn ranged pump returned clean");

    // The fanout form: the tapped arm's feed to a torn consumer.
    let seed: Vec<u8> = (0..64u32).map(|i| (i % 91) as u8).collect();
    let fanout_hex = hex_of(&seed);
    let fanout_key = key_of(&seed);
    let publisher = ctx
        .fanout()
        .begin(&fanout_key, SlowSubscriberPolicy::Stall)
        .expect("the broadcast begins");
    let (_, fetch_establisher, pump) = fetch_openables(Arc::clone(&ctx));
    let tapped = fetch_establisher(json!({ "digest": fanout_hex.clone() }), auth.clone())
        .await
        .expect("the fanout tap establishment");
    let plan = tapped.plan.expect("the fanout tap's plan");
    let (server, client) = pump_stream_pair();
    drop(client);
    let conn = pump_conn(server);
    let torn_fanout = (pump)(json!({}), Some(plan), conn, auth.clone());
    publisher.broadcast(Arc::new(seed.clone())).await;
    tokio::time::timeout(TEST_TIMEOUT, torn_fanout)
        .await
        .expect("the torn fanout pump resolved")
        .expect("the torn fanout pump returned clean");
    publisher.finish();

    let _ = (key, _pin, digest_hex);
}

/// The whole form's establishment — the real establisher over the
/// big entry, the plan the pump tests hand around.
#[cfg(any(feature = "mem", feature = "sqlite"))]
async fn fetch_establish_whole(
    ctx: &Arc<OpsContext>,
    digest_hex: &str,
    auth: &alkcall::core::auth::AuthContext,
) -> alkcall::channels::operations::Establishment {
    let (_, establisher, _) = fetch_openables(Arc::clone(ctx));
    establisher(json!({ "digest": digest_hex }), auth.clone())
        .await
        .expect("the whole establishment")
}

/// The put handler's ingress guards and the over-fed stream's settle
/// (the failure shapes the wire gate's happy path never teaches): the
/// post-schema mandatory-claim guards answer the invalid-input form
/// under direct invocation (the key's and the len's missing-claim
/// shapes), a gate-passing-width-undecodable key answers the declared
/// `INVALID_DIGEST` ingress; and an over-fed known-length offer — the
/// facade's put ending ahead of the tee — settles through the kill
/// path as `VERIFICATION_REFUSED` with zero residue.
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn the_put_handler_ingress_guards_and_the_torn_stream_settle() {
    let store = test_store().await;
    let ctx = Arc::new(OpsContext::new(Arc::clone(&store), OpsConfig::default()));
    let (_, put_establisher, put_handler) = put_openables(Arc::clone(&ctx));
    let auth = super::harness::auth_for(None, BLOBS_CHANNEL_ALPN.as_bytes());

    // The mandatory claims (ADR-020 §Decision 3): missing post-schema
    // → the invalid-input guard, handler-direct.
    for input in [
        json!({}),
        json!({ "namespace": "ns-1", "key": wire_hex_of_seed(b"a claimless key") }),
        json!({ "namespace": "ns-1", "len": 4 }),
    ] {
        let refused = put_handler(input.clone(), None, put_conn(), auth.clone())
            .await
            .expect_err("the offer's ingest guards refused");
        assert_eq!(
            refused.code, "INVALID_INPUT",
            "the post-schema offer guards swept {input}: {refused:?}"
        );
    }
    // The key ingress: a non-hex string handler-direct answers the
    // declared invalid-digest shape (on the wire the schema gate
    // rejects it first — the ingress is the rejects-never-guesses
    // decoder below the gate).
    let refused = put_handler(
        json!({ "namespace": "ns-1", "key": "ZZZ-not-hex", "len": 4 }),
        None,
        put_conn(),
        auth.clone(),
    )
    .await
    .expect_err("the key's ingress refused");
    assert_eq!(
        refused.code, INVALID_DIGEST,
        "the key claim's ingress is the rejects-never-guesses decoder: {refused:?}"
    );
    assert!(
        refused
            .message
            .contains("the digest is not tag-prefixed key hex"),
        "the ingress names its contract: {refused:?}"
    );

    // The bare-hex death, handler-direct (ADR-020 §Decision 2): the
    // wave-13 wire form — a bare 40/64-hex oid key claim — cannot
    // decode (the tag is the validation, the length never a family
    // guess), never a default-family read.
    for bare_hex in ["a".repeat(40), "b".repeat(64)] {
        let refused = put_handler(
            json!({ "namespace": "ns-1", "key": bare_hex, "len": 4 }),
            None,
            put_conn(),
            auth.clone(),
        )
        .await
        .expect_err("the bare-hex key claim's ingress refused");
        assert_eq!(
            refused.code, INVALID_DIGEST,
            "the bare-hex key claim cannot decode: {refused:?}"
        );
        assert!(
            refused
                .message
                .contains("the digest is not tag-prefixed key hex"),
            "the ingress names its contract: {refused:?}"
        );
    }

    // The good offer's ack rides establishment (with the mandatory
    // claim present); a claimless establishment refuses.
    put_establisher(
        json!({ "namespace": "ns-1", "key": wire_hex_of_seed(b"the ack ride's key") }),
        auth.clone(),
    )
    .await
    .expect("the offer's ack rides establishment");
    assert!(
        put_establisher(json!({ "namespace": "ns-1" }), auth.clone())
            .await
            .is_err(),
        "the mandatory key claim's establisher guard refuses"
    );

    // The over-fed known-length offer: the facade's put rejects ahead
    // of the stream (received > len), the tee observes the ended put
    // after its next read, and the settle kills the feed — the
    // response is the facade's rejection through the put's failure
    // family, nothing committed. The stream stays open through the
    // resolve: no EOF path can race the kill.
    let oversized: Vec<u8> = (0..2u32 * 1024 * 1024).map(|i| (i % 251) as u8).collect();
    let key_hex = wire_hex_of_seed(b"four bytes");
    let (_, _harness, client) = put_serving(&store).await;
    let (_channel_id, mut send, recv, reply) = open_put(
        &client,
        json!({ "namespace": "ns-1", "key": key_hex.clone(), "len": 4 }),
    )
    .await;
    send.write_all(&oversized)
        .await
        .expect("the over-feed streams");
    let rejected = tokio::time::timeout(TEST_TIMEOUT, reply.resolve())
        .await
        .expect("the over-fed put resolves")
        .expect_err("the facade's over-read rejection surfaces");
    let failed = rejected.call_error().expect("the wire error");
    assert_eq!(
        failed.code, VERIFICATION_REFUSED,
        "the put's failure settle through the torn-stream family: {failed:?}"
    );
    assert!(
        failed.message.contains("the put of"),
        "the offered key is named in the refusal prefix: {failed:?}"
    );
    assert!(
        !store
            .has(&key_of(b"four bytes").as_bytes())
            .await
            .expect("the has probe"),
        "nothing committed"
    );
    drop(send);
    drop(recv);
}

/// The put refusal's stable text at the commit-verification synthesis
/// point (review-001 S-4): real media failure — the local tier's
/// committed-shard directory pre-made unwritable, so the staged put's
/// commit-rename fails strictly after the stream's EOF (pin-first
/// holds on the facade path; the failure cannot precede the tee's
/// settle) — settles as `PUT_REFUSED` whose message names the stage
/// and the refusal's shape, with **no** store-core `Display` detail
/// (no path, no `io:` form, no os-error fragment) and nothing
/// committed. (The shared helper's other call site — the store arm's
/// `put_failed_response` settle — is the same stable template.)
#[cfg(feature = "mem")]
#[cfg(unix)]
#[tokio::test]
async fn the_put_refusal_answers_the_stable_text_without_store_core_detail() {
    let unique = format!(
        "alkblobs-ops-s4-put-refusal-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos()
    );
    let root = std::env::temp_dir().join(&unique);
    std::fs::create_dir_all(&root).expect("the commit-failure root");
    let store = Arc::new(
        Store::dual_tier_mem_local(&root, 8)
            .await
            .expect("the mem+local dual tier constructs"),
    );

    let content: Vec<u8> = (0..512u32 * 1024).map(|i| (i % 179) as u8).collect();
    let key = Key::from(Algorithm::GitBlobSha256.derive(&content, content.len() as u64));
    let digest_hex = wire_hex_of(&key);
    let key_hex = hex::encode(key.as_bytes());
    let shard = root.join(&key_hex[..2]).join(&key_hex[2..4]);
    std::fs::create_dir_all(&shard).expect("the committed shard dir is pre-created");
    chmod_000(&shard);

    let (_, _harness, client) = put_serving(&store).await;
    let (_channel_id, mut send, recv, reply) = open_put(
        &client,
        json!({ "namespace": "ns-1", "key": digest_hex.clone(), "len": content.len() }),
    )
    .await;
    send.write_all(&content)
        .await
        .expect("the offered stream writes");
    drop(send);
    let refused = tokio::time::timeout(TEST_TIMEOUT, reply.resolve())
        .await
        .expect("the refused put resolves")
        .expect_err("the commit failure surfaces as the put refusal");
    let failed = refused.call_error().expect("the wire error");
    assert_eq!(
        failed.code, PUT_REFUSED,
        "the commit-time landing is the put-time refusal family: {failed:?}"
    );
    assert_eq!(
        failed.message,
        "the put refused at the commit verification: the store core refused the put — \
         nothing committed",
        "the stable domain text: the stage and shape named, the store core's Display \
         detail dropped (review-001 S-4): {failed:?}"
    );
    drop(recv);

    chmod_755(&shard);
    assert!(
        !store.has(&key.as_bytes()).await.expect("the has probe"),
        "nothing committed"
    );
    assert_eq!(
        store.gc().pin_count(&key),
        0,
        "the failed commit's pin released with the facade's guard"
    );
    let _ = std::fs::remove_dir_all(&root);
    let _ = (store, _harness, client);
}

/// The fanout registry's begin-None form and its dead-arm pruning
/// (the A3 shape's edges): a broadcast already live refuses the second
/// begin (the incumbent carries the same bytes under CAS); a
/// subscriber arm whose consumer left is pruned at the next broadcast
/// under the Stall policy too — the registry never grows unbounded on
/// the arms.
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn fanout_begin_refuses_the_second_broadcast_and_prunes_dead_arms() {
    let store = test_store().await;
    let ctx = Arc::new(OpsContext::new(Arc::clone(&store), OpsConfig::default()));
    let seed = b"the pruned arm's broadcast";
    let key = Key::from(Algorithm::GitBlobSha256.derive(seed, seed.len() as u64));

    let incumbent = ctx
        .fanout()
        .begin(&key, SlowSubscriberPolicy::Stall)
        .expect("the first broadcast begins");
    assert!(
        ctx.fanout()
            .begin(&key, SlowSubscriberPolicy::Stall)
            .is_none(),
        "a broadcast already live: the begin-None form, store-arm-only continues"
    );

    let stalled = ctx.fanout().subscribe(&key).expect("the arm subscribes");
    drop(stalled);
    incumbent
        .broadcast(Arc::new(b"the chunk the dead arm skipped".to_vec()))
        .await;
    let mut fresh = ctx
        .fanout()
        .subscribe(&key)
        .expect("the live broadcast admits");
    incumbent
        .broadcast(Arc::new(b"the chunk the fresh arm carries".to_vec()))
        .await;
    assert_eq!(
        fresh.recv().await,
        Some(Arc::new(b"the chunk the fresh arm carries".to_vec())),
        "the pruned arm freed the registry: the fresh arm rides"
    );
    incumbent.finish();
    assert_eq!(
        fresh.recv().await,
        None,
        "the broadcast end is the degrade signal (the fresh arm)"
    );
}

/// A ranged fetch of a committed pool's absent digest is the typed
/// miss — the ranged form's consult reaches the store's
/// `Err(Missing)` and answers the same `unknown_resource` refusal the
/// whole form answers (the miss is the need announcement on both
/// shapes).
#[cfg(any(feature = "mem", feature = "sqlite"))]
#[tokio::test]
async fn a_ranged_fetch_of_an_absent_digest_is_the_typed_miss() {
    let store = test_store().await;
    let ctx = Arc::new(OpsContext::new(Arc::clone(&store), OpsConfig::default()));
    let harness = OpsHarness::assemble(vec![]);
    harness.with_token("token:alice", identity_named("alice"));
    harness.grant("alice", "ns-1", &["read"]);
    let client = harness
        .spawn_channel_halves(
            vec![fetch_openable(Arc::clone(&ctx))],
            Some(identity_named("alice")),
        )
        .await;

    let absent = wire_hex_of(&key_of(b"ranged never landed"));
    let refused = open_fetch(
        &client,
        "ns-1",
        &absent,
        Some(json!([{ "offset": 0, "len": 4 }])),
    )
    .await;
    match refused {
        Err(error) => {
            let call_error = error.call_error().expect("the wire error");
            assert_eq!(
                call_error.code, "channel:open_failed",
                "the ranged miss refuses establishment: {error:?}"
            );
            assert_eq!(
                error.establishment_reason(),
                Some("unknown_resource"),
                "the typed vocabulary for the absent resource, ranged form too"
            );
            assert!(
                call_error.message.contains(&absent),
                "the refusal carries the digest: {}",
                call_error.message
            );
        }
        Ok(_) => panic!("the absent digest refused, got a ranged channel"),
    }
}

/// The no-side-door audit, its two halves named: (1) the heuristic
/// enumeration — a tripwire, not a guarantee — of the ops module's
/// store access from its own sources: the observed method set equals
/// the public facade verbs plus exactly the crate-internal renewal
/// seam (`ops_pin_check`/`ops_pin_renew`); no `Backend` touch, no
/// engine types, nothing around the facade. (2) The mechanical
/// guarantee, asserted below the enumeration: the non-test source
/// never *names* an engine, backend, or driver identifier at all.
/// Recorded for the wave reviews' gates to re-check. (Adapted for the
/// wave-8 split: the enumeration scans the module's files, each cut
/// at its first `#[cfg(test)]` gate.)
#[test]
fn the_no_side_door_audit_enumerates_the_module_store_access_and_finds_only_the_facade() {
    let sources: String = [
        ("mod.rs", include_str!("mod.rs")),
        ("tokens.rs", include_str!("tokens.rs")),
        ("wire.rs", include_str!("wire.rs")),
        ("specs.rs", include_str!("specs.rs")),
        ("fetch.rs", include_str!("fetch.rs")),
        ("put.rs", include_str!("put.rs")),
    ]
    .iter()
    .map(|(name, source)| {
        let test_tree_start = source.find("#[cfg(test)]").unwrap_or(source.len());
        format!("// {name}\n{}", &source[..test_tree_start])
    })
    .collect();
    let code: String = sources
        .lines()
        .filter(|line| {
            let trimmed = line.trim_start();
            !(trimmed.starts_with("///") || trimmed.starts_with("//!") || trimmed.starts_with("//"))
        })
        .collect::<Vec<_>>()
        .join("\n")
        .replace('\n', " ");

    let mut found: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
    for (idx, _) in code.match_indices("store") {
        let mut rest = code[idx + "store".len()..].trim_start();
        if let Some(paren) = rest.strip_prefix('(') {
            rest = paren.trim_start();
            let Some(paren_end) = rest.strip_prefix(')') else {
                continue;
            };
            rest = paren_end.trim_start();
        }
        let Some(rest) = rest.strip_prefix('.') else {
            continue;
        };
        let ident: String = rest
            .chars()
            .take_while(|c| *c == '_' || c.is_ascii_alphanumeric())
            .collect();
        if !ident.is_empty() {
            found.insert(ident);
        }
    }
    let expected: std::collections::BTreeSet<String> = [
        "put_as",
        "get",
        "stat",
        "has",
        "read_range",
        "delete",
        "fleet",
        "gc",
        "ops_pin_check",
        "ops_pin_renew",
    ]
    .into_iter()
    .map(str::to_owned)
    .collect();
    assert_eq!(
        found, expected,
        "the enumeration recorded: the facade verbs plus exactly the crate-internal \
         renewal seam — anything else in the set is a side-door to remove; anything \
         missing is an audit stale to refresh"
    );

    for forbidden in [
        "Backend",
        "PostgresBackend",
        "PgLoBackend",
        "KvEngine",
        "LargeEngine",
        "rusqlite",
        "tokio_postgres",
        "deadpool",
        "crate::postgres",
        "crate::sqlite",
        "crate::pg_lo",
        "crate::mem",
        "crate::local",
    ] {
        assert!(
            !code.contains(forbidden),
            "no side-door: the ops module's non-test source never names {forbidden}"
        );
    }
}