bsv-overlay-engine 0.1.6

Transaction admission, lookup and GASP synchronization for BSV overlay services.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
//! Overlay Services Engine — the core orchestrator.
//!
//! Receives transactions (submit), answers queries (lookup), manages advertisements,
//! and coordinates GASP sync. All storage, topic management, and lookup service
//! operations go through trait interfaces.
//!
//! Ported from `~/bsv/overlay-services/src/Engine.ts` (1,337 lines).

use crate::beef_limits;

use bsv_rs::transaction::{Beef, Transaction};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use tracing::{error, info, warn};

use crate::advertiser::{Advertiser, AdvertiserError};
use crate::broadcaster::{ArcBroadcaster, Broadcaster};
use crate::lookup_service::{LookupService, LookupServiceError};
use crate::storage::{Storage, StorageError};
use crate::topic_manager::{TopicManager, TopicManagerError};
use crate::types::*;

/// Controls how much spend history to include in lookup responses.
///
/// Maps to the TS `historySelector` parameter which can be a number
/// (depth limit) or an async function (per-output decider).
#[derive(Debug, Clone)]
pub enum HistorySelector {
    /// Include up to N levels of ancestor spend history.
    Depth(u32),
}

/// Configuration for constructing the Engine.
pub struct EngineConfig {
    /// URL where this engine is hosted. Required for advertisement sync.
    pub hosting_url: Option<String>,
    /// Known SHIP tracker URLs for bootstrapping.
    pub ship_trackers: Vec<String>,
    /// Known SLAP tracker URLs for bootstrapping.
    pub slap_trackers: Vec<String>,
    /// Configuration for GASP topic synchronization.
    pub sync_configuration: SyncConfiguration,
    /// Whether to suppress default SHIP/SLAP sync advertisements.
    pub suppress_default_sync_advertisements: bool,
}

impl Default for EngineConfig {
    fn default() -> Self {
        Self {
            hosting_url: None,
            ship_trackers: Vec::new(),
            slap_trackers: Vec::new(),
            sync_configuration: HashMap::new(),
            suppress_default_sync_advertisements: true,
        }
    }
}

/// The Overlay Services Engine.
///
/// Orchestrates topic managers, lookup services, storage, and advertisements.
/// Does NOT include an HTTP server — that's the job of overlay-cloudflare.
pub struct Engine {
    managers: HashMap<String, Box<dyn TopicManager>>,
    lookup_services: HashMap<String, Box<dyn LookupService>>,
    storage: Box<dyn Storage>,
    advertiser: Option<Box<dyn Advertiser>>,
    broadcaster: Option<Box<dyn Broadcaster>>,
    arc_broadcaster: Option<Box<dyn ArcBroadcaster>>,
    chain_tracker: Option<Box<dyn bsv_rs::transaction::ChainTracker>>,
    gasp_remote_factory: Option<Box<dyn crate::gasp::GASPRemoteFactory>>,
    ship_lookup_client: Option<Box<dyn crate::ship_lookup::ShipLookupClient>>,
    ship_bootstrap_peers: HashMap<String, Vec<String>>,
    /// OPT-IN / OFF BY DEFAULT chain-backed ancestor fetcher for GASP ingest.
    /// When `None` (default / production), GASP ingest is byte-identical to
    /// today. A platform crate may set `Some` (one-time-migration only) to let
    /// ingest self-heal missing ancestry by fetching it from chain.
    ancestor_fetcher: Option<std::rc::Rc<dyn crate::gasp::AncestorFetcher>>,
    gasp_ancestor_fetcher: Option<std::rc::Rc<dyn crate::gasp::AncestorFetcher>>,
    /// bsv-low#302: per-peer GASP sync wall-clock budget —
    /// `(sleep factory, budget ms)`. `None` (default) = unbounded per-peer
    /// sync, byte-identical to the pre-#302 behavior. When set, each peer's
    /// `GASPSync::sync` is raced against `sleep(budget_ms)`; a peer that
    /// exceeds the budget is DROPPED (loud log, failure recorded, cursor NOT
    /// advanced) and the loop continues with the next peer.
    peer_sync_budget: Option<(SleepFactory, u64)>,
    /// The per-GRAPH GASP budget (bsv-low #555): the sleep, the calls, the
    /// ms. `None`: no graph is deferred.
    graph_budget: Option<(SleepFactory, u32, u64)>,
    /// The per-graph budget's bytes and nodes limbs (bsv-low #586,
    /// [`Engine::set_graph_budget_limbs`]): in force once a graph budget is
    /// set.
    graph_budget_limbs: (u64, u32),
    /// The bound of one transaction's finalize submit (bsv-low #559), see
    /// [`Engine::set_finalize_submit_budget`].
    finalize_submit_budget: Option<(SleepFactory, u64)>,
    /// Open around each GASP finalize submit, so no deadline that races the
    /// sync drops a transaction between its writes (bsv-low #552, the lens
    /// fold's HIGH-1). See [`Engine::finalize_submit_gate`].
    finalize_gate: crate::gasp::SubmitGate,
    /// (txid, topic) pairs whose Phase-3 writes FAULTED in this engine and
    /// have not landed since (bsv-low #559): a successor that finds no coin
    /// while its predecessor is in here is not recorded as applied. One
    /// invocation's memory; across invocations the same question is put to
    /// the store ([`Engine::unlanded_predecessor`]).
    not_landed: std::cell::RefCell<HashSet<(String, String)>>,
    /// Asked before the door lands a carried predecessor (bsv-low #575, the
    /// E1D delta-2 fold, L2). See [`Engine::set_landing_guard`].
    landing_guard: Option<LandingGuard>,
    /// Reference-parity spend verification on submit (2026-09-08). `true`
    /// (DEFAULT): every submit outside `HistoricalTxNoSpv` runs the
    /// reference's `Transaction.verify` walk: merkle paths against the chain
    /// tracker AND every input's unlocking script EXECUTED, recursively over
    /// the unproven ancestry in the BEEF; with no chain tracker the walk is
    /// the ts-sdk's `'scripts only'` (roots accepted unchecked, scripts still
    /// run). `false` is an ESCAPE HATCH, not a mode: it restores the
    /// pre-2026-09-08 structural check (`Beef::verify_valid` + every root
    /// against the tracker; NOTHING without a tracker), which admitted an
    /// invalid spend on structure alone. See
    /// [`Engine::set_script_verification`].
    verify_scripts: bool,
    /// The two limbs of the submit's own script walk (bsv-low #592): the
    /// door's [`DoorBudget`], [`DoorBudget::DEFAULT`] unless set. See
    /// [`Engine::set_walk_budget`].
    walk_budget: DoorBudget,
    config: EngineConfig,
}

/// Boxed platform sleep future (bsv-low#302). Not `Send` — the engine runs
/// single-threaded on wasm (Workers) and under `#[tokio::test]` locally.
pub type SleepFuture = std::pin::Pin<Box<dyn std::future::Future<Output = ()>>>;

/// Platform sleep factory (bsv-low#302): milliseconds → a future that
/// resolves after that delay. The Cloudflare crate passes its `sleep_ms`;
/// tests pass `ready(())` (instant deadline) or `pending()` (no deadline)
/// to drive the race deterministically.
pub type SleepFactory = std::rc::Rc<dyn Fn(u64) -> SleepFuture>;

/// The answer of a [`LandingGuard`]: `Ok` lets the body land, `Err` says why
/// it may not (the topic waits).
pub type LandingGuardFuture =
    std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), String>>>>;

/// The caller's admission predicate over a carried predecessor the door is
/// about to land: `(predecessor txid, topic)`. See
/// [`Engine::set_landing_guard`].
pub type LandingGuard = std::rc::Rc<dyn Fn(&str, &str) -> LandingGuardFuture>;

/// The bound of ONE GASP finalize submit's storage calls and hooks (bsv-low
/// #559, the lens fold of 2026-10-07, F2). The submit itself is never
/// dropped: it is the write section no deadline drops, and c9921ee, which
/// raced the whole submit against its budget inside the section, dropped it
/// between two writes all the same. Each storage call, lookup hook and topic
/// manager call inside it is raced against the section's ONE deadline
/// instead, and a call that has not answered when the deadline falls due is
/// dropped ALONE and reported as that call's fault: the submit runs on to
/// its end as for any storage fault. Once the deadline is due no further
/// call is started (each answers "no answer" at once), so a transaction
/// costs at most its budget, and once more for the undo
/// ([`CallBound::renew`]).
struct CallBound {
    sleep: SleepFactory,
    budget_ms: u64,
    deadline: std::cell::RefCell<SleepFuture>,
    due: std::cell::Cell<bool>,
}

impl CallBound {
    fn new(sleep: &SleepFactory, budget_ms: u64) -> Self {
        Self {
            deadline: std::cell::RefCell::new(sleep(budget_ms)),
            sleep: sleep.clone(),
            budget_ms,
            due: std::cell::Cell::new(false),
        }
    }

    /// A fresh allowance of the same length, for the undo of a faulted
    /// submit: the calls that put the store back as it was found must not be
    /// refused because the deadline the fault answered to has passed.
    fn renew(&self) {
        *self.deadline.borrow_mut() = (self.sleep)(self.budget_ms);
        self.due.set(false);
    }

    /// Whether a call under this bound went unanswered (or was not started
    /// because one had) since the last [`CallBound::renew`].
    fn is_due(&self) -> bool {
        self.due.get()
    }

    /// `call`, or `None` when the deadline fell due first.
    async fn call<T>(&self, call: impl std::future::Future<Output = T>) -> Option<T> {
        if self.due.get() {
            return None;
        }
        let mut call = std::pin::pin!(call);
        std::future::poll_fn(|cx| {
            if let std::task::Poll::Ready(v) = call.as_mut().poll(cx) {
                return std::task::Poll::Ready(Some(v));
            }
            if self.deadline.borrow_mut().as_mut().poll(cx).is_ready() {
                self.due.set(true);
                return std::task::Poll::Ready(None);
            }
            std::task::Poll::Pending
        })
        .await
    }
}

/// `call` under `bound` (or unbounded with none); `Err` is "no answer".
async fn bounded<T>(
    bound: Option<&CallBound>,
    call: impl std::future::Future<Output = T>,
) -> Result<T, String> {
    match bound {
        Some(bound) => bound
            .call(call)
            .await
            .ok_or_else(|| format!("no answer within {} ms", bound.budget_ms)),
        None => Ok(call.await),
    }
}

/// A storage call under `bound`: no answer in time is that call's fault.
async fn stored<T>(
    bound: Option<&CallBound>,
    call: impl std::future::Future<Output = Result<T, StorageError>>,
) -> Result<T, StorageError> {
    match bounded(bound, call).await {
        Ok(answer) => answer,
        Err(no_answer) => Err(StorageError::Database(no_answer)),
    }
}

/// A lookup hook under `bound`, its error as the report carries it.
async fn hooked(
    bound: Option<&CallBound>,
    call: impl std::future::Future<Output = Result<(), LookupServiceError>>,
) -> Result<(), String> {
    bounded(bound, call).await?.map_err(|e| e.to_string())
}

/// The most store reads [`Engine::unlanded_predecessor`] makes for one
/// topic of one submit (bsv-low #559, F3): the question is asked of every
/// transaction that admits nothing and found no coin, so it is kept cheap.
/// Counted are the reads spent on a body the BEEF does not prove and the
/// store does not hold as landed (the second delta fold of 2026-10-07, M2);
/// the 17th of those is never made: out of reads is "not now" (the delta
/// fold of 2026-10-07, M2). An unproven body still needs room under it for
/// the reads that find it landed (one for an applied row, two for a held
/// output): each is tested before it is made.
const PREDECESSOR_READS: usize = 16;

/// The most store reads [`Engine::unlanded_predecessor`] makes for one
/// SUBMIT (the third delta fold of 2026-10-07, M1): every read of the
/// question, counted against [`PREDECESSOR_READS`] or not (those of proven
/// and landed bodies included), in every topic of the submit together. The
/// 257th is never made: past the allowance the answer is "not now", never
/// "landed". Without it the question read as far as the BEEF reached (one
/// read per 41 bytes: 66,305 reads measured from one 2.7 MB BEEF), on a
/// public route. Per submit and not per topic because what it protects, the
/// invocation's D1 allowance, is per invocation; 256 is the door's own unit
/// ([`DoorBudget`]'s inputs per transaction), no derived figure.
const PREDECESSOR_READS_PER_SUBMIT: usize = 256;

/// Why a successor must wait ([`Engine::unlanded_predecessor`]), and the
/// unlanded predecessor whose body the BEEF carries, when the answer names
/// one: the door lands it first ([`Engine::land_carried`]).
/// A submit's STEAK and report, and the carried predecessor that blocks each
/// topic of a carried predecessor's own submit ([`Engine::submit_counted`]).
type Counted = (Steak, MutationReport, HashMap<String, String>);

/// What the landings of carried predecessors take from their successor's
/// submit (the E592 lens fold, M1): its breach policy, and whether its own
/// walk RAN (only then are the bodies it reached trusted).
#[derive(Debug, Clone, Copy)]
struct Landing {
    policy: WalkBreachPolicy,
    subject_walk_ran: bool,
}

struct NotNow {
    why: String,
    carried: Option<String>,
}

/// Summary of an [`Engine::complete_missing_proofs`] pass.
///
/// All counts are over the single bounded page scanned this tick. A no-fetcher
/// (production) build returns the all-zero default.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct ProofCompletionSummary {
    /// Stored transactions inspected this tick (the bounded page size).
    pub scanned: usize,
    /// Of `scanned`, how many still lacked a merkle proof for their own tx.
    pub proofless: usize,
    /// Proofless txs whose BUMP was fetched + stitched into the stored BEEF.
    pub completed: usize,
    /// Proofless txs the fetcher could serve but that are not yet mined
    /// (no BUMP yet) — retried on a later tick.
    pub still_unconfirmed: usize,
    /// Proofless txs the fetcher errored on (e.g. budget exhausted, 429) —
    /// retried on a later tick.
    pub fetch_failed: usize,
    /// Proofless txs whose proof came back but failed to stitch into storage.
    pub stitch_failed: usize,
    /// Scanned rows that ALREADY carried a valid proof (stale `has_proof = 0`
    /// flag) and were marked proven this tick so they drop out of the candidate
    /// window — clearing the window-clog (#130).
    pub already_proven: usize,
}

/// Outcome of one [`Engine::sync_advertisements`] run (bsv-low #320 defect
/// 3a).
///
/// The engine used to swallow create/submit failures into `error!` and
/// return `Ok(())`, so the admin route reported `success` while zero
/// advertisements were admitted locally; a caller could not tell a
/// converged no-op (`to_create == 0`) from a silent failure. Every field
/// here is observational — the sync's behavior is unchanged, its outcome is
/// no longer hidden.
#[derive(Debug, Default, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SyncAdvertisementsReport {
    /// Advertisements the diff found missing (attempted this run). A
    /// converged node reports 0 here.
    pub to_create: usize,
    /// Stale advertisements the diff said to revoke.
    pub to_revoke: usize,
    /// `advertiser.create_advertisements` failure, verbatim.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub create_error: Option<String>,
    /// Local `Engine::submit` failure for the created ads, verbatim — the
    /// path that silently hid the self-admission failure live (our own
    /// ls_ship/ls_slap never gained our ads, so every cycle re-created all
    /// of them).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub submit_error: Option<String>,
    /// Outputs admitted per topic by the local submit (from the STEAK).
    /// A successful submit that admitted NOTHING (topic-manager refusal)
    /// shows up here as explicit zeros.
    pub admitted: std::collections::BTreeMap<String, usize>,
    /// `advertiser.find_all_advertisements` failure, verbatim (#320 M2).
    /// When set, creation was REFUSED this run: a blind read must never
    /// become "current ads = none" and re-create (re-pay) the entire set.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lookup_error: Option<String>,
    /// Stale ads the diff wanted revoked but the advertiser declined to
    /// build a revocation for (the CF advertiser's documented v1 no-op —
    /// #320 L2). Distinguishes "revoke happened" from "revoke skipped".
    pub revoke_skipped: usize,
    /// `advertiser.revoke_advertisements` failure, verbatim.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub revoke_error: Option<String>,
    /// Local `Engine::submit` failure for the revocation, verbatim.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub revoke_submit_error: Option<String>,
}

impl SyncAdvertisementsReport {
    /// True when nothing errored. NOTE: a submit that admitted zero outputs
    /// is not an error at this layer — that refusal is [`Self::effective`]'s
    /// job.
    #[must_use]
    pub fn ok(&self) -> bool {
        self.create_error.is_none()
            && self.submit_error.is_none()
            && self.lookup_error.is_none()
            && self.revoke_error.is_none()
            && self.revoke_submit_error.is_none()
    }

    /// Total outputs admitted by the local submit across topics.
    #[must_use]
    pub fn admitted_total(&self) -> usize {
        self.admitted.values().sum()
    }

    /// True when the run errored nowhere AND the local submit admitted
    /// EVERY created ad (#320 M1 + delta D1): each advertisement is exactly
    /// one output and change is never a SHIP/SLAP token, so full admission
    /// means `admitted_total() >= to_create` (defensive `>=`). A weaker
    /// `> 0` bar let a PARTIAL admit pass — the live set is 9 SHIP + 8 SLAP
    /// in ONE tx with independent per-topic admission, so tm_ship admitting
    /// its 9 while tm_slap refused all 8 read as success while the diff
    /// re-created (re-paid for) the refused 8 every cycle. Subsumes the
    /// converged no-op (`0 >= 0`).
    #[must_use]
    pub fn effective(&self) -> bool {
        self.ok() && self.admitted_total() >= self.to_create
    }
}

/// Internal result from Phase 1 + 2 validation.
///
/// Carries per-topic admittance decisions, previous coins, and the parsed
/// transaction so that Phase 3 (mutations) can proceed without re-parsing.
struct TopicValidation {
    topic: String,
    is_dupe: bool,
    /// Input indices that spend previously-admitted outputs from this topic.
    previous_coins: Vec<u32>,
    /// The previous outputs found in storage (parallel to previous_coins).
    previous_outputs: Vec<Output>,
    admittance: AdmittanceInstructions,
    failed: bool,
    /// The FIRST storage read fault hit while scanning this topic's
    /// previous outputs (S2, bsv-low 2026-08-29). A faulted read makes a
    /// spend look like it consumes nothing — the settle's spend pointer is
    /// then never written — so it is carried into the [`MutationReport`]
    /// and blocks the `applied_transactions` record for this topic: a
    /// replay re-reads instead of being deduplicated away. With the read
    /// that faulted: `find_output` (a previous coin) or
    /// `does_applied_transaction_exist` (the dedup read, the delta fold of
    /// 2026-10-07, H3).
    read_fault: Option<(&'static str, String)>,
}

/// One Phase-3 write — or the validation read it depends on — that FAILED
/// during a submit (S2 queue-durable admission, bsv-low 2026-08-29).
///
/// Before this existed every such failure was `error!`-logged and swallowed
/// while `submit` returned `Ok(steak)`: under a D1-overload storm the
/// overlay ACKED admissions whose writes never landed (the 2026-08-26
/// phantom class — `c4d2ed06…`/`62c2a9b3…` absent from the engine store,
/// beta D1 queried directly). A fault is now a VALUE the caller can act on
/// (re-queue for an idempotent replay) instead of a log line nobody reads.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MutationFault {
    /// The topic whose mutation faulted.
    pub topic: String,
    /// The write (or read) that failed: `insert_output`,
    /// `mark_utxo_as_spent`, `update_consumed_by`, `delete_utxo_deep`,
    /// `insert_applied_transaction`, `find_output` (validation read),
    /// `does_applied_transaction_exist` (the dedup read),
    /// `lookup_service.output_spent`, `lookup_service.output_admitted_by_topic`,
    /// `undo_insert_output` (the undo of a faulted submit's inserts),
    /// `record_spent_coin_applied` (the applied row a spender writes for the
    /// transaction of a coin it deletes), `predecessor_not_landed`.
    pub site: &'static str,
    /// The backend's own error text.
    pub error: String,
}

/// What Phase 3 actually landed for a submit — the durability report.
///
/// `applied_topics` are the topics whose EVERY write (and lookup-service
/// notification) succeeded and were therefore recorded in
/// `applied_transactions`. A topic with any fault is deliberately NOT
/// recorded: the dedup in Phase 1 would otherwise turn a replay into a
/// no-op and make the loss permanent (the ordering was already
/// write-then-record; the record is now conditional on the writes).
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct MutationReport {
    pub faults: Vec<MutationFault>,
    pub applied_topics: Vec<String>,
    /// Topics this (txid, topic) pair had ALREADY been applied under — the
    /// Phase-1 dedup skipped them, so their STEAK entry is an empty default
    /// that means "nothing new", never "judged another tx" (loop-3 client
    /// belt re-presents read the empty STEAK as index-pending).
    pub deduped_topics: Vec<String>,
    /// The predecessors the door LANDED first from this submit's BEEF, as
    /// `(txid, topic)`, ancestors first ([`Engine::land_carried`]; the E1D
    /// delta fold, L2). Each is an admission write of its own that no
    /// caller asked for: a caller that guards its admission writes (the
    /// worker's eviction ledger, bsv-low #513) guards these too.
    pub landed_predecessors: Vec<(String, String)>,
    /// The submit's own script walk could not run within the engine's
    /// budget (bsv-low #592) and the submit went on as under
    /// `HistoricalTxNoSpv` ([`WalkBreachPolicy::NetworkAccepted`] only; under
    /// `NotNow` a breach is [`EngineError::WalkCouldNotRun`]). `None` when it
    /// ran (or the mode does not walk). A caller counts it; it never makes a
    /// report undurable.
    pub walk_could_not_run: Option<WalkCouldNotRun>,
    /// The walks of the carried predecessors this submit tried to land
    /// ([`Engine::land_carried`]) that could not run within the budget (the
    /// E592 lens fold, L3): under `NotNow` each one's landing did not happen
    /// (the successor waits), under `NetworkAccepted` each went on. Counted
    /// by the caller beside `walk_could_not_run`.
    pub landed_walks_could_not_run: Vec<WalkCouldNotRun>,
}

/// bsv-low PLAN-PRE-LOOP4 §H4 (2026-09-06): what [`Engine::renotify_admitted`] did.
#[derive(Debug, Default, Clone, PartialEq, Eq, serde::Serialize)]
pub struct RenotifyReport {
    /// stored outputs of (txid, topic) the engine had ALREADY admitted
    pub outputs: u32,
    /// lookup-service notifications that returned Ok (outputs × services)
    pub notified: u32,
    /// notifications that failed — `<service>: <error>`; the others still ran
    pub faults: Vec<String>,
    /// the output indexes re-notified (the caller's spend discovery keys on them)
    pub vouts: Vec<u32>,
}

impl MutationReport {
    fn fault(&mut self, topic: &str, site: &'static str, error: String) {
        self.faults.push(MutationFault {
            topic: topic.to_string(),
            site,
            error,
        });
    }

    /// True when every mutation this submit needed landed (nothing to
    /// replay). A dupe-only submit is durable (there was nothing to write).
    #[must_use]
    pub fn is_durable(&self) -> bool {
        self.faults.is_empty()
    }

    /// One log line naming every fault (`topic/site: error`), each error
    /// clipped so a D1 stack dump cannot flood the log stream.
    #[must_use]
    pub fn summary(&self) -> String {
        self.faults
            .iter()
            .map(|f| {
                let err: String = f.error.chars().take(120).collect();
                format!("{}/{}: {}", f.topic, f.site, err)
            })
            .collect::<Vec<_>>()
            .join("; ")
    }
}

/// The DOOR's static work bound (bsv-low W-A gate MED-1, 2026-09-09). Bitcoin
/// script has no loops: every opcode runs at most once, so an input's work is
/// bounded BEFORE execution by its opcode census times the interpreter's
/// element limit (the stack memory limit bounds every element, and every
/// CAT / NUM2BIN / SPLIT result with it) plus its signature checks times the
/// transaction's own size or a floor, whichever is more (a BIP-143 preimage
/// hashes the prevouts and the outputs; the EC verification costs the same
/// whatever the transaction weighs). The estimate is computed from the bytes;
/// nothing executes past the budget, and a budget breach is the DOOR's
/// verdict (inconclusive: the network judges), never the interpreter's.
///
/// THE BODY IS NOT COUNTED (bsv-low #585, door 1). Until #585 the budget also
/// counted the BODY: 64 unproven transactions, 256 inputs per transaction,
/// 512 KB per transaction, and the parse's own size and counts. A valid BEEF
/// is never left unjudged for its size or its counts, so those are gone: the
/// walk reads the body through the streaming reader ([`crate::script_door`]).
///
/// TWO LIMBS, both a budget whose breach is "the network judges" and never a
/// refusal: the WORK the interpreter will do, and the MEMORY the door will
/// hold beside the caller's body. Each is estimated from the bytes before it
/// is spent.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DoorBudget {
    /// The interpreter's stack memory limit: bounds every element, and is the
    /// unit of the work estimate (a hash-class opcode is charged one element).
    /// Not a bound on the BEEF: a script that trips it is "the network
    /// judges", as a breach of the work is.
    pub memory_limit: usize,
    /// The whole walk's estimated work, in bytes hashed or pushed.
    pub max_work_bytes: u64,
    /// The least a signature check is charged (the doors lens E585-D12-M1).
    /// A check is charged `max(its transaction's bytes, this)`: the digest
    /// hashes about the transaction, and the EC verification behind it costs
    /// the same whatever the transaction weighs (about 95 us native). Charged
    /// the transaction's bytes alone, a 106 byte `OP_CHECKSIG OP_NOT`
    /// transaction bought a verification for 106 bytes of budget: 90,000 of
    /// them walked at a fifth of the budget in 9.6 s. With the floor the
    /// budget bounds the EC verifications of one walk at
    /// `max_work_bytes / sig_check_floor`.
    pub sig_check_floor: u64,
    /// The whole walk's estimated memory beside the body, in bytes (the doors
    /// lens E585-D12-L3): what the index, the stream's element in hand and
    /// the walk's layout of a transaction hold, estimated from the frame's
    /// lengths and counts by [`crate::stream_sizing::estimate`] BEFORE the
    /// stream is opened; and, per input, what its two scripts hold once
    /// parsed and run (the delta lens E585-D12-DELTA-M1: bsv-rs's chunk
    /// records, their clones, a signature's subscript, the empty stack
    /// entries the interpreter's memory limit does not count), charged from
    /// the scripts' chunk count and bytes BEFORE either is parsed
    /// (`script_door::script_parse_charge`, 512 bytes a chunk and 8 a byte).
    ///
    /// How the two compose: the frame's estimate is the most the walk holds
    /// at any moment apart from the input being run (what is kept, and the
    /// heaviest transaction in hand, counted once with its raw bytes and the
    /// interpreter's raw copies of the unlocking script); the scripts' charge
    /// is the EXPANSION of one input's scripts past those bytes, held while
    /// that input runs and released after it. An input is run only while the
    /// frame's estimate plus its own charge is within this limb.
    pub max_memory_bytes: u64,
}

impl DoorBudget {
    /// Sized for LOW's real shapes with a wide margin. What the static census
    /// BOUNDS: hashing (hash-class ops × the element limit) and signature
    /// checks (× the transaction's size or the floor, whichever is more; a
    /// CHECKMULTISIG weighted by its static key count when the count is a
    /// small-int push, else by the most keys the element limit admits).
    ///
    /// THE FLOOR, 64 KiB (half the hash charge), chosen against LOW's shapes
    /// as the pin `door_low_shapes_sit_under_a_quarter_of_the_work_budget`
    /// measures them (work, of the 64 MiB; memory, the frame's and the
    /// largest input's scripts, of the 48 MiB limb; work before the floor in
    /// brackets):
    ///
    /// | shape | inputs | work | memory |
    /// |---|---|---|---|
    /// | the real covenant settle (5 hash opcodes, 4 checks: a CHECKSIG and the stated `OP_3` CHECKMULTISIG) | 1 | 924,112, 1.4 % (676,284) | 1,282,178, 2.55 % |
    /// | the real covenant refund | 1 | 924,112, 1.4 % (676,284) | 1,282,178, 2.55 % |
    /// | LOW's JOIN: two seats (bsv-low `template_tx_sizes.rs:76`), the real pot lock, each coin 40 unproven P2PKH hops deep (the deepest the fleet's record names) | 82 | 16,132,638, 24.0 % | 67,026, 0.13 % |
    /// | STRESS, not LOW's shape: nine seats, three hops each | 36 | 7,082,619, 10.6 % (4,740,838) | 36,420, 0.07 % |
    /// | a coin 30 P2PKH hops deep | 30 | 5,902,188, 8.8 % (3,941,856) | 23,720, 0.05 % |
    ///
    /// A P2PKH input is charged 196,739 bytes (a hash opcode at
    /// the element limit, a check at the floor, its 131 script bytes): 341 of
    /// them are the budget, 85 a quarter of it. The bound on EC verifications
    /// per walk is 64 MiB / 64 KiB = 1,024 (1,023 with their script bytes):
    /// measured natively, 1,000 of them walk in 87 ms in the release profile
    /// (1.4 to 1.8 s in a debug build), and the lens's 17,000 stop at the
    /// 1,024th in 108 ms. wasm32 was not measured.
    ///
    /// THE MEMORY, 48 MiB: three eighths of a 128 MB isolate. Beside it stand,
    /// for a 10 MB request (the figure the arithmetic is made at: since NL-6
    /// the route caps no body, so a heavier one is the isolate's), the
    /// request's body, the completed BEEF the route hands the door (a second
    /// copy of up to as much) and the EF batch (the route's 2 MB bound, twice
    /// while it is serialized): 24 MB, which leaves 56 MB for the module, the
    /// runtime, the allocator's fragmentation and what a native estimate does
    /// not see of wasm32. The limb bounds the walk (the door's, and since
    /// bsv-low #592 the submit's own and the GASP anchor's under
    /// [`Engine::set_walk_budget`]) and nothing else: the route's own
    /// hydrated parses before it are bounded by the isolate only (the land
    /// lens E585-LAND-M1: 1.43 GB natively for a 9.9 MB body of 900,000
    /// minimal transactions, before the route's 429). What
    /// it lets through, by the door's charges (`script_door::DOOR_CHARGES`,
    /// each an upper bound: the pins measure 1.3 to 5.3 times the heap the
    /// walk reaches): a BUMP of up to 72,944 leaves (690 bytes a level-0
    /// leaf); a single transaction of up to about 12 MB (4 bytes a byte)
    /// whose walked inputs' scripts are few chunks (a script is charged 520
    /// bytes a one-byte opcode and 8 a pushed byte: an input whose two
    /// scripts are about 96,000 opcodes, or a 1 MB `OP_NOP` lock, is past
    /// the limb before it is parsed, the network judges; LOW's covenant leg,
    /// 6,608 script bytes, is charged 1.3 MB); a 10 MB body of one-input,
    /// one-output P2PKH transactions (191 bytes, charged 570: 30 MB). What it
    /// stops: 111,848 transactions of no input and no output, whatever
    /// follows them.
    ///
    /// THE OPEN RESIDUAL (the W-A gate's delta-verify, 2026-09-09, measured):
    /// the interpreter itself meters nothing, so two classes stay charged
    /// only by their script bytes — bignum arithmetic (`OP_MUL`/`OP_DIV`/
    /// `OP_MOD` on operands up to the element limit: ~1.3 ms per 30 KB×30 KB
    /// round, linear in rounds) and `OP_NUM2BIN`, which
    /// allocates its size operand BEFORE the memory limit is consulted (up to
    /// bsv-rs's 1 GB element size: an isolate kill, not a refusal). None of
    /// them can refuse a spend (a breach and a trip are the door's bound and
    /// the request proceeds); all of them cost the beta overlay CPU until
    /// bsv-rs meters work dynamically (a `work_limit` charged per op with the
    /// real operand sizes, and a pre-allocation check in NUM2BIN) — OWED
    /// before any PROD flip of `SCRIPT_VERIFY_NETWORK_GATED`. Since #585 the
    /// count of such rounds is bounded by the body alone (the script bytes
    /// are charged, the transactions and inputs are not counted). A third,
    /// as before #585 (the doors lens N7): an opcode that copies an element
    /// (`OP_DUP`, `OP_CAT`, `OP_PICK`) is charged its one script byte and can
    /// copy up to the element limit. The class the floor CLOSED: a
    /// CHECKMULTISIG whose key count is a computed value was charged the most
    /// keys the element limit admits (3,971) at its transaction's bytes and
    /// run (~80 µs per key tried); at the floor those are 260 MB, past the
    /// budget, so such an input is never run at the door (the network
    /// judges). LOW's covenant states its count (`OP_3`).
    pub const DEFAULT: DoorBudget = DoorBudget {
        memory_limit: 128 * 1024,
        max_work_bytes: 64 * 1024 * 1024,
        sig_check_floor: 64 * 1024,
        max_memory_bytes: 48 * 1024 * 1024,
    };
}

/// Which limb of the [`DoorBudget`] a walk went past.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DoorLimb {
    /// The static work estimate, or the interpreter's own memory limit
    /// tripping inside one input.
    Work,
    /// The estimate of what the door holds beside the body.
    Memory,
}

/// What [`Engine::run_validation`] answers: the topics' validations, the
/// preliminary STEAK, the subject and its txid, and whether the walk could
/// not run within the budget (bsv-low #592).
type Validated = (
    Vec<TopicValidation>,
    Steak,
    Transaction,
    String,
    Option<WalkCouldNotRun>,
);

/// Which limb of the [`DoorBudget`] a submit's own walk went past (bsv-low
/// #592): the [`DoorLimb`] of the door's error, with the interpreter's own
/// memory limit told apart from the static work estimate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WalkLimb {
    /// The static work estimate.
    OverWork,
    /// The estimate of what the walk holds beside the body.
    OverMemory,
    /// The interpreter's own memory limit (the budget's element limit)
    /// tripping inside one input.
    InterpreterMemory,
}

impl WalkLimb {
    /// The door's word for the same limb ([`DoorLimb`]: the interpreter's
    /// trip is `Work` there).
    #[must_use]
    pub fn door_limb(self) -> DoorLimb {
        match self {
            WalkLimb::OverWork | WalkLimb::InterpreterMemory => DoorLimb::Work,
            WalkLimb::OverMemory => DoorLimb::Memory,
        }
    }

    /// The limb's name in a log line and a counter's reason.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            WalkLimb::OverWork => "over_work",
            WalkLimb::OverMemory => "over_memory",
            WalkLimb::InterpreterMemory => "interpreter_memory",
        }
    }
}

/// What a submit does when its own script walk could not run within the
/// engine's [`DoorBudget`] (bsv-low #592; the E592 lens fold, H1, the owner's
/// ruling 3a read with the lens): a breach is NEVER an admission without the
/// network's word on record.
///
/// The work limb is a static estimate from the bytes, and a LOCK can be made
/// to pass it cheaply (a bare `OP_CHECKMULTISIG` in a fabricated parent's
/// lock is charged 3,971 keys). So a breach says nothing about whether the
/// spend is valid, and on a path where nothing else judges it an admission
/// would admit a spend nobody checked: the lens's forged spend of a held coin.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WalkBreachPolicy {
    /// "Not now" ([`EngineError::WalkCouldNotRun`]): nothing judged, nothing
    /// written, never a final refusal. Every door but one: the ungated
    /// modes, `/admin/readmit`, the peer crawler, a library consumer's
    /// submit; the GASP anchor HOLDS its UTXO the same way.
    #[default]
    NotNow,
    /// The network's ACCEPT of these bytes is on record (the queue's replay
    /// of a gated submission, whose producer broadcast them and marked the
    /// message): the submit goes on exactly as under `HistoricalTxNoSpv`,
    /// reported on [`MutationReport::walk_could_not_run`]. The roots the walk
    /// reached are still checked, and a bad one is still the `SpvError` it is.
    NetworkAccepted,
}

/// A submit whose own script walk COULD NOT RUN within the engine's
/// [`DoorBudget`] (bsv-low #592, the owner's ruling 3a of 2026-10-10). Shaped
/// like [`EngineError::ScriptWalkOverBudget`]. Under
/// [`WalkBreachPolicy::NotNow`] it is carried by
/// [`EngineError::WalkCouldNotRun`] (not now); under
/// [`WalkBreachPolicy::NetworkAccepted`] the submit went on as under
/// `HistoricalTxNoSpv` and this says so on its [`MutationReport`]. The
/// reference (`Engine.submit`, `tx.verify`) has no budget; this is the
/// platform's addition, on the door's lineage (D8).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WalkCouldNotRun {
    /// The submitted transaction.
    pub subject_txid: String,
    /// The transaction the walk stopped at.
    pub at_txid: String,
    /// Whether the subject's own inputs had all executed before the stop.
    pub subject_judged: bool,
    /// The limb it went past.
    pub limb: WalkLimb,
    /// The estimate against the limb, in the door's words.
    pub what: String,
}

/// What the walk did (the door's cost instrument, since `Date.now()` is
/// frozen during synchronous work on Workers and cannot time it).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct WalkStats {
    /// Unproven transactions whose inputs were executed.
    pub unproven_txs: usize,
    /// Inputs executed (scripts run).
    pub inputs_executed: usize,
    /// Unlocking + locking script bytes executed.
    pub script_bytes: usize,
    /// Hash-class opcodes seen (SHA1/SHA256/HASH160/HASH256/RIPEMD160).
    pub hash_ops: usize,
    /// Signature checks seen (CHECKSIG counts 1, CHECKMULTISIG counts its
    /// consensus maximum of 20).
    pub sig_ops: usize,
    /// The static work estimate charged against the budget.
    pub work_bytes: u64,
    /// The memory estimate charged against the budget: the frame's, made
    /// before the stream was opened, plus the largest charge of one walked
    /// input's scripts, made before they were parsed.
    pub memory_bytes: u64,
    /// Whether the SUBJECT's own inputs were all executed (an ancestor may
    /// still have faulted afterwards).
    pub subject_judged: bool,
}

/// Static opcode census of one input's scripts: (bytes, hash ops, sig ops).
///
/// A CHECKMULTISIG is weighted by its KEY COUNT: the small-int push that
/// precedes it when the script states the count (the Poc5 covenant's
/// `OP_3`), else the most 33-byte keys the element limit admits (the count is
/// a computed value the census cannot see; bsv-rs allows up to `i32::MAX`).
pub(crate) fn script_census(
    unlocking: &[u8],
    locking: &[u8],
    memory_limit: usize,
) -> Result<(usize, usize, usize), String> {
    use bsv_rs::script::op::*;
    let most_keys = (memory_limit / 33).max(1);
    let mut hash_ops = 0usize;
    let mut sig_ops = 0usize;
    for (label, bytes) in [("unlocking", unlocking), ("locking", locking)] {
        let script = bsv_rs::script::Script::from_binary(bytes)
            .map_err(|e| format!("{label} script does not parse: {e}"))?;
        let chunks = script.chunks();
        for (i, chunk) in chunks.iter().enumerate() {
            match chunk.op {
                OP_RIPEMD160 | OP_SHA1 | OP_SHA256 | OP_HASH160 | OP_HASH256 => hash_ops += 1,
                OP_CHECKSIG | OP_CHECKSIGVERIFY => sig_ops += 1,
                OP_CHECKMULTISIG | OP_CHECKMULTISIGVERIFY => {
                    let stated = i
                        .checked_sub(1)
                        .map(|j| chunks[j].op)
                        .and_then(|op| match op {
                            OP_1..=OP_16 => Some((op - OP_1 + 1) as usize),
                            _ => None,
                        });
                    sig_ops += stated.unwrap_or(most_keys);
                }
                _ => {}
            }
        }
    }
    Ok((unlocking.len() + locking.len(), hash_ops, sig_ops))
}

impl Engine {
    /// Page size used by `/requestSyncResponse` when the (public) caller
    /// omits `limit`. A bounded page is not lossy for a conforming
    /// initiator: ours ([`crate::gasp::GASPSync`]) keeps requesting pages
    /// for as long as the `since` score cursor advances (gate finding M1 —
    /// it must NOT require a "full" page to continue, because this clamp
    /// makes a full-by-the-initiator's-limit page impossible).
    pub const SYNC_RESPONSE_DEFAULT_LIMIT: u64 = 500;
    /// Hard cap on a `/requestSyncResponse` page. Before bsv-low #291 an
    /// absent/huge caller-supplied limit meant an unbounded scan of the
    /// outputs table on a public route.
    pub const SYNC_RESPONSE_MAX_LIMIT: u64 = 1000;

    /// Clamp the public `/requestSyncResponse` page size: absent → the
    /// default page; anything larger than the cap → the cap. The result is
    /// ALWAYS `Some`-worthy — a sync response is never unbounded (bsv-low
    /// #291). Completeness relies on the INITIATOR paging while its `since`
    /// cursor advances (see `SYNC_RESPONSE_DEFAULT_LIMIT`'s doc) — the
    /// responder alone cannot page for it.
    pub fn clamp_sync_limit(requested: Option<u64>) -> u64 {
        requested
            .unwrap_or(Self::SYNC_RESPONSE_DEFAULT_LIMIT)
            .min(Self::SYNC_RESPONSE_MAX_LIMIT)
    }

    /// Create a new Overlay Services Engine.
    pub fn new(
        managers: HashMap<String, Box<dyn TopicManager>>,
        lookup_services: HashMap<String, Box<dyn LookupService>>,
        storage: Box<dyn Storage>,
        advertiser: Option<Box<dyn Advertiser>>,
        config: EngineConfig,
    ) -> Self {
        Self::with_chain_tracker(
            managers,
            lookup_services,
            storage,
            advertiser,
            None,
            None,
            config,
        )
    }

    /// Create a new Engine with an optional ChainTracker for SPV verification.
    pub fn with_chain_tracker(
        managers: HashMap<String, Box<dyn TopicManager>>,
        lookup_services: HashMap<String, Box<dyn LookupService>>,
        storage: Box<dyn Storage>,
        advertiser: Option<Box<dyn Advertiser>>,
        broadcaster: Option<Box<dyn Broadcaster>>,
        chain_tracker: Option<Box<dyn bsv_rs::transaction::ChainTracker>>,
        config: EngineConfig,
    ) -> Self {
        Self::with_all(
            managers,
            lookup_services,
            storage,
            advertiser,
            broadcaster,
            None,
            chain_tracker,
            config,
        )
    }

    /// Create a new Engine with all optional components.
    #[allow(clippy::too_many_arguments)]
    pub fn with_all(
        managers: HashMap<String, Box<dyn TopicManager>>,
        lookup_services: HashMap<String, Box<dyn LookupService>>,
        storage: Box<dyn Storage>,
        advertiser: Option<Box<dyn Advertiser>>,
        broadcaster: Option<Box<dyn Broadcaster>>,
        arc_broadcaster: Option<Box<dyn ArcBroadcaster>>,
        chain_tracker: Option<Box<dyn bsv_rs::transaction::ChainTracker>>,
        mut config: EngineConfig,
    ) -> Self {
        // Build default sync configuration: SHIP for all topics except tm_ship/tm_slap
        // which get their trackers merged with provided shipTrackers/slapTrackers.
        for manager_name in managers.keys() {
            if manager_name == "tm_ship" {
                if matches!(
                    config.sync_configuration.get(manager_name),
                    Some(SyncTarget::Disabled)
                ) {
                    continue;
                }
                let mut combined: HashSet<String> = HashSet::new();
                if let Some(SyncTarget::Peers(peers)) = config.sync_configuration.get(manager_name)
                {
                    combined.extend(peers.iter().cloned());
                }
                combined.extend(config.ship_trackers.iter().cloned());
                if !combined.is_empty() {
                    config.sync_configuration.insert(
                        manager_name.clone(),
                        SyncTarget::Peers(combined.into_iter().collect()),
                    );
                }
            } else if manager_name == "tm_slap" {
                if matches!(
                    config.sync_configuration.get(manager_name),
                    Some(SyncTarget::Disabled)
                ) {
                    continue;
                }
                let mut combined: HashSet<String> = HashSet::new();
                if let Some(SyncTarget::Peers(peers)) = config.sync_configuration.get(manager_name)
                {
                    combined.extend(peers.iter().cloned());
                }
                combined.extend(config.slap_trackers.iter().cloned());
                if !combined.is_empty() {
                    config.sync_configuration.insert(
                        manager_name.clone(),
                        SyncTarget::Peers(combined.into_iter().collect()),
                    );
                }
            } else if !config.sync_configuration.contains_key(manager_name) {
                config
                    .sync_configuration
                    .insert(manager_name.clone(), SyncTarget::Ship);
            }
        }

        Self {
            managers,
            lookup_services,
            storage,
            advertiser,
            broadcaster,
            arc_broadcaster,
            chain_tracker,
            gasp_remote_factory: None,
            ship_lookup_client: None,
            ship_bootstrap_peers: HashMap::new(),
            ancestor_fetcher: None,
            gasp_ancestor_fetcher: None,
            peer_sync_budget: None,
            graph_budget: None,
            graph_budget_limbs: (
                crate::gasp::DEFAULT_GRAPH_BUDGET_BYTES,
                crate::gasp::DEFAULT_GRAPH_BUDGET_NODES,
            ),
            finalize_submit_budget: None,
            finalize_gate: crate::gasp::SubmitGate::default(),
            not_landed: std::cell::RefCell::new(HashSet::new()),
            landing_guard: None,
            verify_scripts: true,
            walk_budget: DoorBudget::DEFAULT,
            config,
        }
    }

    /// Set the ARC broadcaster for network broadcast to miners.
    ///
    /// When set, the Engine broadcasts transactions to ARC during Phase 2
    /// of `submit()` for `CurrentTx` submissions.
    pub fn set_arc_broadcaster(&mut self, arc: Box<dyn ArcBroadcaster>) {
        self.arc_broadcaster = Some(arc);
    }

    /// Set the GASP remote factory for peer communication during sync.
    ///
    /// Platform-specific crates (like overlay-cloudflare) provide an implementation
    /// that creates HTTP-based remotes using their native fetch API.
    pub fn set_gasp_remote_factory(&mut self, factory: Box<dyn crate::gasp::GASPRemoteFactory>) {
        self.gasp_remote_factory = Some(factory);
    }

    /// Set the platform lookup transport for network SHIP discovery.
    /// Trackers come from [`EngineConfig::slap_trackers`].
    pub fn set_ship_lookup_client(
        &mut self,
        client: Box<dyn crate::ship_lookup::ShipLookupClient>,
    ) {
        self.ship_lookup_client = Some(client);
    }

    /// Keep these peers in a topic's SHIP union even when trackers fail.
    /// This leaves the existing [`SyncTarget`] serialization unchanged.
    /// Such topics run ahead of tracker imports so discovery and sync can
    /// proceed without spending the tick on importing discovery records.
    pub fn set_ship_bootstrap_peers(&mut self, topic: impl Into<String>, peers: Vec<String>) {
        self.ship_bootstrap_peers.insert(topic.into(), peers);
    }

    /// Set the OPT-IN chain-backed ancestor fetcher for GASP ingest.
    ///
    /// **OFF BY DEFAULT.** When set, a peer's failure to serve a needed
    /// ancestor during GASP ingest falls back to fetching that ancestor's raw
    /// tx from chain (via the supplied fetcher), self-healing the graph and
    /// also enabling strict-BEEF finalize so missing ancestry fails loud.
    ///
    /// This is a deliberate one-time-migration escape hatch. Production must
    /// NOT call this — when unset, GASP ingest behavior is unchanged.
    pub fn set_ancestor_fetcher(&mut self, fetcher: std::rc::Rc<dyn crate::gasp::AncestorFetcher>) {
        self.ancestor_fetcher = Some(fetcher);
    }

    /// Supply a courier reserved for sync. Completion retains its own budget.
    pub fn set_gasp_ancestor_fetcher(
        &mut self,
        fetcher: std::rc::Rc<dyn crate::gasp::AncestorFetcher>,
    ) {
        self.gasp_ancestor_fetcher = Some(fetcher);
    }

    /// Set the admission predicate asked BEFORE the door lands a carried
    /// predecessor (bsv-low #575, the E1D delta-2 fold, L2;
    /// [`Engine::land_carried`]). It is asked once per body the landing
    /// would submit, before that body's submit (a dry one included) and
    /// before its reads are charged; an `Err` (the caller's refusal, or its
    /// own read fault) ends the landing with nothing of that body written
    /// and the successor's topic answers "not now", as on `683dffd`. The
    /// worker installs its eviction ledger here: an OPEN eviction of the
    /// body refuses it. Its read is not one of the submit's 256 (it is the
    /// caller's store, at most one per landed body). Unset (default): every
    /// carried predecessor may land. What the predicate cannot see (a row
    /// opened while the landing writes) stays the caller's to guard after
    /// the write ([`MutationReport::landed_predecessors`]).
    pub fn set_landing_guard(&mut self, guard: LandingGuard) {
        self.landing_guard = Some(guard);
    }

    /// Set the per-peer GASP sync budget (bsv-low#302).
    ///
    /// `sleep` is the platform sleep factory (ms → future); `budget_ms` is
    /// the wall-clock slice ONE peer's sync may consume. A peer exceeding it
    /// is dropped (loudly logged, listed in the topic's `errors`) and the
    /// loop moves on. Unset (default) = unbounded, the pre-#302 behavior.
    ///
    /// **Progress survives the deadline (bsv-low #552).** With a budget set,
    /// every graph is submitted AS IT FINALIZES, inside the raced future (the
    /// reference submits inside `finalizeGraph` too), so what was finalized
    /// before the deadline stays admitted. At the deadline the cursor is
    /// advanced to `GASPSync::completed_cursor`: past the UTXOs whose graphs
    /// were completed, never past the one in flight. That graph is lost
    /// whole (nothing of it was finalized) and the next tick walks it again,
    /// down to whatever is now in storage.
    ///
    /// **The deadline never lands inside a transaction's writes** (the lens
    /// fold's HIGH-1). It is cooperative around a finalize submit
    /// ([`Engine::finalize_submit_gate`]): a deadline that falls due while
    /// one transaction is being written waits for that transaction, and the
    /// sync is dropped at the boundary. What a dropped tick leaves of the
    /// graph being submitted is an ancestors-first prefix of WHOLE
    /// transactions, with the cursor below its UTXO. Everywhere else (a
    /// request to the peer, the walk, the anchor check) the deadline drops
    /// the sync at once, as a budget against a dead peer must. A dropped tick that finalized a
    /// graph or moved the cursor is recorded as a SUCCESSFUL attempt for the
    /// quarantine count: a peer serving a long bootstrap is not a dead peer.
    /// One with no progress is a failed attempt, as before.
    ///
    /// The budget bounds the work of a TICK. Without a per-graph budget
    /// nothing bounds a GRAPH (parity: the reference has no node cap): one
    /// graph whose own walk outlasts the budget is dropped on every tick
    /// (`deadline_dropped_graphs`) and never admitted. With one
    /// ([`Engine::set_graph_budget`], bsv-low #555) that walk is deferred
    /// with its progress kept, here too, and resumed next tick.
    pub fn set_peer_sync_budget(&mut self, sleep: SleepFactory, budget_ms: u64) {
        self.peer_sync_budget = Some((sleep, budget_ms));
    }

    /// Set the per-GRAPH GASP budget and turn DEFERRAL on (bsv-low #555).
    ///
    /// A graph whose walk makes `max_calls` requests (to the peer, or chain
    /// fetches) or runs `budget_ms` in one pass is DEFERRED: its partial walk
    /// (the nodes fetched with their proofs, the inputs still pending, the
    /// calls spent, its age in passes) is saved as ONE record of the storage
    /// ([`Storage::put_deferred_graph`], replaced on every deferral), its
    /// UTXO is held below the cursor as a failed one is (the gap guard) and
    /// not walked again in the sync (#554), and the sync goes on to the next
    /// UTXO and topic. The next sync that is served that UTXO RESUMES the
    /// walk from the record, asking only what is pending, under the same
    /// budget; a graph so converges over passes and is then completed as
    /// any graph is (#551's anchor check, the finalize submits, e1d's
    /// rules). A walk cut by the per-peer deadline is deferred the same way.
    ///
    /// Bounds: a record deferred [`crate::gasp::DEFERRED_GRAPH_MAX_PASSES`]
    /// times is dropped with its reason and the UTXO fails as before (the
    /// gap guard asks again, from the root); a record has no byte bound
    /// (bsv-low #585); at most
    /// [`crate::gasp::DEFERRED_GRAPHS_PER_PEER_TOPIC`] records per (peer,
    /// topic). Keep `budget_ms` below the per-peer budget so that a deep
    /// graph leaves the pass time for the UTXOs after it. Defaults offered:
    /// [`crate::gasp::DEFAULT_GRAPH_BUDGET_CALLS`],
    /// [`crate::gasp::DEFAULT_GRAPH_BUDGET_MS`].
    ///
    /// Every resume of one sync shares ONE such budget (the lens fold's M1),
    /// so the deferred UTXOs, served first, leave the pass the rest; a walk
    /// that fetched nothing keeps no record and is a failed attempt for the
    /// quarantine (H1); a walk that cannot be kept, or whose save faulted,
    /// goes on under the per-peer budget alone (L4, the delta fold's D-L2);
    /// a FRESH walk's error keeps no record (D-M1). With a budget, a sync the
    /// peer served work that finalized no graph and moved no cursor is
    /// YIELDLESS, and past [`crate::gasp::PEER_YIELDLESS_SYNCS_ALLOWED`] in a
    /// row AND [`crate::gasp::PEER_YIELDLESS_SECS_ALLOWED`] since the streak
    /// began each is a failed attempt (D-M2, the delta-2 fold's D2-M1; the
    /// streak is kept by [`Storage::record_peer_sync_yield`], keyed on the
    /// peer's [`crate::gasp::peer_origin`] as its quarantine is). A FRESH
    /// walk that faults after half its calls or half its time keeps its
    /// record (D2-L1); a RESUMED one that faults having appended nothing
    /// [`crate::gasp::DEFERRED_GRAPH_MAX_IDLE_FAULTS`] passes in a row is
    /// dropped (D2-M2). Each record says whether its peer is configured
    /// (`SyncTarget::Peers`), for a storage that reserves part of its
    /// ceiling for those (the worker reserves half).
    ///
    /// Unset (the default) nothing is deferred and the walk is the one
    /// before #555 (parity: the reference has no budget and no deferral).
    /// The storage must KEEP records (the four required deferred-graph
    /// methods of [`Storage`]): over one that refuses every save, every
    /// graph past the budget is walked from its root under the per-peer
    /// budget alone on every pass, as before #555, so do not set a budget
    /// there.
    ///
    /// The budget has two more limbs (bsv-low #586), in force with it at
    /// their defaults: the bytes one graph may be SERVED in one pass
    /// ([`crate::gasp::DEFAULT_GRAPH_BUDGET_BYTES`], a budget per pass only:
    /// a record has no byte bound since bsv-low #585 door 4) and the nodes it
    /// may APPEND ([`crate::gasp::DEFAULT_GRAPH_BUDGET_NODES`], 64);
    /// [`Engine::set_graph_budget_limbs`] names others.
    pub fn set_graph_budget(&mut self, sleep: SleepFactory, max_calls: u32, budget_ms: u64) {
        self.graph_budget = Some((sleep, max_calls, budget_ms));
    }

    /// The bytes and nodes limbs of the per-graph budget (bsv-low #586,
    /// zanaadu-v2 #377): a graph whose walk is SERVED `max_bytes_fetched`
    /// bytes in one pass (the hex of each node's raw transaction and proof,
    /// as the peer sends it and a record keeps it, every answer counted), or
    /// APPENDS `max_nodes` nodes, is DEFERRED exactly as at the call budget
    /// (reason `bytes` or `nodes`): its record saved, its UTXO held below
    /// the cursor, the walk resumed by the next pass from what is pending.
    /// Never a drop, a refusal or a discarded graph: these are budgets PER
    /// PASS, not limits on a graph or a BEEF. A pass always makes one
    /// request whatever a node's size; the resumes of one sync share one
    /// such budget, as they share its calls (M1); a walk that cannot be
    /// KEPT goes on under the per-peer budget alone (L4), as at the calls.
    /// They bound what one pass adds to the pending graph and to its record
    /// while the anchor check and the finalize hold it in memory. No effect
    /// until [`Engine::set_graph_budget`] turns deferral on; the reference
    /// has neither. This setter is UNCAPPED, as the worker's
    /// `GASP_GRAPH_BUDGET_BYTES` var is (bsv-low #585 door 4: the engine keeps
    /// no record cap for the limb to sit under). A consumer whose STORAGE caps
    /// a record must keep the bytes limb under that cap, or a pass whose
    /// record cannot be saved walks afresh (E586-L1).
    pub fn set_graph_budget_limbs(&mut self, max_bytes_fetched: u64, max_nodes: u32) {
        self.graph_budget_limbs = (max_bytes_fetched, max_nodes);
    }

    /// Bound ONE transaction's GASP finalize submit (bsv-low #559, the delta
    /// lens's DELTA-3). That submit is the write section no deadline drops
    /// ([`Engine::finalize_submit_gate`]), so a storage call or lookup hook
    /// that never answers inside it held the per-peer budget and any outer
    /// race for as long as it hung. With this set EACH storage call, lookup
    /// hook and topic manager call of that submit is raced against one
    /// `sleep(budget_ms)` of the section (the lens fold of 2026-10-07, F2):
    /// a call still unanswered when it falls due is dropped alone and is
    /// that call's FAULT, and no call is started after it. The SUBMIT is
    /// never dropped: it runs to its end and leaves what a fault leaves
    /// ([`Engine::submit_with_report`]: nothing of the transaction, or all
    /// of it), the transaction did not land, the rest of its graph is not
    /// submitted, its UTXO fails and the cursor stays below it. The undo of
    /// a faulted submit has one more `sleep(budget_ms)` of its own, so a
    /// peer costs at most its budget plus twice this one. What the backend
    /// does with a statement whose caller stopped waiting is its own: a
    /// write that lands after its timeout is not seen by this submit.
    ///
    /// DEFAULT: none (a native engine has no clock). A caller that sets a
    /// per-peer budget should set this too.
    pub fn set_finalize_submit_budget(&mut self, sleep: SleepFactory, budget_ms: u64) {
        self.finalize_submit_budget = Some((sleep, budget_ms));
    }

    /// The gate around every GASP finalize submit (bsv-low #552, the lens
    /// fold's HIGH-1). `start_gasp_sync` races each peer against its budget
    /// with [`crate::gasp::race_or_deadline_guarded`] over this gate. A
    /// caller that races `start_gasp_sync` ITSELF against a deadline (the
    /// worker's scheduled step) must use the same function over the same
    /// gate: a plain `race_or_deadline` there can still drop a finalize
    /// submit between its writes.
    pub fn finalize_submit_gate(&self) -> &crate::gasp::SubmitGate {
        &self.finalize_gate
    }

    /// Turn reference-parity script verification on submit on or off.
    /// **DEFAULT ON** (set in every constructor).
    ///
    /// On, every submit outside `HistoricalTxNoSpv` executes every unproven
    /// input's unlocking script against its source output (and checks every
    /// merkle path against the chain tracker), exactly as the reference's
    /// `Engine.submit` → `tx.verify(this.chainTracker)` does. Off is an
    /// ESCAPE HATCH for an operator who must admit a body the interpreter
    /// refuses (a bsv-rs interpreter defect, say) while it is fixed. It is
    /// NOT a mode: it restores the pre-2026-09-08 structural check, under
    /// which an invalid spend that no broadcaster had yet refused was
    /// admitted on BEEF structure alone. Prefer
    /// [`crate::builder::EngineBuilder::with_script_verification`].
    pub fn set_script_verification(&mut self, enabled: bool) {
        self.verify_scripts = enabled;
    }

    /// Whether submits execute input scripts, see
    /// [`Engine::set_script_verification`]. `true` by default.
    pub fn script_verification(&self) -> bool {
        self.verify_scripts
    }

    /// The budget of the submit's own script walk (bsv-low #592, the owner's
    /// ruling 3a of 2026-10-10). Every submit that walks (every mode but
    /// `HistoricalTxNoSpv`), and the GASP anchor check, read the BEEF through
    /// the door's stream walk ([`crate::script_door`]) under this budget's
    /// two limbs, the work and the memory, each estimated from the bytes
    /// before it is spent. A breach is "the walk could not run"
    /// ([`WalkCouldNotRun`], on [`MutationReport::walk_could_not_run`]),
    /// never a refusal: the submit goes on as under `HistoricalTxNoSpv`.
    /// A library consumer that sets nothing gets [`DoorBudget::DEFAULT`]
    /// (64 MiB of work, 48 MiB of memory). Prefer
    /// [`crate::builder::EngineBuilder::with_walk_budget`].
    pub fn set_walk_budget(&mut self, budget: DoorBudget) {
        self.walk_budget = budget;
    }

    /// The budget of the submit's own script walk, see
    /// [`Engine::set_walk_budget`].
    pub fn walk_budget(&self) -> DoorBudget {
        self.walk_budget
    }

    /// The reference's `tx.verify('scripts only')` over a BEEF: every unproven
    /// transaction from `subject_txid` down executes every input's unlocking
    /// script against its source output and obeys the value rule, while a
    /// transaction that carries a merkle path is TRUSTED AS-IS — no root is
    /// computed and no chain tracker is consulted (the ts-sdk's own shape when
    /// `chainTracker === 'scripts only'`: a proven tx is added to the verified
    /// set and the walk stops there).
    ///
    /// Built for an admission path whose bar is the NETWORK, not a proof
    /// (bsv-low's `broadcast-gated`, register row D1): the overlay broadcasts
    /// and admits on network evidence, so a lagging tracker must never read as
    /// a refused transaction — but a spend the interpreter refuses is one the
    /// network will refuse too, and executing it at the door saves the
    /// broadcast and names the fault. Independent of
    /// [`Engine::set_script_verification`] (that switch governs `submit`; this
    /// is an explicit ask) and of [`Engine::submit`]'s mode (`HistoricalTxNoSpv`
    /// still skips, as the reference does).
    ///
    /// Runs under the engine's budget ([`Engine::set_walk_budget`], the
    /// submit's own; [`DoorBudget::DEFAULT`] unless set: one budget per
    /// engine, the E592 lens fold's NOTE-2): the work is bounded statically
    /// before anything executes, and the interpreter's stack memory limit is
    /// the budget's element limit. The body is read through the streaming
    /// reader ([`crate::script_door`], bsv-low #585): no bound on its size,
    /// its transactions or a transaction's inputs or bytes; the budget's two
    /// limbs are the work and the memory beside the body.
    ///
    /// Errors: [`EngineError::ScriptVerificationFailed`] is the INTERPRETER's
    /// verdict and the only refusal; [`EngineError::ScriptWalkInconclusive`]
    /// is a structural fault (a transaction or source missing from the BEEF,
    /// a parse fault, the value rule) and [`EngineError::ScriptWalkOverBudget`]
    /// the door's own bound (the static budget or the memory limit) — both
    /// name whether the SUBJECT was judged before the fault, and a caller with
    /// a stronger bar behind it does not refuse on either.
    #[allow(
        clippy::unused_async,
        reason = "the door's callers await it on an engine; 'scripts only' asks no tracker"
    )]
    pub async fn verify_scripts_only(
        &self,
        beef_bytes: &[u8],
        subject_txid: &str,
    ) -> Result<WalkStats, EngineError> {
        crate::script_door::walk(beef_bytes, subject_txid, self.walk_budget)
    }

    /// [`Engine::verify_scripts_only`] under a budget the caller names (the
    /// pins measure the door with a limb lifted; a caller with another
    /// platform's ceiling sets its own).
    #[allow(
        clippy::unused_async,
        clippy::unused_self,
        reason = "the twin of `verify_scripts_only`"
    )]
    pub async fn verify_scripts_only_under(
        &self,
        beef_bytes: &[u8],
        subject_txid: &str,
        budget: DoorBudget,
    ) -> Result<WalkStats, EngineError> {
        crate::script_door::walk(beef_bytes, subject_txid, budget)
    }

    // ========================================================================
    // Submit — 3-phase pipeline
    // ========================================================================

    /// Validate a tagged BEEF without applying mutations.
    ///
    /// Runs Phase 1 (topic validation) and Phase 2 (broadcast) but NOT Phase 3
    /// (storage mutations). Returns the Steak (admittance decisions) that
    /// `submit()` would return.
    ///
    /// Used by the onSteakReady pattern to return results to clients before
    /// mutations are applied via a queue consumer or `ctx.wait_until()`.
    ///
    /// The topic managers are called with `dry_run: true`
    /// (`TopicAdmittanceContext::DRY_RUN`): nothing is admitted on this call, so a
    /// manager that writes on admission leaves no trace of it.
    pub async fn submit_validate_only(
        &self,
        tagged_beef: &TaggedBEEF,
        mode: SubmitMode,
    ) -> Result<Steak, EngineError> {
        // A validate-only call admits nothing: a dry run by its own name. A
        // manager that writes on admission must not write here, or the real
        // submit that follows meets a head this call already advanced.
        let (_validations, steak, _tx, _txid, _could_not_run) = self
            .run_validation(
                tagged_beef,
                mode,
                &TopicAdmittanceContext::DRY_RUN,
                None,
                None,
                WalkBreachPolicy::NotNow,
            )
            .await?;
        Ok(steak)
    }

    /// Submit a transaction for processing by the overlay.
    ///
    /// Three phases:
    /// 1. **VALIDATE** — check topics, dedup, find previous coins, call topic managers
    /// 2. **BROADCAST** — broadcast to network (if mode is CurrentTx)
    /// 3. **MUTATE** — mark spent, delete stale, insert new outputs, notify lookup services
    ///
    /// Returns a STEAK mapping each topic to its admittance instructions.
    ///
    /// Phase-3 faults are reported through [`Engine::submit_with_report`];
    /// this convenience keeps the historical signature and only LOGS the
    /// report's summary. A caller that must not ack an admission whose
    /// writes did not land (the `/submit` route — S2) uses the report form.
    pub async fn submit(
        &self,
        tagged_beef: &TaggedBEEF,
        mode: SubmitMode,
    ) -> Result<Steak, EngineError> {
        let (steak, report) = self.submit_with_report(tagged_beef, mode).await?;
        if !report.is_durable() {
            warn!(
                "submit: {} mutation fault(s) — not durable: {}",
                report.faults.len(),
                report.summary()
            );
        }
        Ok(steak)
    }

    /// [`Engine::submit`] plus the Phase-3 durability report (S2
    /// queue-durable admission, bsv-low 2026-08-29).
    ///
    /// The STEAK is the admission DECISION; the report says whether the
    /// decision was DURABLY WRITTEN. They are returned together because
    /// they are answered by different things: Phase 1+2 decide, Phase 3
    /// lands, and only the caller knows whether an undurable landing may
    /// be acked (never, on the money path — re-queue it instead).
    ///
    /// Every write failure is still logged AND still non-fatal to the
    /// other topics (a faulted topic does not un-admit its siblings); what
    /// changed is that the failure is also VISIBLE, and that the faulted
    /// topic is not recorded as applied — so a replay of the same bytes is
    /// re-validated and re-written (every backend write is idempotent:
    /// `INSERT OR IGNORE` / `OR REPLACE` / `UPDATE`).
    ///
    /// What a fault leaves (bsv-low #559 and its lens fold of 2026-10-07):
    /// a topic's previous coins are deleted once EVERY admitted output of
    /// the transaction is inserted, and only then. A fault before that
    /// (a validation read, the spent mark of a coin the manager retains, an
    /// insert) leaves the previous coins held and nothing of the
    /// transaction: what did get inserted is taken out again, so the replay
    /// is the same judgement and no successor can spend half of it. A fault
    /// after it (a lookup notification, the consumed-by update, the applied
    /// row) leaves the transaction's outputs and no previous coin. A fault
    /// before any delete was started (the record of the spent coin's
    /// transaction, the read of the coin) is the first case if the coins
    /// are read back still held; once a delete was started its fault never
    /// undoes, answered or not (it may land yet): the outputs stay beside
    /// the stale coin, marked spent. A submit that deletes a stale coin
    /// first records that coin's transaction as applied, so a replay of it
    /// after its successor is a dupe. So a non-retaining chain never has
    /// two unspent heads and never none, whatever single call faults. The
    /// applied row is withheld on ANY fault. And a successor that was
    /// judged without the coin an unlanded predecessor has yet to leave is
    /// reported as a fault (`predecessor_not_landed`), not recorded as
    /// applied.
    ///
    /// A walk that could not run within the engine's budget is "not now"
    /// here ([`WalkBreachPolicy::NotNow`], [`EngineError::WalkCouldNotRun`]):
    /// never an admission. [`Engine::submit_with_report_under`] names the
    /// policy.
    pub async fn submit_with_report(
        &self,
        tagged_beef: &TaggedBEEF,
        mode: SubmitMode,
    ) -> Result<(Steak, MutationReport), EngineError> {
        self.submit_with_report_under(tagged_beef, mode, WalkBreachPolicy::NotNow)
            .await
    }

    /// [`Engine::submit_with_report`] under an explicit
    /// [`WalkBreachPolicy`] (the E592 lens fold, H1): what a walk that could
    /// not run within the budget does. `NetworkAccepted` is for a caller that
    /// holds the network's accept of these very bytes (the queue's replay of
    /// a gated submission) and for nothing else: it admits a breached body
    /// with its scripts unrun.
    pub async fn submit_with_report_under(
        &self,
        tagged_beef: &TaggedBEEF,
        mode: SubmitMode,
        policy: WalkBreachPolicy,
    ) -> Result<(Steak, MutationReport), EngineError> {
        self.submit_bounded(tagged_beef, mode, None, false, policy)
            .await
    }

    /// [`Engine::submit_with_report`] with every storage call, lookup hook
    /// and topic manager call under `bound` (the GASP finalize submit,
    /// [`CallBound`]); `None` is the unbounded submit of every other door.
    /// `finalize` is `true` for the GASP finalize submit alone, bounded or
    /// not: it does not ask the store's predecessor question.
    async fn submit_bounded(
        &self,
        tagged_beef: &TaggedBEEF,
        mode: SubmitMode,
        bound: Option<&CallBound>,
        finalize: bool,
        policy: WalkBreachPolicy,
    ) -> Result<(Steak, MutationReport), EngineError> {
        // The reads the store's predecessor question has made in this
        // submit, every topic together ([`PREDECESSOR_READS_PER_SUBMIT`]),
        // the predecessors the door lands first from the BEEF included.
        let mut question_reads = 0usize;
        self.submit_counted(
            tagged_beef,
            mode,
            bound,
            finalize,
            None,
            &mut question_reads,
            policy,
        )
        .await
        .map(|(steak, report, _)| (steak, report))
    }

    /// [`Engine::submit_bounded`] over the submit's read allowance
    /// (`question_reads`), which a predecessor the door lands first from the
    /// BEEF shares with the successor that carried it (lane E1D's lens fold,
    /// M1). `carried` is `Some` for such a predecessor's own submit
    /// ([`Engine::land_carried`]), holding the bodies whose SPV walk already
    /// passed in this submit (none is walked twice; the delta fold, L4): it
    /// lands nothing first itself, and it names instead the carried
    /// predecessor that blocks each topic (the third value), so the landing
    /// is an explicit stack and never a recursion of submits (nested polls
    /// grow the stack, and a Worker's is small). Its manager is asked as a
    /// DRY RUN first, and for real only once its topic is not blocked: a
    /// link blocked below is judged twice and admitted once. Boxed: the
    /// landing is a submit of its own.
    #[allow(clippy::too_many_arguments)]
    fn submit_counted<'a>(
        &'a self,
        tagged_beef: &'a TaggedBEEF,
        mode: SubmitMode,
        bound: Option<&'a CallBound>,
        finalize: bool,
        carried: Option<&'a HashSet<String>>,
        question_reads: &'a mut usize,
        policy: WalkBreachPolicy,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Counted, EngineError>> + 'a>>
    {
        Box::pin(async move {
            self.submit_counted_inner(
                tagged_beef,
                mode,
                bound,
                finalize,
                carried,
                question_reads,
                policy,
            )
            .await
        })
    }

    #[allow(clippy::too_many_arguments)]
    async fn submit_counted_inner(
        &self,
        tagged_beef: &TaggedBEEF,
        mode: SubmitMode,
        bound: Option<&CallBound>,
        finalize: bool,
        walked: Option<&HashSet<String>>,
        question_reads: &mut usize,
        policy: WalkBreachPolicy,
    ) -> Result<Counted, EngineError> {
        // A submit is a real admission, never a dry run; a carried
        // predecessor's is judged dry until its topic is known not to wait.
        let carried = walked.is_some();
        let context = if carried {
            TopicAdmittanceContext::DRY_RUN
        } else {
            TopicAdmittanceContext::default()
        };
        let (mut validations, mut steak, tx, txid, could_not_run) = self
            .run_validation(tagged_beef, mode, &context, bound, walked, policy)
            .await?;
        if finalize {
            let now = (current_timestamp_ms() / 1000.0) as u64;
            for validation in &mut validations {
                let manager = &self.managers[&validation.topic];
                validation.admittance.outputs_to_admit.retain(|index| {
                    tx.outputs.get(*index as usize).is_none_or(|output| {
                        manager
                            .sync_expiry(&output.locking_script)
                            .is_none_or(|expiry| expiry > now)
                    })
                });
                steak.insert(validation.topic.clone(), validation.admittance.clone());
            }
        }
        let mut report = MutationReport {
            walk_could_not_run: could_not_run,
            ..MutationReport::default()
        };
        // The body every LOOKUP SERVICE receives NAMES the subject (BRC-95
        // atomic prefix over the WHOLE submitted body — bsv-rs's
        // `to_binary_atomic` sorts, names, never prunes). Lookup services
        // re-parse it with `from_beef(_, None)`; on a plain incomplete body
        // that pick is the wire-last ANCESTOR, so the pot index's admit hook
        // shape-checked a hop and wrote no record while the engine had
        // admitted the pot (loop-2 fleet, 2026-09-05; the live proof after
        // the engine's own subject fix). A body that cannot be re-serialized
        // (never, for a parsed subject) is handed through as submitted.
        let subject_named_beef: Vec<u8> =
            beef_limits::parse_beef(&tagged_beef.beef, &beef_limits::ENGINE_BEEF_LIMITS)
                .ok()
                .and_then(|mut b| b.to_binary_atomic(&txid).ok())
                .unwrap_or_else(|| tagged_beef.beef.clone());

        // The successor rule, asked of every topic that found no coin before
        // anything of this submit is written ([`Engine::successors_waiting`]):
        // the topics that must wait, each with why.
        let mut blocked: HashMap<String, String> = HashMap::new();
        // The landing trusts the subject's walk only if it RAN (the E592
        // lens fold, M1): after a breach nothing it reaches was walked.
        let landing = Landing {
            policy,
            subject_walk_ran: report.walk_could_not_run.is_none(),
        };
        let waits = self
            .successors_waiting(
                &tx,
                &txid,
                &subject_named_beef,
                &mut validations,
                &mut steak,
                tagged_beef.off_chain_values.as_deref(),
                mode,
                bound,
                finalize,
                !carried,
                &mut blocked,
                question_reads,
                &mut report.landed_predecessors,
                landing,
                &mut report.landed_walks_could_not_run,
            )
            .await;
        // A carried predecessor's topic that does not wait is judged again,
        // for real: what it admits is this call's word, over the same coins.
        if carried {
            for v in &mut validations {
                if v.is_dupe || v.failed || v.read_fault.is_some() || waits.contains_key(&v.topic) {
                    continue;
                }
                match self
                    .judge(
                        &tx,
                        &v.topic,
                        &v.previous_coins,
                        tagged_beef.off_chain_values.as_deref(),
                        mode,
                        &TopicAdmittanceContext::default(),
                        bound,
                    )
                    .await
                {
                    Ok(admittance) => v.admittance = admittance,
                    Err(e) => {
                        error!("Error validating topic {} during submit: {e}", v.topic);
                        v.failed = true;
                        v.previous_coins.clear();
                        v.previous_outputs.clear();
                        v.admittance = AdmittanceInstructions::default();
                    }
                }
                steak.insert(v.topic.clone(), v.admittance.clone());
            }
        }

        // =================================================================
        // PHASE 3: MUTATE STORAGE
        // =================================================================
        for v in &validations {
            if v.is_dupe {
                report.deduped_topics.push(v.topic.clone());
                continue;
            }
            // A failed topic comes first, a read fault of it included: a
            // previous-coin read that faulted and a manager that then ERRED
            // is a failed topic with a durable report, no fault and no
            // replay. Parity: the reference fails the topic and never
            // replays. Nothing was written, so the store is as it was.
            if v.failed {
                continue;
            }

            let topic = &v.topic;
            let admittance = &v.admittance;
            let faults_before = report.faults.len();

            // A validation read that faulted: the manager judged without a
            // coin the store may hold, so NOTHING is written on that
            // judgement (the lens fold of 2026-10-07). Writing its outputs
            // would leave them beside the unseen coin, for a successor to
            // spend before the replay deletes it.
            if let Some((read, err)) = &v.read_fault {
                report.fault(topic, read, err.clone());
                self.hold_unapplied(&txid, topic, "a validation read faulted, nothing written");
                continue;
            }

            // bsv-low #559 and lane E1D: a topic that found no coin while a
            // predecessor's landing is unknown is "not now", recorded
            // nowhere ([`Engine::successors_waiting`]).
            if let Some(not_now) = waits.get(topic) {
                report.fault(topic, "predecessor_not_landed", not_now.clone());
                self.hold_unapplied(
                    &txid,
                    topic,
                    &format!("found no coin and its predecessor {not_now}"),
                );
                continue;
            }

            // ── Handle stale vs retained previous coins ──
            let mut outputs_consumed: Vec<Outpoint> = Vec::new();
            let mut stale_coins: Vec<&Output> = Vec::new();

            for (coin_idx, prev_output) in v.previous_outputs.iter().enumerate() {
                let input_index = v.previous_coins[coin_idx];
                if admittance.coins_to_retain.contains(&input_index) {
                    // Retained: track as consumed (will update consumedBy later)
                    outputs_consumed
                        .push(Outpoint::new(&prev_output.txid, prev_output.output_index));
                } else {
                    // Not retained: mark as stale for deletion
                    stale_coins.push(prev_output);
                }
            }

            // Update STEAK with removed coins
            if let Some(steak_entry) = steak.get_mut(topic) {
                steak_entry.coins_removed = Some(
                    stale_coins
                        .iter()
                        .enumerate()
                        .filter_map(|(i, _)| {
                            // Map back to input indices
                            v.previous_coins.get(i).copied()
                        })
                        .collect(),
                );
            }

            // ── Mark previous outputs as spent + notify lookup services ──
            // A mark that faults does not skip the notification (the
            // reference skips it): the coin is spent whatever the row says,
            // a stale one is deleted below and its lookup services must
            // know. The mark of a RETAINED coin is part of what landed: that
            // row stays, and left unspent it would be listed as a UTXO
            // beside the output that consumed it.
            let mut retained_mark_faulted = false;
            for (prev_idx, prev_output) in v.previous_outputs.iter().enumerate() {
                if let Err(e) = stored(
                    bound,
                    self.storage.mark_utxo_as_spent(
                        &prev_output.txid,
                        prev_output.output_index,
                        topic,
                    ),
                )
                .await
                {
                    error!("Error marking UTXO as spent: {e}");
                    report.fault(topic, "mark_utxo_as_spent", e.to_string());
                    retained_mark_faulted |= admittance
                        .coins_to_retain
                        .contains(&v.previous_coins[prev_idx]);
                }

                // The input index within tx.inputs that spends this previous output.
                let spending_input_idx = v.previous_coins[prev_idx] as usize;

                // Notify all lookup services about the spent output
                for ls in self.lookup_services.values() {
                    let payload = match ls.spend_notification_mode() {
                        SpendNotificationMode::None => OutputSpent::None {
                            txid: prev_output.txid.clone(),
                            output_index: prev_output.output_index,
                            topic: topic.clone(),
                        },
                        SpendNotificationMode::Txid => OutputSpent::Txid {
                            txid: prev_output.txid.clone(),
                            output_index: prev_output.output_index,
                            topic: topic.clone(),
                            spending_txid: txid.clone(),
                        },
                        SpendNotificationMode::Script => {
                            // Extract unlocking script and sequence from the spending input
                            let input = &tx.inputs[spending_input_idx];
                            let unlocking_script = input
                                .unlocking_script
                                .as_ref()
                                .map(bsv_rs::UnlockingScript::to_binary)
                                .unwrap_or_default();
                            OutputSpent::Script {
                                txid: prev_output.txid.clone(),
                                output_index: prev_output.output_index,
                                topic: topic.clone(),
                                spending_txid: txid.clone(),
                                input_index: spending_input_idx as u32,
                                unlocking_script,
                                sequence_number: input.sequence,
                                off_chain_values: tagged_beef.off_chain_values.clone(),
                            }
                        }
                        SpendNotificationMode::WholeTx => OutputSpent::WholeTx {
                            txid: prev_output.txid.clone(),
                            output_index: prev_output.output_index,
                            topic: topic.clone(),
                            spending_atomic_beef: subject_named_beef.clone(),
                            off_chain_values: tagged_beef.off_chain_values.clone(),
                        },
                    };
                    if let Err(e) = hooked(bound, ls.output_spent(&payload)).await {
                        error!("Error notifying lookup service of spent output: {e}");
                        report.fault(topic, "lookup_service.output_spent", e);
                    }
                }
            }
            if retained_mark_faulted {
                self.hold_unapplied(
                    &txid,
                    topic,
                    "the spent mark of a retained coin faulted, nothing inserted",
                );
                continue;
            }

            // ── Insert admitted outputs ──
            // The inserts stop at the first one that faults: what follows is
            // the undo, not the rest of the transaction.
            let mut new_utxos: Vec<Outpoint> = Vec::new();
            let mut attempted: Vec<u32> = Vec::new();
            let mut insert_faulted = false;

            for &output_index in &admittance.outputs_to_admit {
                let (script_bytes, sats) =
                    if let Some(tx_output) = tx.outputs.get(output_index as usize) {
                        (
                            tx_output.locking_script.to_binary(),
                            tx_output.get_satoshis(),
                        )
                    } else {
                        (Vec::new(), 0)
                    };

                let output = Output {
                    txid: txid.clone(),
                    output_index,
                    output_script: script_bytes,
                    satoshis: sats,
                    topic: topic.clone(),
                    spent: false,
                    outputs_consumed: outputs_consumed.clone(),
                    consumed_by: Vec::new(),
                    beef: Some(tagged_beef.beef.clone()),
                    block_height: None,
                    score: Some(current_timestamp_ms()),
                };

                attempted.push(output_index);
                if let Err(e) = stored(bound, self.storage.insert_output(&output)).await {
                    error!("Error inserting output for topic {topic}: {e}");
                    report.fault(topic, "insert_output", e.to_string());
                    insert_faulted = true;
                    break;
                }

                new_utxos.push(Outpoint::new(&txid, output_index));

                // Notify lookup services
                for ls in self.lookup_services.values() {
                    let (ls_script, ls_sats) =
                        if let Some(tx_out) = tx.outputs.get(output_index as usize) {
                            (tx_out.locking_script.to_binary(), tx_out.get_satoshis())
                        } else {
                            (Vec::new(), 0)
                        };

                    let payload = match ls.admission_mode() {
                        AdmissionMode::LockingScript => OutputAdmittedByTopic::LockingScript {
                            txid: txid.clone(),
                            output_index,
                            topic: topic.clone(),
                            satoshis: ls_sats,
                            locking_script: ls_script,
                            off_chain_values: tagged_beef.off_chain_values.clone(),
                        },
                        AdmissionMode::WholeTx => OutputAdmittedByTopic::WholeTx {
                            atomic_beef: subject_named_beef.clone(),
                            output_index,
                            topic: topic.clone(),
                            off_chain_values: tagged_beef.off_chain_values.clone(),
                        },
                    };

                    if let Err(e) = hooked(bound, ls.output_admitted_by_topic(&payload)).await {
                        error!("Error notifying lookup service: {e}");
                        report.fault(topic, "lookup_service.output_admitted_by_topic", e);
                    }
                }
            }

            // An insert faulted: the transaction did not land, so NOTHING of
            // it stays (the lens fold of 2026-10-07, F1). The previous coins
            // are kept (#559: with the delete first, one faulted insert left
            // a non-retaining head chain with NO head) and the outputs that
            // were inserted are taken out again, the faulted one included (a
            // backend's insert can fault after its row landed). Left in,
            // they could be spent and deleted by a successor before the
            // replay, and the replay, which still finds the previous coin,
            // would insert them a second time: a spent head back among the
            // UTXOs for good.
            if insert_faulted {
                if let Some(bound) = bound {
                    bound.renew();
                }
                self.undo_inserts(&txid, topic, &attempted, bound, &mut report)
                    .await;
                self.hold_unapplied(
                    &txid,
                    topic,
                    &format!(
                        "an insert faulted: {} previous coin(s) kept, nothing of it held",
                        stale_coins.len()
                    ),
                );
                continue;
            }

            // ── Delete stale outputs recursively ──
            // AFTER the inserts, and once every one of them landed (bsv-low
            // #559 and the lens fold of 2026-10-07, F1). The reference
            // deletes first (`applyTopicStorageMutation`: `removeStaleOutputs`,
            // then `admitOutput`), catches a throw per topic and never
            // replays; here a fault is survived and replayed, so the order
            // is ours, an addition. The delete does NOT wait for a clean
            // report (c9921ee did, and one faulted mark or notification
            // after the insert then left the stale coin beside the new
            // output for good: two unspent heads): a fault of the mark, of
            // a notification, deletes as the reference does.
            //
            // Before a stale coin is deleted its transaction is recorded as
            // applied in the topic (the delta fold of 2026-10-07, H2; an
            // addition, one idempotent write per deleted coin). A held coin
            // proves the inserts of its transaction landed, but that
            // transaction may have no applied row (a fault after its
            // inserts withheld it, or its insert landed after its timeout),
            // and then its replay is judged again: a manager that admits it
            // with NO previous coin (the opener of a chain) had it inserted
            // a second time, unspent, beside the output that spent it, for
            // good. With the row its replay is a dupe. A record that faults
            // leaves its coin undeleted: that is a delete fault, below.
            let due_before_the_delete = bound.is_some_and(CallBound::is_due);
            let mut delete_faulted = false;
            let mut delete_started = false;
            for stale in &stale_coins {
                let spent_coin_tx = AppliedTransaction {
                    txid: stale.txid.clone(),
                    topic: topic.clone(),
                };
                if let Err(e) = stored(
                    bound,
                    self.storage.insert_applied_transaction(&spent_coin_tx),
                )
                .await
                {
                    error!(
                        "Error recording {} as applied before its coin is deleted from topic {topic}: {e}",
                        stale.txid
                    );
                    report.fault(topic, "record_spent_coin_applied", e.to_string());
                    delete_faulted = true;
                    continue;
                }
                self.not_landed
                    .borrow_mut()
                    .remove(&(stale.txid.clone(), topic.clone()));
                match stored(
                    bound,
                    self.storage.find_output(
                        &stale.txid,
                        stale.output_index,
                        Some(topic),
                        None,
                        false,
                    ),
                )
                .await
                {
                    Ok(Some(stale_output)) => {
                        delete_started = true;
                        if let Err(e) = self.delete_utxo_deep(&stale_output, bound).await {
                            error!("Error deleting stale output for topic {topic}: {e}");
                            report.fault(topic, "delete_utxo_deep", e.to_string());
                            delete_faulted = true;
                        }
                    }
                    Ok(None) => {}
                    Err(e) => {
                        error!("Error reading stale output for topic {topic}: {e}");
                        report.fault(topic, "find_output", e.to_string());
                        delete_faulted = true;
                    }
                }
            }

            // A fault here, and what it leaves. The store is put back as it
            // was found (the inserts undone, the replay does the whole
            // transaction) only when NO delete was started: the fault is of
            // H2's record or of the read before the delete, the call
            // answered, and EVERY stale coin is read back still held.
            //
            // Once a delete was STARTED nothing is undone, whether it
            // answered or not (the delta fold of 2026-10-07, H1, for a call
            // that did not answer; the second delta fold, M1, for one that
            // answered an error). A statement can land after its caller was
            // told it failed, as after its caller stopped waiting: the coin
            // is read back held now and is deleted a moment later, and the
            // undo then left the chain with no head, for good, for a manager
            // that needs the previous coin. So the outputs stay, the stale
            // coin stays (marked spent) until its delete lands or is done
            // again, and there is no applied row. Since H2 every order from
            // there converges. The replay first, the delete never landed:
            // the coin is found, the manager admits again, the inserts are
            // no-ops, the delete is done and the row written. The replay
            // first, the delete landed late: no previous coin, so a manager
            // that needs one admits nothing and the transaction is recorded
            // with its outputs held. A successor first: it recorded this
            // transaction as applied (H2) and the replay is a dupe; the
            // stale coin's spent row is then left behind, no UTXO.
            //
            // A call that did not ANSWER before any delete (the record, the
            // read) undoes nothing either: it is not known what it did. A
            // deadline that was already due BEFORE the first of these calls
            // started nothing here, so the coins are certainly held and the
            // store is put back.
            if delete_faulted {
                let unanswered = !due_before_the_delete && bound.is_some_and(CallBound::is_due);
                if let Some(bound) = bound {
                    bound.renew();
                }
                let mut all_held = !unanswered && !delete_started;
                for stale in &stale_coins {
                    if !all_held {
                        break;
                    }
                    let read = stored(
                        bound,
                        self.storage.find_output(
                            &stale.txid,
                            stale.output_index,
                            Some(topic),
                            None,
                            false,
                        ),
                    )
                    .await;
                    if !matches!(read, Ok(Some(_))) {
                        all_held = false;
                        break;
                    }
                }
                if all_held {
                    self.undo_inserts(&txid, topic, &attempted, bound, &mut report)
                        .await;
                }
                self.hold_unapplied(
                    &txid,
                    topic,
                    if all_held {
                        "no delete of a stale coin was started: the coins are held, its outputs taken out"
                    } else if unanswered {
                        "the delete of a stale coin did not answer: nothing undone, its outputs stay"
                    } else if delete_started {
                        "the delete of a stale coin faulted: nothing undone, its outputs stay"
                    } else {
                        "no delete was started and a stale coin was not read back held: nothing undone, its outputs stay"
                    },
                );
                continue;
            }

            // ── Update consumedBy on retained previous outputs ──
            for consumed_outpoint in &outputs_consumed {
                let consumed_output = match stored(
                    bound,
                    self.storage.find_output(
                        &consumed_outpoint.txid,
                        consumed_outpoint.output_index,
                        Some(topic),
                        None,
                        false,
                    ),
                )
                .await
                {
                    Ok(Some(o)) => o,
                    Ok(None) => continue,
                    Err(e) => {
                        error!("Error reading consumed output for topic {topic}: {e}");
                        report.fault(topic, "find_output", e.to_string());
                        continue;
                    }
                };
                {
                    let mut new_consumed_by = consumed_output.consumed_by.clone();
                    for new_utxo in &new_utxos {
                        if !new_consumed_by.iter().any(|c| {
                            c.txid == new_utxo.txid && c.output_index == new_utxo.output_index
                        }) {
                            new_consumed_by.push(new_utxo.clone());
                        }
                    }
                    if let Err(e) = stored(
                        bound,
                        self.storage.update_consumed_by(
                            &consumed_outpoint.txid,
                            consumed_outpoint.output_index,
                            topic,
                            &new_consumed_by,
                        ),
                    )
                    .await
                    {
                        error!("Error updating consumedBy: {e}");
                        report.fault(topic, "update_consumed_by", e.to_string());
                    }
                }
            }

            // Record applied transaction — ONLY when every write above
            // landed. A faulted topic stays unrecorded so the Phase-1 dedup
            // cannot turn its replay into a no-op (S2).
            if report.faults.len() > faults_before {
                self.hold_unapplied(
                    &txid,
                    topic,
                    &format!(
                        "{} mutation fault(s); a replay of these bytes re-applies",
                        report.faults.len() - faults_before
                    ),
                );
                continue;
            }
            let tx_record = AppliedTransaction {
                txid: txid.clone(),
                topic: topic.clone(),
            };
            match stored(bound, self.storage.insert_applied_transaction(&tx_record)).await {
                Ok(()) => {
                    report.applied_topics.push(topic.clone());
                    self.not_landed
                        .borrow_mut()
                        .remove(&(txid.clone(), topic.clone()));
                }
                Err(e) => {
                    error!("Error inserting applied transaction for topic {topic}: {e}");
                    report.fault(topic, "insert_applied_transaction", e.to_string());
                    self.not_landed
                        .borrow_mut()
                        .insert((txid.clone(), topic.clone()));
                }
            }
        }

        Ok((steak, report, blocked))
    }

    /// The successor rule (bsv-low #559; lane E1D, bsv-low #575; and its
    /// lens fold of 2026-10-08), asked of every topic of a submit that found
    /// NO previous coin while the transaction spends something, before
    /// anything of the submit is written. Returns the topics that must wait,
    /// each with why: those are reported as a fault (`predecessor_not_landed`)
    /// and recorded nowhere, "not now". An addition to the reference, which
    /// records every non-failed topic.
    ///
    /// Such a topic was judged without the coin a predecessor has yet to
    /// leave. Recorded as applied, its replay was a dupe for good: a
    /// transaction that admits nothing ended the chain at the predecessor
    /// (#559), and one the manager admits WITHOUT its coin (the pf head
    /// manager over its own head state, E1D) was inserted, and the
    /// predecessor, landing later, stood unspent beside the tip.
    ///
    /// "Has not landed" is known two ways: this engine saw it fault
    /// (`not_landed`, one invocation, every door), or the store says so
    /// ([`Engine::unlanded_predecessor`], any invocation, never at a GASP
    /// finalize submit: its graph passed the anchor check, every parent
    /// inside the graph was submitted just before it and the sequence stops
    /// at the first that does not land; the second delta fold of 2026-10-07,
    /// M2). For a successor that admits something, both look only at the
    /// inputs the manager NAMES as its history (`identify_needed_inputs`
    /// over the subject-named BEEF; the lens fold, L1): a manager that
    /// names nothing (all 16 of this workspace) asks nothing there, as in
    /// the reference. A successor that admits NOTHING is asked of every
    /// input whatever its manager names (D17 (a)), so under such a manager
    /// it still waits for, or lands first, a carried body that spends a
    /// coin the topic holds: there the store differs from the reference's
    /// (the E1D delta fold, L3).
    ///
    /// The door lands a carried predecessor FIRST (the lens fold, M1; the
    /// GASP walk's rule, at the door): when the question names an unlanded
    /// predecessor whose body the BEEF carries, that body is submitted on
    /// its own to this topic ([`Engine::land_carried`]), under the submit's
    /// read allowance, and once it lands the topic is judged again
    /// ([`Engine::validate_topic`]) and asked again. The re-judgement's
    /// reads (the applied row, one coin per input) are charged to that
    /// allowance BEFORE the landing (the E1D delta fold, M1): a landing whose
    /// re-judgement would not fit is not made, and the topic waits. So one
    /// submit reads at most its own validation and writes plus
    /// [`PREDECESSOR_READS_PER_SUBMIT`], landings (on their clean path) and
    /// re-judgements included; a faulted landing's read-backs and undo, and
    /// a deep delete's walk of retained history, are not charged.
    /// Nothing is landed into a topic whose manager or a lookup
    /// service reads off-chain values (the delta fold, L1: the landing has
    /// none to give, and the predecessor's own submit would be a dupe): the
    /// topic waits for that submit. The first predecessor that does not land
    /// ends it: the topic waits. A predecessor whose body the BEEF does not
    /// carry is never landed here: its successor converges only when it
    /// lands (its own replay, a GASP peer, a resubmit).
    #[allow(clippy::too_many_arguments)]
    async fn successors_waiting(
        &self,
        tx: &Transaction,
        txid: &str,
        subject_named_beef: &[u8],
        validations: &mut [TopicValidation],
        steak: &mut Steak,
        off_chain_values: Option<&[u8]>,
        mode: SubmitMode,
        bound: Option<&CallBound>,
        finalize: bool,
        lands: bool,
        blocked: &mut HashMap<String, String>,
        question_reads: &mut usize,
        landed: &mut Vec<(String, String)>,
        landing: Landing,
        landed_breaches: &mut Vec<WalkCouldNotRun>,
    ) -> HashMap<String, String> {
        let mut waits = HashMap::new();
        let spent: Vec<(String, u32)> = tx
            .inputs
            .iter()
            .filter_map(|input| {
                let source = input.get_source_txid().ok()?;
                (!source.is_empty()).then_some((source, input.source_output_index))
            })
            .collect();
        if spent.is_empty() {
            return waits;
        }
        let found_no_coin = |v: &TopicValidation| {
            !v.is_dupe && !v.failed && v.read_fault.is_none() && v.previous_outputs.is_empty()
        };
        for v in validations.iter_mut() {
            if !found_no_coin(v) {
                continue;
            }
            let Some(manager) = self.managers.get(&v.topic) else {
                continue;
            };
            let topic = v.topic.clone();
            // The manager's word on the subject's history, asked at most
            // once per topic: up front for a successor that admits, by the
            // question when it needs it for one that does not.
            let mut subject_names: Option<HashSet<String>> = None;
            loop {
                let admits = !v.admittance.outputs_to_admit.is_empty();
                if admits && subject_names.is_none() {
                    subject_names = Some(
                        self.named_history(manager.as_ref(), subject_named_beef, bound)
                            .await,
                    );
                }
                let remembered = spent.iter().find(|(source, vout)| {
                    (!admits
                        || subject_names
                            .as_ref()
                            .is_some_and(|named| named.contains(&format!("{source}.{vout}"))))
                        && self
                            .not_landed
                            .borrow()
                            .contains(&(source.clone(), topic.clone()))
                });
                if let Some((predecessor, _)) = remembered {
                    waits.insert(topic.clone(), format!("{predecessor} has not landed"));
                    break;
                }
                if finalize {
                    break;
                }
                let Some(not_now) = self
                    .unlanded_predecessor(
                        tx,
                        txid,
                        subject_named_beef,
                        &topic,
                        mode,
                        admits,
                        &mut subject_names,
                        question_reads,
                        bound,
                    )
                    .await
                else {
                    break;
                };
                let Some(carried) = not_now.carried else {
                    waits.insert(topic.clone(), not_now.why);
                    break;
                };
                if !lands {
                    blocked.insert(topic.clone(), carried);
                    waits.insert(topic.clone(), not_now.why);
                    break;
                }
                if !self.lands_without_values(&topic) {
                    waits.insert(
                        topic.clone(),
                        format!(
                            "{}; not landed first from the BEEF: the topic's manager or a lookup service reads off-chain values, and only the predecessor's own submit carries them",
                            not_now.why
                        ),
                    );
                    break;
                }
                // The re-judgement after the landing, charged before it.
                let rejudge = 1 + spent.len();
                if *question_reads + rejudge > PREDECESSOR_READS_PER_SUBMIT {
                    waits.insert(
                        topic.clone(),
                        format!(
                            "{}; its landing and the re-judgement after it do not fit in the submit's {PREDECESSOR_READS_PER_SUBMIT} reads",
                            not_now.why
                        ),
                    );
                    break;
                }
                *question_reads += rejudge;
                match self
                    .land_carried(
                        subject_named_beef,
                        txid,
                        &carried,
                        &topic,
                        mode,
                        bound,
                        question_reads,
                        landed,
                        landing,
                        landed_breaches,
                    )
                    .await
                {
                    Ok(()) => {
                        *v = self
                            .validate_topic(
                                tx,
                                txid,
                                &topic,
                                off_chain_values,
                                mode,
                                &TopicAdmittanceContext::default(),
                                bound,
                            )
                            .await;
                        steak.insert(topic.clone(), v.admittance.clone());
                        if !found_no_coin(v) {
                            break;
                        }
                    }
                    Err(did_not_land) => {
                        // No re-judgement follows: its reads were not made.
                        *question_reads -= rejudge;
                        waits.insert(
                            topic.clone(),
                            format!(
                                "{}; submitted first from the BEEF, it did not land ({did_not_land})",
                                not_now.why
                            ),
                        );
                        break;
                    }
                }
            }
            // A subject that already HOLDS an output in the topic landed
            // there before (the leftover of its own earlier submit whose
            // delete was started and faulted, D17 M1: its outputs held, no
            // applied row), and that admission was judged with its coin.
            // Its replay finishes it and does not wait (the E1D lens fold,
            // L4: a proven head spend that names a decoy no peer serves was
            // "not now" on every replay, three and a dead letter). One read,
            // only on the way to "not now", inside the allowance.
            if !finalize
                && waits.contains_key(&topic)
                && *question_reads < PREDECESSOR_READS_PER_SUBMIT
            {
                *question_reads += 1;
                if let Ok(outputs) = stored(
                    bound,
                    self.storage.find_outputs_for_transaction(txid, false),
                )
                .await
                {
                    if outputs.iter().any(|o| o.topic == topic) {
                        info!("topic {topic}: {txid} holds its outputs already; its replay finishes it");
                        waits.remove(&topic);
                        blocked.remove(&topic);
                    }
                }
            }
        }
        waits
    }

    /// Land an unlanded predecessor whose body the successor's BEEF carries
    /// (lane E1D's lens fold, M1): submit it on its own to `topic`, its
    /// atomic BEEF out of the successor's, no off-chain values (the caller
    /// lands nothing into a topic that reads them; the delta fold, L1),
    /// never a broadcast (`current-tx` is submitted as `historical-tx`: the
    /// successor's BEEF carries it to the network).
    ///
    /// Each body is WALKED once in this submit (the delta fold, L4): the
    /// successor's own SPV walk (`subject`, the same mode, tracker and
    /// switch) already passed over every body it reaches without crossing a
    /// proven one, so those are not walked again; a body reached only
    /// through a proven one (which the successor's walk does not descend)
    /// gets its own walk, trusting what this submit already walked, and so
    /// does nothing twice. A walk that refuses a body ends the landing.
    ///
    /// A predecessor whose own submit waits on a carried predecessor of ITS
    /// own goes on a stack under it: ancestors first, the walk's rule at
    /// the door. Its manager was asked only a DRY RUN then and nothing was
    /// written; once the one under it landed it is submitted again and
    /// admitted for real, once ([`Engine::submit_counted`]). Each submit's
    /// reads on its clean path (its applied row, one coin per input, and
    /// its writes' one read of each coin it spends) are charged to the
    /// submit's allowance before it starts, and its predecessor
    /// question shares that allowance, so the landings of one submit stop
    /// at [`PREDECESSOR_READS_PER_SUBMIT`] reads, however deep the chain.
    /// Each body that lands is pushed on `landed` (the report's
    /// `landed_predecessors`, for the caller's admission guard; the delta
    /// fold, L2). Each body is asked of the caller's landing guard first,
    /// once ([`Engine::set_landing_guard`]; the delta-2 fold, L2): a refusal
    /// ends the landing before that body is submitted.
    /// `Ok` once `predecessor` LANDED in `topic` (recorded there,
    /// now or before); otherwise why not, at the first that did not.
    #[allow(clippy::too_many_arguments)]
    async fn land_carried(
        &self,
        beef_bytes: &[u8],
        subject: &str,
        predecessor: &str,
        topic: &str,
        mode: SubmitMode,
        bound: Option<&CallBound>,
        question_reads: &mut usize,
        landed: &mut Vec<(String, String)>,
        landing: Landing,
        landed_breaches: &mut Vec<WalkCouldNotRun>,
    ) -> Result<(), String> {
        let beef = beef_limits::parse_beef(beef_bytes, &beef_limits::ENGINE_BEEF_LIMITS)
            .map_err(|e| format!("the BEEF could not be read again ({e})"))?;
        let mode = match mode {
            SubmitMode::CurrentTx => SubmitMode::HistoricalTx,
            other => other,
        };
        let walks = mode != SubmitMode::HistoricalTxNoSpv;
        // The trust set is what a walk that RAN covered (the E592 lens fold,
        // M1): a subject whose walk breached covered nothing, so each carried
        // predecessor is walked by its own submit (and its own breach is
        // reported, `landed_breaches`), never trusted by a breached walk.
        let mut walked: HashSet<String> = if walks && landing.subject_walk_ran {
            walk_cover(&beef, subject)
        } else {
            HashSet::new()
        };
        let mut stack = vec![predecessor.to_string()];
        let mut guarded: HashSet<String> = HashSet::new();
        while let Some(next) = stack.last().cloned() {
            let body = beef
                .find_atomic_transaction(&next)
                .ok_or_else(|| format!("{next}: its body is not in the BEEF"))?;
            // The caller's admission predicate, before anything of this body
            // is submitted (the delta-2 fold, L2).
            if let Some(guard) = &self.landing_guard {
                if guarded.insert(next.clone()) {
                    bounded(bound, guard(&next, topic))
                        .await
                        .and_then(|answer| answer)
                        .map_err(|why| format!("{next}: refused by the landing guard ({why})"))?;
                }
            }
            // Its validation (the applied row, one coin per input) and its
            // writes' one read of each coin it spends.
            let cost = 1 + 2 * body.inputs.len();
            if *question_reads + cost > PREDECESSOR_READS_PER_SUBMIT {
                return Err(format!(
                    "{next}: its submit does not fit in the submit's {PREDECESSOR_READS_PER_SUBMIT} reads"
                ));
            }
            *question_reads += cost;
            let atomic = body
                .to_atomic_beef(true)
                .map_err(|e| format!("{next}: its BEEF could not be built ({e})"))?;
            let tagged = TaggedBEEF::new(atomic, vec![topic.to_string()]);
            let (_, report, blocked) = match self
                .submit_counted(
                    &tagged,
                    mode,
                    bound,
                    false,
                    Some(&walked),
                    question_reads,
                    landing.policy,
                )
                .await
            {
                Ok(counted) => counted,
                // Its walk could not run and nothing stands in for it: it does
                // not land now, and the successor waits (counted, L3).
                Err(EngineError::WalkCouldNotRun(stop)) => {
                    let why = format!("{next}: {}", EngineError::WalkCouldNotRun(stop.clone()));
                    landed_breaches.push(stop);
                    return Err(why);
                }
                Err(e) => return Err(format!("{next}: {e}")),
            };
            // Its walk passed, so did that of every body it reaches; a walk
            // that went on past a breach (`NetworkAccepted`) passed nothing.
            if let Some(stop) = &report.walk_could_not_run {
                landed_breaches.push(stop.clone());
            } else if walks && !walked.contains(&next) {
                walked.extend(walk_cover(&beef, &next));
            }
            let landed_now = report.applied_topics.iter().any(|t| t == topic);
            if report.is_durable()
                && (landed_now || report.deduped_topics.iter().any(|t| t == topic))
            {
                info!("topic {topic}: {next} landed first from its successor's BEEF");
                if landed_now {
                    landed.push((next.clone(), topic.to_string()));
                }
                stack.pop();
                continue;
            }
            match blocked.get(topic) {
                Some(under) if !stack.contains(under) => stack.push(under.clone()),
                _ if report.is_durable() => return Err(format!("{next}: the manager failed it")),
                _ => return Err(format!("{next}: {}", report.summary())),
            }
        }
        Ok(())
    }

    /// A topic of a submit that is NOT recorded as applied: logged, and
    /// remembered for the successor rule (`not_landed`).
    fn hold_unapplied(&self, txid: &str, topic: &str, why: &str) {
        warn!("topic {topic}: {txid}: {why}; applied_transactions NOT recorded (bsv-low #559)");
        self.not_landed
            .borrow_mut()
            .insert((txid.to_string(), topic.to_string()));
    }

    /// Take out again the outputs a faulted submit inserted (bsv-low #559,
    /// the lens fold of 2026-10-07, F1), so that nothing of a transaction
    /// that did not land is held. Only a row nobody has touched since is
    /// deleted: unspent and consumed by nothing. A plain delete, not the
    /// deep one: the row's retained inputs were not pointed at it yet. A
    /// fault here is reported (`undo_insert_output`) and the row stays: the
    /// limit of an undo made of separate calls.
    async fn undo_inserts(
        &self,
        txid: &str,
        topic: &str,
        output_indices: &[u32],
        bound: Option<&CallBound>,
        report: &mut MutationReport,
    ) {
        for &output_index in output_indices {
            let row = stored(
                bound,
                self.storage
                    .find_output(txid, output_index, Some(topic), None, false),
            )
            .await;
            let undone = match row {
                Ok(Some(row)) if !row.spent && row.consumed_by.is_empty() => {
                    stored(bound, self.storage.delete_output(txid, output_index, topic)).await
                }
                Ok(_) => Ok(()),
                Err(e) => Err(e),
            };
            if let Err(e) = undone {
                error!("Error taking {txid}.{output_index} out of topic {topic} again: {e}");
                report.fault(topic, "undo_insert_output", e.to_string());
            }
        }
    }

    /// The store's own answer to "has a predecessor of `tx` not landed?"
    /// (bsv-low #559, the lens fold of 2026-10-07, F3; lane E1D, bsv-low
    /// #575, and its lens fold of 2026-10-08), for a transaction that found
    /// no previous coin. The engine's memory of a faulted submit
    /// (`not_landed`) dies with the invocation; this does not. A transaction
    /// HAS LANDED in `topic` when it has an applied row there or an output
    /// held there; anything else is not known to have landed, and it is a
    /// PREDECESSOR of `tx` when one of these says so:
    ///
    /// - its body is in the BEEF and it spends a coin the topic HOLDS (or,
    ///   one step up, a coin of another such transaction): a spend of this
    ///   topic the store has not taken yet (#559);
    /// - its body is in the BEEF, it spends no coin the topic holds, the
    ///   manager NAMES the outpoint the walk spends from it as overlay
    ///   history (`identify_needed_inputs` over the BEEF of the transaction
    ///   that spends it, `tx` or a body the walk reached), and the manager,
    ///   asked of that body in a dry run with no coins
    ///   (`TopicAdmittanceContext::DRY_RUN`, the submit's mode, no off-chain
    ///   values), would admit that named output: an OPENER that has not
    ///   landed (E1D, the cure D17 named). Only a NAMED output is dry-run
    ///   (the lens fold, H1): with every unheld body dry-run, a manager that
    ///   admits on output shape (all 16 of this workspace) made a spend of a
    ///   shape-admissible output this node never held (a revocation of an
    ///   ad it never saw; a stranger's own few-sat SHIP output) "not now" on
    ///   every presentation, three replays and a dead letter each, where the
    ///   reference records it. A manager `Err` in the dry run is "not now"
    ///   (the manager's contract at the anchor replay, D15), except its
    ///   typed refusal `NoAdmissibleOutputs`, which is "not admitted";
    /// - its body is NOT in the BEEF (a PROVEN successor carries none) and
    ///   the manager names the outpoint `tx` spends from it as overlay
    ///   history (D13's word; an `Err` there names nothing, as in the walk).
    ///
    /// The manager is asked over `beef_bytes`, the SUBJECT-NAMED BEEF of the
    /// submit (BRC-95 atomic, the body the lookup services get; the lens
    /// fold, M2): over the submitted bytes a manager that parses
    /// `from_beef(_, None)` took the wire-LAST transaction of a non-atomic
    /// BEEF, named an ancestor's inputs, and the question asked nothing.
    ///
    /// `admits` says which inputs of `tx` start the walk. A transaction that
    /// admits nothing (D17's class) starts from every input. One that admits
    /// WITHOUT its coin (E1D) starts only from the inputs the manager names:
    /// a manager that admits a successor with no coin has said the coin does
    /// not decide the admission, so only its own word makes an input a
    /// predecessor. Every manager of this workspace names nothing: an
    /// admitting successor is then asked nothing, as in the reference, and
    /// so is a spend of an unheld output nobody names (the lens fold, H1);
    /// but a successor that admits nothing still finds case (a), a carried
    /// body that spends a coin the topic holds, and waits for it or has it
    /// landed first, where the reference records the successor and never
    /// admits that body (the E1D delta fold, L3). A named input whose body
    /// the BEEF carries is still walked and dry-run, so a named decoy the
    /// manager would not admit is no predecessor.
    ///
    /// The answer carries the predecessor when its body is in the BEEF (the
    /// first two cases): the door lands it first ([`Engine::successors_waiting`]).
    ///
    /// The limits, stated. It cannot tell a faulted predecessor from one
    /// nobody submitted yet: a successor is "not now" in both until the
    /// predecessor lands (the door lands a carried one itself). A named
    /// input whose body is absent and which never lands (a decoy no one
    /// submits, beside a real predecessor that landed and holds no coin)
    /// keeps its successor "not now" at the door; the GASP walk prunes such
    /// an input instead (D14). Deeper than the successor's own inputs, an
    /// absent body ends the walk as before.
    ///
    /// "Landed" needs a clean answer (the delta fold of 2026-10-07, M1 and
    /// M2): a read that faults, or the question running out of its reads
    /// (the 16 of a topic or the 256 of the submit), answers "not now" too,
    /// naming the transaction it could not settle. Recording the successor
    /// there made its replay a dupe and stopped the chain behind it for
    /// good; a retried no-op is the lesser cost.
    ///
    /// What the bound counts (the second delta fold of 2026-10-07, M2): the
    /// reads spent on a body that is NEITHER proven in the BEEF NOR found
    /// landed, [`PREDECESSOR_READS`] of them per topic. A body the BEEF
    /// proves, and one whose applied row or held output answers "landed", is
    /// read and costs nothing against that bound: counted, they made a
    /// transaction that admits nothing over 17 landed parents, over six
    /// proven parents the topic never saw, or over one proven parent with 15
    /// inputs "not now" on every submit, with no unlanded predecessor
    /// anywhere. A landed body still needs ROOM under it: each read of an
    /// unproven body is tested before it is made, so with 15 counted reads
    /// spent one that landed by a held output (no applied row) is refused at
    /// its second read, and with 16 spent any unproven body at its first.
    ///
    /// "Proven" is the BEEF's word here: a body that carries a merkle path
    /// (a bump index) is counted as proven for the read bound ONLY. No proof
    /// is checked at this question; the SPV walk of the submit and the GASP
    /// anchor check are where proofs are checked, and under
    /// `historical-tx-no-spv` or the scripts-only walk nothing checked this
    /// one, so the 16 are the caller's to switch off. Nothing is recorded on
    /// that word (a proven body is walked like any other), and the allowance
    /// below does not ask it.
    ///
    /// The hard allowance (the third delta fold of 2026-10-07, M1):
    /// `question_reads`, owned by the submit, counts EVERY read of the
    /// question, those of proven and landed bodies included, over every
    /// topic of the submit, and stops it at
    /// [`PREDECESSOR_READS_PER_SUBMIT`]; the 16 stay inside it. A later
    /// topic's question starts from what the earlier ones left.
    ///
    /// The costs, stated. A transaction that admits nothing, found no coin
    /// and carries more UNPROVEN, UNLANDED bodies than 16 reads settle (five
    /// single-input ancestors, fewer with more inputs), or a BEEF whose
    /// question needs more than 256 reads over the submit's topics (a
    /// landed body costs one read by its applied row or two by a held
    /// output, a proven, unlanded one two and one per input), is never
    /// recorded, where the reference records it: each submit of it is a
    /// fault and a replay. The manager CPU it adds: one names call per
    /// spender a dry run needs (the subject's, and one per walked body with
    /// an unheld source), and at most one dry run per body the reads
    /// reached; each candidate is built out of the BEEF parsed once (the
    /// lens fold, L2).
    ///
    /// Returns why the submit must wait, for the report.
    #[allow(clippy::too_many_arguments)]
    async fn unlanded_predecessor(
        &self,
        tx: &Transaction,
        txid: &str,
        beef_bytes: &[u8],
        topic: &str,
        mode: SubmitMode,
        admits: bool,
        subject_names: &mut Option<HashSet<String>>,
        question_reads: &mut usize,
        bound: Option<&CallBound>,
    ) -> Option<NotNow> {
        let manager = self.managers.get(topic)?;
        let wait = |why: String| Some(NotNow { why, carried: None });
        // The outpoints `tx` spends, as `txid.vout`.
        let starts: Vec<(String, u32)> = tx
            .inputs
            .iter()
            .filter_map(|input| {
                let source = input.get_source_txid().ok()?;
                (!source.is_empty()).then_some((source, input.source_output_index))
            })
            .collect();
        // The outputs of each candidate that the walk spends, and who spends
        // each: a dry run asks only of an output its spender names.
        let mut spent_of: HashMap<String, HashSet<u32>> = HashMap::new();
        let mut spenders: HashMap<String, Vec<(String, u32)>> = HashMap::new();
        let mut ask: Vec<String> = Vec::new();
        for (source, vout) in &starts {
            if admits
                && subject_names
                    .as_ref()
                    .is_some_and(|named| !named.contains(&format!("{source}.{vout}")))
            {
                continue;
            }
            spent_of.entry(source.clone()).or_default().insert(*vout);
            spenders
                .entry(source.clone())
                .or_default()
                .push((txid.to_string(), *vout));
            ask.push(source.clone());
        }
        // Nothing to ask (a transaction that admits and names nothing, every
        // manager of this workspace): the BEEF is not even parsed.
        if ask.is_empty() {
            return None;
        }
        let direct: HashSet<String> = ask.iter().cloned().collect();
        let beef = beef_limits::parse_beef(beef_bytes, &beef_limits::ENGINE_BEEF_LIMITS).ok()?;
        // Each body the BEEF carries, and whether the BEEF says it is
        // proven (a bump index: its word, no proof is checked here).
        let bodies: HashMap<String, (&Transaction, bool)> = beef
            .txs
            .iter()
            .filter_map(|btx| {
                btx.tx()
                    .map(|body| (btx.txid(), (body, btx.bump_index().is_some())))
            })
            .collect();
        // The manager's names over each walked body other than `tx`.
        let mut names_over: HashMap<String, HashSet<String>> = HashMap::new();
        // The reads spent on bodies neither proven nor found landed.
        let mut reads = 0usize;
        let mut asked: HashSet<String> = HashSet::new();
        while let Some(candidate) = ask.pop() {
            if candidate.is_empty() || !asked.insert(candidate.clone()) {
                continue;
            }
            let spent_outputs = spent_of.get(&candidate).cloned().unwrap_or_default();
            // An absent body is asked of the store only when it is one of
            // `tx`'s own inputs and the manager names it (E1D).
            let body = bodies.get(&candidate).copied();
            if body.is_none() {
                if !direct.contains(&candidate) {
                    continue;
                }
                if subject_names.is_none() {
                    *subject_names = Some(
                        self.named_history(manager.as_ref(), beef_bytes, bound)
                            .await,
                    );
                }
                let is_named = subject_names.as_ref().is_some_and(|named| {
                    spent_outputs
                        .iter()
                        .any(|vout| named.contains(&format!("{candidate}.{vout}")))
                });
                if !is_named {
                    continue;
                }
            }
            let proven = body.is_some_and(|(_, proven)| proven);
            // This candidate's own reads: they join `reads` once it is
            // found not landed, and never if the BEEF proves it.
            let mut spent = 0usize;
            let out_of = |spent: usize| !proven && reads + spent >= PREDECESSOR_READS;
            let out_of_reads = || {
                wait(format!(
                    "{candidate} is not known to have landed: the question ran out of its {PREDECESSOR_READS} reads"
                ))
            };
            // The submit's allowance, over every read: proven or landed,
            // this topic or an earlier one.
            let out_of_allowance = || {
                wait(format!(
                    "{candidate} is not known to have landed: the question ran out of the submit's {PREDECESSOR_READS_PER_SUBMIT} reads"
                ))
            };
            let unread = |e: StorageError| {
                wait(format!(
                    "{candidate} is not known to have landed: the store could not say ({e})"
                ))
            };
            let carried = |why: String| {
                Some(NotNow {
                    why,
                    carried: Some(candidate.clone()),
                })
            };
            let record = AppliedTransaction {
                txid: candidate.clone(),
                topic: topic.to_string(),
            };
            // An applied row, or an output held, ends the question for this
            // transaction: it landed.
            if out_of(spent) {
                return out_of_reads();
            }
            if *question_reads >= PREDECESSOR_READS_PER_SUBMIT {
                return out_of_allowance();
            }
            spent += 1;
            *question_reads += 1;
            match stored(bound, self.storage.does_applied_transaction_exist(&record)).await {
                Ok(false) => {}
                Ok(true) => continue,
                Err(e) => return unread(e),
            }
            if out_of(spent) {
                return out_of_reads();
            }
            if *question_reads >= PREDECESSOR_READS_PER_SUBMIT {
                return out_of_allowance();
            }
            spent += 1;
            *question_reads += 1;
            match stored(
                bound,
                self.storage.find_outputs_for_transaction(&candidate, false),
            )
            .await
            {
                Ok(outputs) if outputs.iter().all(|o| o.topic != topic) => {}
                Ok(_) => continue,
                Err(e) => return unread(e),
            }
            // Not landed. With no body to walk, the manager's word is the
            // whole answer (E1D).
            let Some((body, _)) = body else {
                return wait(format!(
                    "{candidate} has not landed (the manager names it as history; the BEEF does not carry it)"
                ));
            };
            for input in &body.inputs {
                let source = input.get_source_txid().unwrap_or_default();
                if source.is_empty() {
                    continue;
                }
                if out_of(spent) {
                    return out_of_reads();
                }
                if *question_reads >= PREDECESSOR_READS_PER_SUBMIT {
                    return out_of_allowance();
                }
                spent += 1;
                *question_reads += 1;
                let coin = stored(
                    bound,
                    self.storage.find_output(
                        &source,
                        input.source_output_index,
                        Some(topic),
                        None,
                        false,
                    ),
                )
                .await;
                match coin {
                    Ok(Some(_)) => return carried(format!("{candidate} has not landed")),
                    // Not held: its own transaction may be the one that has
                    // not landed.
                    Ok(None) => {
                        spent_of
                            .entry(source.clone())
                            .or_default()
                            .insert(input.source_output_index);
                        spenders
                            .entry(source.clone())
                            .or_default()
                            .push((candidate.clone(), input.source_output_index));
                        ask.push(source);
                    }
                    Err(e) => return unread(e),
                }
            }
            // It spends no coin the topic holds. Does a spender NAME an
            // output the walk spends of it (the lens fold, H1)? A names call
            // per spender, no store read.
            let mut named_outputs: HashSet<u32> = HashSet::new();
            for (spender, vout) in spenders.get(&candidate).cloned().unwrap_or_default() {
                let names = if spender == txid {
                    if subject_names.is_none() {
                        *subject_names = Some(
                            self.named_history(manager.as_ref(), beef_bytes, bound)
                                .await,
                        );
                    }
                    subject_names.as_ref()
                } else {
                    if !names_over.contains_key(&spender) {
                        let names = match beef
                            .find_atomic_transaction(&spender)
                            .and_then(|spender| spender.to_atomic_beef(true).ok())
                        {
                            Some(spender_beef) => {
                                self.named_history(manager.as_ref(), &spender_beef, bound)
                                    .await
                            }
                            None => HashSet::new(),
                        };
                        names_over.insert(spender.clone(), names);
                    }
                    names_over.get(&spender)
                };
                if names.is_some_and(|named| named.contains(&format!("{candidate}.{vout}"))) {
                    named_outputs.insert(vout);
                }
            }
            if !named_outputs.is_empty() {
                // Would the manager admit a named output of it with no coins
                // (E1D, the opener)? A dry run over the candidate built out
                // of the BEEF parsed above (its proof and, unproven, its
                // sources linked): no store read, nothing counted.
                let judged = beef
                    .find_atomic_transaction(&candidate)
                    .unwrap_or_else(|| body.clone());
                let verdict = bounded(
                    bound,
                    manager.identify_admissible_outputs(
                        &judged,
                        &[],
                        None,
                        mode,
                        &TopicAdmittanceContext::DRY_RUN,
                    ),
                )
                .await;
                match verdict {
                    Ok(Ok(admittance)) => {
                        if admittance
                            .outputs_to_admit
                            .iter()
                            .any(|vout| named_outputs.contains(vout))
                        {
                            return carried(format!(
                                "{candidate} has not landed (the manager names the output spent from it and would admit it with no coin: an opener)"
                            ));
                        }
                    }
                    Ok(Err(TopicManagerError::NoAdmissibleOutputs(_))) => {}
                    Ok(Err(e)) => {
                        return wait(format!(
                            "{candidate} is not known to have landed: the manager could not judge it ({e})"
                        ))
                    }
                    Err(no_answer) => {
                        return wait(format!(
                            "{candidate} is not known to have landed: the manager did not answer ({no_answer})"
                        ))
                    }
                }
            }
            if !proven {
                reads += spent;
            }
        }
        None
    }

    /// The outpoints (`txid.vout`) the topic manager NAMES as overlay
    /// history of the transaction `beef_bytes` names (`identify_needed_inputs`,
    /// D13's word; an atomic BEEF, so a manager that parses
    /// `from_beef(_, None)` reads that transaction). An `Err` or no answer
    /// names nothing, as the GASP walk treats it (logged).
    async fn named_history(
        &self,
        manager: &dyn TopicManager,
        beef_bytes: &[u8],
        bound: Option<&CallBound>,
    ) -> HashSet<String> {
        match bounded(bound, manager.identify_needed_inputs(beef_bytes, None)).await {
            Ok(Ok(named)) => named.iter().map(Outpoint::to_graph_id).collect(),
            Ok(Err(e)) => {
                warn!("the predecessor question: the manager could not name its inputs: {e}");
                HashSet::new()
            }
            Err(no_answer) => {
                warn!("the predecessor question: the manager did not name its inputs: {no_answer}");
                HashSet::new()
            }
        }
    }

    /// The reference's `tx.verify(chainTracker)` on submit: every unproven
    /// transaction from the subject down has every input's script executed
    /// against its source output and obeys the value rule; a proven one is
    /// not descended, and its BUMP's root is checked against the chain
    /// tracker (computed and accepted with none).
    ///
    /// Since bsv-low #592 (the owner's ruling 3a of 2026-10-10) the scripts
    /// are walked by the DOOR's stream walk ([`crate::script_door`]) under
    /// `budget`, the engine's [`DoorBudget`]: one walker, the same estimates
    /// charged from the bytes before anything is parsed or run. Before it this
    /// was a walk of its own over a hydrated `Beef` with no memory charge and
    /// no interpreter limit: 219.7 MB natively on a 1.9 MB push-only unproven
    /// parent, an isolate kill on Workers, met by every `historical-tx` replay
    /// of the queue. The roots are then asked for the proven transactions the
    /// walk reached, in its order, once per BUMP.
    ///
    /// `Ok(Some(_))` is a walk that COULD NOT RUN within the budget, never a
    /// refusal (below, at the match). The interpreter's refusal and a
    /// structural fault are what they were: `ScriptVerificationFailed`, and
    /// `SpvError` in the same words.
    ///
    /// The tracker is an ARGUMENT, not `self`'s: the GASP anchor check
    /// ([`verify_spv_like_the_reference`]) runs this same walk from
    /// `OverlayGASPStorage`, which borrows the engine's tracker.
    ///
    /// Why not bsv-rs `Transaction::verify`: it walks `source_transaction`
    /// links that `from_beef` builds by CLONING, once per input. Two inputs
    /// sourcing the same unproven parent (a covenant head output plus that
    /// spend's own change, the shape of every second head spend of a wallet)
    /// leave the second clone bare ("Input 0 has no source transaction"), and
    /// re-linking every clone materializes the ancestry EXPONENTIALLY along a
    /// diamond chain: a 12-deep unmined chain of head spends took a Worker past
    /// its memory on beta (zanaadu, 2026-09-08). The stream walk reads each
    /// transaction once, in place, keyed by txid.
    async fn verify_beef_linear(
        chain_tracker: Option<&dyn bsv_rs::transaction::ChainTracker>,
        beef_bytes: &[u8],
        subject_txid: &str,
        trusted: &HashSet<String>,
        budget: DoorBudget,
    ) -> Result<Option<WalkCouldNotRun>, EngineError> {
        // A structural fault is the reference walk's `SpvError`.
        let spv =
            |msg: String| EngineError::SpvError(format!("Unable to verify SPV information: {msg}"));

        // THE SCRIPTS (bsv-low #592): the door's own stream walk, under the
        // engine's budget. One walker (Rule 10): the door and the submit run
        // the same function, the same estimates and the same interpreter
        // limit; the submit adds the roots below.
        let mut trace = crate::script_door::WalkTrace::default();
        match crate::script_door::walk_trusting(
            beef_bytes,
            subject_txid,
            budget,
            trusted,
            &mut trace,
        ) {
            Ok(_) => {}
            // The interpreter's verdict, the reference's refusal: unchanged.
            Err(refused @ EngineError::ScriptVerificationFailed { .. }) => return Err(refused),
            // A structural fault (a source missing, the value rule, ...):
            // the reference walk's `SpvError`, in the same words as before.
            Err(EngineError::ScriptWalkInconclusive { reason, .. }) => return Err(spv(reason)),
            // The budget, not the transaction: the walk COULD NOT RUN. Not a
            // refusal: the bytes are a BEEF the walk was not given the room
            // to judge, which says nothing about whether its scripts are
            // valid (refusing would refuse a valid BEEF for its size, the
            // owner's posture). Not an admission either: the caller's
            // [`WalkBreachPolicy`] decides, and only the network's word on
            // record lets the submit go on (the E592 lens fold, H1). The roots
            // the walk reached are checked first, below.
            Err(EngineError::ScriptWalkOverBudget {
                at_txid,
                subject_judged,
                limb,
                what,
            }) => {
                let limb = match limb {
                    DoorLimb::Memory => WalkLimb::OverMemory,
                    DoorLimb::Work if trace.interpreter_tripped => WalkLimb::InterpreterMemory,
                    DoorLimb::Work => WalkLimb::OverWork,
                };
                // THE ROOTS OF A BREACHED WALK (the E592 lens fold, H1): every
                // proven transaction it reached, and every proven source an
                // input read, whatever the scripts' verdict. A bad root is
                // the `SpvError` it is on a walk that ran: a breach never
                // skips a proof the walk relied on. Their cost is a tracker
                // question per BUMP, which the budget does not bound and
                // does not need to (the clean walk asks the same).
                let reached: Vec<String> = trace
                    .proven
                    .iter()
                    .chain(&trace.proven_sources)
                    .cloned()
                    .collect();
                Self::check_reached_roots(chain_tracker, beef_bytes, &reached).await?;
                return Ok(Some(WalkCouldNotRun {
                    subject_txid: subject_txid.to_string(),
                    at_txid,
                    subject_judged,
                    limb,
                    what,
                }));
            }
            Err(other) => return Err(other),
        }

        // THE ROOTS: every proven transaction the walk reached, in the order
        // it reached them, its BUMP's root computed and asked of the tracker
        // once per BUMP (NL-6e). With no tracker the roots are computed and
        // accepted (`'scripts only'`). The walk trusted them as it went; the
        // reference checks them in the same walk, so a body with BOTH a bad
        // script and a bad root now names the script.
        Self::check_reached_roots(chain_tracker, beef_bytes, &trace.proven).await?;
        Ok(None)
    }

    /// The roots of `reached` (display txids, in order; a repeat or a second
    /// transaction of one BUMP asks nothing more), each BUMP's root computed
    /// and asked of the tracker once. None reached: the body is not parsed.
    async fn check_reached_roots(
        chain_tracker: Option<&dyn bsv_rs::transaction::ChainTracker>,
        beef_bytes: &[u8],
        reached: &[String],
    ) -> Result<(), EngineError> {
        let spv =
            |msg: String| EngineError::SpvError(format!("Unable to verify SPV information: {msg}"));
        if reached.is_empty() {
            return Ok(());
        }
        let beef = beef_limits::parse_beef(beef_bytes, &beef_limits::ENGINE_BEEF_LIMITS)
            .map_err(|e| EngineError::BeefParseError(e.to_string()))?;
        let proven_in = proven_index(&beef);
        let mut checked: HashSet<usize> = HashSet::new();
        for txid in reached {
            let Some(&at) = proven_in.get(txid.as_str()) else {
                return Err(spv(format!("transaction {txid} is not in the BEEF")));
            };
            if !checked.insert(at) {
                continue; // its BUMP's root is the chain's, asked once
            }
            let mp = &beef.bumps[at];
            let root = mp
                .compute_root(Some(txid))
                .map_err(|e| spv(format!("invalid merkle path for transaction {txid}: {e}")))?;
            if let Some(tracker) = chain_tracker {
                match tracker
                    .is_valid_root_for_height(&root, mp.block_height)
                    .await
                {
                    Ok(true) => {}
                    Ok(false) => {
                        return Err(EngineError::SpvError(format!(
                            "Invalid merkle path for transaction {txid}: root {root} is not valid for block height {}",
                            mp.block_height
                        )));
                    }
                    Err(e) => {
                        return Err(EngineError::SpvError(format!(
                            "Chain tracker error at height {}: {e}",
                            mp.block_height
                        )));
                    }
                }
            }
        }
        Ok(())
    }

    /// The pre-2026-09-08 SPV block, kept as the
    /// [`Engine::set_script_verification`] `false` escape hatch: BEEF
    /// structural validity plus every root against the chain tracker, and
    /// NOTHING when no tracker is configured. It never executes a script.
    ///
    /// The structure is the streaming reader's
    /// ([`beef_limits::structure_roots`], bsv-rs 0.4.2): one element in hand,
    /// each BUMP walked once, linear in its leaves (NL-6e). Until NL-6e it
    /// was `Beef::verify_valid`, whose root check at bsv-rs 0.4.0 walked a
    /// BUMP once per leaf: one BUMP of 8,192 leaves gave no answer in 120 s
    /// (bsv-stack-lean NL-8 W1). The reader reads the wire's order, where
    /// `verify_valid` sorted first: an input that names a later transaction
    /// is refused here.
    async fn verify_spv_structurally(
        chain_tracker: Option<&dyn bsv_rs::transaction::ChainTracker>,
        beef_bytes: &[u8],
    ) -> Result<(), EngineError> {
        let Some(chain_tracker) = chain_tracker else {
            return Ok(());
        };
        let roots = beef_limits::structure_roots(beef_bytes)
            .map_err(|r| EngineError::SpvError(format!("BEEF structure refused: {r}")))?;
        let mut asked: HashSet<(u64, &str)> = HashSet::new();
        for (height, root) in &roots {
            if !asked.insert((*height, root.as_str())) {
                continue;
            }
            let Ok(height) = u32::try_from(*height) else {
                return Err(EngineError::SpvError(format!(
                    "Merkle root {root} invalid for block height {height}"
                )));
            };
            match chain_tracker.is_valid_root_for_height(root, height).await {
                Ok(true) => {}
                Ok(false) => {
                    return Err(EngineError::SpvError(format!(
                        "Merkle root {root} invalid for block height {height}"
                    )));
                }
                Err(e) => {
                    return Err(EngineError::SpvError(format!(
                        "Chain tracker error at height {height}: {e}"
                    )));
                }
            }
        }
        Ok(())
    }

    /// Phase 1 of ONE topic: the dedup read, the previous coins, the
    /// manager's judgement. Read-only. [`Engine::run_validation`] asks it of
    /// every topic; the door asks it again of a topic whose predecessor it
    /// landed first from the BEEF (lane E1D's lens fold, M1).
    #[allow(clippy::too_many_arguments)]
    async fn validate_topic(
        &self,
        tx: &Transaction,
        txid: &str,
        topic: &str,
        off_chain_values: Option<&[u8]>,
        mode: SubmitMode,
        context: &TopicAdmittanceContext,
        bound: Option<&CallBound>,
    ) -> TopicValidation {
        let tx_record = AppliedTransaction {
            txid: txid.to_string(),
            topic: topic.to_string(),
        };
        // A dedup read that FAULTS is the topic's read fault (the delta
        // fold of 2026-10-07, H3): nothing is judged and nothing is
        // written for the topic, the fault rides the report and the
        // replay asks again. The reference fails the topic there
        // (`Engine.ts` `submit`: the throw lands in the per-topic catch,
        // `failedTopics.add`). Read as "not a dupe", as it was, a
        // re-presented transaction the manager admits with no previous
        // coin was inserted a second time, unspent, beside the output
        // that had spent it, under a durable report.
        let is_dupe = match stored(
            bound,
            self.storage.does_applied_transaction_exist(&tx_record),
        )
        .await
        {
            Ok(is_dupe) => is_dupe,
            Err(e) => {
                error!("Error reading the applied row of {txid} for topic {topic}: {e}");
                return TopicValidation {
                    topic: topic.to_string(),
                    is_dupe: false,
                    previous_coins: vec![],
                    previous_outputs: vec![],
                    admittance: AdmittanceInstructions::default(),
                    failed: false,
                    read_fault: Some(("does_applied_transaction_exist", e.to_string())),
                };
            }
        };

        if is_dupe {
            return TopicValidation {
                topic: topic.to_string(),
                is_dupe: true,
                previous_coins: vec![],
                previous_outputs: vec![],
                admittance: AdmittanceInstructions::default(),
                failed: false,
                read_fault: None,
            };
        }

        let mut previous_coins: Vec<u32> = Vec::new();
        let mut previous_outputs: Vec<Output> = Vec::new();
        let mut read_fault: Option<(&'static str, String)> = None;

        for (input_idx, input) in tx.inputs.iter().enumerate() {
            let source_txid = input.get_source_txid().unwrap_or_default();
            if source_txid.is_empty() {
                continue;
            }
            match stored(
                bound,
                self.storage.find_output(
                    &source_txid,
                    input.source_output_index,
                    Some(topic),
                    None,
                    false,
                ),
            )
            .await
            {
                Ok(Some(prev_output)) => {
                    previous_coins.push(input_idx as u32);
                    previous_outputs.push(prev_output);
                }
                Ok(None) => {}
                Err(e) => {
                    // A faulted read is NOT "no previous coin": the
                    // spend may consume an admitted output we simply
                    // could not read. Validation proceeds (the topic
                    // manager decides on what it can see) but the fault
                    // rides the report and blocks the applied record.
                    error!(
                        "Error reading previous output {source_txid}:{} for topic {topic}: {e}",
                        input.source_output_index
                    );
                    if read_fault.is_none() {
                        read_fault = Some(("find_output", e.to_string()));
                    }
                }
            }
        }

        let judged = self
            .judge(
                tx,
                topic,
                &previous_coins,
                off_chain_values,
                mode,
                context,
                bound,
            )
            .await;
        match judged {
            Ok(admittance) => TopicValidation {
                topic: topic.to_string(),
                is_dupe: false,
                previous_coins,
                previous_outputs,
                admittance,
                failed: false,
                read_fault: read_fault.clone(),
            },
            Err(e) => {
                error!("Error validating topic {topic} during submit: {e}");
                TopicValidation {
                    topic: topic.to_string(),
                    is_dupe: false,
                    previous_coins: vec![],
                    previous_outputs: vec![],
                    admittance: AdmittanceInstructions::default(),
                    failed: true,
                    read_fault,
                }
            }
        }
    }

    /// The topic manager's judgement of `tx` over the previous coins found
    /// (input indices), as [`Engine::validate_topic`] asks it; a carried
    /// predecessor's submit asks it again for real once its topic does not
    /// wait (the E1D delta fold, L4).
    #[allow(clippy::too_many_arguments)]
    async fn judge(
        &self,
        tx: &Transaction,
        topic: &str,
        previous_coins: &[u32],
        off_chain_values: Option<&[u8]>,
        mode: SubmitMode,
        context: &TopicAdmittanceContext,
        bound: Option<&CallBound>,
    ) -> Result<AdmittanceInstructions, TopicManagerError> {
        let manager = &self.managers[topic];
        let previous_coin_bytes = previous_coins
            .iter()
            .flat_map(|i| i.to_le_bytes())
            .collect::<Vec<u8>>();
        // Under a finalize submit's bound a manager that does not answer
        // is a manager that failed: nothing is written for the topic.
        bounded(
            bound,
            manager.identify_admissible_outputs(
                // The ONE engine parse of the submitted BEEF, shared by
                // every topic on this submit (bsv-low #289 — managers
                // used to re-parse the same bytes independently).
                tx,
                &previous_coin_bytes,
                off_chain_values,
                mode,
                // `dry_run` is `false` on a submit, `true` on a
                // validate-only call.
                context,
            ),
        )
        .await
        .map_err(TopicManagerError::Other)
        .and_then(|judged| judged)
    }

    /// Whether the door may land a carried predecessor into `topic` (the
    /// E1D delta fold, L1): neither its manager nor any lookup service
    /// reads off-chain values there, which the landing does not have.
    fn lands_without_values(&self, topic: &str) -> bool {
        self.managers
            .get(topic)
            .is_some_and(|manager| !manager.reads_off_chain_values())
            && self
                .lookup_services
                .values()
                .all(|ls| !ls.reads_off_chain_values(topic))
    }

    /// Run Phase 1 (topic validation) and Phase 2 (broadcast) without mutating storage.
    ///
    /// Returns (validations, steak, parsed_tx, txid) so the caller can either
    /// stop (validate-only) or proceed with Phase 3 (mutations).
    async fn run_validation(
        &self,
        tagged_beef: &TaggedBEEF,
        mode: SubmitMode,
        context: &TopicAdmittanceContext,
        bound: Option<&CallBound>,
        walked: Option<&HashSet<String>>,
        policy: WalkBreachPolicy,
    ) -> Result<Validated, EngineError> {
        // Validate all topics are supported
        for topic in &tagged_beef.topics {
            if !self.managers.contains_key(topic) {
                return Err(EngineError::UnsupportedTopic(topic.clone()));
            }
        }

        // Parse the SUBJECT from the BEEF — order-independent (`subject.rs`,
        // loop-2 hardening 2026-09-05): `from_beef(_, None)` takes the last
        // tx in wire order, which an SDK-sorted INCOMPLETE ancestry fills
        // with a fully-sourced ancestor; the engine then judged a hop, admitted
        // nothing and the pot never entered the index while its JOIN mined.
        let subject = {
            let mut b =
                beef_limits::parse_beef(&tagged_beef.beef, &beef_limits::ENGINE_BEEF_LIMITS)
                    .map_err(|e| EngineError::BeefParseError(e.to_string()))?;
            crate::subject::subject_txid_of(&mut b)
        };
        let tx = beef_limits::transaction_from_beef(
            &tagged_beef.beef,
            subject.as_deref(),
            &beef_limits::ENGINE_BEEF_LIMITS,
        )
        .map_err(|e| EngineError::BeefParseError(e.to_string()))?;
        let txid = tx.id();

        // SPV verification, skipped ONLY for HistoricalTxNoSpv, exactly the
        // reference's `if (mode !== 'historical-tx-no-spv') tx.verify(...)`.
        // That mode exists for GASP `finalizeGraph`, whose graphs
        // `validateGraphAnchor` already verified, and since bsv-low #551 that
        // is TRUE here: `OverlayGASPStorage::validate_graph_anchor` runs this
        // same check ([`verify_spv_like_the_reference`], the same tracker and
        // the same switch) over the ROOT node's BEEF and replays the graph
        // through the topic manager before a single BEEF of it reaches this
        // door. Before #551 the anchor check was a no-op and this skip
        // admitted a peer's graph on structure alone.
        //
        // A predecessor the door lands first (`walked`, the E1D delta fold,
        // L4) is not walked again when this submit's walks already passed
        // over it, and its walk trusts what they passed over.
        //
        // The walk runs under the engine's budget (bsv-low #592,
        // [`Engine::set_walk_budget`]): one that could not run within it is
        // NOT a refusal (see `verify_beef_linear`), and NOT an admission
        // unless the caller holds the network's accept of these bytes (the
        // E592 lens fold, H1, [`WalkBreachPolicy`]): "not now" before any
        // manager is asked, or, under `NetworkAccepted`, this submit goes on
        // as under `HistoricalTxNoSpv` and the report says so.
        let mut could_not_run = None;
        if mode != SubmitMode::HistoricalTxNoSpv {
            match walked {
                Some(walked) if walked.contains(&txid) => {}
                trusted => {
                    could_not_run = verify_spv_trusting(
                        self.chain_tracker.as_deref(),
                        self.verify_scripts,
                        &tagged_beef.beef,
                        &txid,
                        trusted.unwrap_or(&HashSet::new()),
                        self.walk_budget,
                    )
                    .await?;
                }
            }
        }
        if let Some(stop) = could_not_run.take() {
            match policy {
                WalkBreachPolicy::NotNow => {
                    warn!(
                        "submit: the engine's script walk could not run for {} ({}: at {}, subject judged: {}; {}): not now, nothing judged or written; present it proven (bsv-low #592, E592 fold)",
                        stop.subject_txid,
                        stop.limb.as_str(),
                        stop.at_txid,
                        stop.subject_judged,
                        stop.what
                    );
                    return Err(EngineError::WalkCouldNotRun(stop));
                }
                WalkBreachPolicy::NetworkAccepted => {
                    warn!(
                        "submit: the engine's script walk could not run for {} ({}: at {}, subject judged: {}; {}): the network accepted these bytes, the submit goes on as historical-tx-no-spv (bsv-low #592)",
                        stop.subject_txid,
                        stop.limb.as_str(),
                        stop.at_txid,
                        stop.subject_judged,
                        stop.what
                    );
                    could_not_run = Some(stop);
                }
            }
        }

        let mut steak = Steak::new();

        // =============================================================
        // PHASE 1: VALIDATE (read-only)
        // =============================================================
        let mut validations = Vec::new();

        for topic in &tagged_beef.topics {
            validations.push(
                self.validate_topic(
                    &tx,
                    &txid,
                    topic,
                    tagged_beef.off_chain_values.as_deref(),
                    mode,
                    context,
                    bound,
                )
                .await,
            );
        }

        // Build preliminary STEAK
        for v in &validations {
            steak.insert(v.topic.clone(), v.admittance.clone());
        }

        // =============================================================
        // PHASE 2: BROADCAST / SHIP propagation (before mutations)
        // =============================================================
        if mode == SubmitMode::CurrentTx {
            // ── ARC network broadcast ──────────────────────────────────
            // Broadcast to miners via ARC, matching the TS Engine pattern.
            // Skip if the tx already has a merkle path (already mined).
            //
            // INCIDENT D1-CALLBACK-FLOOD 2026-09-01: also skip when EVERY
            // topic classified the tx as a dupe (already applied) — the
            // exact `!v.is_dupe` filter the SHIP arm below has always had,
            // ten lines away. Without it, every RE-PRESENT of an
            // already-applied tx (cron ad-sync, peer crawl, a client
            // retrying a default-mode /submit) re-POSTed to Arcade and
            // re-registered the status callback, and registrations
            // accumulate per POST on Arcade's side — the flood's fuel. A
            // genuinely new tx (any topic non-dupe) broadcasts exactly as
            // before.
            let all_topics_dupe = !validations.is_empty() && validations.iter().all(|v| v.is_dupe);
            if let Some(ref arc) = self.arc_broadcaster {
                if all_topics_dupe {
                    info!(
                        "Skipping ARC broadcast — tx already applied to every topic (re-present)"
                    );
                } else if tx.merkle_path.is_none() {
                    let raw_tx_hex = tx.to_hex();
                    match arc.broadcast(&raw_tx_hex).await {
                        Ok(arc_txid) => {
                            info!("ARC broadcast succeeded: txid={arc_txid}");
                        }
                        Err(e) => {
                            error!("ARC broadcast failed (non-fatal): {e}");
                        }
                    }
                } else {
                    info!("Skipping ARC broadcast — tx already has merkle proof");
                }
            }

            // ── SHIP peer propagation ──────────────────────────────────
            if let Some(ref broadcaster) = self.broadcaster {
                let relevant_topics: Vec<String> = validations
                    .iter()
                    .filter(|v| {
                        !v.is_dupe && !v.failed && !v.admittance.outputs_to_admit.is_empty()
                    })
                    .map(|v| v.topic.clone())
                    .collect();

                if !relevant_topics.is_empty() {
                    if let Some(ship_ls) = self.lookup_services.get("ls_ship") {
                        for topic in &relevant_topics {
                            let question = LookupQuestion::new(
                                "ls_ship",
                                serde_json::json!({ "topics": [topic] }),
                            );
                            match ship_ls.lookup(&question).await {
                                Ok(LookupResult::OutputList(refs)) => {
                                    for reference in &refs {
                                        if let Ok(Some(output)) = self
                                            .storage
                                            .find_output(
                                                &reference.txid,
                                                reference.output_index,
                                                None,
                                                None,
                                                false,
                                            )
                                            .await
                                        {
                                            if let Some(domain) =
                                                parse_ship_domain_from_script(&output.output_script)
                                            {
                                                if let Some(ref our_url) = self.config.hosting_url {
                                                    if domain.trim_end_matches('/')
                                                        == our_url.trim_end_matches('/')
                                                    {
                                                        continue;
                                                    }
                                                }
                                                if let Err(e) = broadcaster
                                                    .broadcast_to_host(&domain, tagged_beef)
                                                    .await
                                                {
                                                    error!(
                                                        "SHIP propagation to {domain} failed for topic {topic}: {e}"
                                                    );
                                                }
                                            }
                                        }
                                    }
                                }
                                Ok(LookupResult::Answer(_)) => {
                                    // SHIP only ever returns OutputList; an Answer here means
                                    // a misconfigured replacement service. Skip rather than
                                    // attempt to extract refs from a freeform/formula payload.
                                    error!(
                                        "SHIP lookup for topic {topic} returned a pre-formed \
                                         LookupAnswer; expected OutputList. Skipping fanout."
                                    );
                                }
                                Err(e) => {
                                    error!("SHIP lookup for topic {topic} failed: {e}");
                                }
                            }
                        }
                    }
                }
            }
        }

        Ok((validations, steak, tx, txid, could_not_run))
    }

    // ========================================================================
    // Lookup
    // ========================================================================

    /// Answer a lookup query.
    ///
    /// Delegates to the appropriate LookupService, then hydrates results with BEEF.
    ///
    /// When `history_selector` is provided, each output is hydrated with its
    /// ancestor spend chain (via `get_utxo_history`) before building the response.
    /// This matches the TS Engine behavior when a history selector is configured.
    pub async fn lookup(
        &self,
        question: &LookupQuestion,
        history_selector: Option<HistorySelector>,
    ) -> Result<LookupAnswer, EngineError> {
        Ok(self.lookup_with_txids(question, history_selector).await?.0)
    }

    /// Same as [`Engine::lookup`], additionally returning each hydrated
    /// output's txid, aligned index-for-index with the `OutputList` items
    /// (empty for pre-formed `Answer`s).
    ///
    /// The txid IS the storage primary key the row was just fetched by —
    /// handing it to the caller lets the aggregated wire serializer write it
    /// directly instead of re-deriving it with a full BEEF parse plus a
    /// double-SHA256 per output (bsv-low #289).
    pub async fn lookup_with_txids(
        &self,
        question: &LookupQuestion,
        history_selector: Option<HistorySelector>,
    ) -> Result<(LookupAnswer, Vec<String>), EngineError> {
        let service = self
            .lookup_services
            .get(&question.service)
            .ok_or_else(|| EngineError::LookupServiceNotFound(question.service.clone()))?;

        // Preserve WHOSE fault it was. A lookup service reports a malformed
        // query as `InvalidQuery` / `Unsupported`; stringifying both into
        // `LookupFailed` (as this did) threw that away and reported every
        // caller mistake as a 500.
        let result = service.lookup(question).await.map_err(|e| match e {
            LookupServiceError::InvalidQuery(m) | LookupServiceError::Unsupported(m) => {
                EngineError::InvalidQuery(m)
            }
            other => EngineError::LookupFailed(other.to_string()),
        })?;

        // Two paths per LookupResult:
        // - OutputList(refs): the LS yields outpoints; we hydrate each with
        //   BEEF (and optional ancestor chain via history_selector) and
        //   assemble LookupAnswer::OutputList.
        // - Answer(answer): the LS already produced the full answer
        //   (Freeform/Formula); pass through verbatim. The Engine does NOT
        //   apply history-selector hydration to a pre-formed Answer — the
        //   LS is presumed to have embedded whatever ancestry it wants.
        let refs = match result {
            LookupResult::OutputList(refs) => refs,
            LookupResult::Answer(answer) => return Ok((answer, Vec::new())),
        };

        // ONE batched hydration query for the whole result set instead of a
        // D1 round-trip per row (the #289 N+1). Order is preserved: the
        // batch contract returns outputs in input-outpoint order, skipping
        // outpoints with no stored row. A storage error is a REAL error now
        // (it used to be swallowed per-row into a silently-empty list — the
        // "vanishing table" failure mode): an uncertain read must never
        // masquerade as a confidently-empty lobby.
        let outpoints: Vec<Outpoint> = refs
            .iter()
            .map(|r| Outpoint::new(&r.txid, r.output_index))
            .collect();
        let found = self
            .storage
            .find_served_outputs(&outpoints)
            .await
            .map_err(|e| EngineError::StorageError(e.to_string()))?;

        let mut outputs = Vec::new();
        let mut txids = Vec::new();
        for output in found {
            // If history selector provided, hydrate ancestor chain
            let final_output = if history_selector.is_some() {
                match self
                    .get_utxo_history(&output, history_selector.clone())
                    .await
                {
                    Ok(Some(hydrated)) => hydrated,
                    _ => output,
                }
            } else {
                output
            };

            // Skip an output whose BEEF is missing OR empty: a lookup item
            // without decodable BEEF is useless to the client (it can only
            // drop it), and returning an empty-BEEF row is what made a fresh
            // LOW table show up in a query yet be undecodable/invisible to
            // opponents (the "vanishing table" — 2026-07-11). Only ever
            // return fully-hydrated, decodable outputs.
            if let Some(beef) = final_output.beef {
                if !beef.is_empty() {
                    txids.push(final_output.txid.clone());
                    outputs.push(OutputListItem {
                        beef,
                        output_index: final_output.output_index,
                        context: None,
                    });
                }
            }
        }

        Ok((LookupAnswer::OutputList { outputs }, txids))
    }

    // ========================================================================
    // Metadata
    // ========================================================================

    // ========================================================================
    // UTXO History
    // ========================================================================

    /// Traverse and return the history of a UTXO.
    ///
    /// If no `history_selector` is provided, returns the output as-is.
    /// If a depth selector is provided, includes up to N levels of ancestor
    /// transactions by embedding them as source_transactions in the BEEF.
    pub async fn get_utxo_history(
        &self,
        output: &Output,
        history_selector: Option<HistorySelector>,
    ) -> Result<Option<Output>, EngineError> {
        let Some(selector) = history_selector else {
            return Ok(Some(output.clone()));
        };

        // Verify BEEF exists before attempting hydration
        if output.beef.is_none() {
            return Err(EngineError::Other(
                "Output must have associated transaction BEEF!".into(),
            ));
        }

        match self.hydrate_utxo_history(output, &selector, 0).await {
            Ok(Some(hydrated_output)) => Ok(Some(hydrated_output)),
            Ok(None) => Ok(None),
            Err(e) => Err(EngineError::Other(format!(
                "Error retrieving UTXO history: {e}"
            ))),
        }
    }

    /// Recursive UTXO history hydration.
    fn hydrate_utxo_history<'a>(
        &'a self,
        output: &'a Output,
        selector: &'a HistorySelector,
        current_depth: u32,
    ) -> std::pin::Pin<
        Box<dyn std::future::Future<Output = Result<Option<Output>, EngineError>> + 'a>,
    > {
        Box::pin(async move {
            let beef_data = output.beef.as_ref().ok_or_else(|| {
                EngineError::Other("Output must have associated transaction BEEF!".into())
            })?;

            // Check if we should traverse at this depth
            let should_traverse = match selector {
                HistorySelector::Depth(max_depth) => current_depth <= *max_depth,
            };

            if !should_traverse {
                return Ok(None);
            }

            // Start from the STORED BEEF, not from a re-parsed subject.
            //
            // #4: this used to be `Transaction::from_beef(beef_data, None)` followed
            // by `tx.to_beef(true)`, which keeps only the subject transaction and
            // therefore DESTROYS the stored BUMPs. Measured on prod before the fix:
            // `ls_low` byGameId `73de6e48…` returned 1,172 B / 1 tx / 1 bump (PROVEN)
            // with no header, and 676 B / 1 tx / 0 bumps with `x-history-depth: 3` —
            // a caller asking for MORE provenance got back a BEEF no wallet can
            // verify, silently, behind a 200.
            //
            // Accumulating into the stored BEEF fixes both halves: its own bumps
            // survive, and so does any ancestry that arrived inside the submitted
            // bytes but was never admitted as an output of its own (a foreign
            // parent), which the `outputs_consumed` walk below cannot see.
            let mut acc = beef_limits::parse_beef(beef_data, &beef_limits::STORED_BEEF_LIMITS)
                .map_err(|e| EngineError::BeefParseError(e.to_string()))?;

            // For each consumed output, recursively hydrate and embed as source transaction
            for consumed in &output.outputs_consumed {
                if let Ok(Some(child_output)) = self
                    .storage
                    .find_output(&consumed.txid, consumed.output_index, None, None, true)
                    .await
                {
                    if let Ok(Some(hydrated_child)) = self
                        .hydrate_utxo_history(&child_output, selector, current_depth + 1)
                        .await
                    {
                        // MERGE the hydrated ancestor in, rather than embedding it
                        // as a `source_transaction` on a re-parsed subject: a merge
                        // carries the child's own BUMPs across, which is the whole
                        // point of asking for history. An unparseable child is
                        // skipped — never allowed to poison the accumulator.
                        if let Some(ref child_beef) = hydrated_child.beef {
                            if let Ok(child) = Beef::from_binary(child_beef) {
                                acc.merge_beef(&child);
                            }
                        }
                    }
                }
            }

            Ok(Some(Output {
                beef: Some(acc.to_binary()),
                ..output.clone()
            }))
        })
    }

    // ========================================================================
    // Metadata
    // ========================================================================

    pub async fn list_topic_managers(&self) -> HashMap<String, ServiceMetadata> {
        let mut result = HashMap::new();
        for (name, manager) in &self.managers {
            let meta = manager.get_metadata().await;
            result.insert(name.clone(), meta);
        }
        result
    }

    /// List all registered lookup services with their metadata.
    pub async fn list_lookup_service_providers(&self) -> HashMap<String, ServiceMetadata> {
        let mut result = HashMap::new();
        for (name, service) in &self.lookup_services {
            let meta = service.get_metadata().await;
            result.insert(name.clone(), meta);
        }
        result
    }

    /// Get documentation for a specific topic manager.
    pub async fn get_documentation_for_topic_manager(&self, name: &str) -> String {
        match self.managers.get(name) {
            Some(manager) => manager.get_documentation().await,
            None => "No documentation found!".to_string(),
        }
    }

    /// Get documentation for a specific lookup service.
    pub async fn get_documentation_for_lookup_service(&self, name: &str) -> String {
        match self.lookup_services.get(name) {
            Some(service) => service.get_documentation().await,
            None => "No documentation found!".to_string(),
        }
    }

    // ========================================================================
    // GASP endpoints
    // ========================================================================

    /// Respond to a GASP initial sync request.
    ///
    /// Returns UTXOs for the given topic since the requested score.
    ///
    /// The caller-supplied `limit` is CLAMPED to
    /// [`Engine::SYNC_RESPONSE_MAX_LIMIT`] (and defaulted when absent):
    /// `/requestSyncResponse` is a PUBLIC route, and an absent limit used to
    /// mean an unbounded scan of the outputs table (bsv-low #291). Bounding
    /// is lossless for sync correctness because the initiator
    /// ([`crate::gasp::GASPSync`]) pages for as long as its `since` score
    /// cursor advances — a truncated page is fetched by its NEXT request
    /// within the same run (gate finding M1: pagination must not demand a
    /// full page, which this clamp can make impossible).
    pub async fn provide_foreign_sync_response(
        &self,
        request: &GASPInitialRequest,
        topic: &str,
    ) -> Result<GASPInitialResponse, EngineError> {
        let limit = Self::clamp_sync_limit(request.limit);
        let outputs = self
            .storage
            .find_utxos_for_topic(topic, Some(request.since as f64), Some(limit), false)
            .await
            .map_err(|e| EngineError::StorageError(e.to_string()))?;

        Ok(GASPInitialResponse {
            utxo_list: outputs
                .iter()
                .map(|o| GASPOutput {
                    txid: o.txid.clone(),
                    output_index: o.output_index,
                    score: o.score.unwrap_or(0.0),
                })
                .collect(),
            since: request.since,
        })
    }

    /// Provide a GASPNode for a specific transaction within a graph.
    ///
    /// Searches the BEEF tree of the root output (identified by graphID) for
    /// the requested txid. If not found in the BEEF tree, recurses through
    /// outputsConsumed in storage.
    pub async fn provide_foreign_gasp_node(
        &self,
        graph_id: &str,
        txid: &str,
        output_index: u32,
    ) -> Result<GASPNode, EngineError> {
        let root_outpoint = Outpoint::from_graph_id(graph_id)
            .ok_or_else(|| EngineError::Other(format!("Invalid graphID: {graph_id}")))?;

        let root_output = self
            .storage
            .find_output(
                &root_outpoint.txid,
                root_outpoint.output_index,
                None,
                None,
                true,
            )
            .await
            .map_err(|e| EngineError::StorageError(e.to_string()))?
            .ok_or(EngineError::NodeNotFound)?;

        self.hydrate_gasp_node(&root_output, graph_id, txid, output_index)
            .await
    }

    /// Recursively search a BEEF tree for a specific txid and return a GASPNode.
    fn hydrate_gasp_node<'a>(
        &'a self,
        output: &'a Output,
        graph_id: &'a str,
        txid: &'a str,
        output_index: u32,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<GASPNode, EngineError>> + 'a>>
    {
        Box::pin(async move {
            let beef_data = output.beef.as_ref().ok_or(EngineError::NodeNotFound)?;

            // The stored body's SUBJECT by the same order-independent rule
            // (`subject.rs`) — a plain stored body's last tx can be an ancestor.
            let root = beef_limits::parse_beef(beef_data, &beef_limits::STORED_BEEF_LIMITS)
                .ok()
                .and_then(|mut b| crate::subject::subject_txid_of(&mut b));
            let root_tx = beef_limits::transaction_from_beef(
                beef_data,
                root.as_deref(),
                &beef_limits::STORED_BEEF_LIMITS,
            )
            .map_err(|e| EngineError::BeefParseError(e.to_string()))?;

            // Search the transaction tree for the requested txid
            if let Some(node) = Self::search_tx_tree(&root_tx, graph_id, txid, output_index) {
                return Ok(node);
            }

            // Fallback: try parsing BEEF with the target txid directly
            // (some BEEF structures have the tx in the list but not linked as source_transaction)
            if let Some(node) = Self::search_beef_for_txid(beef_data, graph_id, txid, output_index)
            {
                return Ok(node);
            }

            // Not found in BEEF tree — recurse through outputsConsumed in storage
            for consumed in &output.outputs_consumed {
                if let Ok(Some(consumed_output)) = self
                    .storage
                    .find_output(&consumed.txid, consumed.output_index, None, None, true)
                    .await
                {
                    if let Ok(node) = self
                        .hydrate_gasp_node(&consumed_output, graph_id, txid, output_index)
                        .await
                    {
                        return Ok(node);
                    }
                }
            }

            // The graph root is known but neither its BEEF nor anything it
            // consumed holds the requested transaction. That is a definite
            // "not held", the same answer as an unknown root: the reference
            // throws `Unable to find output associated with your request!`
            // here and its route answers 400. A syncing peer reads the 400 as
            // `GASPError::NodeNotFound` and prunes a decoy input on it (the D8
            // rule, `GASPSync::process_incoming_node`); a 500 would read as a
            // fault of the moment and strand the chain behind the decoy.
            Err(EngineError::NodeNotFound)
        })
    }

    /// Search a Transaction tree (via sourceTransaction links) for a specific txid.
    fn search_tx_tree(
        tx: &Transaction,
        graph_id: &str,
        target_txid: &str,
        output_index: u32,
    ) -> Option<GASPNode> {
        let current_txid = tx.id();

        if current_txid == target_txid {
            let mut node = GASPNode {
                graph_id: graph_id.to_string(),
                raw_tx: tx.to_hex(),
                output_index,
                proof: None,
                tx_metadata: None,
                output_metadata: None,
                inputs: None,
            };
            if let Some(ref merkle_path) = tx.merkle_path {
                node.proof = Some(merkle_path.to_hex());
            }
            return Some(node);
        }

        // Recurse into inputs via source_transaction
        for input in &tx.inputs {
            if let Some(ref source_tx) = input.source_transaction {
                if let Some(node) =
                    Self::search_tx_tree(source_tx, graph_id, target_txid, output_index)
                {
                    return Some(node);
                }
            }
        }

        None
    }

    /// Alternative search: try parsing the BEEF with the target txid directly.
    /// Some BEEF structures may not link source_transaction on inputs but
    /// still contain the transaction in the BEEF's transaction list.
    fn search_beef_for_txid(
        beef_data: &[u8],
        graph_id: &str,
        target_txid: &str,
        output_index: u32,
    ) -> Option<GASPNode> {
        // Try parsing BEEF with the specific txid
        if let Ok(tx) = beef_limits::transaction_from_beef(
            beef_data,
            Some(target_txid),
            &beef_limits::STORED_BEEF_LIMITS,
        ) {
            if tx.id() == target_txid {
                let mut node = GASPNode {
                    graph_id: graph_id.to_string(),
                    raw_tx: tx.to_hex(),
                    output_index,
                    proof: None,
                    tx_metadata: None,
                    output_metadata: None,
                    inputs: None,
                };
                if let Some(ref merkle_path) = tx.merkle_path {
                    node.proof = Some(merkle_path.to_hex());
                }
                return Some(node);
            }
        }
        None
    }

    // ========================================================================
    // Merkle proof handling
    // ========================================================================

    /// Handle a new merkle proof for a transaction.
    ///
    /// When a transaction gets mined, ARC calls back with the merkle proof.
    /// This method:
    /// 1. Finds all outputs for the txid in storage
    /// 2. Parses the BEEF, updates the merkle path in the transaction tree
    /// 3. Serializes updated BEEF back to storage
    /// 4. Recursively updates the consumedBy chain (outputs that spent this one)
    /// 5. Updates blockHeight on the outputs
    pub async fn handle_new_merkle_proof(
        &self,
        txid: &str,
        proof_hex: &str,
        block_height: Option<u32>,
    ) -> Result<(), EngineError> {
        let outputs = self
            .storage
            .find_outputs_for_transaction(txid, true)
            .await
            .map_err(|e| EngineError::StorageError(e.to_string()))?;

        if outputs.is_empty() {
            return Err(EngineError::Other(
                "Could not find matching transaction outputs for proof ingest!".into(),
            ));
        }

        // Parse merkle proof if provided
        let proof = if proof_hex.is_empty() {
            None
        } else {
            Some(
                beef_limits::merkle_path_from_hex(proof_hex, beef_limits::PUSH_PROOF_MAX_BYTES)
                    .map_err(|e| EngineError::Other(format!("Invalid merkle proof hex: {e}")))?,
            )
        };

        for output in &outputs {
            // Stitch the proof into the STORED BEEF (#284) — never rebuild it
            // around a re-picked subject; see stitch_proof_into_stored_beef.
            if let (Some(ref beef_data), Some(ref proof)) = (&output.beef, &proof) {
                if let Some(new_beef) = Self::stitch_proof_into_stored_beef(beef_data, txid, proof)
                {
                    let _ = self
                        .storage
                        .update_transaction_beef(&output.txid, &new_beef)
                        .await;
                }
            }

            // Update block height
            if let Some(height) = block_height {
                let _ = self
                    .storage
                    .update_output_block_height(
                        &output.txid,
                        output.output_index,
                        &output.topic,
                        height,
                    )
                    .await;
            }

            // Recursively update consumedBy chain
            for consuming in &output.consumed_by {
                if let Ok(consumed_outputs) = self
                    .storage
                    .find_outputs_for_transaction(&consuming.txid, true)
                    .await
                {
                    for consumed_output in &consumed_outputs {
                        // The consuming row's BEEF carries this tx as an
                        // ancestor — stitch the same bump in there too, again
                        // without rebuilding the tx set (#284: this branch is
                        // the one that was observed replacing a head-spend's
                        // stored BEEF with parent ancestry only).
                        if let (Some(ref beef_data), Some(ref proof)) =
                            (&consumed_output.beef, &proof)
                        {
                            if let Some(new_beef) =
                                Self::stitch_proof_into_stored_beef(beef_data, txid, proof)
                            {
                                let _ = self
                                    .storage
                                    .update_transaction_beef(&consumed_output.txid, &new_beef)
                                    .await;
                            }
                        }
                    }
                }
            }
        }

        Ok(())
    }

    /// Complete missing merkle proofs for stored, confirmed transactions.
    ///
    /// The `/submit`-admitted ingest path stores a proofless BEEF for each
    /// transaction (the submitter does not yet have a merkle proof at submit
    /// time). When such a transaction later mines, nothing in the overlay
    /// re-fetches its proof, so its stored BEEF stays proofless forever — and a
    /// frontend that trims `inputBEEF` to `{source tx + its BUMP}` for a P2PKH
    /// payment-import spend has no BUMP to trim to, hanging the import (#130).
    ///
    /// This pass closes that gap from chain (the one blessed server-side WoC
    /// use). It:
    /// 1. Pulls a bounded page (`limit`) of stored `(txid, beef)` from storage.
    /// 2. Parses each BEEF and keeps only those whose target tx still lacks a
    ///    merkle proof (`Beef::find_txid(txid).has_proof() == false`).
    /// 3. For each proofless candidate, fetches its BUMP via the configured
    ///    [`AncestorFetcher`](crate::gasp::AncestorFetcher). If a proof comes
    ///    back, it calls [`Self::handle_new_merkle_proof`], which stitches the
    ///    BUMP into the stored BEEF (D1 + R2 mirror), updates output block
    ///    height, and recurses the `consumedBy` chain.
    /// 4. Skips (does NOT error) txs the fetcher can't prove yet (still
    ///    unconfirmed) — those are simply retried on a later tick.
    ///
    /// **No-op when no [`AncestorFetcher`] is configured** — production-safe
    /// default (the same opt-in switch as GASP ancestor hydration). Bounded by
    /// `limit` (a per-tick budget, like the platform fetcher's own budget).
    ///
    /// `min_age_secs` is the PUSH-PRIMARY BACKSTOP gate (bsv-low #228 /
    /// arcade#259): since the Arcade MINED webhook (`/arc-ingest`) pushes a
    /// verified proof ~150 ms after a tx mines, this poll pass is a BACKSTOP,
    /// not the primary source — rows stored less than `min_age_secs` ago are
    /// skipped entirely (their push is still expected). Pass `0` to disable
    /// the gate (poll everything — the pre-#228 behaviour, and the degradation
    /// mode if pushes stop: an old-enough row is ALWAYS polled, so webhook
    /// loss degrades to polling, never to nothing). Unknown-age rows are
    /// always eligible (fail-safe — see the storage-trait doc).
    pub async fn complete_missing_proofs(
        &self,
        limit: u64,
        min_age_secs: u64,
    ) -> Result<ProofCompletionSummary, EngineError> {
        let mut summary = ProofCompletionSummary::default();

        // Production-safe: with no fetcher there is no chain source to complete
        // from, so this is a pure no-op (matches GASP-hydration opt-in).
        let Some(fetcher) = self.ancestor_fetcher.clone() else {
            return Ok(summary);
        };

        let candidates = self
            .storage
            .find_transactions_for_proof_check(limit, min_age_secs)
            .await
            .map_err(|e| EngineError::StorageError(e.to_string()))?;
        summary.scanned = candidates.len();

        for cand in candidates {
            // Read the stored BEEF for the subject's OWN bump by streaming
            // folds (one element in hand, no `Beef` built: NL-6); skip
            // anything unparseable (don't error the whole pass on one bad row).
            let own_bump = match beef_limits::own_proof(&cand.beef, &cand.txid) {
                Ok(b) => b,
                Err(e) => {
                    warn!(txid = %cand.txid, error = %e, "[PROOF COMPLETION] unparseable BEEF, skipping");
                    continue;
                }
            };

            // Already structurally proven? The stored BEEF carries a merkle bump
            // for the target tx, but its backend `has_proof` flag may still be 0
            // — EITHER a legitimate GASP-synced proof written before overlay
            // migration 0010 (which defaulted every existing row to 0), OR an
            // admit-time bump that was NEVER SPV-verified (`/submit` skips SPV on
            // historical topics) or is outright forged. Serve-time BEEF trimming
            // trusts the `has_proof` flag, so latching one on STRUCTURE ALONE
            // would let a forged bump be trimmed on (#192/#193 MEDIUM). Re-verify
            // the STORED bump against chaintracks (via the fetcher — its header
            // source is the only arbiter of a merkle root). Genuine → latch
            // (fast, no re-fetch). Otherwise DON'T trust it: fall through to the
            // fetch+stitch path below, which overwrites the bump with a
            // chaintracks-verified one (or leaves the row proofless for retry).
            // Fail-closed throughout.
            // the tx's OWN bump (its `bump_index`), never `find_bump`
            // (the FIRST bump containing the txid — the stale one after a
            // same-height reorg; review HIGH-1).
            if let Some(bump_hex) = own_bump
                .as_ref()
                .map(bsv_rs::transaction::MerklePath::to_hex)
            {
                if fetcher.verify_proof(&cand.txid, &bump_hex).await {
                    // Idempotent + best-effort: a failure here is logged, not
                    // fatal — the row simply lingers one more tick.
                    // bsv-low M19 R2 round 3 (review MED-2): latch WITH the
                    // anchor height (from the tx's OWN verified bump) so the
                    // revalidation sweep's transactions leg can window this
                    // row — `mark_transaction_proven` alone left every
                    // fast-path row anchorless, in no window forever.
                    let height = bsv_rs::transaction::MerklePath::from_hex(&bump_hex)
                        .ok()
                        .map(|mp| u64::from(mp.block_height));
                    if let Err(e) = self
                        .storage
                        .mark_transaction_proven_at(&cand.txid, height)
                        .await
                    {
                        warn!(txid = %cand.txid, error = %e, "[PROOF COMPLETION] failed to mark verified-proven row");
                    } else {
                        summary.already_proven += 1;
                    }
                    continue;
                }
                warn!(txid = %cand.txid, "[PROOF COMPLETION] stored structural bump FAILED chaintracks re-verify — not trusting it, refetching");
            }
            // Unverifiable structural bump → treat as proofless (fall through).
            summary.proofless += 1;

            // Fetch this tx's own VERIFIED bump from chain — PROOF ONLY (the raw
            // is already in the stored BEEF, so no redundant raw fetch; #192/#193
            // FIX 2). A tx with no verified proof yet (still unconfirmed, or an
            // unverifiable/forged courier response) is skipped, not errored.
            let Some(proof_hex) = fetcher.verified_proof_for(&cand.txid).await else {
                summary.still_unconfirmed += 1;
                continue;
            };

            // Pull the block height out of the BUMP so the output rows update too.
            let block_height =
                beef_limits::merkle_path_from_hex(&proof_hex, beef_limits::COURIER_PROOF_MAX_BYTES)
                    .ok()
                    .map(|mp| mp.block_height);

            match self
                .handle_new_merkle_proof(&cand.txid, &proof_hex, block_height)
                .await
            {
                Ok(()) => summary.completed += 1,
                Err(e) => {
                    warn!(txid = %cand.txid, error = %e, "[PROOF COMPLETION] stitch failed");
                    summary.stitch_failed += 1;
                }
            }
        }

        info!(
            scanned = summary.scanned,
            proofless = summary.proofless,
            completed = summary.completed,
            still_unconfirmed = summary.still_unconfirmed,
            fetch_failed = summary.fetch_failed,
            stitch_failed = summary.stitch_failed,
            already_proven = summary.already_proven,
            "[PROOF COMPLETION] pass complete"
        );

        Ok(summary)
    }

    /// Recursively update merkle paths in a transaction's input tree.
    ///
    /// If the transaction's id matches txid, set its merkle_path.
    /// Otherwise, recurse into sourceTransactions of each input.
    /// Stitch a verified BUMP for `txid` into a STORED BEEF, preserving every
    /// transaction and every other proof in it (#284).
    ///
    /// The old path round-tripped the stored bytes through
    /// `Transaction::from_beef(bytes, None)` -> `to_beef(true)`, and
    /// `from_beef(_, None)` picks **`txs.last()`** — it ignores the atomic
    /// subject pointer entirely. Whenever the subject was not the last tx in
    /// wire order, a PARENT was picked, `to_beef(true)` then serialized that
    /// parent's world, and the rewrite dropped the subject transaction from its
    /// own stored BEEF — observed live on every pf head-spend (list / reprice /
    /// delist / buy) the moment it mined, breaking the NEXT spend on that name
    /// (zanaadu#284). `update_input_proofs`' "already has a proof — update it"
    /// arm could even stamp the child's bump onto that mis-picked parent.
    /// This is the same destroy-the-stored-BEEF class the #4 fix note above
    /// (`hydrate_utxo_history`) already documents for lookup hydration.
    ///
    /// Operating on [`Beef`] directly has none of those failure modes:
    /// `merge_bump` dedupes against existing bumps by (height, root) and
    /// assigns the bump ONLY to transactions that appear as flagged txid
    /// leaves, so stitching tx X's proof can never mislabel tx Y, and the tx
    /// set is never rebuilt at all.
    ///
    /// Returns `None` when the bytes do not parse or `txid` is not in this
    /// BEEF (nothing to stitch — e.g. a consuming row whose ancestry got
    /// trimmed), so callers skip the write instead of writing garbage.
    ///
    /// bsv-low M19 R2 round 3 (review HIGH-1): a same-height DIFFERENT-root
    /// proof (the 2026-09-07 reorg shape) does NOT combine in `merge_bump`
    /// (the roots differ) — it is pushed as a SECOND bump, and
    /// `update_bump_indices` assigns it only to txs whose `bump_index` is
    /// `None`, so the reorged subject keeps its index on the STALE bump.
    /// Left alone, `has_proof`/`proofHeight` and every `find_txid(txid)
    /// .bump_index()` reader then keep pointing at the orphan bump, and the
    /// row refutes again next sweep pass forever. So after the merge, FORCE
    /// the subject onto the bump that actually proves it, then drop any bump
    /// no transaction references (the orphan's, now unreferenced).
    pub fn stitch_proof_into_stored_beef(
        stored: &[u8],
        txid: &str,
        proof: &bsv_rs::transaction::MerklePath,
    ) -> Option<Vec<u8>> {
        let mut beef = beef_limits::parse_beef(stored, &beef_limits::STORED_BEEF_LIMITS).ok()?;
        beef.find_txid(txid)?;
        let i = beef.merge_bump(proof.clone());
        // Does the merged bump actually prove `txid` (a flagged txid leaf)?
        // (It always does for a completion proof; the guard keeps a stray
        // caller from mis-anchoring a subject onto an ancestor's bump.)
        let proves_subject = beef.bumps.get(i).is_some_and(|b| {
            b.path.first().is_some_and(|leaves| {
                leaves
                    .iter()
                    .any(|l| l.txid && l.hash.as_deref() == Some(txid))
            })
        });
        if proves_subject {
            if let Some(tx) = beef.find_txid_mut(txid) {
                tx.set_bump_index(Some(i));
            }
        }
        Self::gc_unreferenced_bumps(&mut beef);
        Some(beef.to_binary())
    }

    /// Drop every BUMP no transaction references and re-index the survivors
    /// (bsv-low M19 R2 round 3, review HIGH-1): after the subject is moved
    /// off an orphan bump, that bump is usually dead weight the next reader
    /// would still `find_bump`. A bump still referenced by ANOTHER tx (a
    /// sibling mined in the same block) is kept.
    fn gc_unreferenced_bumps(beef: &mut bsv_rs::transaction::Beef) {
        let referenced: std::collections::HashSet<usize> = beef
            .txs
            .iter()
            .filter_map(bsv_rs::transaction::BeefTx::bump_index)
            .collect();
        if referenced.len() == beef.bumps.len() {
            return;
        }
        let mut remap: Vec<Option<usize>> = vec![None; beef.bumps.len()];
        let mut kept = Vec::with_capacity(referenced.len());
        for (old, bump) in std::mem::take(&mut beef.bumps).into_iter().enumerate() {
            if referenced.contains(&old) {
                remap[old] = Some(kept.len());
                kept.push(bump);
            }
        }
        beef.bumps = kept;
        for tx in &mut beef.txs {
            if let Some(old) = tx.bump_index() {
                tx.set_bump_index(remap[old]);
            }
        }
    }

    // ========================================================================
    // Advertisement sync
    // ========================================================================

    /// Sync SHIP/SLAP advertisements with configured managers and services.
    ///
    /// Creates missing advertisements and revokes stale ones. Returns a
    /// [`SyncAdvertisementsReport`] so a create/submit failure is VISIBLE to
    /// the caller (bsv-low #320 defect 3a): this method used to swallow both
    /// into `error!` and return `Ok(())`, so `/admin/syncAdvertisements`
    /// reported `success` while zero advertisements were admitted locally —
    /// a caller could not tell a converged no-op from a silent failure, and
    /// every cycle re-created the full ad set.
    pub async fn sync_advertisements(&self) -> Result<SyncAdvertisementsReport, EngineError> {
        let mut report = SyncAdvertisementsReport::default();

        let Some(advertiser) = &self.advertiser else {
            return Ok(report); // No advertiser configured
        };

        let hosting_url = match &self.config.hosting_url {
            Some(url) if !url.is_empty() => url.clone(),
            _ => return Ok(report), // No hosting URL
        };

        // Get configured topics and services
        let mut configured_topics: Vec<String> = self.managers.keys().cloned().collect();
        let mut configured_services: Vec<String> = self.lookup_services.keys().cloned().collect();

        if self.config.suppress_default_sync_advertisements {
            configured_topics.retain(|t| t != "tm_ship" && t != "tm_slap");
            configured_services.retain(|s| s != "ls_ship" && s != "ls_slap");
        }

        // Fetch current advertisements. A read failure REFUSES creation
        // (#320 M2): swallowing it into "current ads = none" made a
        // transient D1/storage fault re-create — and re-pay for — the
        // entire advertisement set, reported as a legitimate `to_create`.
        let current_ship = match advertiser.find_all_advertisements(Protocol::Ship).await {
            Ok(ads) => ads,
            Err(e) => {
                error!("Failed to read current SHIP advertisements — refusing to create: {e}");
                report.lookup_error = Some(format!("ship: {e}"));
                return Ok(report);
            }
        };
        let current_slap = match advertiser.find_all_advertisements(Protocol::Slap).await {
            Ok(ads) => ads,
            Err(e) => {
                error!("Failed to read current SLAP advertisements — refusing to create: {e}");
                report.lookup_error = Some(format!("slap: {e}"));
                return Ok(report);
            }
        };

        // Determine what to create
        let ships_to_create: Vec<AdvertisementData> = configured_topics
            .iter()
            .filter(|topic| {
                !current_ship
                    .iter()
                    .any(|a| a.topic_or_service == **topic && a.domain == hosting_url)
            })
            .map(|topic| AdvertisementData {
                protocol: Protocol::Ship,
                topic_or_service_name: topic.clone(),
            })
            .collect();

        let slaps_to_create: Vec<AdvertisementData> = configured_services
            .iter()
            .filter(|service| {
                !current_slap
                    .iter()
                    .any(|a| a.topic_or_service == **service && a.domain == hosting_url)
            })
            .map(|service| AdvertisementData {
                protocol: Protocol::Slap,
                topic_or_service_name: service.clone(),
            })
            .collect();

        // Determine what to revoke
        let ships_to_revoke: Vec<Advertisement> = current_ship
            .into_iter()
            .filter(|a| !configured_topics.contains(&a.topic_or_service))
            .collect();

        let slaps_to_revoke: Vec<Advertisement> = current_slap
            .into_iter()
            .filter(|a| !configured_services.contains(&a.topic_or_service))
            .collect();

        // Create new advertisements
        let mut all_to_create = ships_to_create;
        all_to_create.extend(slaps_to_create);
        report.to_create = all_to_create.len();
        if !all_to_create.is_empty() {
            match advertiser.create_advertisements(&all_to_create).await {
                Ok(tagged_beef) => match self.submit(&tagged_beef, SubmitMode::CurrentTx).await {
                    Ok(steak) => {
                        for (topic, instructions) in &steak {
                            report
                                .admitted
                                .insert(topic.clone(), instructions.outputs_to_admit.len());
                        }
                    }
                    Err(e) => {
                        error!("Failed to submit new advertisements: {e}");
                        report.submit_error = Some(e.to_string());
                    }
                },
                Err(e) => {
                    error!("Failed to create advertisements: {e}");
                    report.create_error = Some(e.to_string());
                }
            }
        }

        // Revoke stale advertisements
        let mut all_to_revoke = ships_to_revoke;
        all_to_revoke.extend(slaps_to_revoke);
        report.to_revoke = all_to_revoke.len();
        if !all_to_revoke.is_empty() {
            match advertiser.revoke_advertisements(&all_to_revoke).await {
                // An advertiser that declines to build a revocation (e.g. the
                // CF advertiser's documented v1 no-op) returns an EMPTY
                // TaggedBEEF — submitting it would only manufacture a parse
                // error. Skip, but say so in the report (#320 L2): the stale
                // ads stay on-chain until they age out.
                Ok(tagged_beef) if tagged_beef.topics.is_empty() => {
                    report.revoke_skipped = all_to_revoke.len();
                }
                Ok(tagged_beef) => {
                    if let Err(e) = self.submit(&tagged_beef, SubmitMode::CurrentTx).await {
                        error!("Failed to submit revocation: {e}");
                        report.revoke_submit_error = Some(e.to_string());
                    }
                }
                Err(e) => {
                    error!("Failed to revoke advertisements: {e}");
                    report.revoke_error = Some(e.to_string());
                }
            }
        }

        Ok(report)
    }

    // ========================================================================
    // Deep deletion
    // ========================================================================

    /// Recursively delete a UTXO and all stale consumed inputs.
    ///
    /// Only deletes if the output has no remaining consumers (consumedBy is empty).
    /// Then recurses into outputsConsumed, removing the deleted output from their
    /// consumedBy lists and deleting them if they become unreferenced.
    #[allow(dead_code)] // Used by submit() once BEEF parsing is wired up
    ///
    /// `bound` is a finalize submit's [`CallBound`] over each call here
    /// (bsv-low #559); `None` everywhere else.
    fn delete_utxo_deep<'a>(
        &'a self,
        output: &'a Output,
        bound: Option<&'a CallBound>,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), EngineError>> + 'a>> {
        Box::pin(async move {
            // Only delete if nothing consumes this output
            if output.consumed_by.is_empty() {
                stored(
                    bound,
                    self.storage
                        .delete_output(&output.txid, output.output_index, &output.topic),
                )
                .await
                .map_err(|e| EngineError::StorageError(e.to_string()))?;

                // Notify lookup services. A hook error is dropped, not
                // reported (parity: the reference catches it, best effort).
                for ls in self.lookup_services.values() {
                    let _ = hooked(
                        bound,
                        ls.output_no_longer_retained_in_history(
                            &output.txid,
                            output.output_index,
                            &output.topic,
                        ),
                    )
                    .await;
                }
            }

            // Recurse into consumed outputs
            for consumed in &output.outputs_consumed {
                if let Ok(Some(mut stale_output)) = stored(
                    bound,
                    self.storage.find_output(
                        &consumed.txid,
                        consumed.output_index,
                        Some(&output.topic),
                        None,
                        false,
                    ),
                )
                .await
                {
                    // Remove the deleted output from consumedBy
                    stale_output.consumed_by.retain(|c| {
                        !(c.txid == output.txid && c.output_index == output.output_index)
                    });

                    stored(
                        bound,
                        self.storage.update_consumed_by(
                            &consumed.txid,
                            consumed.output_index,
                            &output.topic,
                            &stale_output.consumed_by,
                        ),
                    )
                    .await
                    .map_err(|e| EngineError::StorageError(e.to_string()))?;

                    // Recurse
                    let _ = self.delete_utxo_deep(&stale_output, bound).await;
                }
            }

            Ok(())
        }) // Box::pin
    }

    // ========================================================================
    // Eviction
    // ========================================================================

    /// Evict a specific outpoint from the overlay.
    ///
    /// 1. Deletes the output from storage for the given topic.
    /// 2. Notifies all lookup services via `output_evicted()`.
    ///
    /// If no topic is specified, finds all outputs for the txid and evicts the
    /// matching outputIndex across every topic.
    ///
    /// Matches TS OverlayExpress `/admin/evictOutpoint` (lines 974-1004).
    /// bsv-low PLAN-PRE-LOOP4 §H4 (2026-09-06): RE-NOTIFY every lookup service
    /// of the outputs the engine ALREADY admitted for (`txid`, `topic`).
    ///
    /// Phase-1 dedup means a (txid, topic) once recorded in
    /// `applied_transactions` never re-enters through `/submit`, so a lookup
    /// service that missed — or mis-parsed — its admit notification could
    /// never be told again (the loop-2 subject trap: the pot index's admit
    /// hook shape-checked a wire-last hop and wrote no record while the engine
    /// had admitted the pot). This replays `output_admitted_by_topic` from the
    /// engine's OWN stored outputs (with their BEEF) and the subject-NAMED body
    /// exactly as `submit_with_report` sends it. It validates nothing anew
    /// (the topic manager judged these outputs at admit), writes none of the
    /// engine's tables, and is idempotent for every lookup service whose
    /// writes are (the pot index's `store_record` is insert-if-absent for the
    /// spend fields — re-admission never regresses spend state).
    /// `outputs == 0` means the engine never admitted this txid on this topic:
    /// nothing to re-notify — the caller re-SUBMITS instead.
    pub async fn renotify_admitted(
        &self,
        txid: &str,
        topic: &str,
    ) -> Result<RenotifyReport, EngineError> {
        let txid = txid.to_ascii_lowercase();
        let outputs = self
            .storage
            .find_outputs_for_transaction(&txid, true)
            .await
            .map_err(|e| EngineError::StorageError(e.to_string()))?;
        let mut report = RenotifyReport::default();
        for output in outputs.iter().filter(|o| o.topic == topic) {
            report.outputs += 1;
            report.vouts.push(output.output_index);
            // the body every WholeTx service receives NAMES the subject (BRC-95
            // atomic prefix) — the same rule as the live submit path
            let subject_named: Option<Vec<u8>> = output.beef.as_ref().map(|beef| {
                beef_limits::parse_beef(beef, &beef_limits::STORED_BEEF_LIMITS)
                    .ok()
                    .and_then(|mut b| b.to_binary_atomic(&txid).ok())
                    .unwrap_or_else(|| beef.clone())
            });
            for (name, ls) in &self.lookup_services {
                let payload = match ls.admission_mode() {
                    AdmissionMode::LockingScript => OutputAdmittedByTopic::LockingScript {
                        txid: txid.clone(),
                        output_index: output.output_index,
                        topic: topic.to_string(),
                        satoshis: output.satoshis,
                        locking_script: output.output_script.clone(),
                        off_chain_values: None,
                    },
                    AdmissionMode::WholeTx => {
                        let Some(atomic_beef) = subject_named.as_ref() else {
                            report.faults.push(format!(
                                "{name}: {txid}:{} is stored without its BEEF — a WholeTx service cannot be re-notified",
                                output.output_index
                            ));
                            continue;
                        };
                        OutputAdmittedByTopic::WholeTx {
                            atomic_beef: atomic_beef.clone(),
                            output_index: output.output_index,
                            topic: topic.to_string(),
                            off_chain_values: None,
                        }
                    }
                };
                match ls.output_admitted_by_topic(&payload).await {
                    Ok(()) => report.notified += 1,
                    Err(e) => report.faults.push(format!("{name}: {e}")),
                }
            }
        }
        Ok(report)
    }

    /// bsv-low PLAN-PRE-LOOP4 §H4 (2026-09-06): FORGET a PHANTOM applied row —
    /// (txid, topic) recorded in `applied_transactions` while the topic holds
    /// NO output of that txid (the engine judged the tx and admitted nothing:
    /// the loop-2 JOIN `f9e85aab…` under the pre-D5 subject rule). Such a row
    /// does nothing but block a correct re-submit through the Phase-1 dedup
    /// (`/admin/readmit` on beta answered `deduped: ["tm_pot_beta"]` and the
    /// pot stayed `known:false`). A row with ANY stored output on the topic is
    /// a real admission and is never touched (returns false, as does a missing
    /// row). The forgotten bytes are then re-VALIDATED by the topic manager
    /// like any first submit — nothing is admitted here.
    pub async fn forget_phantom_applied(
        &self,
        txid: &str,
        topic: &str,
    ) -> Result<bool, EngineError> {
        let txid = txid.to_ascii_lowercase();
        let outputs = self
            .storage
            .find_outputs_for_transaction(&txid, false)
            .await
            .map_err(|e| EngineError::StorageError(e.to_string()))?;
        if outputs.iter().any(|o| o.topic == topic) {
            return Ok(false);
        }
        let rec = AppliedTransaction {
            txid: txid.clone(),
            topic: topic.to_string(),
        };
        let exists = self
            .storage
            .does_applied_transaction_exist(&rec)
            .await
            .map_err(|e| EngineError::StorageError(e.to_string()))?;
        if !exists {
            return Ok(false);
        }
        self.storage
            .delete_applied_transaction(&rec)
            .await
            .map_err(|e| EngineError::StorageError(e.to_string()))?;
        Ok(true)
    }

    pub async fn evict_output(
        &self,
        txid: &str,
        output_index: u32,
        topic: Option<&str>,
    ) -> Result<(), EngineError> {
        if let Some(topic) = topic {
            // Delete from storage
            self.storage
                .delete_output(txid, output_index, topic)
                .await
                .map_err(|e| EngineError::StorageError(e.to_string()))?;

            // Notify all lookup services
            for ls in self.lookup_services.values() {
                let _ = ls.output_evicted(txid, output_index).await;
            }
        } else {
            // No topic specified — find all outputs for this txid and evict matching ones
            let outputs = self
                .storage
                .find_outputs_for_transaction(txid, false)
                .await
                .map_err(|e| EngineError::StorageError(e.to_string()))?;

            for output in &outputs {
                if output.output_index == output_index {
                    self.storage
                        .delete_output(txid, output_index, &output.topic)
                        .await
                        .map_err(|e| EngineError::StorageError(e.to_string()))?;
                }
            }

            // Notify all lookup services once
            for ls in self.lookup_services.values() {
                let _ = ls.output_evicted(txid, output_index).await;
            }
        }

        Ok(())
    }

    // ========================================================================
    // GASP sync
    // ========================================================================

    /// Start GASP synchronization with peers for all configured topics.
    ///
    /// For each topic in `sync_configuration`:
    /// - `SyncTarget::Ship`: unions local SHIP records, network discovery via
    ///   configured SLAP trackers, and the topic's bootstrap peers.
    /// - `SyncTarget::Peers(urls)` — uses the provided peer URLs directly.
    /// - `SyncTarget::Disabled` — skips the topic.
    ///
    /// Filters out our own `hosting_url` to avoid self-sync.
    ///
    /// Returns a `GASPSyncResult` summarizing discovered peers per topic.
    ///
    /// Discovers peers for each configured topic and runs GASP sync with each.
    ///
    /// When a `GASPRemoteFactory` is set (via `set_gasp_remote_factory`), this
    /// method creates `OverlayGASPStorage` + `GASPRemote` instances per
    /// (topic, peer) pair and runs `GASPSync::sync()` to exchange UTXOs.
    ///
    /// Without a factory, peer discovery still runs but no actual sync occurs
    /// (backwards-compatible with the previous discovery-only behavior).
    pub async fn start_gasp_sync(&self) -> Result<GASPSyncResult, EngineError> {
        use crate::gasp::{GASPSync, ENGINE_GASP_SYNC_PAGE_LIMIT};
        use crate::gasp_overlay::OverlayGASPStorage;

        if self.config.sync_configuration.is_empty() {
            info!("[GASP SYNC] No sync configuration — nothing to sync");
            return Ok(GASPSyncResult {
                topics_synced: HashMap::new(),
            });
        }

        let mut topics_synced: HashMap<String, TopicSyncResult> = HashMap::new();
        // Resolve SLAP providers once per invocation, sharing their host cap
        // across all SHIP topics. Every topic still queries each lookup host.
        let mut ship_lookup_hosts = None;
        let mut topic_order = sync_order(&self.config.sync_configuration);
        // Explicit bootstrap-backed SHIP topics run ahead of large tracker
        // imports. Stable sorting preserves the existing order elsewhere.
        topic_order.sort_by_key(|(topic, target)| {
            !(matches!(target, SyncTarget::Ship)
                && self
                    .ship_bootstrap_peers
                    .get(topic.as_str())
                    .is_some_and(|peers| !peers.is_empty()))
        });

        for (topic, target) in topic_order {
            // A CONFIGURED topic's peers are reserved part of a storage's
            // deferred-graph ceiling (bsv-low #555, the delta-2 fold's D2-M2).
            let configured_peers = matches!(target, SyncTarget::Peers(_));
            let (peers, sync_type) = match target {
                SyncTarget::Disabled => {
                    info!("[GASP SYNC] Topic {topic} is disabled — skipping");
                    continue;
                }
                SyncTarget::Ship => {
                    info!("[GASP SYNC] Topic {topic} configured for SHIP discovery");
                    let peers = self
                        .discover_ship_peers(topic, &mut ship_lookup_hosts)
                        .await;
                    info!(
                        "[GASP SYNC] Discovered {} peer(s) for topic {topic}",
                        peers.len()
                    );
                    (peers, "ship".to_string())
                }
                SyncTarget::Peers(peer_urls) => {
                    info!(
                        "[GASP SYNC] Topic {topic} configured with {} hardcoded peer(s)",
                        peer_urls.len()
                    );
                    let peers: Vec<String> = peer_urls
                        .iter()
                        .filter(|url| {
                            if let Some(ref our_url) = self.config.hosting_url {
                                url.trim_end_matches('/') != our_url.trim_end_matches('/')
                            } else {
                                true
                            }
                        })
                        .cloned()
                        .collect();

                    info!(
                        "[GASP SYNC] {} peer(s) for topic {topic} after self-filtering",
                        peers.len()
                    );
                    (peers, "peers".to_string())
                }
            };

            let mut errors = Vec::new();
            let mut pruned_inputs: u64 = 0;
            let mut discarded_graphs: u64 = 0;
            let mut expired_refused: u64 = 0;
            let expired = std::rc::Rc::default();
            let mut anchor_walk_held_graphs: u64 = 0;
            let mut finalized_graphs: u64 = 0;
            let mut deadline_dropped_graphs: u64 = 0;
            let mut cursor_moves: Vec<CursorMove> = Vec::new();
            let mut deferred_graphs: u64 = 0;
            let mut resumed_graphs: u64 = 0;
            let mut converged_graphs: u64 = 0;
            let mut dropped_graphs: Vec<DroppedDeferral> = Vec::new();
            let mut stalled_graphs: u64 = 0;
            let mut held_back_graphs: u64 = 0;

            // If we have a remote factory, actually run GASP sync
            if let Some(ref factory) = self.gasp_remote_factory {
                for peer_url in &peers {
                    // bsv-low#302 quarantine gate: a peer at
                    // PEER_QUARANTINE_THRESHOLD consecutive failures is
                    // SKIPPED (no attempt recorded — its last-attempt age
                    // keeps growing) until the re-probe window opens. A
                    // health-read FAULT treats the peer as healthy: broken
                    // bookkeeping must never silence a live peer.
                    //
                    // The peer's health (its quarantine, its yieldless
                    // streak) is keyed on its NORMALIZED ORIGIN (bsv-low
                    // #555, the delta-2 fold's D2-M2): keyed on the URL, one
                    // server was a fresh peer for every spelling it
                    // advertised.
                    let health_key = crate::gasp::peer_origin(peer_url);
                    let health = self
                        .storage
                        .get_peer_sync_health(&health_key, topic)
                        .await
                        .unwrap_or_default();
                    if crate::gasp::peer_sync_quarantined(&health) {
                        warn!(
                            "[GASP SYNC] Peer {peer_url} for {topic} QUARANTINED ({} consecutive failed syncs, last attempt {:?}s ago) — skipped until the {}s re-probe window (bsv-low#302)",
                            health.consecutive_failures,
                            health.secs_since_last_attempt,
                            crate::gasp::PEER_QUARANTINE_REPROBE_SECS
                        );
                        continue;
                    }

                    info!("[GASP SYNC] Syncing topic {topic} with peer {peer_url}");

                    // Get last interaction score for this (peer, topic) pair
                    let last_interaction = self
                        .storage
                        .get_last_interaction(peer_url, topic)
                        .await
                        .unwrap_or(0);

                    // Create shared sink for finalized graphs
                    let sink = crate::gasp_overlay::new_finalized_graph_sink();

                    // OPT-IN ancestor hydration: only when a fetcher is
                    // configured do we enable chain-backed ancestor fallback +
                    // strict-BEEF finalize. Default (None) = byte-identical to
                    // today (tolerant BEEF, peer errors abandon the graph;
                    // the one exception is the D8 prune of a manager-named
                    // input the peer answers it does not hold, which exists
                    // only WITHOUT a fetcher, see
                    // `GASPSync::process_incoming_node`).
                    let sync_fetcher = self
                        .gasp_ancestor_fetcher
                        .as_ref()
                        .or(self.ancestor_fetcher.as_ref());
                    let hydration_on = sync_fetcher.is_some();

                    // Create storage adapter and remote
                    let mut gasp_storage =
                        OverlayGASPStorage::new(self.storage.as_ref(), topic, sink.clone())
                            .with_peer(peer_url.as_str())
                            .with_configured_peer(configured_peers)
                            .with_strict_beef(hydration_on)
                            .with_script_verification(self.verify_scripts)
                            .with_walk_budget(self.walk_budget);
                    if let Some(manager) = self.managers.get(topic) {
                        gasp_storage = gasp_storage.with_topic_manager(manager.as_ref());
                    }
                    // bsv-low #551: the anchor check verifies each graph's
                    // root against THIS engine's tracker, with this engine's
                    // script switch, before finalize. No tracker is the
                    // reference's 'scripts only'.
                    if let Some(tracker) = self.chain_tracker.as_deref() {
                        gasp_storage = gasp_storage.with_chain_tracker(tracker);
                    }
                    let gasp_remote = factory.create_remote(peer_url, topic);

                    let log_prefix = format!("[GASP {topic} <-> {peer_url}]");
                    // Graphs of this peer handed to submit (bsv-low #552).
                    let peer_finalized = std::cell::Cell::new(0u64);
                    let mut sync = GASPSync::new(
                        Box::new(gasp_storage),
                        gasp_remote,
                        last_interaction,
                        &log_prefix,
                        true, // unidirectional — overlay GASP is pull-only (submitNode throws); matches TS Engine.startGASPSync
                    )
                    .with_ancestor_fetcher(sync_fetcher.cloned())
                    .with_expired_outpoints(std::rc::Rc::clone(&expired));
                    // bsv-low #555: a graph past its own budget is deferred,
                    // not dropped with the sync.
                    if let Some((sleep, max_calls, budget_ms)) = &self.graph_budget {
                        let (sleep, budget_ms) = (sleep.clone(), *budget_ms);
                        let half_sleep = sleep.clone();
                        sync = sync.with_graph_budget(crate::gasp::GraphBudget {
                            max_calls: *max_calls,
                            max_bytes_fetched: self.graph_budget_limbs.0,
                            max_nodes: self.graph_budget_limbs.1,
                            deadline: Box::new(move || sleep(budget_ms)),
                            half_deadline: Some(Box::new(move || half_sleep(budget_ms / 2))),
                        });
                    }
                    // bsv-low #552: under a budget each graph is submitted as
                    // it finalizes, so the deadline cannot take it back. With
                    // no budget nothing can drop the sync, and the graphs are
                    // submitted after it as they always were.
                    if self.peer_sync_budget.is_some() {
                        sync = sync.with_finalized_graph_hook(Box::new(SubmitAsFinalized {
                            engine: self,
                            sink: sink.clone(),
                            peer_url,
                            topic,
                            submitted: &peer_finalized,
                        }));
                    }

                    // bsv-low#302: bound THIS peer's sync to the configured
                    // budget. `None` from the race = the budget won and the
                    // sync future was dropped mid-flight. What it finalized
                    // before that is already submitted (the hook above); the
                    // cursor then advances to `completed_cursor` only, see
                    // the deadline arm below. The race is GUARDED: it never
                    // drops the sync inside one transaction's finalize
                    // submit (the lens fold's HIGH-1), it waits for that
                    // transaction and the hook stops at the boundary.
                    let sync_outcome = match &self.peer_sync_budget {
                        Some((sleep, budget_ms)) => {
                            crate::gasp::race_or_deadline_guarded(
                                sync.sync(Some(ENGINE_GASP_SYNC_PAGE_LIMIT)),
                                sleep(*budget_ms),
                                &self.finalize_gate,
                            )
                            .await
                        }
                        None => Some(sync.sync(Some(ENGINE_GASP_SYNC_PAGE_LIMIT)).await),
                    };

                    let mut outcome_success = matches!(sync_outcome, Some(Ok(())));
                    // D8 decoy rule: branches pruned in this peer's walk. Not
                    // an error and not a failed UTXO, so it is counted apart
                    // from `errors` and never touches the outcome or cursor.
                    // Summed over peers: one decoy seen through two peers
                    // counts twice.
                    pruned_inputs += sync.pruned_inputs();
                    expired_refused += sync.expired_refused();
                    // bsv-low #551: graphs the anchor check refused. Counted
                    // apart from `errors` for the same reason as a prune: a
                    // refused graph is not a failed sync (the reference
                    // discards it and carries on).
                    discarded_graphs += sync.discarded_graphs();
                    anchor_walk_held_graphs += sync.anchor_walk_held();
                    // Whether the sync ran (to its end, or to the deadline)
                    // and whether it moved the cursor (bsv-low #555, the
                    // delta fold's D-M2).
                    let ran = !matches!(sync_outcome, Some(Err(_)));
                    let mut advanced_cursor = false;
                    match sync_outcome {
                        None => {
                            let budget_ms = self.peer_sync_budget.as_ref().map_or(0, |(_, ms)| *ms);
                            let msg = format!(
                                "{peer_url}: per-peer sync budget of {budget_ms} ms EXCEEDED — dropped (bsv-low#302)"
                            );
                            warn!("[GASP SYNC] {msg}");
                            errors.push(msg);

                            // bsv-low #552: the work COMPLETED before the
                            // deadline is kept. Its graphs are already
                            // submitted (the hook); the cursor moves past the
                            // UTXOs that were completed and stops below the
                            // one in flight, whose graph is lost whole and
                            // walked again next tick. A graph the deadline
                            // met while it was being SUBMITTED is not "in
                            // flight" here: it left a prefix of whole
                            // transactions, is counted finalized, and its
                            // UTXO is below the cursor too.
                            let in_flight = u64::from(sync.graph_in_flight());
                            deadline_dropped_graphs += in_flight;
                            // bsv-low #555: the walk in hand is saved, so the
                            // next tick resumes it instead of walking it again.
                            sync.defer_in_flight().await;
                            let completed = sync.completed_cursor();
                            if completed > last_interaction {
                                match self
                                    .storage
                                    .update_last_interaction(peer_url, topic, completed)
                                    .await
                                {
                                    Ok(()) => cursor_moves.push(CursorMove {
                                        peer: peer_url.clone(),
                                        from: last_interaction,
                                        to: completed,
                                    }),
                                    Err(e) => warn!(
                                        "[GASP SYNC] Failed to update last_interaction for {peer_url}/{topic}: {e}"
                                    ),
                                }
                            }
                            // A tick that finalized a graph or moved the
                            // cursor reached a live peer: not a failed
                            // attempt for the quarantine count. So did one
                            // whose walk PROGRESSED (bsv-low #555: it
                            // appended a node, or completed its graph). A
                            // deferral that fetched nothing is no progress
                            // (the lens fold's H1: a hung peer deferred with
                            // 0 nodes on every tick and was never
                            // quarantined).
                            advanced_cursor = completed > last_interaction;
                            outcome_success = peer_finalized.get() > 0
                                || completed > last_interaction
                                || sync.deferral_stats().progressed > 0;
                            warn!(
                                "[GASP SYNC] {peer_url} for {topic} at the deadline: finalized_graphs={} deadline_dropped_graphs={in_flight} cursor {last_interaction} -> {} (bsv-low #552)",
                                peer_finalized.get(),
                                completed.max(last_interaction)
                            );
                        }
                        Some(Ok(())) => {
                            // Submit finalized graphs to the Engine (under a
                            // budget the hook already did, graph by graph,
                            // and the sink is empty here).
                            let landed = self
                                .submit_finalized_graphs(&sink, peer_url, topic, &peer_finalized)
                                .await;
                            // bsv-low #555, the lens fold's H1: a sync that
                            // ran to its end with walks the per-graph budget
                            // cut having FETCHED NOTHING, and nothing else
                            // got done (no walk progressed, no graph
                            // finalized, the cursor did not move), reached
                            // a peer that does not answer: a FAILED attempt.
                            // Before #555 such a peer held the sync to the
                            // per-peer deadline, a failure; the per-graph
                            // budget had made it an `Ok` sync. A sync whose
                            // UTXOs failed in any other way is unchanged.
                            let stats = sync.deferral_stats();
                            if stats.stalled > 0
                                && stats.progressed == 0
                                && peer_finalized.get() == 0
                                && !(landed && sync.last_interaction > last_interaction)
                            {
                                outcome_success = false;
                                let msg = format!(
                                    "{peer_url}: {} graph walk(s) cut by the per-graph budget with nothing fetched (bsv-low #555)",
                                    stats.stalled
                                );
                                warn!("[GASP SYNC] {msg}");
                                errors.push(msg);
                            }

                            // Advance the persisted cursor when it moved forward — i.e.
                            // the peer reported UTXOs at a higher score than our last
                            // `since` (the in-memory cursor only grows on SEEN scores,
                            // so `>` already excludes the empty-bootstrap case where no
                            // UTXOs were seen). Mirrors TS `if (gasp.lastInteraction >
                            // lastInteraction)` — NOT gated on a new submission: a sync
                            // that re-sees already-known UTXOs must still advance, else
                            // every cron re-scans the same range forever (the cursor
                            // stayed pinned at 0 in prod).
                            //
                            // NOT advanced when a finalize submit above did
                            // not land (the lens fold's MEDIUM-1): the sink
                            // does not say which UTXO that graph was, so the
                            // whole cursor stays and the next sync is served
                            // the range again (what did land is known and
                            // skipped). Under a budget the hook fails that
                            // one UTXO instead and the gap guard has already
                            // capped `sync.last_interaction` below it.
                            advanced_cursor = landed && sync.last_interaction > last_interaction;
                            if !landed {
                                warn!(
                                    "[GASP SYNC] a finalize submit for {topic} from {peer_url} did not land: the cursor stays at {last_interaction}"
                                );
                            } else if sync.last_interaction > last_interaction {
                                match self
                                    .storage
                                    .update_last_interaction(peer_url, topic, sync.last_interaction)
                                    .await
                                {
                                    Ok(()) => cursor_moves.push(CursorMove {
                                        peer: peer_url.clone(),
                                        from: last_interaction,
                                        to: sync.last_interaction,
                                    }),
                                    Err(e) => warn!(
                                        "[GASP SYNC] Failed to update last_interaction for {peer_url}/{topic}: {e}"
                                    ),
                                }
                            }
                            info!(
                                "[GASP SYNC] Sync with {peer_url} for {topic} completed (last_interaction={})",
                                sync.last_interaction
                            );
                        }
                        Some(Err(e)) => {
                            let msg = format!("{peer_url}: {e}");
                            warn!("[GASP SYNC] Sync failed: {msg}");
                            errors.push(msg);
                        }
                    }
                    // bsv-low #555, the delta fold's D-M2: "progress" (a node
                    // appended) is the peer's word. A sync the peer served
                    // work that finalized no graph and moved no cursor is
                    // YIELDLESS; past PEER_YIELDLESS_SYNCS_ALLOWED of them in
                    // a row each is a FAILED attempt, so a peer that serves
                    // one fresh root a tick and hangs on its input is
                    // quarantined. A quiet sync (nothing served) leaves the
                    // count; a fault of the count is fail-safe (no failure).
                    // Only with a per-graph budget: without one nothing is
                    // deferred and #302's rule is unchanged.
                    if ran && self.graph_budget.is_some() {
                        let yielded = peer_finalized.get() > 0 || advanced_cursor;
                        if yielded || sync.graphs_attempted() > 0 {
                            match self
                                .storage
                                .record_peer_sync_yield(&health_key, topic, yielded)
                                .await
                            {
                                Ok(streak)
                                    if !yielded
                                        && crate::gasp::yieldless_sync_failed(&streak)
                                        && outcome_success =>
                                {
                                    outcome_success = false;
                                    let msg = format!(
                                        "{peer_url}: {} consecutive syncs over {} s finalized no graph and moved no cursor (past {} and {} s; bsv-low #555)",
                                        streak.yieldless_syncs,
                                        streak.secs_since_first.unwrap_or(0),
                                        crate::gasp::PEER_YIELDLESS_SYNCS_ALLOWED,
                                        crate::gasp::PEER_YIELDLESS_SECS_ALLOWED
                                    );
                                    warn!("[GASP SYNC] {msg}");
                                    errors.push(msg);
                                }
                                Ok(_) => {}
                                Err(e) => warn!(
                                    "[GASP SYNC] failed to record the yield of {peer_url}/{topic}: {e}"
                                ),
                            }
                        }
                    }
                    finalized_graphs += peer_finalized.get();
                    let deferral = sync.deferral_stats();
                    deferred_graphs += deferral.deferred;
                    resumed_graphs += deferral.resumed;
                    converged_graphs += deferral.converged;
                    stalled_graphs += deferral.stalled;
                    held_back_graphs += deferral.held_back;
                    dropped_graphs.extend(deferral.dropped.into_iter().map(|d| DroppedDeferral {
                        peer: peer_url.clone(),
                        outpoint: d.outpoint,
                        reason: d.reason.as_str().to_string(),
                    }));

                    // bsv-low#302: record the attempt outcome (success resets
                    // the consecutive-failure count; timeout/error increments
                    // it). Best-effort — a bookkeeping fault must never fail
                    // the sync pass itself.
                    //
                    // bsv-low #555, the delta-4 fold's D4-L2: with a
                    // per-graph budget, a peer that was at the quarantine
                    // threshold when this sync began is re-admitted only by
                    // a YIELD (a graph finalized, the cursor moved). A sync
                    // that did not fail and yielded nothing (an empty
                    // listing at its probe, a walk that only progressed) is
                    // NOT RECORDED: the failures stay, and so does the
                    // last-attempt stamp, so the peer is attended again on
                    // the next tick and its next failure re-arms the
                    // quarantine at once. Recorded as a success, a hostile
                    // peer's empty listing at each probe reset its failures
                    // and (the decay being for a peer that is not failed)
                    // its yieldless streak: 100 of 200 ticks. A health read
                    // that faulted read 0 failures: the old rule, fail-safe.
                    if outcome_success
                        && !(peer_finalized.get() > 0 || advanced_cursor)
                        && self.graph_budget.is_some()
                        && health.consecutive_failures >= crate::gasp::PEER_QUARANTINE_THRESHOLD
                    {
                        info!(
                            "[GASP SYNC] {peer_url} for {topic}: a sync with no yield does not lift its quarantine ({} consecutive failed syncs kept; bsv-low #555)",
                            health.consecutive_failures
                        );
                    } else if let Err(e) = self
                        .storage
                        .record_peer_sync_outcome(&health_key, topic, outcome_success)
                        .await
                    {
                        warn!(
                            "[GASP SYNC] failed to record peer sync outcome for {peer_url}/{topic}: {e}"
                        );
                    }
                }
            }

            topics_synced.insert(
                topic.clone(),
                TopicSyncResult {
                    expired_refused,
                    peers,
                    sync_type,
                    errors,
                    pruned_inputs,
                    discarded_graphs,
                    anchor_walk_held_graphs,
                    finalized_graphs,
                    deadline_dropped_graphs,
                    cursor_moves,
                    deferred_graphs,
                    resumed_graphs,
                    converged_graphs,
                    dropped_graphs,
                    stalled_graphs,
                    held_back_graphs,
                },
            );
        }

        info!(
            "[GASP SYNC] Peer discovery complete for {} topic(s)",
            topics_synced.len()
        );

        let expired: u64 = topics_synced.values().map(|r| r.expired_refused).sum();
        if expired > 0 {
            info!("[GASP SYNC] gaspExpiredRefused={expired}");
        }
        Ok(GASPSyncResult { topics_synced })
    }

    /// Drain `sink` and submit every finalized graph in it, ancestors first
    /// (`historical-tx-no-spv`: the anchor check already verified them).
    /// Each graph is added to `submitted` as its first submit starts. Returns
    /// whether EVERY transaction of every graph landed.
    ///
    /// Each graph here passed the anchor check: its root verified and the
    /// replay admitted it, so these submits rest on a checked premise and are
    /// not expected to fail. If one does not LAND, the REST OF THAT GRAPH is
    /// not submitted: the reference's `finalizeGraph` awaits each submit in
    /// order and its throw ends the loop (the BEEFs already submitted stay,
    /// it has no rollback either). A later BEEF would otherwise be judged
    /// without the coin its ancestor failed to leave, admit nothing and be
    /// recorded as applied, a dupe for good. "Landed" is read from the
    /// durability report, not from `Ok`: `submit` answers `Ok` when a storage
    /// write faulted and when the topic manager failed, and in both it
    /// records no applied row. A transaction landed when its topic is applied
    /// or was already applied (a dupe). Other graphs carry on, and the caller
    /// keeps the cursor from passing a graph that did not land.
    ///
    /// Each transaction's submit is one write section of the engine's gate
    /// ([`Engine::finalize_submit_gate`]) and the gate is asked between two:
    /// a deadline that is due stops the sequence there (this future is
    /// dropped at that await, between two whole transactions).
    async fn submit_finalized_graphs(
        &self,
        sink: &crate::gasp_overlay::FinalizedGraphSink,
        peer_url: &str,
        topic: &str,
        submitted: &std::cell::Cell<u64>,
    ) -> bool {
        let finalized: Vec<_> = sink
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .drain(..)
            .collect();

        let mut all_landed = true;
        for graph in &finalized {
            for (position, beef_bytes) in graph.beefs.iter().enumerate() {
                self.finalize_gate.stop_if_due().await;
                if position == 0 {
                    submitted.set(submitted.get() + 1);
                }
                let tagged = TaggedBEEF::new(beef_bytes.clone(), vec![graph.topic.clone()]);
                // No deadline drops a write section, and the section does
                // not drop ITSELF either (bsv-low #559, the delta lens's
                // DELTA-3 and the lens fold of 2026-10-07, F2,
                // `set_finalize_submit_budget`): the submit always runs to
                // its end. What is bounded is each storage call and hook
                // inside it ([`CallBound`]): one that never answers is that
                // call's FAULT, the submit handles it as any fault (nothing
                // of the transaction held, or all of it), the transaction
                // did not land, its UTXO fails and the cursor stays.
                let outcome = {
                    let _writing = self.finalize_gate.write_section();
                    let bound = self
                        .finalize_submit_budget
                        .as_ref()
                        .map(|(sleep, budget_ms)| CallBound::new(sleep, *budget_ms));
                    self.submit_bounded(
                        &tagged,
                        SubmitMode::HistoricalTxNoSpv,
                        bound.as_ref(),
                        true,
                        WalkBreachPolicy::NotNow,
                    )
                    .await
                };
                let not_landed = match outcome {
                    Ok((_, report)) => {
                        let landed = report.is_durable()
                            && (report.applied_topics.contains(&graph.topic)
                                || report.deduped_topics.contains(&graph.topic));
                        (!landed).then(|| {
                            if report.is_durable() {
                                "the topic manager failed on it".to_string()
                            } else {
                                format!("not durable: {}", report.summary())
                            }
                        })
                    }
                    Err(e) => Some(e.to_string()),
                };
                if let Some(why) = not_landed {
                    warn!(
                        "[GASP SYNC] A finalize submit for topic {} did not land ({why}); the rest of its graph is not submitted",
                        graph.topic
                    );
                    all_landed = false;
                    break;
                }
            }
        }

        if !finalized.is_empty() {
            info!(
                "[GASP SYNC] Submitted {} finalized graph(s) for {topic} from {peer_url}",
                finalized.len()
            );
        }
        all_landed
    }

    /// Union local records, tracker answers, SLAP-named providers and bootstrap.
    /// Reference: overlay-services@480d77a src/Engine.ts:839-876 and
    /// ts-stack@edf6e03 packages/sdk/src/overlay-tools/LookupResolver.ts:1976.
    /// Ask the configured topic peers for held outputs, using the same SHIP
    /// discovery as sync. Only a header-verified proof can change stored bytes.
    pub async fn rerequest_held_proofs(
        &self,
        candidates: &[crate::proof_window::HeldOutput],
        progress: &std::cell::Cell<crate::proof_window::PeerProofSummary>,
    ) {
        use crate::proof_window::{PEER_PROOF_REQUEST_MS, PEER_PROOF_ROW_LIMIT};
        let Some(factory) = &self.gasp_remote_factory else {
            return;
        };
        let Some(tracker) = self.chain_tracker.as_deref() else {
            return;
        };
        let mut lookup_hosts = None;
        let mut topic_peers = HashMap::new();
        let mut landed = HashSet::new();
        for candidate in candidates.iter().take(PEER_PROOF_ROW_LIMIT) {
            if !self.managers.contains_key(&candidate.topic) {
                continue;
            }
            if let std::collections::hash_map::Entry::Vacant(entry) =
                topic_peers.entry(candidate.topic.clone())
            {
                let peers = match self.config.sync_configuration.get(&candidate.topic) {
                    Some(SyncTarget::Ship) => {
                        self.discover_ship_peers(&candidate.topic, &mut lookup_hosts)
                            .await
                    }
                    Some(SyncTarget::Peers(peers)) => self.ship_peers_excluding_self(peers.clone()),
                    _ => Vec::new(),
                };
                entry.insert(peers);
            }
            for peer in &topic_peers[&candidate.topic] {
                let remote = factory.create_remote(peer, &candidate.topic);
                let graph_id = format!("{}.{}", candidate.txid, candidate.output_index);
                let mut summary = progress.get();
                summary.requests += 1;
                progress.set(summary);
                let ask =
                    remote.request_node(&graph_id, &candidate.txid, candidate.output_index, false);
                let response = if let Some((sleep, _)) = &self.peer_sync_budget {
                    crate::gasp::race_or_deadline(ask, sleep(PEER_PROOF_REQUEST_MS)).await
                } else {
                    Some(ask.await)
                };
                let Some(Ok(node)) = response else {
                    let mut summary = progress.get();
                    summary.faults += 1;
                    progress.set(summary);
                    continue;
                };
                if landed.contains(&candidate.txid) {
                    continue;
                }
                let Some(proof_hex) = node.proof else {
                    continue;
                };
                let Ok(mut proof) = beef_limits::merkle_path_from_hex(
                    &proof_hex,
                    beef_limits::COURIER_PROOF_MAX_BYTES,
                ) else {
                    let mut summary = progress.get();
                    summary.refused += 1;
                    progress.set(summary);
                    continue;
                };
                let valid = match proof.compute_root(Some(&candidate.txid)) {
                    Ok(root) => tracker
                        .is_valid_root_for_height(&root, proof.block_height)
                        .await
                        .unwrap_or(false),
                    Err(_) => false,
                };
                if !valid {
                    let mut summary = progress.get();
                    summary.refused += 1;
                    progress.set(summary);
                    continue;
                }
                // Root verification accepts a hash leaf too. Mark the verified
                // subject so BEEF attaches the path before its proof flag moves.
                for leaf in &mut proof.path[0] {
                    if leaf.hash.as_deref() == Some(&candidate.txid) {
                        leaf.txid = true;
                    }
                }
                match self.land_peer_proof(candidate, &proof).await {
                    Ok(()) => {
                        landed.insert(candidate.txid.clone());
                        let mut summary = progress.get();
                        summary.landed += 1;
                        progress.set(summary);
                    }
                    Err(error) => {
                        warn!(%error, "[proof window] verified proof could not be stored");
                        let mut summary = progress.get();
                        summary.faults += 1;
                        progress.set(summary);
                    }
                }
            }
        }
    }

    async fn land_peer_proof(
        &self,
        candidate: &crate::proof_window::HeldOutput,
        proof: &bsv_rs::transaction::MerklePath,
    ) -> Result<(), EngineError> {
        let output = self
            .storage
            .find_output(
                &candidate.txid,
                candidate.output_index,
                Some(&candidate.topic),
                None,
                true,
            )
            .await
            .map_err(|e| EngineError::StorageError(e.to_string()))?
            .ok_or(EngineError::NodeNotFound)?;
        let beef = output
            .beef
            .ok_or_else(|| EngineError::BeefParseError("missing stored BEEF".into()))?;
        let stitched = Self::stitch_proof_into_stored_beef(&beef, &candidate.txid, proof)
            .ok_or_else(|| {
                EngineError::BeefParseError("proof does not stitch into stored subject".into())
            })?;
        self.storage
            .update_transaction_beef(&candidate.txid, &stitched)
            .await
            .map_err(|e| EngineError::StorageError(e.to_string()))?;
        self.storage
            .mark_transaction_proven_at(&candidate.txid, Some(u64::from(proof.block_height)))
            .await
            .map_err(|e| EngineError::StorageError(e.to_string()))
    }

    async fn discover_ship_peers(
        &self,
        topic: &str,
        lookup_hosts: &mut Option<Vec<String>>,
    ) -> Vec<String> {
        let mut domains = self.local_ship_peers(topic).await;
        if let Some(bootstrap) = self.ship_bootstrap_peers.get(topic) {
            domains.extend(bootstrap.iter().cloned());
        }
        if let Some(client) = &self.ship_lookup_client {
            if lookup_hosts.is_none() {
                *lookup_hosts = Some(self.discover_ship_lookup_hosts(client.as_ref()).await);
            }
            let question = LookupQuestion::new("ls_ship", serde_json::json!({"topics": [topic]}));
            for host in lookup_hosts.as_ref().into_iter().flatten() {
                match client.lookup(host, &question).await {
                    Ok(outputs) => {
                        domains.extend(outputs.iter().filter_map(|output| {
                            parse_lookup_advertisement(output, b"SHIP", topic)
                        }));
                    }
                    Err(e) => warn!("[GASP SYNC] SHIP lookup at {host} for {topic} failed: {e}"),
                }
            }
        }
        self.ship_peers_excluding_self(domains)
    }

    async fn discover_ship_lookup_hosts(
        &self,
        client: &dyn crate::ship_lookup::ShipLookupClient,
    ) -> Vec<String> {
        use crate::ship_lookup::SHIP_DISCOVERY_MAX_HOSTS_PER_TICK;
        let trackers = self.ship_peers_excluding_self(self.config.slap_trackers.clone());
        let tracker_origins: HashSet<_> = trackers
            .iter()
            .map(|host| crate::gasp::peer_origin(host))
            .collect();
        let question = LookupQuestion::new("ls_slap", serde_json::json!({"service": "ls_ship"}));
        let mut advertised = Vec::new();
        for tracker in &trackers {
            match client.lookup(tracker, &question).await {
                Ok(outputs) => {
                    advertised.extend(outputs.iter().filter_map(|output| {
                        parse_lookup_advertisement(output, b"SLAP", "ls_ship")
                    }));
                }
                Err(e) => warn!("[GASP SYNC] SLAP lookup at {tracker} failed: {e}"),
            }
        }
        let providers = self
            .ship_peers_excluding_self(advertised)
            .into_iter()
            .filter(|host| !tracker_origins.contains(&crate::gasp::peer_origin(host)))
            .take(SHIP_DISCOVERY_MAX_HOSTS_PER_TICK);
        trackers.into_iter().chain(providers).collect()
    }

    fn ship_peers_excluding_self(&self, domains: impl IntoIterator<Item = String>) -> Vec<String> {
        crate::gasp::ship_peers_by_origin(domains.into_iter().filter(|domain| {
            self.config.hosting_url.as_ref().is_none_or(|our_url| {
                crate::gasp::peer_origin(domain) != crate::gasp::peer_origin(our_url)
            })
        }))
    }

    /// Read local SHIP records independently of network discovery failures.
    async fn local_ship_peers(&self, topic: &str) -> Vec<String> {
        let Some(ship_ls) = self.lookup_services.get("ls_ship") else {
            warn!("[GASP SYNC] No local ls_ship; retaining network and bootstrap discovery");
            return Vec::new();
        };

        let question = LookupQuestion::new("ls_ship", serde_json::json!({ "topics": [topic] }));

        let refs = match ship_ls.lookup(&question).await {
            Ok(LookupResult::OutputList(refs)) => refs,
            Ok(LookupResult::Answer(_)) => {
                error!(
                    "[GASP SYNC] SHIP lookup for topic {topic} returned a pre-formed \
                     LookupAnswer; expected OutputList. Skipping."
                );
                return Vec::new();
            }
            Err(e) => {
                error!("[GASP SYNC] SHIP lookup for topic {topic} failed: {e}");
                return Vec::new();
            }
        };

        let mut domains = HashSet::new();
        for reference in &refs {
            if let Ok(Some(output)) = self
                .storage
                .find_output(&reference.txid, reference.output_index, None, None, false)
                .await
            {
                if let Some(domain) = parse_ship_domain_from_script(&output.output_script) {
                    // Every spelling of our own origin is ourselves (the
                    // delta-2 fold's D2-M2: `https://us/?x` passed the
                    // string compare).
                    if let Some(ref our_url) = self.config.hosting_url {
                        if domain.trim_end_matches('/') == our_url.trim_end_matches('/')
                            || crate::gasp::peer_origin(&domain)
                                == crate::gasp::peer_origin(our_url)
                        {
                            continue;
                        }
                    }
                    domains.insert(domain);
                }
            }
        }

        // One peer per normalized origin (bsv-low #555, the delta-2 fold's
        // D2-M2, restored by the delta-4 fold's D4-M1): eight spellings of
        // one server are one peer, the one its health row is keyed by.
        crate::gasp::ship_peers_by_origin(domains)
    }

    // ========================================================================
    // Helpers
    // ========================================================================

    /// Get a reference to the storage backend.
    pub fn storage(&self) -> &dyn Storage {
        self.storage.as_ref()
    }

    /// Get the engine configuration.
    pub fn config(&self) -> &EngineConfig {
        &self.config
    }
}

/// The SPV check of [`Engine::submit`], as one function over a BORROWED
/// tracker: the reference's `tx.verify(chainTracker)` (roots against the
/// tracker, every unproven input's script executed, the value rule), its
/// `tx.verify('scripts only')` when `chain_tracker` is `None` (roots accepted
/// unchecked, scripts still run), and the pre-2026-09-08 structural check when
/// `verify_scripts` is `false` ([`Engine::set_script_verification`]'s escape
/// hatch).
///
/// There is ONE verifier. `Engine::submit` calls this with its own tracker,
/// switch and walk budget; the GASP anchor check
/// (`OverlayGASPStorage::validate_graph_anchor`, bsv-low #551) calls it with
/// the same three, handed over by `Engine::start_gasp_sync`.
///
/// `Ok(Some(_))` is a walk that COULD NOT RUN within `budget` (bsv-low #592):
/// not a verdict on the transaction. The caller goes on as it would without a
/// walk and says so.
pub(crate) async fn verify_spv_like_the_reference(
    chain_tracker: Option<&dyn bsv_rs::transaction::ChainTracker>,
    verify_scripts: bool,
    beef_bytes: &[u8],
    subject_txid: &str,
    budget: DoorBudget,
) -> Result<Option<WalkCouldNotRun>, EngineError> {
    verify_spv_trusting(
        chain_tracker,
        verify_scripts,
        beef_bytes,
        subject_txid,
        &HashSet::new(),
        budget,
    )
    .await
}

/// [`verify_spv_like_the_reference`] trusting the transactions an earlier
/// walk of the same submit passed over (a predecessor the door lands first,
/// the E1D delta fold, L4): the script walk neither checks nor descends
/// them. The structural escape hatch checks the whole BEEF it is given.
async fn verify_spv_trusting(
    chain_tracker: Option<&dyn bsv_rs::transaction::ChainTracker>,
    verify_scripts: bool,
    beef_bytes: &[u8],
    subject_txid: &str,
    trusted: &HashSet<String>,
    budget: DoorBudget,
) -> Result<Option<WalkCouldNotRun>, EngineError> {
    if verify_scripts {
        Engine::verify_beef_linear(chain_tracker, beef_bytes, subject_txid, trusted, budget).await
    } else {
        Engine::verify_spv_structurally(chain_tracker, beef_bytes)
            .await
            .map(|()| None)
    }
}

/// The BUMP that proves each txid of `beef`: the first BUMP whose level 0
/// carries it, as `Beef::find_bump` picks, built in one pass over the BUMPs'
/// leaves (NL-6e; `find_bump` per transaction scans them all each time).
fn proven_index(beef: &Beef) -> HashMap<&str, usize> {
    let mut proven: HashMap<&str, usize> = HashMap::new();
    for (at, bump) in beef.bumps.iter().enumerate() {
        for leaf in bump.path.first().into_iter().flatten() {
            if let Some(hash) = leaf.hash.as_deref() {
                proven.entry(hash).or_insert(at);
            }
        }
    }
    proven
}

/// The transactions the SPV walk of `from` passes over in `beef`
/// ([`Engine::verify_beef_linear_with`]'s traversal, nothing checked): `from`
/// and every source the BEEF carries, a proven transaction included and not
/// descended. The E1D delta fold, L4: what a landing need not walk again.
fn walk_cover(beef: &Beef, from: &str) -> HashSet<String> {
    let bodies: HashMap<String, &Transaction> = beef
        .txs
        .iter()
        .filter_map(|btx| btx.tx().map(|tx| (btx.txid(), tx)))
        .collect();
    let proven = proven_index(beef);
    let mut cover = HashSet::new();
    let mut queue = vec![from.to_string()];
    while let Some(txid) = queue.pop() {
        if !cover.insert(txid.clone()) || proven.contains_key(txid.as_str()) {
            continue;
        }
        if let Some(tx) = bodies.get(&txid) {
            queue.extend(tx.inputs.iter().filter_map(|i| i.source_txid.clone()));
        }
    }
    cover
}

/// The engine's [`crate::gasp::FinalizedGraphHook`] (bsv-low #552): submit
/// what a peer's sync just finalized, before its next UTXO is asked for.
struct SubmitAsFinalized<'e> {
    engine: &'e Engine,
    sink: crate::gasp_overlay::FinalizedGraphSink,
    peer_url: &'e str,
    topic: &'e str,
    submitted: &'e std::cell::Cell<u64>,
}

#[async_trait::async_trait(?Send)]
impl crate::gasp::FinalizedGraphHook for SubmitAsFinalized<'_> {
    async fn graph_completed(&self) -> Result<(), crate::gasp::GASPError> {
        // A graph is counted as its first submit starts, and the deadline
        // cannot land inside a submit: a sync dropped in here has written at
        // least that transaction whole (an ancestors-first prefix).
        let landed = self
            .engine
            .submit_finalized_graphs(&self.sink, self.peer_url, self.topic, self.submitted)
            .await;
        if landed {
            Ok(())
        } else {
            // Fails this UTXO: the cursor stays below it and the next sync
            // asks for it again (the lens fold's MEDIUM-1).
            Err(crate::gasp::GASPError::StorageError(
                "a finalize submit did not land".to_string(),
            ))
        }
    }
}

/// Result of a GASP sync operation.
///
/// Returned by `Engine::start_gasp_sync()` to summarize what happened.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GASPSyncResult {
    /// Per-topic sync results.
    pub topics_synced: HashMap<String, TopicSyncResult>,
}

/// Sync result for a single topic.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TopicSyncResult {
    /// Distinct expired advert roots skipped before any proof request.
    #[serde(default)]
    pub expired_refused: u64,
    /// Peer URLs discovered or configured for this topic.
    pub peers: Vec<String>,
    /// How peers were determined: "ship" or "peers".
    pub sync_type: String,
    /// Any errors encountered during sync (peer URL -> error message): a
    /// peer whose sync failed or ran over its budget. A single UTXO whose
    /// graph ingest failed is NOT listed here: it is warned (`Error ingesting
    /// UTXO`), held back by the cursor gap guard and asked for again by the
    /// next sync.
    pub errors: Vec<String>,
    /// Manager-named inputs pruned because a peer answered that it does not
    /// hold them (the D8 decoy rule, `GASPSync::pruned_inputs`). Counted per
    /// distinct outpoint PER PEER per sync and summed over this topic's
    /// peers: one decoy seen through two peers reads 2. Not errors: the
    /// graphs completed without those branches.
    #[serde(default)]
    pub pruned_inputs: u64,
    /// Graphs the anchor check REFUSED and discarded whole (bsv-low #551,
    /// `GASPSync::discarded_graphs`): a root whose BEEF does not verify, or
    /// one the topic manager does not admit at the end of the replay. Summed
    /// over this topic's peers. Not errors, and nothing of them was admitted.
    #[serde(default)]
    pub discarded_graphs: u64,
    /// Graphs HELD because their anchor's script walk could not run within
    /// the engine's walk budget (bsv-low #592; the E592 lens fold, H1 and
    /// L3; `GASPSync::anchor_walk_held`), summed over this topic's peers.
    /// Nothing of them was finalized; each UTXO stays below its cursor until
    /// the peer serves its root proven. Not errors and not discarded.
    #[serde(default)]
    pub anchor_walk_held_graphs: u64,
    /// Graphs that passed the anchor check and were handed to submit, summed
    /// over this topic's peers (bsv-low #552). Under a per-peer budget a
    /// graph is counted, and submitted, the moment it finalizes, so the
    /// count includes those of a peer the deadline then dropped. A counted
    /// graph had its first transaction submitted whole (the deadline never
    /// lands inside a submit); one whose later submit did not land is still
    /// counted, and its UTXO stays below the cursor.
    /// A graph is counted as its first submit STARTS; a first submit that FAULTS
    /// still counts here, so this is not a delivered count (bsv-low #559).
    #[serde(default)]
    pub finalized_graphs: u64,
    /// Graphs that were mid-walk when a peer's sync was dropped at its
    /// budget (bsv-low #552): at most one per peer per sync. NOTHING of such
    /// a graph was admitted; the next sync walks it again. The same root
    /// counted tick after tick with no `finalized_graphs` and no
    /// `cursor_moves` is ONE graph whose walk outlasts the budget (with a
    /// per-graph budget it is also counted in `deferred_graphs` and resumed,
    /// bsv-low #555).
    #[serde(default)]
    pub deadline_dropped_graphs: u64,
    /// Every persisted cursor that moved in this sync (bsv-low #552), one
    /// entry per peer. After a completed sync `to` is the peer's highest
    /// score seen (less the gap guard); after a deadline it is
    /// `GASPSync::completed_cursor`: past completed UTXOs only.
    #[serde(default)]
    pub cursor_moves: Vec<CursorMove>,
    /// Graphs DEFERRED in this sync, summed over peers (bsv-low #555,
    /// `Engine::set_graph_budget`): a new record, or a resumed graph
    /// deferred again. Their UTXOs are held below the cursor.
    #[serde(default)]
    pub deferred_graphs: u64,
    /// Graphs RESUMED from a record in this sync.
    #[serde(default)]
    pub resumed_graphs: u64,
    /// Resumed graphs that completed and landed in this sync (their record
    /// deleted).
    #[serde(default)]
    pub converged_graphs: u64,
    /// Records deleted without converging, with their reason.
    #[serde(default)]
    pub dropped_graphs: Vec<DroppedDeferral>,
    /// Walks the per-graph budget (or the per-peer deadline) cut having
    /// fetched NOTHING in their pass (bsv-low #555, the lens fold's H1). A
    /// peer's sync whose only outcome was these is a failed attempt for the
    /// quarantine count.
    #[serde(default)]
    pub stalled_graphs: u64,
    /// Records NOT resumed in this sync: the resumes of a peer's pass share
    /// ONE per-graph budget and had spent it (the lens fold's M1). Held for
    /// the next sync, untouched.
    #[serde(default)]
    pub held_back_graphs: u64,
}

/// A deferred graph's record deleted without converging (bsv-low #555,
/// [`TopicSyncResult::dropped_graphs`]).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DroppedDeferral {
    /// The peer URL.
    pub peer: String,
    /// The graph's root outpoint.
    pub outpoint: String,
    /// [`crate::gasp::DropReason::as_str`].
    pub reason: String,
}

/// One peer's persisted `last_interaction` cursor moving `from` -> `to` in a
/// sync ([`TopicSyncResult::cursor_moves`]).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CursorMove {
    /// The peer URL.
    pub peer: String,
    /// The cursor the sync entered with.
    pub from: u64,
    /// The cursor it persisted.
    pub to: u64,
}

/// Get current time in milliseconds (for output scores).
///
/// Uses `js_sys::Date::now()` on wasm32 (Cloudflare Workers) since
/// `std::time::SystemTime` is not available on that platform.
pub(crate) fn current_timestamp_ms() -> f64 {
    #[cfg(target_arch = "wasm32")]
    {
        js_sys::Date::now()
    }
    #[cfg(not(target_arch = "wasm32"))]
    {
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0.0, |d| d.as_millis() as f64)
    }
}

/// Extract the domain field from a SHIP PushDrop locking script.
///
/// SHIP PushDrop format: field[0] = "SHIP", field[1] = identity_key,
/// field[2] = domain (UTF-8), field[3] = topic.
/// Returns `None` if the script cannot be parsed or is not a SHIP advertisement.
fn parse_ship_domain_from_script(output_script: &[u8]) -> Option<String> {
    parse_advertisement_domain_from_script(output_script, b"SHIP", None)
}

fn parse_lookup_advertisement(
    output: &OutputListItem,
    protocol: &[u8],
    scope: &str,
) -> Option<String> {
    let tx = beef_limits::transaction_from_beef(&output.beef, None, &beef_limits::PEER_BEEF_LIMITS)
        .ok()?;
    let script = tx
        .outputs
        .get(output.output_index as usize)?
        .locking_script
        .to_binary();
    parse_advertisement_domain_from_script(&script, protocol, Some(scope))
}

fn parse_advertisement_domain_from_script(
    output_script: &[u8],
    protocol: &[u8],
    scope: Option<&str>,
) -> Option<String> {
    use bsv_rs::script::templates::PushDrop;

    let script = bsv_rs::script::Script::from_binary(output_script).ok()?;
    let pushdrop = PushDrop::decode(&script.into()).ok()?;

    if pushdrop.fields.len() < 3 {
        return None;
    }

    if pushdrop.fields[0] != protocol {
        return None;
    }

    if scope.is_some_and(|expected| {
        pushdrop
            .fields
            .get(3)
            .is_none_or(|actual| actual != expected.as_bytes())
    }) {
        return None;
    }

    let domain = String::from_utf8_lossy(&pushdrop.fields[2]).to_string();
    if domain.is_empty() {
        return None;
    }

    Some(domain)
}

// ============================================================================
// Submit-time spend verification helpers (reference parity, 2026-09-08)
// ============================================================================

// ============================================================================
// Error type
// ============================================================================

#[derive(Debug, thiserror::Error)]
pub enum EngineError {
    #[error("This server does not support this topic: {0}")]
    UnsupportedTopic(String),

    #[error("Lookup service not found for provider: {0}")]
    LookupServiceNotFound(String),

    /// GASP: `/requestForeignGASPNode` asked for a graph/txid we don't
    /// have locally. Matches mainline's 400-class "not found" response.
    #[error("No matching output found!")]
    NodeNotFound,

    #[error("lookup failed: {0}")]
    LookupFailed(String),

    /// The CALLER's query was malformed — a bad identity key, a gameId that is
    /// not 32 bytes of hex, a missing required field. Distinct from
    /// `LookupFailed`, which means WE failed: without the distinction every
    /// caller mistake was reported as a server fault (HTTP 500), so a malformed
    /// query and a genuine outage were indistinguishable in logs and alerts on
    /// an unauthenticated endpoint anyone can hit.
    #[error("invalid query: {0}")]
    InvalidQuery(String),

    #[error("storage error: {0}")]
    StorageError(String),

    #[error("broadcast error: {0}")]
    BroadcastError(String),

    #[error("SPV verification failed: {0}")]
    SpvError(String),

    #[error("BEEF parsing failed: {0}")]
    BeefParseError(String),

    /// A spend in the submitted BEEF does not satisfy its source output's
    /// locking script: the input's unlocking script was EXECUTED (reference
    /// parity, 2026-09-08) and the interpreter refused it. Distinct from
    /// [`EngineError::SpvError`] (a bad or unverifiable PROOF, a missing
    /// source, a chain-tracker fault) so an operator can tell a bad spend from
    /// a bad proof. `input_index` is the failing input's position in the
    /// transaction whose script failed (the subject, or an unproven
    /// ancestor of it in the same BEEF); `reason` is the interpreter's own
    /// message.
    #[error("script verification failed (subject {subject_txid}): input {input_index}: {reason}")]
    ScriptVerificationFailed {
        subject_txid: String,
        input_index: u32,
        reason: String,
    },

    /// The DOOR walk ([`Engine::verify_scripts_only`]) hit a STRUCTURAL fault
    /// before reaching a verdict on `at_txid` (a source the BEEF lacks, a
    /// parse fault, the value rule): not the interpreter's verdict, so not a
    /// refusal for a caller whose bar is the network. `subject_judged` says
    /// whether the subject's own inputs had all executed before the fault
    /// (an ancestor faulted) or not (the subject itself is unjudged).
    #[error("script walk inconclusive at {at_txid} (subject judged: {subject_judged}): {reason}")]
    ScriptWalkInconclusive {
        at_txid: String,
        subject_judged: bool,
        reason: String,
    },

    /// The DOOR walk exceeded its own bound ([`DoorBudget`]: the static work
    /// estimate, the interpreter's memory limit tripping, or the estimate of
    /// the door's own memory; `limb` says which): the door's verdict, never
    /// the network's — the request proceeds to the network.
    #[error("script walk over budget at {at_txid} (subject judged: {subject_judged}): {what}")]
    ScriptWalkOverBudget {
        at_txid: String,
        subject_judged: bool,
        limb: DoorLimb,
        what: String,
    },

    /// The submit's own script walk COULD NOT RUN within the engine's
    /// [`DoorBudget`] (bsv-low #592) and nothing on record stands in for it
    /// ([`WalkBreachPolicy::NotNow`], every door but the queue replay of a
    /// gated submission; the E592 lens fold, H1). NOT NOW: nothing was
    /// judged, nothing written, and it is NOT a refusal either: the budget
    /// says nothing about the transaction. The way out is the subject
    /// PROVEN: a proven transaction is not walked, so an honest body too
    /// big to walk unmined lands once its block is mined (a client retries
    /// after the block, not at once).
    #[error(
        "the script walk could not run within the budget ({}: {}); not now: present the subject proven, after its block",
        .0.limb.as_str(),
        .0.what
    )]
    WalkCouldNotRun(WalkCouldNotRun),

    #[error("{0}")]
    Other(String),
}

impl From<StorageError> for EngineError {
    fn from(e: StorageError) -> Self {
        EngineError::StorageError(e.to_string())
    }
}

impl From<TopicManagerError> for EngineError {
    fn from(e: TopicManagerError) -> Self {
        EngineError::Other(e.to_string())
    }
}

impl From<LookupServiceError> for EngineError {
    fn from(e: LookupServiceError) -> Self {
        EngineError::LookupFailed(e.to_string())
    }
}

impl From<AdvertiserError> for EngineError {
    fn from(e: AdvertiserError) -> Self {
        EngineError::Other(e.to_string())
    }
}

// ============================================================================
// Tests
// ============================================================================

/// Baseline sync order: configured peer topics before SHIP discovery topics,
/// each by name (bsv-low #555, D-M1). `start_gasp_sync` advances SHIP topics
/// with explicit bootstrap peers ahead of this order so their sync can run
/// without importing tracker records. Deferred-graph reservations still use
/// each topic's configured target.
pub(crate) fn sync_order(config: &SyncConfiguration) -> Vec<(&String, &SyncTarget)> {
    let mut order: Vec<(&String, &SyncTarget)> = config.iter().collect();
    order.sort_by_key(|(topic, target)| (!matches!(target, SyncTarget::Peers(_)), topic.as_str()));
    order
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lookup_service::LookupService as LookupServiceTrait;
    use crate::storage::memory::MemoryStorage;
    use crate::topic_manager::TopicManager as TopicManagerTrait;
    use async_trait::async_trait;
    use std::sync::Mutex;

    // bsv-low #555, the delta fold's D-M1: the configured peers' topics are
    // synced before the ls_ship-discovered ones, each class by name; the map's
    // order was arbitrary.
    #[test]
    fn delta555_m1_configured_peers_are_synced_before_discovered_ones() {
        let peers = |p: &str| SyncTarget::Peers(vec![p.to_string()]);
        let config: SyncConfiguration = HashMap::from([
            ("tm_a".to_string(), SyncTarget::Ship),
            ("tm_z".to_string(), peers("https://z")),
            ("tm_b".to_string(), SyncTarget::Ship),
            ("tm_m".to_string(), peers("https://m")),
            ("tm_off".to_string(), SyncTarget::Disabled),
        ]);
        let order: Vec<&str> = sync_order(&config)
            .iter()
            .map(|(t, _)| t.as_str())
            .collect();
        assert_eq!(order, vec!["tm_m", "tm_z", "tm_a", "tm_b", "tm_off"]);
    }

    // ── Mock TopicManager ──────────────────────────────────────────────

    struct MockTopicManager {
        admit_indices: Vec<u32>,
    }

    impl MockTopicManager {
        fn admitting(indices: Vec<u32>) -> Self {
            Self {
                admit_indices: indices,
            }
        }
    }

    #[async_trait(?Send)]
    impl TopicManagerTrait for MockTopicManager {
        async fn identify_admissible_outputs(
            &self,
            _tx: &Transaction,
            _previous_coins: &[u8],
            _off_chain_values: Option<&[u8]>,
            _mode: SubmitMode,
            _context: &TopicAdmittanceContext,
        ) -> Result<AdmittanceInstructions, TopicManagerError> {
            Ok(AdmittanceInstructions {
                outputs_to_admit: self.admit_indices.clone(),
                coins_to_retain: vec![],
                coins_removed: None,
            })
        }

        async fn get_documentation(&self) -> String {
            "Mock topic manager".to_string()
        }

        async fn get_metadata(&self) -> ServiceMetadata {
            ServiceMetadata {
                name: "mock-tm".to_string(),
                description: Some("Mock for testing".to_string()),
                ..Default::default()
            }
        }
    }

    // ── Mock LookupService ─────────────────────────────────────────────

    struct MockLookupService {
        records: Mutex<Vec<UTXOReference>>,
    }

    impl MockLookupService {
        fn new() -> Self {
            Self {
                records: Mutex::new(Vec::new()),
            }
        }
    }

    #[async_trait(?Send)]
    impl LookupServiceTrait for MockLookupService {
        fn admission_mode(&self) -> AdmissionMode {
            AdmissionMode::LockingScript
        }

        fn spend_notification_mode(&self) -> SpendNotificationMode {
            SpendNotificationMode::None
        }

        async fn output_admitted_by_topic(
            &self,
            payload: &OutputAdmittedByTopic,
        ) -> Result<(), LookupServiceError> {
            let (txid, oi) = match payload {
                OutputAdmittedByTopic::LockingScript {
                    txid, output_index, ..
                } => (txid.clone(), *output_index),
                OutputAdmittedByTopic::WholeTx { output_index, .. } => {
                    ("whole".into(), *output_index)
                }
            };
            self.records.lock().unwrap().push(UTXOReference {
                txid,
                output_index: oi,
            });
            Ok(())
        }

        async fn output_evicted(
            &self,
            txid: &str,
            output_index: u32,
        ) -> Result<(), LookupServiceError> {
            self.records
                .lock()
                .unwrap()
                .retain(|r| !(r.txid == txid && r.output_index == output_index));
            Ok(())
        }

        async fn lookup(
            &self,
            _question: &LookupQuestion,
        ) -> Result<LookupResult, LookupServiceError> {
            Ok(LookupResult::OutputList(
                self.records.lock().unwrap().clone(),
            ))
        }

        async fn get_documentation(&self) -> String {
            "Mock lookup service".to_string()
        }

        async fn get_metadata(&self) -> ServiceMetadata {
            ServiceMetadata {
                name: "mock-ls".to_string(),
                ..Default::default()
            }
        }
    }

    // ── Test BEEF data ──────────────────────────────────────────────────

    /// Real BRC-62 BEEF from TS overlay-services test suite.
    const TEST_BEEF_HEX: &str = "0100beef01fe636d0c0007021400fe507c0c7aa754cef1f7889d5fd395cf1f785dd7de98eed895dbedfe4e5bc70d1502ac4e164f5bc16746bb0868404292ac8318bbac3800e4aad13a014da427adce3e010b00bc4ff395efd11719b277694cface5aa50d085a0bb81f613f70313acd28cf4557010400574b2d9142b8d28b61d88e3b2c3f44d858411356b49a28a4643b6d1a6a092a5201030051a05fc84d531b5d250c23f4f886f6812f9fe3f402d61607f977b4ecd2701c19010000fd781529d58fc2523cf396a7f25440b409857e7e221766c57214b1d38c7b481f01010062f542f45ea3660f86c013ced80534cb5fd4c19d66c56e7e8c5d4bf2d40acc5e010100b121e91836fd7cd5102b654e9f72f3cf6fdbfd0b161c53a9c54b12c841126331020100000001cd4e4cac3c7b56920d1e7655e7e260d31f29d9a388d04910f1bbd72304a79029010000006b483045022100e75279a205a547c445719420aa3138bf14743e3f42618e5f86a19bde14bb95f7022064777d34776b05d816daf1699493fcdf2ef5a5ab1ad710d9c97bfb5b8f7cef3641210263e2dee22b1ddc5e11f6fab8bcd2378bdd19580d640501ea956ec0e786f93e76ffffffff013e660000000000001976a9146bfd5c7fbe21529d45803dbcf0c87dd3c71efbc288ac0000000001000100000001ac4e164f5bc16746bb0868404292ac8318bbac3800e4aad13a014da427adce3e000000006a47304402203a61a2e931612b4bda08d541cfb980885173b8dcf64a3471238ae7abcd368d6402204cbf24f04b9aa2256d8901f0ed97866603d2be8324c2bfb7a37bf8fc90edd5b441210263e2dee22b1ddc5e11f6fab8bcd2378bdd19580d640501ea956ec0e786f93e76ffffffff013c660000000000001976a9146bfd5c7fbe21529d45803dbcf0c87dd3c71efbc288ac0000000000";
    const TEST_TXID: &str = "157428aee67d11123203735e4c540fa1bdab3b36d5882c6f8c5ff79f07d20d1c";

    fn decode_hex(hex: &str) -> Vec<u8> {
        (0..hex.len())
            .step_by(2)
            .map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap())
            .collect()
    }

    fn test_beef() -> Vec<u8> {
        decode_hex(TEST_BEEF_HEX)
    }

    fn test_tagged_beef(topics: Vec<&str>) -> TaggedBEEF {
        TaggedBEEF::new(
            test_beef(),
            topics.into_iter().map(str::to_string).collect(),
        )
    }

    // ── Helpers ────────────────────────────────────────────────────────

    fn make_engine(admit_indices: Vec<u32>) -> Engine {
        let mut managers: HashMap<String, Box<dyn TopicManagerTrait>> = HashMap::new();
        managers.insert(
            "tm_test".to_string(),
            Box::new(MockTopicManager::admitting(admit_indices)),
        );

        let mut lookup_services: HashMap<String, Box<dyn LookupServiceTrait>> = HashMap::new();
        lookup_services.insert("ls_test".to_string(), Box::new(MockLookupService::new()));

        let storage = Box::new(MemoryStorage::new());

        Engine::new(
            managers,
            lookup_services,
            storage,
            None,
            EngineConfig::default(),
        )
    }

    // ── Tests ──────────────────────────────────────────────────────────

    /// bsv-low#289 parse-once + zanaadu#284 subject discipline: the tx handed
    /// to every topic manager must be the ATOMIC SUBJECT of the submitted
    /// BEEF, not whatever sits last in wire order. bsv-rs < 0.3.20's
    /// `from_beef(_, None)` picked `txs.last()`; wallet serializers do not all
    /// place the subject last, so a TM could be handed a PARENT to validate.
    /// This pins the engine on the fixed rule (`txid ?? atomicTxid ?? last`).
    #[tokio::test]
    async fn parse_once_hands_tms_the_atomic_subject_not_wire_order() {
        use bsv_rs::transaction::beef_tx::ATOMIC_BEEF;
        use std::cell::RefCell;
        use std::rc::Rc;

        // Rebuild the fixture chain SUBJECT-FIRST via to_writer (to_binary
        // re-sorts parents-first and would hide the trigger).
        let parsed = Beef::from_binary(&test_beef()).unwrap();
        let parent = parsed.txs[0].tx().unwrap().clone();
        let child = parsed.txs[1].tx().unwrap().clone();
        let child_id = child.id();
        let parent_id = parent.id();
        let mut beef = Beef::new();
        // The parent's BUMP rides along: the reference-parity walk
        // (2026-09-08) executes the subject's script against the parent and
        // then trusts the parent on its proof; without the BUMP it would
        // demand the parent's own ancestry ("Input 0 has no source
        // transaction"), which this fixture does not carry.
        for bump in &parsed.bumps {
            beef.merge_bump(bump.clone());
        }
        beef.merge_transaction(child);
        beef.merge_transaction(parent);
        let mut w = bsv_rs::primitives::encoding::Writer::new();
        w.write_u32_le(ATOMIC_BEEF);
        let mut le = hex::decode(&child_id).unwrap();
        le.reverse();
        w.write_bytes(&le);
        beef.to_writer(&mut w);
        let atomic_wire_order = w.into_bytes();

        // A TM that records the txid it is handed.
        struct RecordingTm(Rc<RefCell<Option<String>>>);
        #[async_trait(?Send)]
        impl TopicManagerTrait for RecordingTm {
            async fn identify_admissible_outputs(
                &self,
                tx: &Transaction,
                _previous_coins: &[u8],
                _off_chain_values: Option<&[u8]>,
                _mode: SubmitMode,
                _context: &TopicAdmittanceContext,
            ) -> Result<AdmittanceInstructions, TopicManagerError> {
                *self.0.borrow_mut() = Some(tx.id());
                Ok(AdmittanceInstructions {
                    outputs_to_admit: vec![0],
                    coins_to_retain: vec![],
                    coins_removed: None,
                })
            }
            async fn get_documentation(&self) -> String {
                String::new()
            }
            async fn get_metadata(&self) -> ServiceMetadata {
                ServiceMetadata {
                    name: "tm_test".to_string(),
                    ..Default::default()
                }
            }
        }

        let seen: Rc<RefCell<Option<String>>> = Rc::new(RefCell::new(None));
        let mut managers: HashMap<String, Box<dyn TopicManagerTrait>> = HashMap::new();
        managers.insert(
            "tm_test".to_string(),
            Box::new(RecordingTm(Rc::clone(&seen))),
        );
        let engine = Engine::new(
            managers,
            HashMap::new(),
            Box::new(MemoryStorage::new()),
            None,
            EngineConfig::default(),
        );

        let tagged = TaggedBEEF::new(atomic_wire_order, vec!["tm_test".to_string()]);
        let _ = engine.submit(&tagged, SubmitMode::CurrentTx).await.unwrap();

        let handed = seen.borrow().clone().expect("TM was not invoked");
        assert_eq!(
            handed, child_id,
            "TM must be handed the atomic subject, got the wire-order pick"
        );
        assert_ne!(handed, parent_id);
    }

    /// #4 REGRESSION: history hydration must never DOWNGRADE provenance.
    ///
    /// `get_utxo_history` used to `Transaction::from_beef(beef, None)` and then
    /// `tx.to_beef(true)`, which keeps only the subject and DROPS the stored
    /// BUMPs. Measured on prod before the fix: `ls_low` byGameId `73de6e48…`
    /// returned 1,172 B / 1 tx / 1 bump (PROVEN) with no header, and 676 B /
    /// 1 tx / 0 bumps with `x-history-depth: 3`. A caller asking for MORE
    /// provenance got a BEEF no wallet can verify — silently, behind a 200.
    ///
    /// There was NO test on this function at all, which is exactly how that
    /// shipped. This one asserts the invariant that matters: whatever else
    /// hydration does, a proof that went in comes back out.
    #[tokio::test]
    async fn history_hydration_preserves_the_stored_proof() {
        use bsv_rs::transaction::Beef;

        let engine = make_engine(vec![0]);
        let stored = test_beef();
        let bumps_before = Beef::from_binary(&stored)
            .expect("fixture BEEF parses")
            .bumps
            .len();
        assert!(
            bumps_before > 0,
            "fixture must actually carry a proof, or this cell proves nothing"
        );

        let output = Output {
            txid: TEST_TXID.to_string(),
            output_index: 0,
            output_script: vec![0x76, 0xa9],
            satoshis: 1000,
            topic: "tm_test".to_string(),
            spent: false,
            // No admitted parents: hydration has nothing to add, so anything
            // it REMOVES is pure loss — the cleanest form of the bug.
            outputs_consumed: vec![],
            consumed_by: vec![],
            beef: Some(stored.clone()),
            block_height: None,
            score: Some(1000.0),
        };

        let hydrated = engine
            .get_utxo_history(&output, Some(HistorySelector::Depth(3)))
            .await
            .expect("hydration must not error")
            .expect("hydration must return the output");
        let beef = Beef::from_binary(&hydrated.beef.expect("hydrated BEEF present"))
            .expect("hydrated BEEF parses");

        assert_eq!(
            beef.bumps.len(),
            bumps_before,
            "asking for history must not strip the merkle proof (issue #4)"
        );
    }

    #[tokio::test]
    async fn test_submit_unsupported_topic_errors() {
        let engine = make_engine(vec![0]);
        let beef = test_tagged_beef(vec!["tm_nonexistent"]);

        let result = engine.submit(&beef, SubmitMode::CurrentTx).await;
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            EngineError::UnsupportedTopic(_)
        ));
    }

    #[tokio::test]
    async fn test_submit_admits_outputs() {
        let engine = make_engine(vec![0, 1]);
        let beef = test_tagged_beef(vec!["tm_test"]);

        let steak = engine.submit(&beef, SubmitMode::CurrentTx).await.unwrap();

        // STEAK should have tm_test with outputs 0 and 1 admitted
        let instructions = steak.get("tm_test").unwrap();
        assert_eq!(instructions.outputs_to_admit, vec![0, 1]);

        // Outputs should be in storage with real data
        let txid = TEST_TXID;
        let found = engine
            .storage()
            .find_output(txid, 0, Some("tm_test"), None, true)
            .await
            .unwrap()
            .expect("Output 0 should be in storage");

        assert_eq!(found.txid, TEST_TXID);
        assert_eq!(found.satoshis, 26172); // Real value from BRC62 BEEF
        assert!(
            !found.output_script.is_empty(),
            "Script should be populated"
        );
        assert!(found.beef.is_some(), "BEEF should be stored");
        assert!(!found.spent);
    }

    #[tokio::test]
    async fn test_submit_duplicate_is_skipped() {
        let engine = make_engine(vec![0]);
        let beef = test_tagged_beef(vec!["tm_test"]);

        // First submit
        let steak1 = engine.submit(&beef, SubmitMode::CurrentTx).await.unwrap();
        assert_eq!(steak1["tm_test"].outputs_to_admit, vec![0]);

        // Second submit — should be a dupe, no new outputs admitted
        let steak2 = engine.submit(&beef, SubmitMode::CurrentTx).await.unwrap();
        assert!(steak2["tm_test"].outputs_to_admit.is_empty());
    }

    #[tokio::test]
    async fn test_submit_notifies_lookup_service() {
        let engine = make_engine(vec![0]);
        let beef = test_tagged_beef(vec!["tm_test"]);

        engine.submit(&beef, SubmitMode::CurrentTx).await.unwrap();

        // Lookup service should have the output
        let question = LookupQuestion::new("ls_test", serde_json::json!({}));
        let answer = engine.lookup(&question, None).await.unwrap();

        match answer {
            LookupAnswer::OutputList { outputs } => {
                assert_eq!(outputs.len(), 1);
            }
            _ => panic!("Expected OutputList"),
        }
    }

    /// #289: `lookup_with_txids` returns the storage txid per hydrated
    /// output, aligned with the OutputList — the aggregated serializer
    /// writes it instead of re-hashing the BEEF.
    #[tokio::test]
    async fn test_lookup_with_txids_aligns_txids_with_outputs() {
        let engine = make_engine(vec![0]);
        let beef = test_tagged_beef(vec!["tm_test"]);
        engine.submit(&beef, SubmitMode::CurrentTx).await.unwrap();

        let question = LookupQuestion::new("ls_test", serde_json::json!({}));
        let (answer, txids) = engine.lookup_with_txids(&question, None).await.unwrap();
        match answer {
            LookupAnswer::OutputList { outputs } => {
                assert_eq!(outputs.len(), 1);
                assert_eq!(txids.len(), outputs.len(), "one txid per output");
                assert_eq!(txids[0], TEST_TXID, "the storage primary key, verbatim");
            }
            _ => panic!("Expected OutputList"),
        }
    }

    #[tokio::test]
    async fn proof_window_holds_an_aged_child_with_a_proven_parent() {
        let mut engine = make_engine(vec![0]);
        let storage = std::rc::Rc::new(MemoryStorage::new());
        engine.storage = Box::new(storage.clone());
        engine
            .submit(&test_tagged_beef(vec!["tm_test"]), SubmitMode::CurrentTx)
            .await
            .unwrap();
        assert!(beef_limits::own_proof(&test_beef(), TEST_TXID)
            .unwrap()
            .is_none());
        let question = LookupQuestion::new("ls_test", serde_json::json!({}));
        storage.advance_clock((crate::proof_window::PROOFLESS_FLAG_MS / 1000) as u64);
        assert_eq!(
            engine
                .lookup_with_txids(&question, None)
                .await
                .unwrap()
                .1
                .len(),
            1
        );
        storage.advance_clock(1);
        assert!(
            engine
                .lookup_with_txids(&question, None)
                .await
                .unwrap()
                .1
                .is_empty(),
            "an aged unproven child must be held even when its parent is proven"
        );
    }

    #[tokio::test]
    async fn proof_window_peer_proof_verifies_then_restores_lookup() {
        use crate::proof_window::{HeldOutput, PeerProofSummary, PROOFLESS_FLAG_MS};
        let mut engine = make_engine(vec![0]);
        let storage = std::rc::Rc::new(MemoryStorage::new());
        engine.storage = Box::new(storage.clone());
        engine
            .submit(&test_tagged_beef(vec!["tm_test"]), SubmitMode::CurrentTx)
            .await
            .unwrap();
        storage.advance_clock((PROOFLESS_FLAG_MS / 1000) as u64 + 1);
        let question = LookupQuestion::new("ls_test", serde_json::json!({}));
        let candidate = HeldOutput {
            txid: TEST_TXID.into(),
            output_index: 0,
            topic: "tm_test".into(),
        };
        let (_, mut remote) = budget_page_engine(1);
        remote.node_cost_ms = 0;
        remote.nodes = std::rc::Rc::new(HashMap::from([(
            TEST_TXID.into(),
            crate::types::GASPNode {
                graph_id: String::new(),
                raw_tx: String::new(),
                output_index: 0,
                proof: Some(single_leaf_bump_hex(TEST_TXID, 800_000)),
                tx_metadata: None,
                output_metadata: None,
                inputs: None,
            },
        )]));
        engine
            .config
            .sync_configuration
            .insert("tm_test".into(), SyncTarget::Ship);
        engine.ship_bootstrap_peers.insert(
            "tm_test".into(),
            vec!["https://a.example".into(), "https://b.example".into()],
        );
        engine.set_gasp_remote_factory(Box::new(remote));
        let progress = std::cell::Cell::new(PeerProofSummary::default());
        engine.chain_tracker = Some(Box::new(bsv_rs::transaction::MockChainTracker::new(
            800_001,
        )));
        engine
            .rerequest_held_proofs(std::slice::from_ref(&candidate), &progress)
            .await;
        assert_eq!(progress.get().requests, 2, "ask every topic peer");
        assert_eq!(progress.get().landed, 0);
        assert_eq!(progress.get().refused, 2);
        assert!(engine
            .lookup_with_txids(&question, None)
            .await
            .unwrap()
            .1
            .is_empty());
        let mut tracker = bsv_rs::transaction::MockChainTracker::new(800_001);
        tracker.add_root(800_000, TEST_TXID.into());
        engine.chain_tracker = Some(Box::new(tracker));
        engine.rerequest_held_proofs(&[candidate], &progress).await;
        assert_eq!(progress.get().requests, 4);
        assert_eq!(
            progress.get().landed,
            1,
            "count durable proofs, not peer answers"
        );
        let (_, txids) = engine.lookup_with_txids(&question, None).await.unwrap();
        assert_eq!(txids, vec![TEST_TXID]);
        let stored = storage
            .find_output(TEST_TXID, 0, None, None, true)
            .await
            .unwrap()
            .unwrap();
        assert!(
            beef_limits::own_proof(stored.beef.as_ref().unwrap(), TEST_TXID)
                .unwrap()
                .is_some()
        );
        assert_eq!(storage.proven_at_height(TEST_TXID), Some(Some(800_000)));
    }

    #[tokio::test]
    async fn proof_window_peer_hash_leaf_is_stored_as_own_proof() {
        use crate::proof_window::{HeldOutput, PeerProofSummary, PROOFLESS_FLAG_MS};
        let mut engine = make_engine(vec![0]);
        let storage = std::rc::Rc::new(MemoryStorage::new());
        engine.storage = Box::new(storage.clone());
        engine
            .submit(&test_tagged_beef(vec!["tm_test"]), SubmitMode::CurrentTx)
            .await
            .unwrap();
        storage.advance_clock((PROOFLESS_FLAG_MS / 1000) as u64 + 1);
        let mut proof =
            bsv_rs::transaction::MerklePath::from_hex(&single_leaf_bump_hex(TEST_TXID, 800_000))
                .unwrap();
        proof.path[0][0].txid = false;
        let mut tracker = bsv_rs::transaction::MockChainTracker::new(800_001);
        tracker.add_root(800_000, proof.compute_root(Some(TEST_TXID)).unwrap());
        engine.chain_tracker = Some(Box::new(tracker));
        let (_, mut remote) = budget_page_engine(1);
        remote.node_cost_ms = 0;
        remote.nodes = std::rc::Rc::new(HashMap::from([(
            TEST_TXID.into(),
            crate::types::GASPNode {
                graph_id: String::new(),
                raw_tx: String::new(),
                output_index: 0,
                proof: Some(proof.to_hex()),
                tx_metadata: None,
                output_metadata: None,
                inputs: None,
            },
        )]));
        engine.config.sync_configuration.insert(
            "tm_test".into(),
            SyncTarget::Peers(vec!["https://peer.example".into()]),
        );
        engine.set_gasp_remote_factory(Box::new(remote));
        let progress = std::cell::Cell::new(PeerProofSummary::default());
        engine
            .rerequest_held_proofs(
                &[HeldOutput {
                    txid: TEST_TXID.into(),
                    output_index: 0,
                    topic: "tm_test".into(),
                }],
                &progress,
            )
            .await;
        assert_eq!(progress.get().landed, 1);
        let question = LookupQuestion::new("ls_test", serde_json::json!({}));
        let (answer, txids) = engine.lookup_with_txids(&question, None).await.unwrap();
        assert_eq!(txids, vec![TEST_TXID]);
        let LookupAnswer::OutputList { outputs } = answer else {
            panic!("expected outputs")
        };
        assert!(
            beef_limits::own_proof(&outputs[0].beef, TEST_TXID)
                .unwrap()
                .is_some(),
            "a proven flag must have the child's own path in the served BEEF"
        );
    }

    #[tokio::test]
    async fn proof_window_silent_peers_yield_at_the_request_budget() {
        use crate::proof_window::{HeldOutput, PeerProofSummary, PEER_PROOF_REQUEST_MS};
        let (mut engine, remote) = budget_page_engine(1);
        engine.config.sync_configuration.insert(
            "tm_test".into(),
            SyncTarget::Peers(vec!["https://a.example".into(), "https://b.example".into()]),
        );
        let elapsed = remote.elapsed.clone();
        engine.set_peer_sync_budget(
            std::rc::Rc::new(move |ms| {
                assert_eq!(ms, PEER_PROOF_REQUEST_MS);
                let deadline = elapsed.get() + ms;
                let elapsed = elapsed.clone();
                Box::pin(std::future::poll_fn(move |_| {
                    if elapsed.get() >= deadline {
                        std::task::Poll::Ready(())
                    } else {
                        std::task::Poll::Pending
                    }
                }))
            }),
            30_000,
        );
        let candidate = HeldOutput {
            txid: remote.outputs[0].txid.clone(),
            output_index: 0,
            topic: "tm_test".into(),
        };
        engine.set_gasp_remote_factory(Box::new(remote));
        let progress = std::cell::Cell::new(PeerProofSummary::default());
        engine.rerequest_held_proofs(&[candidate], &progress).await;
        assert_eq!(progress.get().requests, 2);
        assert_eq!(progress.get().faults, 2);
        assert_eq!(progress.get().landed, 0);
    }

    /// #291: the public sync-response page size is always bounded.
    #[test]
    fn sync_limit_clamp() {
        assert_eq!(
            Engine::clamp_sync_limit(None),
            Engine::SYNC_RESPONSE_DEFAULT_LIMIT,
            "absent limit gets the default page, never unbounded"
        );
        assert_eq!(Engine::clamp_sync_limit(Some(7)), 7);
        assert_eq!(
            Engine::clamp_sync_limit(Some(u64::MAX)),
            Engine::SYNC_RESPONSE_MAX_LIMIT,
            "a huge caller-supplied limit is capped"
        );
    }

    #[tokio::test]
    async fn test_lookup_unknown_service_errors() {
        let engine = make_engine(vec![]);
        let question = LookupQuestion::new("ls_nonexistent", serde_json::json!({}));

        let result = engine.lookup(&question, None).await;
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            EngineError::LookupServiceNotFound(_)
        ));
    }

    #[tokio::test]
    async fn test_list_topic_managers() {
        let engine = make_engine(vec![]);
        let managers = engine.list_topic_managers().await;

        assert_eq!(managers.len(), 1);
        assert!(managers.contains_key("tm_test"));
        assert_eq!(managers["tm_test"].name, "mock-tm");
    }

    #[tokio::test]
    async fn test_list_lookup_service_providers() {
        let engine = make_engine(vec![]);
        let services = engine.list_lookup_service_providers().await;

        assert_eq!(services.len(), 1);
        assert!(services.contains_key("ls_test"));
        assert_eq!(services["ls_test"].name, "mock-ls");
    }

    #[tokio::test]
    async fn test_get_documentation() {
        let engine = make_engine(vec![]);

        let tm_docs = engine.get_documentation_for_topic_manager("tm_test").await;
        assert_eq!(tm_docs, "Mock topic manager");

        let ls_docs = engine.get_documentation_for_lookup_service("ls_test").await;
        assert_eq!(ls_docs, "Mock lookup service");

        let missing = engine
            .get_documentation_for_topic_manager("tm_missing")
            .await;
        assert_eq!(missing, "No documentation found!");
    }

    #[tokio::test]
    async fn test_provide_foreign_sync_response() {
        let engine = make_engine(vec![0]);

        // Submit data
        let beef = test_tagged_beef(vec!["tm_test"]);
        engine.submit(&beef, SubmitMode::CurrentTx).await.unwrap();

        // Query GASP sync
        let request = GASPInitialRequest {
            version: 1,
            since: 0,
            limit: Some(100),
        };
        let response = engine
            .provide_foreign_sync_response(&request, "tm_test")
            .await
            .unwrap();

        // One tx admitted with output index 0
        assert_eq!(response.utxo_list.len(), 1);
        assert_eq!(response.utxo_list[0].txid, TEST_TXID);
        assert_eq!(response.since, 0);
    }

    #[tokio::test]
    async fn test_delete_utxo_deep_simple() {
        let engine = make_engine(vec![0]);
        let beef = test_tagged_beef(vec!["tm_test"]);

        engine.submit(&beef, SubmitMode::CurrentTx).await.unwrap();

        let txid = TEST_TXID;
        let output = engine
            .storage()
            .find_output(txid, 0, Some("tm_test"), None, false)
            .await
            .unwrap()
            .unwrap();

        // Delete it
        engine.delete_utxo_deep(&output, None).await.unwrap();

        // Should be gone
        let found = engine
            .storage()
            .find_output(txid, 0, Some("tm_test"), None, false)
            .await
            .unwrap();
        assert!(found.is_none());
    }

    #[tokio::test]
    async fn test_sync_config_defaults_to_ship() {
        let engine = make_engine(vec![]);
        let sync = &engine.config.sync_configuration;

        // tm_test should default to SHIP sync
        assert!(sync.contains_key("tm_test"));
        assert!(matches!(sync["tm_test"], SyncTarget::Ship));
    }

    #[tokio::test]
    async fn test_multiple_topics_in_single_submit() {
        let mut managers: HashMap<String, Box<dyn TopicManagerTrait>> = HashMap::new();
        managers.insert(
            "tm_alpha".to_string(),
            Box::new(MockTopicManager::admitting(vec![0])),
        );
        managers.insert(
            "tm_beta".to_string(),
            Box::new(MockTopicManager::admitting(vec![1])),
        );

        let engine = Engine::new(
            managers,
            HashMap::new(),
            Box::new(MemoryStorage::new()),
            None,
            EngineConfig::default(),
        );

        let beef = test_tagged_beef(vec!["tm_alpha", "tm_beta"]);

        let steak = engine.submit(&beef, SubmitMode::CurrentTx).await.unwrap();

        assert_eq!(steak["tm_alpha"].outputs_to_admit, vec![0]);
        assert_eq!(steak["tm_beta"].outputs_to_admit, vec![1]);
    }

    #[tokio::test]
    async fn test_evict_output_with_topic() {
        let engine = make_engine(vec![0]);
        let beef = test_tagged_beef(vec!["tm_test"]);
        engine.submit(&beef, SubmitMode::CurrentTx).await.unwrap();

        // Output should exist
        let found = engine
            .storage()
            .find_output(TEST_TXID, 0, Some("tm_test"), None, false)
            .await
            .unwrap();
        assert!(found.is_some(), "Output should exist before eviction");

        // Evict with topic
        engine
            .evict_output(TEST_TXID, 0, Some("tm_test"))
            .await
            .unwrap();

        // Output should be gone from storage
        let found = engine
            .storage()
            .find_output(TEST_TXID, 0, Some("tm_test"), None, false)
            .await
            .unwrap();
        assert!(found.is_none(), "Output should be gone after eviction");

        // Lookup service should also have been notified (output evicted)
        let question = LookupQuestion::new("ls_test", serde_json::json!({}));
        let answer = engine.lookup(&question, None).await.unwrap();
        match answer {
            LookupAnswer::OutputList { outputs } => {
                assert!(
                    outputs.is_empty(),
                    "Lookup should return empty after eviction"
                );
            }
            _ => panic!("Expected OutputList"),
        }
    }

    #[tokio::test]
    async fn test_evict_output_without_topic() {
        let engine = make_engine(vec![0]);
        let beef = test_tagged_beef(vec!["tm_test"]);
        engine.submit(&beef, SubmitMode::CurrentTx).await.unwrap();

        // Evict without topic — should find and remove across all topics
        engine.evict_output(TEST_TXID, 0, None).await.unwrap();

        let found = engine
            .storage()
            .find_output(TEST_TXID, 0, Some("tm_test"), None, false)
            .await
            .unwrap();
        assert!(
            found.is_none(),
            "Output should be gone after topic-less eviction"
        );
    }

    #[tokio::test]
    async fn test_evict_nonexistent_output_is_ok() {
        let engine = make_engine(vec![]);

        // Evicting something that doesn't exist should not error
        let result = engine
            .evict_output("nonexistent_txid", 99, Some("tm_test"))
            .await;
        assert!(result.is_ok(), "Evicting nonexistent output should succeed");
    }

    // ── Mock Broadcaster ──────────────────────────────────────────────

    use crate::broadcaster::Broadcaster;
    use std::sync::Arc;

    type BroadcastCallLog = Arc<Mutex<Vec<(String, Vec<String>)>>>;

    struct MockBroadcaster {
        calls: BroadcastCallLog,
    }

    impl MockBroadcaster {
        fn new() -> Self {
            Self {
                calls: Arc::new(Mutex::new(Vec::new())),
            }
        }

        #[allow(dead_code, reason = "kept for future test extension")]
        fn call_count(&self) -> usize {
            self.calls.lock().unwrap().len()
        }

        #[allow(dead_code, reason = "kept for future test extension")]
        fn calls(&self) -> Vec<(String, Vec<String>)> {
            self.calls.lock().unwrap().clone()
        }
    }

    #[async_trait(?Send)]
    impl Broadcaster for MockBroadcaster {
        async fn broadcast_to_host(
            &self,
            host_url: &str,
            tagged_beef: &TaggedBEEF,
        ) -> Result<(), String> {
            self.calls
                .lock()
                .unwrap()
                .push((host_url.to_string(), tagged_beef.topics.clone()));
            Ok(())
        }
    }

    // ── Mock SHIP LookupService ─────────────────────────────────────

    /// A mock "ls_ship" lookup service that returns pre-configured UTXOReferences
    /// when queried. Used to test SHIP propagation without depending on
    /// overlay-discovery in the engine crate's unit tests.
    struct MockSHIPLookupService {
        /// Maps topic -> list of (txid, output_index) references
        records: Mutex<HashMap<String, Vec<UTXOReference>>>,
    }

    impl MockSHIPLookupService {
        fn with_records(records: HashMap<String, Vec<UTXOReference>>) -> Self {
            Self {
                records: Mutex::new(records),
            }
        }
    }

    #[async_trait(?Send)]
    impl LookupServiceTrait for MockSHIPLookupService {
        fn admission_mode(&self) -> AdmissionMode {
            AdmissionMode::LockingScript
        }

        fn spend_notification_mode(&self) -> SpendNotificationMode {
            SpendNotificationMode::None
        }

        async fn output_admitted_by_topic(
            &self,
            _payload: &OutputAdmittedByTopic,
        ) -> Result<(), LookupServiceError> {
            Ok(())
        }

        async fn output_evicted(
            &self,
            _txid: &str,
            _output_index: u32,
        ) -> Result<(), LookupServiceError> {
            Ok(())
        }

        async fn lookup(
            &self,
            question: &LookupQuestion,
        ) -> Result<LookupResult, LookupServiceError> {
            // Parse the topics from the query
            if let Some(topics) = question.query.get("topics").and_then(|v| v.as_array()) {
                let records = self.records.lock().unwrap();
                let mut results = Vec::new();
                for topic_val in topics {
                    if let Some(topic) = topic_val.as_str() {
                        if let Some(refs) = records.get(topic) {
                            results.extend(refs.iter().cloned());
                        }
                    }
                }
                return Ok(LookupResult::OutputList(results));
            }
            Ok(LookupResult::OutputList(vec![]))
        }

        async fn get_documentation(&self) -> String {
            "Mock SHIP lookup service".to_string()
        }

        async fn get_metadata(&self) -> ServiceMetadata {
            ServiceMetadata {
                name: "mock-ls-ship".to_string(),
                ..Default::default()
            }
        }
    }

    /// Build a minimal PushDrop locking script for a SHIP advertisement.
    fn build_ship_pushdrop_script(domain: &str, topic: &str) -> Vec<u8> {
        use bsv_rs::script::templates::PushDrop;
        use bsv_rs::PublicKey;

        let fields = vec![
            b"SHIP".to_vec(),
            vec![0x02; 33], // fake compressed pubkey bytes for identity_key field
            domain.as_bytes().to_vec(),
            topic.as_bytes().to_vec(),
        ];

        // PushDrop requires a real compressed public key for the locking script
        // Use a well-known test key (generator point G)
        let pubkey = PublicKey::from_hex(
            "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
        )
        .expect("valid test pubkey");

        let pd = PushDrop::new(pubkey, fields);
        pd.lock().to_binary()
    }

    /// Create engine with a broadcaster and a mock SHIP lookup service.
    /// The `ship_domains` parameter provides (domain, topic) pairs to pre-populate.
    async fn make_engine_with_broadcaster(
        admit_indices: Vec<u32>,
        broadcaster: MockBroadcaster,
        ship_domains: Vec<(&str, &str)>,
        hosting_url: Option<&str>,
    ) -> (Engine, Arc<Mutex<Vec<(String, Vec<String>)>>>) {
        let calls = broadcaster.calls.clone();

        let mut managers: HashMap<String, Box<dyn TopicManagerTrait>> = HashMap::new();
        managers.insert(
            "tm_test".to_string(),
            Box::new(MockTopicManager::admitting(admit_indices)),
        );

        let storage = Box::new(MemoryStorage::new());

        // Build SHIP records: map each topic to its UTXO references and
        // store outputs in storage with PushDrop scripts so the engine can
        // parse the domain when broadcasting.
        let mut ship_records: HashMap<String, Vec<UTXOReference>> = HashMap::new();

        for (domain, topic) in &ship_domains {
            // Deterministic fake txid per domain+topic
            let fake_txid = format!("{:064x}", {
                let mut h: u64 = 0;
                for b in domain.bytes().chain(topic.bytes()) {
                    h = h.wrapping_mul(31).wrapping_add(u64::from(b));
                }
                h
            });

            // Add to SHIP records for the mock lookup service
            ship_records
                .entry(topic.to_string())
                .or_default()
                .push(UTXOReference {
                    txid: fake_txid.clone(),
                    output_index: 0,
                });

            // Build PushDrop SHIP script and store as an output in main storage
            let script = build_ship_pushdrop_script(domain, topic);

            let output = Output {
                txid: fake_txid,
                output_index: 0,
                output_script: script,
                satoshis: 1,
                topic: "tm_ship".to_string(),
                spent: false,
                outputs_consumed: vec![],
                consumed_by: vec![],
                beef: None,
                block_height: None,
                score: None,
            };

            storage.insert_output(&output).await.unwrap();
        }

        let mut lookup_services: HashMap<String, Box<dyn LookupServiceTrait>> = HashMap::new();
        lookup_services.insert("ls_test".to_string(), Box::new(MockLookupService::new()));
        lookup_services.insert(
            "ls_ship".to_string(),
            Box::new(MockSHIPLookupService::with_records(ship_records)),
        );

        let config = EngineConfig {
            hosting_url: hosting_url.map(str::to_string),
            ..Default::default()
        };

        let engine = Engine::with_chain_tracker(
            managers,
            lookup_services,
            storage,
            None,
            Some(Box::new(broadcaster)),
            None,
            config,
        );

        (engine, calls)
    }

    // ── Broadcaster Tests ─────────────────────────────────────────────

    #[tokio::test]
    async fn test_broadcaster_called_on_current_tx_with_ship_peers() {
        let broadcaster = MockBroadcaster::new();
        let (engine, calls) = make_engine_with_broadcaster(
            vec![0],
            broadcaster,
            vec![("https://peer1.example.com", "tm_test")],
            Some("https://self.example.com"),
        )
        .await;

        let beef = test_tagged_beef(vec!["tm_test"]);
        let steak = engine.submit(&beef, SubmitMode::CurrentTx).await.unwrap();

        // Submit should succeed
        assert!(!steak["tm_test"].outputs_to_admit.is_empty());

        // Broadcaster should have been called for peer1
        let recorded = calls.lock().unwrap();
        assert_eq!(
            recorded.len(),
            1,
            "Broadcaster should be called once for the one SHIP peer"
        );
        assert_eq!(recorded[0].0, "https://peer1.example.com");
    }

    #[tokio::test]
    async fn test_broadcaster_not_called_on_historical_tx() {
        let broadcaster = MockBroadcaster::new();
        let (engine, calls) = make_engine_with_broadcaster(
            vec![0],
            broadcaster,
            vec![("https://peer1.example.com", "tm_test")],
            None,
        )
        .await;

        let beef = test_tagged_beef(vec!["tm_test"]);
        let steak = engine
            .submit(&beef, SubmitMode::HistoricalTx)
            .await
            .unwrap();

        assert!(!steak["tm_test"].outputs_to_admit.is_empty());

        // Broadcaster should NOT have been called
        assert_eq!(
            calls.lock().unwrap().len(),
            0,
            "Broadcaster should not be called for historical TX"
        );
    }

    #[tokio::test]
    async fn test_broadcaster_not_called_on_historical_tx_no_spv() {
        let broadcaster = MockBroadcaster::new();
        let (engine, calls) = make_engine_with_broadcaster(
            vec![0],
            broadcaster,
            vec![("https://peer1.example.com", "tm_test")],
            None,
        )
        .await;

        let beef = test_tagged_beef(vec!["tm_test"]);
        let steak = engine
            .submit(&beef, SubmitMode::HistoricalTxNoSpv)
            .await
            .unwrap();

        assert!(!steak["tm_test"].outputs_to_admit.is_empty());

        assert_eq!(
            calls.lock().unwrap().len(),
            0,
            "Broadcaster should not be called for historical-tx-no-spv"
        );
    }

    #[tokio::test]
    async fn test_broadcaster_skips_self_hosting_url() {
        let broadcaster = MockBroadcaster::new();
        let (engine, calls) = make_engine_with_broadcaster(
            vec![0],
            broadcaster,
            vec![
                ("https://self.example.com", "tm_test"),
                ("https://peer2.example.com", "tm_test"),
            ],
            Some("https://self.example.com"),
        )
        .await;

        let beef = test_tagged_beef(vec!["tm_test"]);
        engine.submit(&beef, SubmitMode::CurrentTx).await.unwrap();

        // Should only broadcast to peer2, not to self
        let recorded = calls.lock().unwrap();
        assert_eq!(
            recorded.len(),
            1,
            "Should broadcast to peer2 only, skipping self"
        );
        assert_eq!(recorded[0].0, "https://peer2.example.com");
    }

    #[tokio::test]
    async fn test_broadcaster_not_called_when_no_outputs_admitted() {
        let broadcaster = MockBroadcaster::new();
        // Topic manager admits nothing
        let (engine, calls) = make_engine_with_broadcaster(
            vec![],
            broadcaster,
            vec![("https://peer1.example.com", "tm_test")],
            None,
        )
        .await;

        let beef = test_tagged_beef(vec!["tm_test"]);
        let steak = engine.submit(&beef, SubmitMode::CurrentTx).await.unwrap();

        assert!(steak["tm_test"].outputs_to_admit.is_empty());

        // No outputs admitted -> no broadcast
        assert_eq!(
            calls.lock().unwrap().len(),
            0,
            "Broadcaster should not be called when no outputs are admitted"
        );
    }

    #[tokio::test]
    async fn test_broadcaster_not_called_when_no_ship_peers() {
        let broadcaster = MockBroadcaster::new();
        // No SHIP peers registered
        let (engine, calls) = make_engine_with_broadcaster(
            vec![0],
            broadcaster,
            vec![], // no SHIP peers
            None,
        )
        .await;

        let beef = test_tagged_beef(vec!["tm_test"]);
        engine.submit(&beef, SubmitMode::CurrentTx).await.unwrap();

        assert_eq!(
            calls.lock().unwrap().len(),
            0,
            "Broadcaster should not be called when no SHIP peers exist"
        );
    }

    // ── Configurable SpendNotification mock ─────────────────────────────

    /// A mock lookup service whose SpendNotificationMode can be configured.
    /// Uses a shared Arc<Mutex<Vec<OutputSpent>>> so the caller can inspect
    /// captured payloads after submit().
    struct SpendModeLookupService {
        mode: SpendNotificationMode,
        records: Mutex<Vec<UTXOReference>>,
        spent_payloads: Arc<Mutex<Vec<OutputSpent>>>,
    }

    impl SpendModeLookupService {
        fn with_mode(mode: SpendNotificationMode, capture: Arc<Mutex<Vec<OutputSpent>>>) -> Self {
            Self {
                mode,
                records: Mutex::new(Vec::new()),
                spent_payloads: capture,
            }
        }
    }

    #[async_trait(?Send)]
    impl LookupServiceTrait for SpendModeLookupService {
        fn admission_mode(&self) -> AdmissionMode {
            AdmissionMode::LockingScript
        }

        fn spend_notification_mode(&self) -> SpendNotificationMode {
            self.mode
        }

        async fn output_admitted_by_topic(
            &self,
            payload: &OutputAdmittedByTopic,
        ) -> Result<(), LookupServiceError> {
            let (txid, oi) = match payload {
                OutputAdmittedByTopic::LockingScript {
                    txid, output_index, ..
                } => (txid.clone(), *output_index),
                OutputAdmittedByTopic::WholeTx { output_index, .. } => {
                    ("whole".into(), *output_index)
                }
            };
            self.records.lock().unwrap().push(UTXOReference {
                txid,
                output_index: oi,
            });
            Ok(())
        }

        async fn output_spent(&self, payload: &OutputSpent) -> Result<(), LookupServiceError> {
            self.spent_payloads.lock().unwrap().push(payload.clone());
            Ok(())
        }

        async fn output_evicted(
            &self,
            txid: &str,
            output_index: u32,
        ) -> Result<(), LookupServiceError> {
            self.records
                .lock()
                .unwrap()
                .retain(|r| !(r.txid == txid && r.output_index == output_index));
            Ok(())
        }

        async fn lookup(
            &self,
            _question: &LookupQuestion,
        ) -> Result<LookupResult, LookupServiceError> {
            Ok(LookupResult::OutputList(
                self.records.lock().unwrap().clone(),
            ))
        }

        async fn get_documentation(&self) -> String {
            "SpendMode mock lookup service".to_string()
        }

        async fn get_metadata(&self) -> ServiceMetadata {
            ServiceMetadata {
                name: "spend-mode-ls".to_string(),
                ..Default::default()
            }
        }
    }

    /// TXID of the input's source transaction in TEST_BEEF_HEX (the "previous coin").
    const PREVIOUS_TXID: &str = "3ecead27a44d013ad1aae40038acbb1883ac9242406808bb4667c15b4f164eac";

    /// Build an engine with a pre-populated previous output and a SpendModeLookupService.
    /// Returns the engine and the shared capture vec for inspecting OutputSpent payloads.
    async fn make_spend_mode_engine(
        mode: SpendNotificationMode,
    ) -> (Engine, Arc<Mutex<Vec<OutputSpent>>>) {
        let storage = MemoryStorage::new();

        // Pre-populate storage with the previous output that TEST_BEEF_HEX's input spends.
        let prev_output = Output {
            txid: PREVIOUS_TXID.to_string(),
            output_index: 0,
            output_script: vec![0x76, 0xa9],
            satoshis: 26174,
            topic: "tm_test".to_string(),
            spent: false,
            outputs_consumed: vec![],
            consumed_by: vec![],
            beef: Some(test_beef()),
            block_height: None,
            score: Some(1000.0),
        };
        storage.insert_output(&prev_output).await.unwrap();

        let mut managers: HashMap<String, Box<dyn TopicManagerTrait>> = HashMap::new();
        managers.insert(
            "tm_test".to_string(),
            Box::new(MockTopicManager::admitting(vec![0])),
        );

        let capture: Arc<Mutex<Vec<OutputSpent>>> = Arc::new(Mutex::new(Vec::new()));
        let ls = SpendModeLookupService::with_mode(mode, capture.clone());
        let mut lookup_services: HashMap<String, Box<dyn LookupServiceTrait>> = HashMap::new();
        lookup_services.insert("ls_test".to_string(), Box::new(ls));

        let engine = Engine::new(
            managers,
            lookup_services,
            Box::new(storage),
            None,
            EngineConfig::default(),
        );

        (engine, capture)
    }

    #[tokio::test]
    async fn test_spend_notification_mode_script() {
        let (engine, capture) = make_spend_mode_engine(SpendNotificationMode::Script).await;

        let beef = test_tagged_beef(vec!["tm_test"]);
        let steak = engine.submit(&beef, SubmitMode::CurrentTx).await.unwrap();

        // The new output should be admitted
        assert_eq!(steak["tm_test"].outputs_to_admit, vec![0]);

        // The lookup service should have received a Script spend notification
        let payloads = capture.lock().unwrap().clone();
        assert_eq!(payloads.len(), 1, "Expected exactly one spend notification");

        match &payloads[0] {
            OutputSpent::Script {
                txid,
                output_index,
                topic,
                spending_txid,
                input_index,
                unlocking_script,
                sequence_number,
                ..
            } => {
                assert_eq!(txid, PREVIOUS_TXID);
                assert_eq!(*output_index, 0);
                assert_eq!(topic, "tm_test");
                assert_eq!(spending_txid, TEST_TXID);
                // The BEEF has a single input at index 0 that spends PREVIOUS_TXID:0
                assert_eq!(*input_index, 0);
                // The unlocking script should be non-empty (it's a P2PKH scriptSig)
                assert!(
                    !unlocking_script.is_empty(),
                    "Unlocking script should be non-empty"
                );
                // Standard final sequence number
                assert_eq!(*sequence_number, 0xffff_ffff);
            }
            other => panic!("Expected OutputSpent::Script, got: {other:?}"),
        }
    }

    #[tokio::test]
    async fn test_spend_notification_mode_whole_tx() {
        let (engine, capture) = make_spend_mode_engine(SpendNotificationMode::WholeTx).await;

        let beef = test_tagged_beef(vec!["tm_test"]);
        let steak = engine.submit(&beef, SubmitMode::CurrentTx).await.unwrap();

        assert_eq!(steak["tm_test"].outputs_to_admit, vec![0]);

        let payloads = capture.lock().unwrap().clone();
        assert_eq!(payloads.len(), 1, "Expected exactly one spend notification");

        match &payloads[0] {
            OutputSpent::WholeTx {
                txid,
                output_index,
                topic,
                spending_atomic_beef,
                ..
            } => {
                assert_eq!(txid, PREVIOUS_TXID);
                assert_eq!(*output_index, 0);
                assert_eq!(topic, "tm_test");
                // The spending BEEF is the entire BEEF we submitted, NAMED
                // (atomic prefix) for the lookup service's own re-parse.
                let mut named =
                    bsv_rs::transaction::Beef::from_binary(spending_atomic_beef).unwrap();
                assert!(named.is_atomic());
                let submitted = bsv_rs::transaction::Beef::from_binary(&test_beef()).unwrap();
                assert_eq!(
                    named.txs.len(),
                    submitted.txs.len(),
                    "the whole body, never pruned"
                );
                let tip = crate::subject::subject_txid_of(&mut named).unwrap();
                assert_eq!(named.atomic_txid.as_deref(), Some(tip.as_str()));
            }
            other => panic!("Expected OutputSpent::WholeTx, got: {other:?}"),
        }
    }

    #[tokio::test]
    async fn test_spend_notification_mode_txid() {
        let (engine, capture) = make_spend_mode_engine(SpendNotificationMode::Txid).await;

        let beef = test_tagged_beef(vec!["tm_test"]);
        let steak = engine.submit(&beef, SubmitMode::CurrentTx).await.unwrap();

        assert_eq!(steak["tm_test"].outputs_to_admit, vec![0]);

        let payloads = capture.lock().unwrap().clone();
        assert_eq!(payloads.len(), 1, "Expected exactly one spend notification");

        match &payloads[0] {
            OutputSpent::Txid {
                txid,
                output_index,
                topic,
                spending_txid,
            } => {
                assert_eq!(txid, PREVIOUS_TXID);
                assert_eq!(*output_index, 0);
                assert_eq!(topic, "tm_test");
                assert_eq!(spending_txid, TEST_TXID);
            }
            other => panic!("Expected OutputSpent::Txid, got: {other:?}"),
        }
    }

    #[tokio::test]
    async fn test_spend_notification_mode_none() {
        let (engine, capture) = make_spend_mode_engine(SpendNotificationMode::None).await;

        let beef = test_tagged_beef(vec!["tm_test"]);
        let steak = engine.submit(&beef, SubmitMode::CurrentTx).await.unwrap();

        assert_eq!(steak["tm_test"].outputs_to_admit, vec![0]);

        let payloads = capture.lock().unwrap().clone();
        assert_eq!(payloads.len(), 1, "Expected exactly one spend notification");

        match &payloads[0] {
            OutputSpent::None {
                txid,
                output_index,
                topic,
            } => {
                assert_eq!(txid, PREVIOUS_TXID);
                assert_eq!(*output_index, 0);
                assert_eq!(topic, "tm_test");
            }
            other => panic!("Expected OutputSpent::None, got: {other:?}"),
        }
    }

    // ── GASP Sync Tests ───────────────────────────────────────────────

    #[tokio::test]
    async fn test_start_gasp_sync_empty_config() {
        let engine = Engine::new(
            HashMap::new(),
            HashMap::new(),
            Box::new(MemoryStorage::new()),
            None,
            EngineConfig {
                sync_configuration: HashMap::new(),
                ..Default::default()
            },
        );

        let result = engine.start_gasp_sync().await.unwrap();
        assert!(
            result.topics_synced.is_empty(),
            "No topics should be synced with empty config"
        );
    }

    #[tokio::test]
    async fn test_start_gasp_sync_disabled_topic_skipped() {
        let mut sync_config: SyncConfiguration = HashMap::new();
        sync_config.insert("tm_test".to_string(), SyncTarget::Disabled);

        let engine = Engine::new(
            HashMap::new(),
            HashMap::new(),
            Box::new(MemoryStorage::new()),
            None,
            EngineConfig {
                sync_configuration: sync_config,
                ..Default::default()
            },
        );

        let result = engine.start_gasp_sync().await.unwrap();
        assert!(
            result.topics_synced.is_empty(),
            "Disabled topics should not appear in results"
        );
    }

    #[tokio::test]
    async fn test_start_gasp_sync_peers_config() {
        let mut sync_config: SyncConfiguration = HashMap::new();
        sync_config.insert(
            "tm_test".to_string(),
            SyncTarget::Peers(vec![
                "https://peer1.example.com".to_string(),
                "https://peer2.example.com".to_string(),
            ]),
        );

        let engine = Engine::new(
            HashMap::new(),
            HashMap::new(),
            Box::new(MemoryStorage::new()),
            None,
            EngineConfig {
                sync_configuration: sync_config,
                ..Default::default()
            },
        );

        let result = engine.start_gasp_sync().await.unwrap();
        assert_eq!(result.topics_synced.len(), 1);

        let topic_result = &result.topics_synced["tm_test"];
        assert_eq!(topic_result.peers.len(), 2);
        assert_eq!(topic_result.sync_type, "peers");
        assert!(topic_result.errors.is_empty());
    }

    #[tokio::test]
    async fn test_start_gasp_sync_peers_filters_self() {
        let mut sync_config: SyncConfiguration = HashMap::new();
        sync_config.insert(
            "tm_test".to_string(),
            SyncTarget::Peers(vec![
                "https://self.example.com".to_string(),
                "https://peer2.example.com".to_string(),
            ]),
        );

        let engine = Engine::new(
            HashMap::new(),
            HashMap::new(),
            Box::new(MemoryStorage::new()),
            None,
            EngineConfig {
                hosting_url: Some("https://self.example.com".to_string()),
                sync_configuration: sync_config,
                ..Default::default()
            },
        );

        let result = engine.start_gasp_sync().await.unwrap();
        let topic_result = &result.topics_synced["tm_test"];
        assert_eq!(
            topic_result.peers.len(),
            1,
            "Self URL should be filtered out"
        );
        assert_eq!(topic_result.peers[0], "https://peer2.example.com");
    }

    #[derive(Clone, Default)]
    struct MockShipLookupClient {
        records: HashMap<(String, String), Vec<OutputListItem>>,
        failures: HashSet<String>,
        calls: std::rc::Rc<std::cell::RefCell<Vec<(String, LookupQuestion)>>>,
    }

    struct RecordingDiscoverySyncFactory {
        calls: std::rc::Rc<std::cell::RefCell<Vec<(String, String)>>>,
    }

    impl crate::gasp::GASPRemoteFactory for RecordingDiscoverySyncFactory {
        fn create_remote(&self, peer: &str, topic: &str) -> Box<dyn crate::gasp::GASPRemote> {
            self.calls
                .borrow_mut()
                .push((peer.to_string(), topic.to_string()));
            Box::new(MockSyncRemote { utxos: Vec::new() })
        }
    }

    #[async_trait(?Send)]
    impl crate::ship_lookup::ShipLookupClient for MockShipLookupClient {
        async fn lookup(
            &self,
            host: &str,
            question: &LookupQuestion,
        ) -> Result<Vec<OutputListItem>, String> {
            self.calls
                .borrow_mut()
                .push((host.to_string(), question.clone()));
            if self.failures.contains(host) {
                return Err("mock tracker unavailable".to_string());
            }
            Ok(self
                .records
                .get(&(host.to_string(), question.service.clone()))
                .cloned()
                .unwrap_or_default())
        }
    }

    fn discovery_output(protocol: &str, domain: &str, scope: &str) -> OutputListItem {
        use bsv_rs::script::templates::PushDrop;
        let pubkey = bsv_rs::PublicKey::from_hex(
            "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
        )
        .unwrap();
        let script = PushDrop::new(
            pubkey,
            vec![
                protocol.as_bytes().to_vec(),
                vec![0x02; 33],
                domain.as_bytes().to_vec(),
                scope.as_bytes().to_vec(),
            ],
        )
        .lock();
        let mut tx = Transaction::from_beef(&test_beef(), None).unwrap();
        tx.outputs[0].locking_script = script;
        tx.merkle_path = None;
        tx.invalidate_caches();
        let beef = tx.to_atomic_beef(true).unwrap();
        let parsed =
            beef_limits::transaction_from_beef(&beef, None, &beef_limits::PEER_BEEF_LIMITS)
                .unwrap();
        assert_eq!(
            parsed.outputs[0].locking_script,
            tx.outputs[0].locking_script
        );
        OutputListItem {
            beef,
            output_index: 0,
            context: None,
        }
    }

    #[tokio::test]
    async fn ship_network_discovery_unions_local_trackers_and_slap_hosts_by_origin() {
        let (mut engine, _) = make_engine_with_broadcaster(
            vec![0],
            MockBroadcaster::new(),
            vec![
                ("https://local.example", "tm_test"),
                ("https://shared.example/?local", "tm_test"),
            ],
            Some("https://self.example"),
        )
        .await;
        engine.config.slap_trackers = vec!["https://tracker.example".to_string()];
        engine.set_ship_bootstrap_peers("tm_test", vec!["https://bootstrap.example".to_string()]);
        let mut client = MockShipLookupClient::default();
        client.records.insert(
            ("https://tracker.example".to_string(), "ls_ship".to_string()),
            vec![
                discovery_output("SHIP", "https://direct.example", "tm_test"),
                discovery_output("SHIP", "https://SHARED.example:443/path", "tm_test"),
                discovery_output("SHIP", "http://SELF.example.:8443/?x#y", "tm_test"),
                discovery_output("SLAP", "https://wrong-protocol.example", "tm_test"),
                discovery_output("SHIP", "https://wrong-topic.example", "tm_other"),
                OutputListItem {
                    beef: vec![1, 2, 3],
                    output_index: 0,
                    context: None,
                },
            ],
        );
        client.records.insert(
            ("https://tracker.example".to_string(), "ls_slap".to_string()),
            vec![
                discovery_output("SLAP", "https://lookup.example", "ls_ship"),
                discovery_output("SLAP", "https://LOOKUP.example:443/path", "ls_ship"),
                discovery_output("SLAP", "https://self.example/?slap", "ls_ship"),
                discovery_output("SLAP", "https://tracker.example/path", "ls_ship"),
                discovery_output("SLAP", "https://other-service.example", "ls_other"),
            ],
        );
        client.records.insert(
            ("https://lookup.example".to_string(), "ls_ship".to_string()),
            vec![
                discovery_output("SHIP", "https://indirect.example", "tm_test"),
                discovery_output("SHIP", "https://self.example:443/#ship", "tm_test"),
            ],
        );
        let calls = client.calls.clone();
        engine.set_ship_lookup_client(Box::new(client));
        let result = engine.start_gasp_sync().await.unwrap();
        assert_eq!(
            result.topics_synced["tm_test"].peers,
            vec![
                "https://bootstrap.example",
                "https://direct.example",
                "https://indirect.example",
                "https://local.example",
                "https://shared.example",
            ]
        );
        let calls = calls.borrow();
        assert_eq!(calls.len(), 3);
        for (_, question) in calls.iter() {
            let expected = if question.service == "ls_slap" {
                serde_json::json!({"service": "ls_ship"})
            } else {
                serde_json::json!({"topics": ["tm_test"]})
            };
            assert_eq!(question.query, expected);
        }
    }

    #[tokio::test]
    async fn ship_network_discovery_empty_local_finds_all_advertised_peers() {
        let (mut engine, _) =
            make_engine_with_broadcaster(vec![0], MockBroadcaster::new(), vec![], None).await;
        engine.config.slap_trackers = vec!["https://tracker.example".to_string()];
        let mut client = MockShipLookupClient::default();
        let outputs = (0..9)
            .map(|n| discovery_output("SHIP", &format!("https://peer{n}.example"), "tm_test"))
            .collect();
        client.records.insert(
            ("https://tracker.example".to_string(), "ls_ship".to_string()),
            outputs,
        );
        engine.set_ship_lookup_client(Box::new(client));
        let sync_calls = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
        engine.set_gasp_remote_factory(Box::new(RecordingDiscoverySyncFactory {
            calls: sync_calls.clone(),
        }));
        let result = engine.start_gasp_sync().await.unwrap();
        let topic = &result.topics_synced["tm_test"];
        assert_eq!(topic.sync_type, "ship");
        assert_eq!(
            topic.peers.len(),
            9,
            "the lookup-host cap must not truncate sync peers"
        );
        assert!(topic.errors.is_empty());
        assert_eq!(sync_calls.borrow().len(), 9);
        for peer in &topic.peers {
            assert!(sync_calls
                .borrow()
                .contains(&(peer.clone(), "tm_test".to_string())));
        }
    }

    #[tokio::test]
    async fn ship_network_discovery_tracker_failure_preserves_other_answers() {
        let mut engine = make_engine(vec![]);
        engine.config.slap_trackers = vec![
            "https://dead.example".to_string(),
            "https://live.example".to_string(),
        ];
        let mut client = MockShipLookupClient::default();
        client.failures.insert("https://dead.example".to_string());
        client.records.insert(
            ("https://live.example".to_string(), "ls_ship".to_string()),
            vec![discovery_output("SHIP", "https://peer.example", "tm_test")],
        );
        engine.set_ship_lookup_client(Box::new(client));
        let result = engine.start_gasp_sync().await.unwrap();
        assert_eq!(
            result.topics_synced["tm_test"].peers,
            vec!["https://peer.example"]
        );
    }

    #[tokio::test]
    async fn ship_network_discovery_provider_cap_is_shared_across_topics() {
        use crate::ship_lookup::SHIP_DISCOVERY_MAX_HOSTS_PER_TICK;
        let mut engine = make_engine(vec![]);
        engine
            .config
            .sync_configuration
            .insert("tm_other".to_string(), SyncTarget::Ship);
        engine.config.slap_trackers = vec!["https://tracker.example".to_string()];
        let mut client = MockShipLookupClient::default();
        let mut providers = Vec::new();
        for n in 0..SHIP_DISCOVERY_MAX_HOSTS_PER_TICK + 3 {
            let host = format!("https://lookup{n}.example");
            providers.push(discovery_output("SLAP", &host, "ls_ship"));
            client.records.insert(
                (host, "ls_ship".to_string()),
                vec![
                    discovery_output("SHIP", &format!("https://peer{n}.example"), "tm_test"),
                    discovery_output("SHIP", &format!("https://other{n}.example"), "tm_other"),
                ],
            );
        }
        client.records.insert(
            ("https://tracker.example".to_string(), "ls_slap".to_string()),
            providers,
        );
        let calls = client.calls.clone();
        engine.set_ship_lookup_client(Box::new(client));
        let result = engine.start_gasp_sync().await.unwrap();
        assert_eq!(
            result.topics_synced["tm_test"].peers.len(),
            SHIP_DISCOVERY_MAX_HOSTS_PER_TICK
        );
        assert_eq!(
            result.topics_synced["tm_other"].peers.len(),
            SHIP_DISCOVERY_MAX_HOSTS_PER_TICK
        );
        let calls = calls.borrow();
        assert_eq!(
            calls.iter().filter(|(_, q)| q.service == "ls_slap").count(),
            1
        );
        let providers: HashSet<_> = calls
            .iter()
            .filter(|(h, q)| h != "https://tracker.example" && q.service == "ls_ship")
            .map(|(h, _)| h)
            .collect();
        assert_eq!(providers.len(), SHIP_DISCOVERY_MAX_HOSTS_PER_TICK);
        assert_eq!(calls.len(), 1 + 2 * (1 + SHIP_DISCOVERY_MAX_HOSTS_PER_TICK));
    }

    #[tokio::test]
    async fn ship_network_discovery_outage_keeps_bootstrap_and_excludes_self() {
        let mut engine = make_engine(vec![]);
        engine.config.hosting_url = Some("https://self.example".to_string());
        engine.config.slap_trackers = vec!["https://dead.example".to_string()];
        let mut client = MockShipLookupClient::default();
        client.failures.insert("https://dead.example".to_string());
        engine.set_ship_lookup_client(Box::new(client));
        engine.set_ship_bootstrap_peers(
            "tm_test",
            vec![
                "https://bootstrap.example".to_string(),
                "https://BOOTSTRAP.example.:443/?x".to_string(),
                "http://SELF.example.:8443/path".to_string(),
            ],
        );
        let result = engine.start_gasp_sync().await.unwrap();
        assert_eq!(
            result.topics_synced["tm_test"].peers,
            vec!["https://bootstrap.example"]
        );
    }

    #[tokio::test]
    async fn ship_network_discovery_bootstrap_topic_runs_before_tracker_import() {
        let mut engine = make_engine(vec![]);
        for topic in ["tm_ship", "tm_slap"] {
            engine.config.sync_configuration.insert(
                topic.to_string(),
                SyncTarget::Peers(vec!["https://tracker.example".to_string()]),
            );
        }
        engine.config.slap_trackers = vec!["https://tracker.example".to_string()];
        let mut client = MockShipLookupClient::default();
        client.records.insert(
            ("https://tracker.example".to_string(), "ls_ship".to_string()),
            vec![discovery_output(
                "SHIP",
                "https://discovered.example",
                "tm_test",
            )],
        );
        let lookups = client.calls.clone();
        engine.set_ship_lookup_client(Box::new(client));
        engine.set_ship_bootstrap_peers("tm_test", vec!["https://bootstrap.example".to_string()]);
        let calls = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
        engine.set_gasp_remote_factory(Box::new(RecordingDiscoverySyncFactory {
            calls: calls.clone(),
        }));
        engine.start_gasp_sync().await.unwrap();
        assert_eq!(
            calls
                .borrow()
                .iter()
                .map(|(_, topic)| topic.as_str())
                .collect::<Vec<_>>(),
            vec!["tm_test", "tm_test", "tm_ship", "tm_slap"]
        );
        assert_eq!(lookups.borrow().len(), 2);
    }

    #[tokio::test]
    async fn test_start_gasp_sync_ship_discovers_peers() {
        let broadcaster = MockBroadcaster::new();
        let (engine, _calls) = make_engine_with_broadcaster(
            vec![0],
            broadcaster,
            vec![
                ("https://peer1.example.com", "tm_test"),
                ("https://peer2.example.com", "tm_test"),
            ],
            Some("https://self.example.com"),
        )
        .await;

        let result = engine.start_gasp_sync().await.unwrap();
        assert!(
            result.topics_synced.contains_key("tm_test"),
            "tm_test should be in sync results"
        );

        let topic_result = &result.topics_synced["tm_test"];
        assert_eq!(topic_result.sync_type, "ship");
        assert_eq!(
            topic_result.peers.len(),
            2,
            "Should discover both SHIP peers"
        );
        assert!(topic_result
            .peers
            .contains(&"https://peer1.example.com".to_string()));
        assert!(topic_result
            .peers
            .contains(&"https://peer2.example.com".to_string()));
    }

    #[tokio::test]
    async fn test_start_gasp_sync_ship_filters_self() {
        let broadcaster = MockBroadcaster::new();
        let (engine, _calls) = make_engine_with_broadcaster(
            vec![0],
            broadcaster,
            vec![
                ("https://self.example.com", "tm_test"),
                ("https://peer2.example.com", "tm_test"),
            ],
            Some("https://self.example.com"),
        )
        .await;

        let result = engine.start_gasp_sync().await.unwrap();
        let topic_result = &result.topics_synced["tm_test"];
        assert_eq!(
            topic_result.peers.len(),
            1,
            "Self URL should be filtered out from SHIP discovery"
        );
        assert_eq!(topic_result.peers[0], "https://peer2.example.com");
    }

    #[tokio::test]
    async fn test_start_gasp_sync_ship_no_ls_ship_returns_empty() {
        let mut managers: HashMap<String, Box<dyn TopicManagerTrait>> = HashMap::new();
        managers.insert(
            "tm_custom".to_string(),
            Box::new(MockTopicManager::admitting(vec![])),
        );

        let mut sync_config: SyncConfiguration = HashMap::new();
        sync_config.insert("tm_custom".to_string(), SyncTarget::Ship);

        let engine = Engine::new(
            managers,
            HashMap::new(),
            Box::new(MemoryStorage::new()),
            None,
            EngineConfig {
                sync_configuration: sync_config,
                ..Default::default()
            },
        );

        let result = engine.start_gasp_sync().await.unwrap();
        let topic_result = &result.topics_synced["tm_custom"];
        assert!(
            topic_result.peers.is_empty(),
            "Without ls_ship, SHIP discovery should return no peers"
        );
    }

    #[tokio::test]
    async fn test_start_gasp_sync_mixed_config() {
        let mut managers: HashMap<String, Box<dyn TopicManagerTrait>> = HashMap::new();
        managers.insert(
            "tm_peers".to_string(),
            Box::new(MockTopicManager::admitting(vec![])),
        );
        managers.insert(
            "tm_disabled".to_string(),
            Box::new(MockTopicManager::admitting(vec![])),
        );
        managers.insert(
            "tm_ship_topic".to_string(),
            Box::new(MockTopicManager::admitting(vec![])),
        );

        let mut sync_config: SyncConfiguration = HashMap::new();
        sync_config.insert(
            "tm_peers".to_string(),
            SyncTarget::Peers(vec!["https://peer.com".to_string()]),
        );
        sync_config.insert("tm_disabled".to_string(), SyncTarget::Disabled);
        sync_config.insert("tm_ship_topic".to_string(), SyncTarget::Ship);

        let engine = Engine::new(
            managers,
            HashMap::new(),
            Box::new(MemoryStorage::new()),
            None,
            EngineConfig {
                sync_configuration: sync_config,
                ..Default::default()
            },
        );

        let result = engine.start_gasp_sync().await.unwrap();
        assert_eq!(result.topics_synced.len(), 2);
        assert!(result.topics_synced.contains_key("tm_peers"));
        assert!(result.topics_synced.contains_key("tm_ship_topic"));
        assert!(!result.topics_synced.contains_key("tm_disabled"));

        assert_eq!(result.topics_synced["tm_peers"].peers.len(), 1);
        assert_eq!(result.topics_synced["tm_peers"].sync_type, "peers");
        assert_eq!(result.topics_synced["tm_ship_topic"].sync_type, "ship");
    }

    #[tokio::test]
    async fn test_gasp_sync_result_serialization() {
        let mut topics_synced = HashMap::new();
        topics_synced.insert(
            "tm_test".to_string(),
            super::TopicSyncResult {
                expired_refused: 0,
                peers: vec!["https://peer.com".to_string()],
                sync_type: "ship".to_string(),
                errors: vec![],
                pruned_inputs: 0,
                discarded_graphs: 0,
                anchor_walk_held_graphs: 0,
                finalized_graphs: 0,
                deadline_dropped_graphs: 0,
                cursor_moves: Vec::new(),
                deferred_graphs: 0,
                resumed_graphs: 0,
                converged_graphs: 0,
                dropped_graphs: Vec::new(),
                stalled_graphs: 0,
                held_back_graphs: 0,
            },
        );

        let result = super::GASPSyncResult { topics_synced };
        let json = serde_json::to_string(&result).unwrap();
        let back: super::GASPSyncResult = serde_json::from_str(&json).unwrap();

        assert_eq!(back.topics_synced.len(), 1);
        assert_eq!(back.topics_synced["tm_test"].peers.len(), 1);
        assert_eq!(back.topics_synced["tm_test"].sync_type, "ship");
    }

    // ── GASP Sync With Factory Tests ─────────────────────────────────

    /// Mock GASPRemote for factory tests
    struct MockSyncRemote {
        utxos: Vec<crate::types::GASPOutput>,
    }

    #[async_trait(?Send)]
    impl crate::gasp::GASPRemote for MockSyncRemote {
        async fn get_initial_response(
            &self,
            request: &crate::types::GASPInitialRequest,
        ) -> Result<crate::types::GASPInitialResponse, crate::gasp::GASPError> {
            let utxos: Vec<crate::types::GASPOutput> = self
                .utxos
                .iter()
                .filter(|u| u.score as u64 >= request.since)
                .cloned()
                .collect();
            Ok(crate::types::GASPInitialResponse {
                utxo_list: utxos,
                since: request.since,
            })
        }
        async fn get_initial_reply(
            &self,
            _: &crate::types::GASPInitialResponse,
        ) -> Result<crate::types::GASPInitialReply, crate::gasp::GASPError> {
            Ok(crate::types::GASPInitialReply {
                utxo_list: Vec::new(),
            })
        }
        async fn request_node(
            &self,
            graph_id: &str,
            txid: &str,
            output_index: u32,
            _: bool,
        ) -> Result<crate::types::GASPNode, crate::gasp::GASPError> {
            Ok(crate::types::GASPNode {
                graph_id: graph_id.to_string(),
                raw_tx: format!("rawtx_{txid}"),
                output_index,
                proof: None,
                tx_metadata: None,
                output_metadata: None,
                inputs: None,
            })
        }
        async fn submit_node(
            &self,
            _: &crate::types::GASPNode,
        ) -> Result<Option<crate::types::GASPNodeResponse>, crate::gasp::GASPError> {
            Ok(None)
        }
    }

    /// Mock factory that creates MockSyncRemote instances
    struct MockGASPRemoteFactory;

    #[derive(Clone)]
    struct BudgetPageRemote {
        outputs: std::rc::Rc<Vec<crate::types::GASPOutput>>,
        nodes: std::rc::Rc<HashMap<String, crate::types::GASPNode>>,
        elapsed: std::rc::Rc<Cell<u64>>,
        requests: std::rc::Rc<std::cell::RefCell<Vec<crate::types::GASPInitialRequest>>>,
        clamp: Option<usize>,
        node_cost_ms: u64,
    }

    #[async_trait(?Send)]
    impl crate::gasp::GASPRemote for BudgetPageRemote {
        async fn get_initial_response(
            &self,
            request: &crate::types::GASPInitialRequest,
        ) -> Result<crate::types::GASPInitialResponse, crate::gasp::GASPError> {
            self.requests.borrow_mut().push(request.clone());
            let page = self
                .outputs
                .iter()
                .filter(|u| u.score as u64 >= request.since);
            let limit = self.clamp.map_or(usize::MAX, |cap| {
                cap.min(request.limit.unwrap_or(u64::MAX) as usize)
            });
            Ok(crate::types::GASPInitialResponse {
                utxo_list: page.take(limit).cloned().collect(),
                since: request.since,
            })
        }

        async fn get_initial_reply(
            &self,
            _: &crate::types::GASPInitialResponse,
        ) -> Result<crate::types::GASPInitialReply, crate::gasp::GASPError> {
            unreachable!()
        }

        async fn request_node(
            &self,
            graph_id: &str,
            txid: &str,
            _: u32,
            _: bool,
        ) -> Result<crate::types::GASPNode, crate::gasp::GASPError> {
            self.elapsed.set(self.elapsed.get() + self.node_cost_ms);
            if self.node_cost_ms > 0 {
                let mut yielded = false;
                std::future::poll_fn(|cx| {
                    if yielded {
                        std::task::Poll::Ready(())
                    } else {
                        yielded = true;
                        cx.waker().wake_by_ref();
                        std::task::Poll::Pending
                    }
                })
                .await;
            }
            let mut node = self
                .nodes
                .get(txid)
                .cloned()
                .ok_or_else(|| crate::gasp::GASPError::NodeNotFound(format!("{txid}.0")))?;
            node.graph_id = graph_id.to_string();
            Ok(node)
        }

        async fn submit_node(
            &self,
            _: &crate::types::GASPNode,
        ) -> Result<Option<crate::types::GASPNodeResponse>, crate::gasp::GASPError> {
            unreachable!()
        }
    }

    impl crate::gasp::GASPRemoteFactory for BudgetPageRemote {
        fn create_remote(&self, _: &str, _: &str) -> Box<dyn crate::gasp::GASPRemote> {
            Box::new(self.clone())
        }
    }

    fn budget_page_engine(count: u32) -> (Engine, BudgetPageRemote) {
        let mut engine = make_engine(vec![0]);
        let mut tracker = bsv_rs::transaction::MockChainTracker::new(1000);
        let mut outputs = Vec::new();
        let mut nodes = HashMap::new();
        for n in 1..=count {
            let tx = child_of(&format!("{n:064x}"), 0);
            let txid = tx.id();
            tracker.add_root(n, txid.clone());
            outputs.push(crate::types::GASPOutput {
                txid: txid.clone(),
                output_index: 0,
                score: f64::from(n * 10),
            });
            nodes.insert(
                txid.clone(),
                crate::types::GASPNode {
                    graph_id: String::new(),
                    raw_tx: tx.to_hex(),
                    output_index: 0,
                    proof: Some(single_leaf_bump_hex(&txid, n)),
                    tx_metadata: None,
                    output_metadata: None,
                    inputs: None,
                },
            );
        }
        engine.chain_tracker = Some(Box::new(tracker));
        engine.config.sync_configuration.insert(
            "tm_test".to_string(),
            SyncTarget::Peers(vec!["https://budget.example".to_string()]),
        );
        let remote = BudgetPageRemote {
            outputs: std::rc::Rc::new(outputs),
            nodes: std::rc::Rc::new(nodes),
            elapsed: std::rc::Rc::new(Cell::new(0)),
            requests: std::rc::Rc::default(),
            clamp: None,
            node_cost_ms: 5000,
        };
        (engine, remote)
    }

    fn virtual_peer_budget(engine: &mut Engine, remote: &BudgetPageRemote) {
        let elapsed = remote.elapsed.clone();
        engine.set_peer_sync_budget(
            std::rc::Rc::new(move |ms| {
                assert_eq!(ms, 30_000);
                let elapsed = elapsed.clone();
                let until = elapsed.get() + ms;
                Box::pin(std::future::poll_fn(move |_| {
                    if elapsed.get() >= until {
                        std::task::Poll::Ready(())
                    } else {
                        std::task::Poll::Pending
                    }
                }))
            }),
            30_000,
        );
    }

    #[tokio::test]
    async fn sync_budget_large_page_persists_a_finalized_score_and_resumes() {
        // This responder ignores the limit: the initiator must safely handle
        // a 3,000-output page under a virtual 30-second peer budget.
        let (mut engine, remote) = budget_page_engine(3000);
        virtual_peer_budget(&mut engine, &remote);
        engine.set_gasp_remote_factory(Box::new(remote.clone()));
        for round in 1..=2 {
            let result = engine.start_gasp_sync().await.unwrap();
            let topic = &result.topics_synced["tm_test"];
            assert_eq!(topic.finalized_graphs, 5);
            assert_eq!(topic.deadline_dropped_graphs, 1);
            assert_eq!(topic.cursor_moves.len(), 1);
            let expected = round * 50;
            assert_eq!(topic.cursor_moves[0].to, expected);
            assert_eq!(
                engine
                    .storage
                    .get_last_interaction("https://budget.example", "tm_test")
                    .await
                    .unwrap(),
                expected
            );
            {
                let requests = remote.requests.borrow();
                assert_eq!(requests[(round - 1) as usize].since, (round - 1) * 50);
            }
            for output in remote.outputs.iter().take((round * 5) as usize) {
                assert!(engine
                    .storage
                    .find_output(&output.txid, 0, Some("tm_test"), None, true)
                    .await
                    .unwrap()
                    .is_some());
            }
            let unfinished = &remote.outputs[(round * 5) as usize];
            assert!(engine
                .storage
                .find_output(&unfinished.txid, 0, Some("tm_test"), None, true)
                .await
                .unwrap()
                .is_none());
        }
    }

    #[tokio::test]
    async fn sync_budget_requests_bounded_pages_and_accepts_responder_clamping() {
        let (mut engine, mut remote) = budget_page_engine(7);
        remote.clamp = Some(3);
        remote.node_cost_ms = 0;
        virtual_peer_budget(&mut engine, &remote);
        engine.set_gasp_remote_factory(Box::new(remote.clone()));
        let result = engine.start_gasp_sync().await.unwrap();
        assert_eq!(result.topics_synced["tm_test"].finalized_graphs, 7);
        let requests = remote.requests.borrow();
        assert_eq!(requests.len(), 4);
        assert!(requests.iter().all(|request| request.limit == Some(100)));
        assert_eq!(
            requests.iter().map(|r| r.since).collect::<Vec<_>>(),
            vec![0, 30, 50, 70]
        );
    }

    #[tokio::test]
    async fn sync_budget_unordered_page_keeps_the_completed_score_below_a_gap() {
        let (mut engine, mut remote) = budget_page_engine(3000);
        std::rc::Rc::make_mut(&mut remote.outputs).swap(0, 9);
        virtual_peer_budget(&mut engine, &remote);
        engine.set_gasp_remote_factory(Box::new(remote));
        let result = engine.start_gasp_sync().await.unwrap();
        let topic = &result.topics_synced["tm_test"];
        assert_eq!(topic.finalized_graphs, 5);
        // Score 100 landed, but score 10 is still ahead in this unordered
        // page. The unfinished lower score must hold the cursor at entry.
        assert!(topic.cursor_moves.is_empty());
    }

    #[tokio::test]
    async fn sync_budget_tied_scores_do_not_skip_an_unfinished_output() {
        let (mut engine, mut remote) = budget_page_engine(3);
        std::rc::Rc::make_mut(&mut remote.outputs)[2].score = 20.0;
        remote.node_cost_ms = 10_000;
        virtual_peer_budget(&mut engine, &remote);
        engine.set_gasp_remote_factory(Box::new(remote));
        let result = engine.start_gasp_sync().await.unwrap();
        let topic = &result.topics_synced["tm_test"];
        assert_eq!(topic.finalized_graphs, 2);
        assert_eq!(topic.cursor_moves[0].to, 10);
    }

    #[tokio::test]
    async fn sync_budget_failed_graph_holds_the_cursor_below_later_finalizations() {
        let (mut engine, mut remote) = budget_page_engine(3000);
        let failed = remote.outputs[2].txid.clone();
        std::rc::Rc::make_mut(&mut remote.nodes).remove(&failed);
        virtual_peer_budget(&mut engine, &remote);
        engine.set_gasp_remote_factory(Box::new(remote));
        let result = engine.start_gasp_sync().await.unwrap();
        let topic = &result.topics_synced["tm_test"];
        assert_eq!(topic.finalized_graphs, 4);
        assert_eq!(topic.cursor_moves[0].to, 20);
    }

    struct ProofOnlyRootFetcher {
        proofs: HashMap<String, String>,
        requested: std::rc::Rc<Cell<u64>>,
    }

    #[async_trait(?Send)]
    impl AncestorFetcher for ProofOnlyRootFetcher {
        async fn fetch_ancestor(&self, _: &str) -> Result<FetchedAncestor, GASPError> {
            Err(GASPError::RemoteError("raw source unavailable".to_string()))
        }
        async fn verified_proof_for(&self, txid: &str) -> Option<String> {
            self.requested.set(self.requested.get() + 1);
            self.proofs.get(txid).cloned()
        }
    }

    #[tokio::test]
    async fn copy_sync_leaves_completion_courier_untouched() {
        let (mut engine, mut remote) = budget_page_engine(1);
        remote.node_cost_ms = 0;
        let txid = remote.outputs[0].txid.clone();
        let proof = std::rc::Rc::make_mut(&mut remote.nodes)
            .get_mut(&txid)
            .unwrap()
            .proof
            .take()
            .unwrap();
        let completion_asks = std::rc::Rc::new(Cell::new(0));
        let sync_asks = std::rc::Rc::new(Cell::new(0));
        engine.set_ancestor_fetcher(std::rc::Rc::new(ProofOnlyRootFetcher {
            proofs: HashMap::new(),
            requested: completion_asks.clone(),
        }));
        engine.set_gasp_ancestor_fetcher(std::rc::Rc::new(ProofOnlyRootFetcher {
            proofs: HashMap::from([(txid.clone(), proof.clone())]),
            requested: sync_asks.clone(),
        }));
        engine.set_gasp_remote_factory(Box::new(remote));
        let result = engine.start_gasp_sync().await.unwrap();
        assert_eq!(result.topics_synced["tm_test"].finalized_graphs, 1);
        assert_eq!(completion_asks.get(), 0);
        assert_eq!(sync_asks.get(), 1);
        let served = engine
            .provide_foreign_gasp_node(&format!("{txid}.0"), &txid, 0)
            .await
            .unwrap();
        assert_eq!(served.proof, Some(proof));
    }

    #[tokio::test]
    async fn sync_budget_proofless_root_uses_own_proof_source_without_raw_refetch() {
        for proven in [true, false] {
            let (mut engine, mut remote) = budget_page_engine(1);
            let txid = remote.outputs[0].txid.clone();
            let proof = remote.nodes[&txid].proof.clone().unwrap();
            std::rc::Rc::make_mut(&mut remote.nodes)
                .get_mut(&txid)
                .unwrap()
                .proof = None;
            let requested = std::rc::Rc::new(Cell::new(0));
            engine.set_ancestor_fetcher(std::rc::Rc::new(ProofOnlyRootFetcher {
                proofs: if proven {
                    HashMap::from([(txid.clone(), proof)])
                } else {
                    HashMap::new()
                },
                requested: requested.clone(),
            }));
            virtual_peer_budget(&mut engine, &remote);
            engine.set_gasp_remote_factory(Box::new(remote));
            let result = engine.start_gasp_sync().await.unwrap();
            assert!(requested.get() > 0);
            assert_eq!(
                result.topics_synced["tm_test"].finalized_graphs,
                u64::from(proven)
            );
            assert_eq!(
                engine
                    .storage
                    .find_output(&txid, 0, Some("tm_test"), None, true)
                    .await
                    .unwrap()
                    .is_some(),
                proven
            );
            if !proven {
                assert!(result.topics_synced["tm_test"].cursor_moves.is_empty());
            }
        }
    }

    #[tokio::test]
    async fn sync_budget_deferred_root_resumes_when_own_proof_becomes_available() {
        let (mut engine, mut remote) = budget_page_engine(1);
        let txid = remote.outputs[0].txid.clone();
        let proof = remote.nodes[&txid].proof.clone().unwrap();
        std::rc::Rc::make_mut(&mut remote.nodes)
            .get_mut(&txid)
            .unwrap()
            .proof = None;
        let requested = std::rc::Rc::new(Cell::new(0));
        engine.set_ancestor_fetcher(std::rc::Rc::new(ProofOnlyRootFetcher {
            proofs: HashMap::new(),
            requested: requested.clone(),
        }));
        virtual_peer_budget(&mut engine, &remote);
        engine.set_graph_budget(
            std::rc::Rc::new(|_| Box::pin(std::future::pending())),
            5,
            5000,
        );
        engine.set_gasp_remote_factory(Box::new(remote));
        let held = engine.start_gasp_sync().await.unwrap();
        assert_eq!(held.topics_synced["tm_test"].finalized_graphs, 0);
        assert_eq!(held.topics_synced["tm_test"].deferred_graphs, 1);
        assert!(held.topics_synced["tm_test"].cursor_moves.is_empty());
        engine.set_ancestor_fetcher(std::rc::Rc::new(ProofOnlyRootFetcher {
            proofs: HashMap::from([(txid.clone(), proof)]),
            requested,
        }));
        let landed = engine.start_gasp_sync().await.unwrap();
        assert_eq!(landed.topics_synced["tm_test"].resumed_graphs, 1);
        assert_eq!(landed.topics_synced["tm_test"].finalized_graphs, 1);
        assert_eq!(landed.topics_synced["tm_test"].cursor_moves[0].to, 10);
        assert!(engine
            .storage
            .find_output(&txid, 0, Some("tm_test"), None, true)
            .await
            .unwrap()
            .is_some());
    }

    #[tokio::test]
    async fn sync_budget_own_proof_without_a_valid_header_is_never_admitted() {
        let (mut engine, mut remote) = budget_page_engine(1);
        let txid = remote.outputs[0].txid.clone();
        std::rc::Rc::make_mut(&mut remote.nodes)
            .get_mut(&txid)
            .unwrap()
            .proof = None;
        engine.set_ancestor_fetcher(std::rc::Rc::new(ProofOnlyRootFetcher {
            proofs: HashMap::from([(txid.clone(), single_leaf_bump_hex(&txid, 999))]),
            requested: std::rc::Rc::default(),
        }));
        virtual_peer_budget(&mut engine, &remote);
        engine.set_gasp_remote_factory(Box::new(remote));
        let result = engine.start_gasp_sync().await.unwrap();
        assert_eq!(result.topics_synced["tm_test"].finalized_graphs, 0);
        assert!(engine
            .storage
            .find_output(&txid, 0, Some("tm_test"), None, true)
            .await
            .unwrap()
            .is_none());
    }

    impl crate::gasp::GASPRemoteFactory for MockGASPRemoteFactory {
        fn create_remote(&self, _peer_url: &str, _topic: &str) -> Box<dyn crate::gasp::GASPRemote> {
            Box::new(MockSyncRemote {
                utxos: vec![
                    crate::types::GASPOutput {
                        txid: "remote_tx1".to_string(),
                        output_index: 0,
                        score: 100.0,
                    },
                    crate::types::GASPOutput {
                        txid: "remote_tx2".to_string(),
                        output_index: 0,
                        score: 200.0,
                    },
                ],
            })
        }
    }

    #[tokio::test]
    async fn test_start_gasp_sync_with_factory_runs_sync() {
        let mut sync_config: SyncConfiguration = HashMap::new();
        sync_config.insert(
            "tm_test".to_string(),
            SyncTarget::Peers(vec!["https://peer1.example.com".to_string()]),
        );

        let mut engine = Engine::new(
            HashMap::new(),
            HashMap::new(),
            Box::new(MemoryStorage::new()),
            None,
            EngineConfig {
                sync_configuration: sync_config,
                ..Default::default()
            },
        );

        engine.set_gasp_remote_factory(Box::new(MockGASPRemoteFactory));

        let result = engine.start_gasp_sync().await.unwrap();
        assert_eq!(result.topics_synced.len(), 1);

        let topic_result = &result.topics_synced["tm_test"];
        assert_eq!(topic_result.peers.len(), 1);
        assert!(
            topic_result.errors.is_empty(),
            "Sync should succeed with mock remote"
        );

        // Verify last_interaction was persisted
        let last = engine
            .storage()
            .get_last_interaction("https://peer1.example.com", "tm_test")
            .await
            .unwrap();
        // Synthetic nodes cannot assemble into BEEF. No score completed,
        // so the entry cursor stays and the next sync re-requests both.
        assert_eq!(
            last, 0,
            "cursor must remain at entry when no output completed"
        );
    }

    #[tokio::test]
    async fn test_start_gasp_sync_with_factory_handles_error() {
        struct FailingFactory;

        impl crate::gasp::GASPRemoteFactory for FailingFactory {
            fn create_remote(
                &self,
                _peer_url: &str,
                _topic: &str,
            ) -> Box<dyn crate::gasp::GASPRemote> {
                struct FailingRemote;
                #[async_trait(?Send)]
                impl crate::gasp::GASPRemote for FailingRemote {
                    async fn get_initial_response(
                        &self,
                        _: &crate::types::GASPInitialRequest,
                    ) -> Result<crate::types::GASPInitialResponse, crate::gasp::GASPError>
                    {
                        Err(crate::gasp::GASPError::RemoteError(
                            "connection refused".into(),
                        ))
                    }
                    async fn get_initial_reply(
                        &self,
                        _: &crate::types::GASPInitialResponse,
                    ) -> Result<crate::types::GASPInitialReply, crate::gasp::GASPError>
                    {
                        unreachable!()
                    }
                    async fn request_node(
                        &self,
                        _: &str,
                        _: &str,
                        _: u32,
                        _: bool,
                    ) -> Result<crate::types::GASPNode, crate::gasp::GASPError>
                    {
                        unreachable!()
                    }
                    async fn submit_node(
                        &self,
                        _: &crate::types::GASPNode,
                    ) -> Result<Option<crate::types::GASPNodeResponse>, crate::gasp::GASPError>
                    {
                        unreachable!()
                    }
                }
                Box::new(FailingRemote)
            }
        }

        let mut sync_config: SyncConfiguration = HashMap::new();
        sync_config.insert(
            "tm_test".to_string(),
            SyncTarget::Peers(vec!["https://bad-peer.example.com".to_string()]),
        );

        let mut engine = Engine::new(
            HashMap::new(),
            HashMap::new(),
            Box::new(MemoryStorage::new()),
            None,
            EngineConfig {
                sync_configuration: sync_config,
                ..Default::default()
            },
        );

        engine.set_gasp_remote_factory(Box::new(FailingFactory));

        let result = engine.start_gasp_sync().await.unwrap();
        assert_eq!(result.topics_synced.len(), 1);

        let topic_result = &result.topics_synced["tm_test"];
        assert_eq!(
            topic_result.errors.len(),
            1,
            "Should have one error for the failing peer"
        );
        assert!(topic_result.errors[0].contains("connection refused"));
    }

    #[tokio::test]
    async fn test_start_gasp_sync_without_factory_still_discovers_peers() {
        let mut sync_config: SyncConfiguration = HashMap::new();
        sync_config.insert(
            "tm_test".to_string(),
            SyncTarget::Peers(vec!["https://peer.example.com".to_string()]),
        );

        // No factory set — should still work (just peer discovery, no sync)
        let engine = Engine::new(
            HashMap::new(),
            HashMap::new(),
            Box::new(MemoryStorage::new()),
            None,
            EngineConfig {
                sync_configuration: sync_config,
                ..Default::default()
            },
        );

        let result = engine.start_gasp_sync().await.unwrap();
        assert_eq!(result.topics_synced.len(), 1);

        let topic_result = &result.topics_synced["tm_test"];
        assert_eq!(topic_result.peers.len(), 1);
        assert!(topic_result.errors.is_empty());
    }

    #[tokio::test]
    async fn test_start_gasp_sync_with_factory_multiple_peers() {
        let mut sync_config: SyncConfiguration = HashMap::new();
        sync_config.insert(
            "tm_test".to_string(),
            SyncTarget::Peers(vec![
                "https://peer1.example.com".to_string(),
                "https://peer2.example.com".to_string(),
            ]),
        );

        let mut engine = Engine::new(
            HashMap::new(),
            HashMap::new(),
            Box::new(MemoryStorage::new()),
            None,
            EngineConfig {
                sync_configuration: sync_config,
                ..Default::default()
            },
        );

        engine.set_gasp_remote_factory(Box::new(MockGASPRemoteFactory));

        let result = engine.start_gasp_sync().await.unwrap();
        let topic_result = &result.topics_synced["tm_test"];
        assert_eq!(topic_result.peers.len(), 2);
        assert!(topic_result.errors.is_empty());

        // Neither peer completed its synthetic graphs.
        let last1 = engine
            .storage()
            .get_last_interaction("https://peer1.example.com", "tm_test")
            .await
            .unwrap();
        let last2 = engine
            .storage()
            .get_last_interaction("https://peer2.example.com", "tm_test")
            .await
            .unwrap();
        assert_eq!(last1, 0);
        assert_eq!(last2, 0);
    }

    // ── Per-peer budget + dead-peer quarantine (bsv-low#302) ──────────

    /// A remote whose initial request HANGS forever — models the dead
    /// ephemeral peers (ngrok tunnels) whose fetch never returns, the #257
    /// root cause the per-peer budget exists for.
    struct HangingRemote;

    #[async_trait(?Send)]
    impl crate::gasp::GASPRemote for HangingRemote {
        async fn get_initial_response(
            &self,
            _: &crate::types::GASPInitialRequest,
        ) -> Result<crate::types::GASPInitialResponse, crate::gasp::GASPError> {
            std::future::pending::<()>().await;
            unreachable!()
        }
        async fn get_initial_reply(
            &self,
            _: &crate::types::GASPInitialResponse,
        ) -> Result<crate::types::GASPInitialReply, crate::gasp::GASPError> {
            unreachable!()
        }
        async fn request_node(
            &self,
            _: &str,
            _: &str,
            _: u32,
            _: bool,
        ) -> Result<crate::types::GASPNode, crate::gasp::GASPError> {
            unreachable!()
        }
        async fn submit_node(
            &self,
            _: &crate::types::GASPNode,
        ) -> Result<Option<crate::types::GASPNodeResponse>, crate::gasp::GASPError> {
            unreachable!()
        }
    }

    /// Factory that HANGS for `hang.example.com` peers and serves the normal
    /// mock sync remote for everyone else, counting `create_remote` calls
    /// (a quarantine-skipped peer never reaches the factory).
    struct SelectiveHangFactory {
        created: std::rc::Rc<std::cell::RefCell<Vec<String>>>,
    }

    impl crate::gasp::GASPRemoteFactory for SelectiveHangFactory {
        fn create_remote(&self, peer_url: &str, _topic: &str) -> Box<dyn crate::gasp::GASPRemote> {
            self.created.borrow_mut().push(peer_url.to_string());
            if peer_url.contains("hang.example.com") {
                Box::new(HangingRemote)
            } else {
                Box::new(MockSyncRemote {
                    utxos: vec![crate::types::GASPOutput {
                        txid: "remote_tx1".to_string(),
                        output_index: 0,
                        score: 100.0,
                    }],
                })
            }
        }
    }

    /// The deterministic "instant deadline" sleep factory: `race_or_deadline`
    /// polls the sync future FIRST, so an in-memory sync that never yields
    /// still completes; only a future that actually returns Pending (the
    /// hanging remote) loses the race.
    fn instant_deadline() -> crate::engine::SleepFactory {
        std::rc::Rc::new(|_ms| Box::pin(std::future::ready(())))
    }

    fn two_peer_engine(store: std::rc::Rc<MemoryStorage>) -> Engine {
        let mut sync_config: SyncConfiguration = HashMap::new();
        sync_config.insert(
            "tm_test".to_string(),
            SyncTarget::Peers(vec![
                "https://hang.example.com".to_string(),
                "https://good.example.com".to_string(),
            ]),
        );
        Engine::new(
            HashMap::new(),
            HashMap::new(),
            Box::new(store),
            None,
            EngineConfig {
                sync_configuration: sync_config,
                ..Default::default()
            },
        )
    }

    #[tokio::test]
    async fn peer_budget_timeout_skips_dead_peer_continues_loop_and_never_advances_cursor() {
        let store = std::rc::Rc::new(MemoryStorage::new());
        let created = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
        let mut engine = two_peer_engine(store.clone());
        engine.set_gasp_remote_factory(Box::new(SelectiveHangFactory {
            created: created.clone(),
        }));
        engine.set_peer_sync_budget(instant_deadline(), 1);

        let result = engine.start_gasp_sync().await.unwrap();
        let topic_result = &result.topics_synced["tm_test"];

        // The hanging peer was dropped LOUDLY (an error entry) and the loop
        // CONTINUED: the good peer was still attempted and completed.
        assert_eq!(topic_result.errors.len(), 1, "one budget-exceeded error");
        assert!(
            topic_result.errors[0].contains("budget"),
            "{:?}",
            topic_result.errors
        );
        assert_eq!(
            created.borrow().as_slice(),
            ["https://hang.example.com", "https://good.example.com"],
            "both peers attempted this tick"
        );

        // A timed-out peer stays at entry. The other peer was reached but
        // served synthetic graphs that cannot complete, so its cursor stays too.
        let hang_cursor = store
            .get_last_interaction("https://hang.example.com", "tm_test")
            .await
            .unwrap();
        assert_eq!(hang_cursor, 0, "timeout must not advance the sync cursor");
        let good_cursor = store
            .get_last_interaction("https://good.example.com", "tm_test")
            .await
            .unwrap();
        assert_eq!(good_cursor, 0, "no synthetic graph completed");

        // Health bookkeeping: timeout = failure, completion = success.
        let hang_health = store
            .get_peer_sync_health("hang.example.com", "tm_test")
            .await
            .unwrap();
        assert_eq!(hang_health.consecutive_failures, 1);
        let good_health = store
            .get_peer_sync_health("good.example.com", "tm_test")
            .await
            .unwrap();
        assert_eq!(good_health.consecutive_failures, 0);
    }

    #[tokio::test]
    async fn peer_quarantined_after_threshold_reprobed_after_window_readmitted_on_success() {
        let store = std::rc::Rc::new(MemoryStorage::new());
        let created = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));

        let mut sync_config: SyncConfiguration = HashMap::new();
        sync_config.insert(
            "tm_test".to_string(),
            SyncTarget::Peers(vec!["https://hang.example.com".to_string()]),
        );
        let mut engine = Engine::new(
            HashMap::new(),
            HashMap::new(),
            Box::new(store.clone()),
            None,
            EngineConfig {
                sync_configuration: sync_config,
                ..Default::default()
            },
        );
        engine.set_gasp_remote_factory(Box::new(SelectiveHangFactory {
            created: created.clone(),
        }));
        engine.set_peer_sync_budget(instant_deadline(), 1);

        // Fail the peer up to (but not past) the quarantine threshold — every
        // tick attempts it (advance the clock between ticks so the attempts
        // are distinguishable in age).
        for i in 0..crate::gasp::PEER_QUARANTINE_THRESHOLD {
            engine.start_gasp_sync().await.unwrap();
            store.advance_clock(900);
            assert_eq!(
                created.borrow().len() as u64,
                i + 1,
                "peer attempted while below the threshold"
            );
        }
        let health = store
            .get_peer_sync_health("hang.example.com", "tm_test")
            .await
            .unwrap();
        assert_eq!(
            health.consecutive_failures,
            crate::gasp::PEER_QUARANTINE_THRESHOLD
        );

        // Next tick: QUARANTINED — the factory is never consulted, no error
        // is emitted, and the attempt count does not grow (a skip is not an
        // attempt, so the re-probe window keeps aging).
        let result = engine.start_gasp_sync().await.unwrap();
        assert!(result.topics_synced["tm_test"].errors.is_empty());
        assert_eq!(
            created.borrow().len() as u64,
            crate::gasp::PEER_QUARANTINE_THRESHOLD,
            "quarantined peer must be skipped"
        );

        // Age past the re-probe window: exactly one fresh probe is allowed.
        store.advance_clock(crate::gasp::PEER_QUARANTINE_REPROBE_SECS);
        engine.start_gasp_sync().await.unwrap();
        assert_eq!(
            created.borrow().len() as u64,
            crate::gasp::PEER_QUARANTINE_THRESHOLD + 1,
            "re-probe attempted after the window"
        );
        // The probe failed again → failure count kept growing → re-armed.
        let health = store
            .get_peer_sync_health("hang.example.com", "tm_test")
            .await
            .unwrap();
        assert_eq!(
            health.consecutive_failures,
            crate::gasp::PEER_QUARANTINE_THRESHOLD + 1
        );
        let result = engine.start_gasp_sync().await.unwrap();
        assert!(
            result.topics_synced["tm_test"].errors.is_empty(),
            "re-quarantined"
        );

        // The peer comes back to life: age to the next re-probe, then answer
        // like a healthy peer → SUCCESS resets the count to 0 (full
        // re-admission — quarantine is never a deletion).
        store.advance_clock(crate::gasp::PEER_QUARANTINE_REPROBE_SECS);
        // Swap the factory for one that serves the healthy mock for this URL.
        engine.set_gasp_remote_factory(Box::new(MockGASPRemoteFactory));
        let result = engine.start_gasp_sync().await.unwrap();
        assert!(result.topics_synced["tm_test"].errors.is_empty());
        let health = store
            .get_peer_sync_health("hang.example.com", "tm_test")
            .await
            .unwrap();
        assert_eq!(health.consecutive_failures, 0, "success fully re-admits");
    }

    // ── Mock ARC Broadcaster ─────────────────────────────────────────

    use crate::broadcaster::ArcBroadcaster;

    struct MockArcBroadcaster {
        calls: Arc<Mutex<Vec<String>>>,
        should_fail: bool,
    }

    impl MockArcBroadcaster {
        fn new() -> Self {
            Self {
                calls: Arc::new(Mutex::new(Vec::new())),
                should_fail: false,
            }
        }

        fn failing() -> Self {
            Self {
                calls: Arc::new(Mutex::new(Vec::new())),
                should_fail: true,
            }
        }
    }

    #[async_trait(?Send)]
    impl ArcBroadcaster for MockArcBroadcaster {
        async fn broadcast(&self, raw_tx_hex: &str) -> Result<String, String> {
            self.calls.lock().unwrap().push(raw_tx_hex.to_string());
            if self.should_fail {
                Err("mock ARC failure".to_string())
            } else {
                Ok("mock_txid_from_arc".to_string())
            }
        }
    }

    /// Create engine with an ARC broadcaster (and optionally a SHIP broadcaster).
    fn make_engine_with_arc(
        admit_indices: Vec<u32>,
        arc: MockArcBroadcaster,
    ) -> (Engine, Arc<Mutex<Vec<String>>>) {
        let arc_calls = arc.calls.clone();

        let mut managers: HashMap<String, Box<dyn TopicManagerTrait>> = HashMap::new();
        managers.insert(
            "tm_test".to_string(),
            Box::new(MockTopicManager::admitting(admit_indices)),
        );

        let mut lookup_services: HashMap<String, Box<dyn LookupServiceTrait>> = HashMap::new();
        lookup_services.insert("ls_test".to_string(), Box::new(MockLookupService::new()));

        let storage = Box::new(MemoryStorage::new());

        let engine = Engine::with_all(
            managers,
            lookup_services,
            storage,
            None,
            None,
            Some(Box::new(arc)),
            None,
            EngineConfig::default(),
        );

        (engine, arc_calls)
    }

    // ── ARC Broadcaster Tests ────────────────────────────────────────

    #[tokio::test]
    async fn test_arc_broadcaster_called_on_current_tx() {
        let arc = MockArcBroadcaster::new();
        let (engine, arc_calls) = make_engine_with_arc(vec![0], arc);

        let beef = test_tagged_beef(vec!["tm_test"]);
        let steak = engine.submit(&beef, SubmitMode::CurrentTx).await.unwrap();

        assert!(!steak["tm_test"].outputs_to_admit.is_empty());

        let calls = arc_calls.lock().unwrap();
        assert_eq!(
            calls.len(),
            1,
            "ARC broadcaster should be called once for CurrentTx"
        );
        assert!(
            !calls[0].is_empty(),
            "ARC should receive non-empty raw tx hex"
        );
    }

    #[tokio::test]
    async fn test_arc_broadcaster_not_called_on_historical_tx() {
        let arc = MockArcBroadcaster::new();
        let (engine, arc_calls) = make_engine_with_arc(vec![0], arc);

        let beef = test_tagged_beef(vec!["tm_test"]);
        engine
            .submit(&beef, SubmitMode::HistoricalTx)
            .await
            .unwrap();

        assert_eq!(
            arc_calls.lock().unwrap().len(),
            0,
            "ARC broadcaster should NOT be called for HistoricalTx"
        );
    }

    #[tokio::test]
    async fn test_arc_broadcaster_not_called_on_historical_tx_no_spv() {
        let arc = MockArcBroadcaster::new();
        let (engine, arc_calls) = make_engine_with_arc(vec![0], arc);

        let beef = test_tagged_beef(vec!["tm_test"]);
        engine
            .submit(&beef, SubmitMode::HistoricalTxNoSpv)
            .await
            .unwrap();

        assert_eq!(
            arc_calls.lock().unwrap().len(),
            0,
            "ARC broadcaster should NOT be called for HistoricalTxNoSpv"
        );
    }

    #[tokio::test]
    async fn test_arc_broadcast_failure_does_not_fail_submit() {
        let arc = MockArcBroadcaster::failing();
        let (engine, arc_calls) = make_engine_with_arc(vec![0], arc);

        let beef = test_tagged_beef(vec!["tm_test"]);
        // submit should succeed even when ARC fails
        let steak = engine.submit(&beef, SubmitMode::CurrentTx).await.unwrap();

        assert!(!steak["tm_test"].outputs_to_admit.is_empty());

        // ARC was called (and failed), but submit still succeeded
        assert_eq!(
            arc_calls.lock().unwrap().len(),
            1,
            "ARC broadcaster should be attempted even if it will fail"
        );
    }

    #[tokio::test]
    async fn test_arc_broadcaster_not_present_still_works() {
        // Engine without ARC broadcaster — should work fine
        let engine = make_engine(vec![0]);

        let beef = test_tagged_beef(vec!["tm_test"]);
        let steak = engine.submit(&beef, SubmitMode::CurrentTx).await.unwrap();

        assert!(!steak["tm_test"].outputs_to_admit.is_empty());
    }

    // ── Sync advertisements URL validation ─────────────────────────────

    /// Mock Advertiser that tracks created advertisements via shared state.
    struct TrackingAdvertiser {
        created: Arc<Mutex<Vec<AdvertisementData>>>,
        existing_ship: Vec<Advertisement>,
        existing_slap: Vec<Advertisement>,
        /// Topics the returned TaggedBEEF is tagged with — a topic with no
        /// registered manager forces the LOCAL submit to fail (#320 3a);
        /// several topics exercise independent per-topic admission (D1).
        tag_topics: Vec<String>,
        /// Simulate a create_advertisements failure (#320 3a).
        create_fails: bool,
        /// Simulate a find_all_advertisements failure (#320 M2).
        find_fails: bool,
        /// Return the v1 no-op EMPTY TaggedBEEF from revoke (#320 L2).
        revoke_empty: bool,
    }

    impl TrackingAdvertiser {
        fn new() -> (Self, Arc<Mutex<Vec<AdvertisementData>>>) {
            let created = Arc::new(Mutex::new(Vec::new()));
            (
                Self {
                    created: created.clone(),
                    existing_ship: vec![],
                    existing_slap: vec![],
                    tag_topics: vec!["tm_test".to_string()],
                    create_fails: false,
                    find_fails: false,
                    revoke_empty: false,
                },
                created,
            )
        }
    }

    use crate::advertiser::{Advertiser, AdvertiserError};

    #[async_trait(?Send)]
    impl Advertiser for TrackingAdvertiser {
        async fn create_advertisements(
            &self,
            ads: &[AdvertisementData],
        ) -> Result<TaggedBEEF, AdvertiserError> {
            if self.create_fails {
                return Err(AdvertiserError::CreationFailed(
                    "mock create refused".into(),
                ));
            }
            self.created.lock().unwrap().extend(ads.iter().cloned());
            Ok(TaggedBEEF::new(test_beef(), self.tag_topics.clone()))
        }

        async fn find_all_advertisements(
            &self,
            protocol: Protocol,
        ) -> Result<Vec<Advertisement>, AdvertiserError> {
            if self.find_fails {
                return Err(AdvertiserError::LookupFailed("mock lookup refused".into()));
            }
            match protocol {
                Protocol::Ship => Ok(self.existing_ship.clone()),
                Protocol::Slap => Ok(self.existing_slap.clone()),
            }
        }

        async fn revoke_advertisements(
            &self,
            _ads: &[Advertisement],
        ) -> Result<TaggedBEEF, AdvertiserError> {
            if self.revoke_empty {
                return Ok(TaggedBEEF::new(vec![], vec![]));
            }
            Ok(TaggedBEEF::new(test_beef(), vec!["tm_test".to_string()]))
        }

        fn parse_advertisement(&self, _script: &[u8]) -> Option<Advertisement> {
            None
        }
    }

    /// TS: "Sync advertisements URL validation"
    /// sync_advertisements should be a no-op when hosting_url is empty string,
    /// and should skip suppressed topics (tm_ship/tm_slap) when configured.
    #[tokio::test]
    async fn test_sync_advertisements_url_validation() {
        // Case 1: Empty hosting URL — should return early without creating ads
        let (adv, created) = TrackingAdvertiser::new();

        let mut managers: HashMap<String, Box<dyn TopicManagerTrait>> = HashMap::new();
        managers.insert(
            "tm_test".to_string(),
            Box::new(MockTopicManager::admitting(vec![0])),
        );

        let engine = Engine::new(
            managers,
            HashMap::new(),
            Box::new(MemoryStorage::new()),
            Some(Box::new(adv)),
            EngineConfig {
                hosting_url: Some(String::new()), // empty string — invalid
                ..Default::default()
            },
        );

        engine.sync_advertisements().await.unwrap();
        assert!(
            created.lock().unwrap().is_empty(),
            "Empty hosting URL should skip advertisement creation"
        );

        // Case 2: Valid hosting URL — should create SHIP advertisements for non-suppressed topics
        let (adv2, created2) = TrackingAdvertiser::new();

        let mut managers2: HashMap<String, Box<dyn TopicManagerTrait>> = HashMap::new();
        managers2.insert(
            "tm_test".to_string(),
            Box::new(MockTopicManager::admitting(vec![0])),
        );
        // Also register tm_ship to verify it gets suppressed
        managers2.insert(
            "tm_ship".to_string(),
            Box::new(MockTopicManager::admitting(vec![])),
        );

        let engine2 = Engine::new(
            managers2,
            HashMap::new(),
            Box::new(MemoryStorage::new()),
            Some(Box::new(adv2)),
            EngineConfig {
                hosting_url: Some("https://valid.example.com".to_string()),
                suppress_default_sync_advertisements: true,
                ..Default::default()
            },
        );

        engine2.sync_advertisements().await.unwrap();
        let ads = created2.lock().unwrap();
        // tm_ship should be suppressed, only tm_test should get an advertisement
        assert!(
            ads.iter().all(|a| a.topic_or_service_name != "tm_ship"),
            "tm_ship should be suppressed when suppress_default_sync_advertisements is true"
        );
        assert!(
            ads.iter().any(|a| a.topic_or_service_name == "tm_test"),
            "tm_test should get a SHIP advertisement"
        );
    }

    // ── sync_advertisements report (bsv-low #320 defect 3a) ────────────
    //
    // Pre-#320 the engine returned `Ok(())` unconditionally: a failed
    // create or a failed LOCAL submit was `error!`-logged and invisible to
    // the caller — the admin route said `success` while the node's own
    // ls_ship/ls_slap never gained its ads, so every cycle re-created the
    // whole set. These cells pin the report contract.

    fn sync_test_engine(adv: TrackingAdvertiser) -> Engine {
        let mut managers: HashMap<String, Box<dyn TopicManagerTrait>> = HashMap::new();
        managers.insert(
            "tm_test".to_string(),
            Box::new(MockTopicManager::admitting(vec![0])),
        );
        Engine::new(
            managers,
            HashMap::new(),
            Box::new(MemoryStorage::new()),
            Some(Box::new(adv)),
            EngineConfig {
                hosting_url: Some("https://valid.example.com".to_string()),
                suppress_default_sync_advertisements: true,
                ..Default::default()
            },
        )
    }

    #[tokio::test]
    async fn sync_report_counts_admitted_outputs_on_success() {
        let (adv, _) = TrackingAdvertiser::new();
        let report = sync_test_engine(adv).sync_advertisements().await.unwrap();
        assert!(report.ok(), "clean run must report ok: {report:?}");
        assert_eq!(report.to_create, 1, "tm_test was missing");
        assert_eq!(
            report.admitted.get("tm_test"),
            Some(&1),
            "the STEAK's admitted count must be surfaced: {report:?}"
        );
    }

    #[tokio::test]
    async fn sync_report_surfaces_local_submit_failure() {
        // The TaggedBEEF comes back tagged for a topic with no registered
        // manager → the LOCAL submit fails. That failure must be in the
        // report, not swallowed (the live silent-failure shape).
        let (mut adv, _) = TrackingAdvertiser::new();
        adv.tag_topics = vec!["tm_unregistered".to_string()];
        let report = sync_test_engine(adv).sync_advertisements().await.unwrap();
        assert!(!report.ok(), "a failed local submit must not report ok");
        assert_eq!(report.to_create, 1);
        let submit_error = report.submit_error.as_deref().unwrap_or_default();
        assert!(
            submit_error.contains("tm_unregistered"),
            "verbatim engine error expected, got: {submit_error}"
        );
        assert!(report.admitted.is_empty());
    }

    #[tokio::test]
    async fn sync_report_surfaces_create_failure() {
        let (mut adv, _) = TrackingAdvertiser::new();
        adv.create_fails = true;
        let report = sync_test_engine(adv).sync_advertisements().await.unwrap();
        assert!(!report.ok());
        assert!(
            report
                .create_error
                .as_deref()
                .unwrap_or_default()
                .contains("mock create refused"),
            "{report:?}"
        );
        assert!(report.submit_error.is_none(), "create failed before submit");
    }

    #[tokio::test]
    async fn sync_report_converged_noop_is_ok_and_creates_nothing() {
        // A node whose own storage already lists its ads must attempt ZERO
        // creates — the convergence direction of #320 defect 3 (live, the
        // missing self-admission made every cycle re-create all 17 ads).
        let (mut adv, created) = TrackingAdvertiser::new();
        adv.existing_ship = vec![Advertisement {
            protocol: Protocol::Ship,
            identity_key: "02aa".to_string(),
            domain: "https://valid.example.com".to_string(),
            topic_or_service: "tm_test".to_string(),
            beef: None,
            output_index: None,
        }];
        let report = sync_test_engine(adv).sync_advertisements().await.unwrap();
        assert!(report.ok(), "{report:?}");
        assert_eq!(report.to_create, 0, "converged ⇒ nothing to create");
        assert!(created.lock().unwrap().is_empty());
        assert!(
            report.effective(),
            "converged-noop is the one zero-admit shape that IS success"
        );
    }

    #[tokio::test]
    async fn sync_report_zero_admit_is_ok_but_not_effective() {
        // #320 M1: the local submit SUCCEEDS but the topic manager admits
        // ZERO outputs — a non-error refusal. The ads never enter our own
        // ls_ship/ls_slap, so the diff re-creates (re-pays) the full set
        // next cycle. `ok()` (errors-only) stays true; `effective()` must
        // refuse, and the route keys success on `effective()`.
        let (adv, _) = TrackingAdvertiser::new();
        let mut managers: HashMap<String, Box<dyn TopicManagerTrait>> = HashMap::new();
        managers.insert(
            "tm_test".to_string(),
            Box::new(MockTopicManager::admitting(vec![])), // refuses everything
        );
        let engine = Engine::new(
            managers,
            HashMap::new(),
            Box::new(MemoryStorage::new()),
            Some(Box::new(adv)),
            EngineConfig {
                hosting_url: Some("https://valid.example.com".to_string()),
                suppress_default_sync_advertisements: true,
                ..Default::default()
            },
        );
        let report = engine.sync_advertisements().await.unwrap();
        assert!(report.ok(), "no ERROR occurred: {report:?}");
        assert_eq!(report.to_create, 1);
        assert_eq!(report.admitted_total(), 0, "{report:?}");
        assert!(
            !report.effective(),
            "zero admitted on a non-empty create must not read as success: {report:?}"
        );
    }

    #[tokio::test]
    async fn sync_report_partial_admit_is_not_effective() {
        // Delta D1: TWO topics in one submitted tx, per-topic admission
        // independent — tm_test admits its output, tm_refuse refuses all.
        // admitted_total (1) > 0 but < to_create (2): the refused ads
        // would be re-created (re-paid) every cycle, so this must NOT
        // read as success.
        let (mut adv, _) = TrackingAdvertiser::new();
        adv.tag_topics = vec!["tm_test".to_string(), "tm_refuse".to_string()];
        let mut managers: HashMap<String, Box<dyn TopicManagerTrait>> = HashMap::new();
        managers.insert(
            "tm_test".to_string(),
            Box::new(MockTopicManager::admitting(vec![0])),
        );
        managers.insert(
            "tm_refuse".to_string(),
            Box::new(MockTopicManager::admitting(vec![])), // refuses everything
        );
        let engine = Engine::new(
            managers,
            HashMap::new(),
            Box::new(MemoryStorage::new()),
            Some(Box::new(adv)),
            EngineConfig {
                hosting_url: Some("https://valid.example.com".to_string()),
                suppress_default_sync_advertisements: true,
                ..Default::default()
            },
        );
        let report = engine.sync_advertisements().await.unwrap();
        assert!(report.ok(), "no ERROR occurred: {report:?}");
        assert_eq!(report.to_create, 2, "{report:?}");
        assert_eq!(report.admitted_total(), 1, "{report:?}");
        assert!(
            !report.effective(),
            "a partial admit must not read as success: {report:?}"
        );
    }

    #[tokio::test]
    async fn sync_report_lookup_failure_refuses_creation() {
        // #320 M2: a transient read failure must never become "current ads
        // = none" and re-create (re-pay) the whole set — creation is
        // REFUSED and the failure lands in the report.
        let (mut adv, created) = TrackingAdvertiser::new();
        adv.find_fails = true;
        let report = sync_test_engine(adv).sync_advertisements().await.unwrap();
        assert!(!report.ok(), "{report:?}");
        assert!(!report.effective());
        assert!(
            report
                .lookup_error
                .as_deref()
                .unwrap_or_default()
                .contains("mock lookup refused"),
            "{report:?}"
        );
        assert_eq!(report.to_create, 0, "creation refused, not attempted");
        assert!(
            created.lock().unwrap().is_empty(),
            "no create call on a blind read"
        );
        assert!(report.submit_error.is_none());
    }

    #[tokio::test]
    async fn sync_report_counts_skipped_revocations() {
        // #320 L2: `to_revoke: N` with a v1 no-op advertiser must be
        // distinguishable from a revoke that actually ran.
        let (mut adv, _) = TrackingAdvertiser::new();
        adv.revoke_empty = true;
        adv.existing_ship = vec![
            Advertisement {
                protocol: Protocol::Ship,
                identity_key: "02aa".to_string(),
                domain: "https://valid.example.com".to_string(),
                topic_or_service: "tm_test".to_string(),
                beef: None,
                output_index: None,
            },
            Advertisement {
                protocol: Protocol::Ship,
                identity_key: "02aa".to_string(),
                domain: "https://valid.example.com".to_string(),
                topic_or_service: "tm_stale".to_string(), // no longer configured
                beef: None,
                output_index: None,
            },
        ];
        let report = sync_test_engine(adv).sync_advertisements().await.unwrap();
        assert!(report.ok(), "{report:?}");
        assert_eq!(report.to_revoke, 1, "tm_stale is stale");
        assert_eq!(
            report.revoke_skipped, 1,
            "the v1 no-op must be visible, not silent: {report:?}"
        );
        assert!(report.revoke_error.is_none());
        assert!(report.revoke_submit_error.is_none());
    }

    // ── complete_missing_proofs (#130) ─────────────────────────────────

    use crate::gasp::{AncestorFetcher, FetchedAncestor, GASPError};
    use std::cell::Cell;

    /// A single raw mainnet tx (no proof) — used to build a proofless BEEF.
    const PROOFLESS_RAW_TX: &str = "0100000001c997a5e56e104102fa209c6a852dd90660a20b2d9c352423edce25857fcd3704000000004847304402204e45e16932b8af514961a1d3a1a25fdf3f4f7732e9d624c6c61548ab5fb8cd410220181522ec8eca07de4860a4acdd12909d831cc56cbbac4622082221a8768d1d0901ffffffff0200ca9a3b00000000434104ae1a62fe09c5f51b13905f07f06b99a2f7159b2225f374cd378d71302fa28414e7aab37397f554a7df5f142c21c1b7303b8a0626f1baded5c72a704f7e6cd84cac00286bee0000000043410411db93e1dcdb8a016b49840f8c53bc1eb68a382e97b1482ecad7b148a6909a5cb2e0eaddfb84ccf9744464f82e160bfa9b8b64f9d4c03f999b8643f656b412a3ac00000000";

    /// Build a proofless single-tx BEEF + return `(beef_bytes, txid)`.
    fn proofless_beef() -> (Vec<u8>, String) {
        use bsv_rs::transaction::{Beef, Transaction};
        let tx = Transaction::from_hex(PROOFLESS_RAW_TX).unwrap();
        let txid = tx.id();
        let mut beef = Beef::new();
        beef.merge_transaction(tx);
        (beef.to_binary(), txid)
    }

    // ── #284: stitching a proof must never rebuild the stored BEEF ─────────

    /// The corruption shape observed live on rust-beta: a stored BEEF whose
    /// SUBJECT is not the last tx in wire order. The old rewrite went through
    /// `Transaction::from_beef(bytes, None)`, whose None arm picks
    /// `txs.last()` — the PARENT here — and `to_beef(true)` then serialized the
    /// parent's world, dropping the subject from its own row. TEST_BEEF_HEX is
    /// exactly a two-tx chain (parent + child spending it), so re-encoding it
    /// child-first reproduces the trigger byte-for-byte.
    fn subject_not_last_beef() -> (Vec<u8>, String, String) {
        use bsv_rs::transaction::Beef;
        let parsed = Beef::from_binary(&test_beef()).unwrap();
        let parent = parsed.txs[0].tx().unwrap().clone();
        let child = parsed.txs[1].tx().unwrap().clone();
        let (parent_id, child_id) = (parent.id(), child.id());
        assert_ne!(parent_id, child_id);

        // Serialize via to_writer, NOT to_binary: to_binary re-sorts
        // parents-first (subject last), which is precisely why bsv_rs's own
        // output never triggers the bug. The corrupt rows held WALLET
        // serialized bytes stored verbatim at admit time, whose wire order is
        // whatever the wallet emitted — model that by writing the child first.
        let mut beef = Beef::new();
        beef.merge_transaction(child); // subject FIRST — the trigger
        beef.merge_transaction(parent);
        let mut w = bsv_rs::primitives::encoding::Writer::new();
        beef.to_writer(&mut w);
        let bytes = w.into_bytes();

        // The premise the whole test rests on: wire order preserved, subject
        // genuinely not last.
        let reread = Beef::from_binary(&bytes).unwrap();
        assert_eq!(reread.txs.last().unwrap().txid(), parent_id);
        (bytes, child_id, parent_id)
    }

    #[test]
    fn stitch_preserves_the_subject_when_it_is_not_last() {
        use bsv_rs::transaction::{Beef, MerklePath};
        let (stored, child_id, parent_id) = subject_not_last_beef();
        let proof = MerklePath::from_hex(&single_leaf_bump_hex(&child_id, 900_000)).unwrap();

        let out = Engine::stitch_proof_into_stored_beef(&stored, &child_id, &proof)
            .expect("stitch must succeed on a beef that contains the txid");

        let after = Beef::from_binary(&out).unwrap();
        assert!(
            after.find_txid(&child_id).is_some(),
            "the SUBJECT must survive its own proof-completion"
        );
        assert!(
            after.find_txid(&parent_id).is_some(),
            "the ancestry must survive too"
        );
        assert!(
            after.find_bump(&child_id).is_some(),
            "the stitched bump must prove the subject"
        );
        assert!(
            after.find_bump(&parent_id).is_none(),
            "the parent must NOT be claimed by the child's bump"
        );
    }

    /// The old path, reproduced against the same input, to pin WHY the new one
    /// exists: it demonstrably drops the subject. If bsv_rs ever changes
    /// `from_beef(_, None)` to honor the subject, this starts failing and the
    /// comment trail can be revisited — until then it documents the hazard.
    #[test]
    fn the_old_round_trip_demonstrably_dropped_the_subject() {
        use bsv_rs::transaction::{Beef, Transaction};
        let (stored, child_id, _parent_id) = subject_not_last_beef();
        let tx = Transaction::from_beef(&stored, None).unwrap();
        assert_ne!(
            tx.id(),
            child_id,
            "from_beef(None) picks txs.last(), not the subject — the trigger"
        );
        let rebuilt = tx.to_beef(true).unwrap();
        let reparsed = Beef::from_binary(&rebuilt).unwrap();
        assert!(
            reparsed.find_txid(&child_id).is_none(),
            "the rebuild loses the subject — exactly the #284 artifact"
        );
    }

    /// bsv-low M19 R2 round 3 (review HIGH-1): a stored BEEF whose SUBJECT
    /// sits on a stale (orphan) bump at height H, re-stitched with a
    /// same-height DIFFERENT-root proof, must serialize with the subject on
    /// the NEW bump and the orphan bump dropped — otherwise the hop leg
    /// churns and re-latches the orphan proof forever.
    #[test]
    fn stitch_reanchors_a_subject_off_a_same_height_orphan_bump() {
        use bsv_rs::transaction::{Beef, BeefTx, MerklePath, MerklePathLeaf, Transaction};
        // subject spends a real parent; both are raw in the BEEF
        let parent = Transaction::from_hex(RAW_PARENT).unwrap();
        let parent_id = parent.id();
        let subject = child_of(&parent_id, 0);
        let subject_id = subject.id();
        // the ORPHAN bump: a two-leaf block at H so its root is NOT the txid,
        // and it differs from the canonical block's root
        let orphan = MerklePath::new_unchecked(
            965_771,
            vec![vec![
                MerklePathLeaf::new_txid(0, subject_id.clone()),
                MerklePathLeaf::new(1, "aa".repeat(32)),
            ]],
        )
        .unwrap();
        let mut beef = Beef::new();
        let bi = beef.merge_bump(orphan.clone());
        beef.merge_raw_tx(parent.to_binary(), None);
        beef.merge_raw_tx(subject.to_binary(), Some(bi));
        let orphan_root = orphan.compute_root(Some(&subject_id)).unwrap();
        let stored = beef.to_binary();
        assert_eq!(
            Beef::from_binary(&stored)
                .unwrap()
                .find_bump(&subject_id)
                .map(|b| b.compute_root(Some(&subject_id)).unwrap()),
            Some(orphan_root.clone())
        );
        // the canonical proof at the SAME height, a DIFFERENT root
        let canonical = MerklePath::new_unchecked(
            965_771,
            vec![vec![
                MerklePathLeaf::new_txid(0, subject_id.clone()),
                MerklePathLeaf::new(1, "bb".repeat(32)),
            ]],
        )
        .unwrap();
        let canonical_root = canonical.compute_root(Some(&subject_id)).unwrap();
        assert_ne!(
            canonical_root, orphan_root,
            "the reorg shape: same height, new root"
        );
        let out = Engine::stitch_proof_into_stored_beef(&stored, &subject_id, &canonical).unwrap();
        let after = Beef::from_binary(&out).unwrap();
        // the subject's OWN bump is the canonical one
        let own = after
            .find_txid(&subject_id)
            .and_then(BeefTx::bump_index)
            .and_then(|bi| after.bumps.get(bi))
            .unwrap();
        assert_eq!(
            own.compute_root(Some(&subject_id)).unwrap(),
            canonical_root,
            "the subject re-anchored to the new bump"
        );
        // the orphan bump is gone (only the canonical one remains)
        assert_eq!(
            after.bumps.len(),
            1,
            "the unreferenced orphan bump was dropped"
        );
        // and a reader that uses the tx's OWN bump sees canonical, never orphan
        assert!(after.find_txid(&parent_id).is_some(), "ancestry preserved");
    }

    #[test]
    fn stitch_refuses_a_beef_that_lacks_the_txid() {
        use bsv_rs::transaction::MerklePath;
        let (stored, _c, _p) = subject_not_last_beef();
        let foreign = "aa".repeat(32);
        let proof = MerklePath::from_hex(&single_leaf_bump_hex(&foreign, 900_000)).unwrap();
        assert!(
            Engine::stitch_proof_into_stored_beef(&stored, &foreign, &proof).is_none(),
            "no txid in the beef -> no write, never garbage"
        );
    }

    /// A real mainnet raw tx, the unproven parent for the re-anchor pin.
    const RAW_PARENT: &str = "0100000001c997a5e56e104102fa209c6a852dd90660a20b2d9c352423edce25857fcd3704000000004847304402204e45e16932b8af514961a1d3a1a25fdf3f4f7732e9d624c6c61548ab5fb8cd410220181522ec8eca07de4860a4acdd12909d831cc56cbbac4622082221a8768d1d0901ffffffff0200ca9a3b00000000434104ae1a62fe09c5f51b13905f07f06b99a2f7159b2225f374cd378d71302fa28414e7aab37397f554a7df5f142c21c1b7303b8a0626f1baded5c72a704f7e6cd84cac00286bee0000000043410411db93e1dcdb8a016b49840f8c53bc1eb68a382e97b1482ecad7b148a6909a5cb2e0eaddfb84ccf9744464f82e160bfa9b8b64f9d4c03f999b8643f656b412a3ac00000000";

    /// A minimal raw tx spending `source:vout` with one OP_TRUE output.
    fn child_of(source_txid: &str, vout: u32) -> bsv_rs::transaction::Transaction {
        let mut sx = String::from("0100000001");
        let mut prev = hex::decode(source_txid).unwrap();
        prev.reverse();
        sx.push_str(&hex::encode(prev));
        sx.push_str(&hex::encode(vout.to_le_bytes()));
        sx.push_str("00ffffffff01");
        sx.push_str(&hex::encode(1000u64.to_le_bytes()));
        sx.push_str("015100000000");
        bsv_rs::transaction::Transaction::from_hex(&sx).unwrap()
    }

    /// A minimal valid single-leaf BUMP hex proving `txid` at `height`.
    fn single_leaf_bump_hex(txid: &str, height: u32) -> String {
        use bsv_rs::transaction::{MerklePath, MerklePathLeaf};
        let leaf = MerklePathLeaf::new_txid(0, txid.to_string());
        MerklePath::new_unchecked(height, vec![vec![leaf]])
            .unwrap()
            .to_hex()
    }

    /// Mock fetcher: returns a configured proof (or none) for any txid, and
    /// counts how many times it was asked.
    struct StubFetcher {
        proof: Option<String>,
        calls: Cell<u32>,
    }

    #[async_trait(?Send)]
    impl AncestorFetcher for StubFetcher {
        async fn fetch_ancestor(&self, _txid: &str) -> Result<FetchedAncestor, GASPError> {
            self.calls.set(self.calls.get() + 1);
            Ok(FetchedAncestor {
                raw_tx: PROOFLESS_RAW_TX.to_string(),
                proof: self.proof.clone(),
            })
        }

        /// Models a fetcher whose header source CONFIRMS a stored bump — so the
        /// already-structurally-proven re-verify gate (the window-clog path)
        /// latches without a re-fetch, exactly as before the #192/#193 hardening.
        /// (`verified_proof_for` is left at its default: it delegates to
        /// `fetch_ancestor` above, so the `calls` counter still tracks fetches.)
        async fn verify_proof(&self, _txid: &str, _bump_hex: &str) -> bool {
            true
        }
    }

    /// Build an engine over a storage holding one proofless output, with an
    /// optional ancestor fetcher.
    async fn engine_with_proofless_output(
        fetcher: Option<std::rc::Rc<StubFetcher>>,
    ) -> (Engine, String) {
        let (beef, txid) = proofless_beef();
        let storage = MemoryStorage::new();
        storage
            .insert_output(&Output {
                txid: txid.clone(),
                output_index: 0,
                output_script: vec![0x76],
                satoshis: 1_000_000_000,
                topic: "Hello".to_string(),
                spent: false,
                outputs_consumed: vec![],
                consumed_by: vec![],
                beef: Some(beef),
                block_height: None,
                score: Some(1.0),
            })
            .await
            .unwrap();

        let mut managers: HashMap<String, Box<dyn TopicManager>> = HashMap::new();
        managers.insert(
            "Hello".into(),
            Box::new(MockTopicManager::admitting(vec![0])),
        );
        let mut engine = Engine::new(
            managers,
            HashMap::new(),
            Box::new(storage),
            None,
            EngineConfig::default(),
        );
        if let Some(f) = fetcher {
            engine.set_ancestor_fetcher(f);
        }
        (engine, txid)
    }

    #[tokio::test]
    async fn complete_missing_proofs_noop_without_fetcher() {
        // No ancestor fetcher configured → pure no-op (production default).
        let (engine, _txid) = engine_with_proofless_output(None).await;
        let summary = engine.complete_missing_proofs(50, 0).await.unwrap();
        assert_eq!(summary, ProofCompletionSummary::default());
    }

    #[tokio::test]
    async fn complete_missing_proofs_stitches_when_fetcher_returns_proof() {
        let (_beef, txid) = proofless_beef();
        let proof_hex = single_leaf_bump_hex(&txid, 850_000);
        let fetcher = std::rc::Rc::new(StubFetcher {
            proof: Some(proof_hex),
            calls: Cell::new(0),
        });
        let (engine, txid) = engine_with_proofless_output(Some(fetcher.clone())).await;

        let summary = engine.complete_missing_proofs(50, 0).await.unwrap();
        assert_eq!(summary.scanned, 1);
        assert_eq!(summary.proofless, 1);
        assert_eq!(
            summary.completed, 1,
            "the proofless BEEF should be completed"
        );
        assert_eq!(fetcher.calls.get(), 1);

        // The stored BEEF now carries a proof for the target tx + the output
        // got its block height.
        let out = engine
            .storage()
            .find_output(&txid, 0, Some("Hello"), None, true)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(out.block_height, Some(850_000));
        let beef = bsv_rs::transaction::Beef::from_binary(out.beef.as_ref().unwrap()).unwrap();
        assert!(
            beef.find_txid(&txid)
                .is_some_and(bsv_rs::transaction::BeefTx::has_proof),
            "completed BEEF must prove the target tx"
        );

        // A second pass is a no-op: the tx is now proven, so it is not counted
        // proofless and the fetcher is not asked again.
        let summary2 = engine.complete_missing_proofs(50, 0).await.unwrap();
        assert_eq!(summary2.proofless, 0);
        assert_eq!(summary2.completed, 0);
        assert_eq!(fetcher.calls.get(), 1, "no re-fetch once proven");
    }

    #[tokio::test]
    async fn complete_missing_proofs_skips_unconfirmed() {
        // Fetcher reachable but the tx is unmined (no BUMP) → skipped, not
        // errored, and counted still_unconfirmed for retry.
        let fetcher = std::rc::Rc::new(StubFetcher {
            proof: None,
            calls: Cell::new(0),
        });
        let (engine, _txid) = engine_with_proofless_output(Some(fetcher.clone())).await;
        let summary = engine.complete_missing_proofs(50, 0).await.unwrap();
        assert_eq!(summary.proofless, 1);
        assert_eq!(summary.completed, 0);
        assert_eq!(summary.still_unconfirmed, 1);
        assert_eq!(fetcher.calls.get(), 1);
    }

    /// Build an engine like [`engine_with_proofless_output`] but keep a shared
    /// handle to the `MemoryStorage` (via the `Rc<T: Storage>` delegation) so
    /// the test can advance its deterministic clock — the push-primary
    /// backstop age-gate tests (#228) need to age rows without sleeping.
    async fn engine_with_proofless_output_shared(
        fetcher: Option<std::rc::Rc<StubFetcher>>,
    ) -> (Engine, String, std::rc::Rc<MemoryStorage>) {
        let (beef, txid) = proofless_beef();
        let storage = std::rc::Rc::new(MemoryStorage::new());
        storage
            .insert_output(&Output {
                txid: txid.clone(),
                output_index: 0,
                output_script: vec![0x76],
                satoshis: 1_000_000_000,
                topic: "Hello".to_string(),
                spent: false,
                outputs_consumed: vec![],
                consumed_by: vec![],
                beef: Some(beef),
                block_height: None,
                score: Some(1.0),
            })
            .await
            .unwrap();

        let mut managers: HashMap<String, Box<dyn TopicManager>> = HashMap::new();
        managers.insert(
            "Hello".into(),
            Box::new(MockTopicManager::admitting(vec![0])),
        );
        let mut engine = Engine::new(
            managers,
            HashMap::new(),
            Box::new(storage.clone()),
            None,
            EngineConfig::default(),
        );
        if let Some(f) = fetcher {
            engine.set_ancestor_fetcher(f);
        }
        (engine, txid, storage)
    }

    #[tokio::test]
    async fn complete_missing_proofs_age_gate_young_rows_wait_for_the_push() {
        // Push-primary backstop (#228): a FRESHLY stored proofless tx must NOT
        // be polled — its proof is expected via /arc-ingest at push speed. The
        // gated pass scans nothing and never asks the fetcher.
        let proof_hex = {
            let (_beef, txid) = proofless_beef();
            single_leaf_bump_hex(&txid, 850_000)
        };
        let fetcher = std::rc::Rc::new(StubFetcher {
            proof: Some(proof_hex),
            calls: Cell::new(0),
        });
        let (engine, _txid, storage) =
            engine_with_proofless_output_shared(Some(fetcher.clone())).await;

        let summary = engine.complete_missing_proofs(50, 1800).await.unwrap();
        assert_eq!(summary.scanned, 0, "a young row is skipped entirely");
        assert_eq!(fetcher.calls.get(), 0, "no courier fetch for a young row");

        // WEBHOOK-OUTAGE DEGRADATION: no push ever arrives. Once the row is
        // older than the gate, the SAME backstop pass polls and completes it
        // exactly as the pre-#228 behaviour — degradation is to polling,
        // never to nothing.
        storage.advance_clock(1800);
        let summary = engine.complete_missing_proofs(50, 1800).await.unwrap();
        assert_eq!(summary.scanned, 1, "an old-enough row is always polled");
        assert_eq!(summary.completed, 1, "the backstop completes the proof");
        assert_eq!(fetcher.calls.get(), 1);
    }

    #[tokio::test]
    async fn complete_missing_proofs_skips_tx_whose_proof_was_pushed() {
        // Pushed-proof-then-chaser-skips (#228): a proof arriving via the real
        // /arc-ingest producer path (`handle_new_merkle_proof` → the
        // `update_transaction_beef` stitch, which latches `has_proof`) drops
        // the tx out of the poll candidate set entirely — even after the age
        // gate opens, the chaser never asks the fetcher about it.
        let fetcher = std::rc::Rc::new(StubFetcher {
            proof: None,
            calls: Cell::new(0),
        });
        let (engine, txid, storage) =
            engine_with_proofless_output_shared(Some(fetcher.clone())).await;

        // The push lands (arc-ingest calls exactly this after its own
        // chaintracks verify).
        let proof_hex = single_leaf_bump_hex(&txid, 850_000);
        engine
            .handle_new_merkle_proof(&txid, &proof_hex, Some(850_000))
            .await
            .unwrap();

        // Age the row well past the backstop gate: still skipped — the pushed
        // proof, not the age, is what removes it from the chaser's world.
        storage.advance_clock(1_000_000);
        let summary = engine.complete_missing_proofs(50, 1800).await.unwrap();
        assert_eq!(summary.scanned, 0, "a pushed-proof tx is never re-polled");
        assert_eq!(summary.completed, 0);
        assert_eq!(fetcher.calls.get(), 0, "the chaser must skip it entirely");
    }

    #[tokio::test]
    async fn complete_missing_proofs_respects_limit() {
        // Two proofless txs, limit 1 → only one row is scanned this tick.
        let (beef1, txid1) = proofless_beef();
        // A second distinct proofless tx (different raw tx → different txid).
        let raw2 = "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff2803dc7e0e0499170e6a0003cf341b017e0000152f476f72696c6c61506f6f6c2e696f20f09fa68d2f0000000003000000000000000032006a0547504f4f4c08dc7e0e0000000000200158a2360a03939451e72c3a9302f5d48712bf54a5b2edf8f3c69aed35a668e312236000000000001976a914068a58835bb93b152c901ffb18f6578824f9d5b788ac6eb66612000000001976a91402fd5a91155231d5799e2d22c490d1664cde62cb88ac00000000";
        let (beef2, txid2) = {
            use bsv_rs::transaction::{Beef, Transaction};
            let tx = Transaction::from_hex(raw2).unwrap();
            let id = tx.id();
            let mut b = Beef::new();
            b.merge_transaction(tx);
            (b.to_binary(), id)
        };

        let storage = MemoryStorage::new();
        for (txid, beef) in [(&txid1, beef1), (&txid2, beef2)] {
            storage
                .insert_output(&Output {
                    txid: txid.clone(),
                    output_index: 0,
                    output_script: vec![0x76],
                    satoshis: 1000,
                    topic: "Hello".to_string(),
                    spent: false,
                    outputs_consumed: vec![],
                    consumed_by: vec![],
                    beef: Some(beef),
                    block_height: None,
                    score: Some(1.0),
                })
                .await
                .unwrap();
        }

        let fetcher = std::rc::Rc::new(StubFetcher {
            proof: None,
            calls: Cell::new(0),
        });
        let mut managers: HashMap<String, Box<dyn TopicManager>> = HashMap::new();
        managers.insert(
            "Hello".into(),
            Box::new(MockTopicManager::admitting(vec![0])),
        );
        let mut engine = Engine::new(
            managers,
            HashMap::new(),
            Box::new(storage),
            None,
            EngineConfig::default(),
        );
        engine.set_ancestor_fetcher(fetcher.clone());

        let summary = engine.complete_missing_proofs(1, 0).await.unwrap();
        assert_eq!(summary.scanned, 1, "limit 1 → only one row scanned");
    }

    #[tokio::test]
    async fn complete_missing_proofs_marks_already_proven_rows_so_window_advances() {
        // Window-clog regression (#130): migration 0010 defaulted EVERY
        // existing `transactions` row to has_proof = 0, including rows whose
        // stored BEEF already carries a proof (e.g. GASP-synced txs). The
        // candidate query (`WHERE has_proof = 0 LIMIT n`) returns those rows
        // every tick; the engine skips them but — before this fix — never
        // flipped the flag, so they lingered in the bounded window forever and
        // starved genuinely-proofless rows behind them. The fix marks each
        // already-proven scanned row so it drops out of the NEXT pass.
        use bsv_rs::transaction::{Beef, MerklePath, Transaction};

        let storage = MemoryStorage::new();

        // Seed several ALREADY-PROVEN rows. They are inserted via
        // `insert_output`, which (modeling migration 0010's default) does NOT
        // set the proof flag — so despite carrying a valid proof they show up
        // as has_proof = 0 candidates: the exact clog.
        let proven_raws = [
            "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff2803dc7e0e0499170e6a0003cf341b017e0000152f476f72696c6c61506f6f6c2e696f20f09fa68d2f0000000003000000000000000032006a0547504f4f4c08dc7e0e0000000000200158a2360a03939451e72c3a9302f5d48712bf54a5b2edf8f3c69aed35a668e312236000000000001976a914068a58835bb93b152c901ffb18f6578824f9d5b788ac6eb66612000000001976a91402fd5a91155231d5799e2d22c490d1664cde62cb88ac00000000",
            "0100000001c997a5e56e104102fa209c6a852dd90660a20b2d9c352423edce25857fcd3704000000004847304402204e45e16932b8af514961a1d3a1a25fdf3f4f7732e9d624c6c61548ab5fb8cd410220181522ec8eca07de4860a4acdd12909d831cc56cbbac4622082221a8768d1d0901ffffffff0200ca9a3b00000000434104ae1a62fe09c5f51b13905f07f06b99a2f7159b2225f374cd378d71302fa28414e7aab37397f554a7df5f142c21c1b7303b8a0626f1baded5c72a704f7e6cd84cac00286bee0000000043410411db93e1dcdb8a016b49840f8c53bc1eb68a382e97b1482ecad7b148a6909a5cb2e0eaddfb84ccf9744464f82e160bfa9b8b64f9d4c03f999b8643f656b412a3ac00000000",
        ];
        let mut proven_ids = Vec::new();
        for raw in proven_raws {
            let mut tx = Transaction::from_hex(raw).unwrap();
            let id = tx.id();
            tx.merkle_path =
                Some(MerklePath::from_hex(&single_leaf_bump_hex(&id, 800_000)).unwrap());
            // to_beef(true) carries the merkle proof into the BEEF, so the row
            // genuinely IS proven — yet its flag stays 0 (insert path).
            let proven_beef = tx.to_beef(true).unwrap();
            assert_eq!(
                Beef::from_binary(&proven_beef)
                    .unwrap()
                    .find_txid(&id)
                    .map(bsv_rs::transaction::BeefTx::has_proof),
                Some(true),
                "proven fixture row must carry its proof"
            );
            proven_ids.push(id.clone());
            storage
                .insert_output(&Output {
                    txid: id,
                    output_index: 0,
                    output_script: vec![0x76],
                    satoshis: 1000,
                    topic: "Hello".to_string(),
                    spent: false,
                    outputs_consumed: vec![],
                    consumed_by: vec![],
                    beef: Some(proven_beef),
                    block_height: Some(800_000),
                    score: Some(1.0),
                })
                .await
                .unwrap();
        }

        let fetcher = std::rc::Rc::new(StubFetcher {
            proof: None,
            calls: Cell::new(0),
        });
        let mut managers: HashMap<String, Box<dyn TopicManager>> = HashMap::new();
        managers.insert(
            "Hello".into(),
            Box::new(MockTopicManager::admitting(vec![0])),
        );
        let mut engine = Engine::new(
            managers,
            HashMap::new(),
            Box::new(storage),
            None,
            EngineConfig::default(),
        );
        engine.set_ancestor_fetcher(fetcher.clone());

        // First pass over a window covering both proven rows: each is detected
        // already-proven and marked. Nothing proofless, nothing fetched.
        let summary = engine.complete_missing_proofs(50, 0).await.unwrap();
        assert_eq!(summary.scanned, proven_ids.len());
        assert_eq!(summary.proofless, 0);
        assert_eq!(summary.completed, 0);
        assert_eq!(
            summary.already_proven,
            proven_ids.len(),
            "every already-proven row is marked this pass"
        );
        assert_eq!(fetcher.calls.get(), 0, "no fetch for already-proven rows");

        // Window has advanced: the NEXT candidate query no longer returns the
        // marked rows, so the pass scans nothing.
        let summary2 = engine.complete_missing_proofs(50, 0).await.unwrap();
        assert_eq!(summary2.scanned, 0, "marked rows dropped out of the window");
        assert_eq!(summary2.already_proven, 0);
    }

    #[tokio::test]
    async fn complete_missing_proofs_reaches_proofless_tx_behind_clogging_proven_rows() {
        // The window-clog in action with a small limit: a genuinely-proofless
        // backlog row sits behind already-proven (stale-flag) rows. Each tick
        // marks the proven rows it scans (dropping them out), so over a few
        // bounded ticks the window advances until the proofless tx is reached
        // + completed — instead of being starved forever.
        use bsv_rs::transaction::{MerklePath, Transaction};

        let storage = MemoryStorage::new();

        let proven_raws = [
            "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff2803dc7e0e0499170e6a0003cf341b017e0000152f476f72696c6c61506f6f6c2e696f20f09fa68d2f0000000003000000000000000032006a0547504f4f4c08dc7e0e0000000000200158a2360a03939451e72c3a9302f5d48712bf54a5b2edf8f3c69aed35a668e312236000000000001976a914068a58835bb93b152c901ffb18f6578824f9d5b788ac6eb66612000000001976a91402fd5a91155231d5799e2d22c490d1664cde62cb88ac00000000",
        ];
        for raw in proven_raws {
            let mut tx = Transaction::from_hex(raw).unwrap();
            let id = tx.id();
            tx.merkle_path =
                Some(MerklePath::from_hex(&single_leaf_bump_hex(&id, 800_000)).unwrap());
            let proven_beef = tx.to_beef(true).unwrap();
            storage
                .insert_output(&Output {
                    txid: id,
                    output_index: 0,
                    output_script: vec![0x76],
                    satoshis: 1000,
                    topic: "Hello".to_string(),
                    spent: false,
                    outputs_consumed: vec![],
                    consumed_by: vec![],
                    beef: Some(proven_beef),
                    block_height: Some(800_000),
                    score: Some(1.0),
                })
                .await
                .unwrap();
        }

        // The historical proofless tx (the f584f846-style backlog row).
        let (proofless, proofless_txid) = proofless_beef();
        storage
            .insert_output(&Output {
                txid: proofless_txid.clone(),
                output_index: 0,
                output_script: vec![0x76],
                satoshis: 1000,
                topic: "Hello".to_string(),
                spent: false,
                outputs_consumed: vec![],
                consumed_by: vec![],
                beef: Some(proofless),
                block_height: None,
                score: Some(1.0),
            })
            .await
            .unwrap();

        let proof_hex = single_leaf_bump_hex(&proofless_txid, 850_000);
        let fetcher = std::rc::Rc::new(StubFetcher {
            proof: Some(proof_hex),
            calls: Cell::new(0),
        });
        let mut managers: HashMap<String, Box<dyn TopicManager>> = HashMap::new();
        managers.insert(
            "Hello".into(),
            Box::new(MockTopicManager::admitting(vec![0])),
        );
        let mut engine = Engine::new(
            managers,
            HashMap::new(),
            Box::new(storage),
            None,
            EngineConfig::default(),
        );
        engine.set_ancestor_fetcher(fetcher.clone());

        // Run bounded ticks (limit 1) until the proofless tx is completed. With
        // 2 rows total a couple of ticks suffice; cap iterations defensively.
        let mut completed_total = 0;
        for _ in 0..5 {
            let s = engine.complete_missing_proofs(1, 0).await.unwrap();
            completed_total += s.completed;
            if completed_total > 0 {
                break;
            }
        }
        assert_eq!(
            completed_total, 1,
            "the proofless backlog tx is reached + completed once the proven rows are marked out of the window"
        );

        let out = engine
            .storage()
            .find_output(&proofless_txid, 0, Some("Hello"), None, true)
            .await
            .unwrap()
            .unwrap();
        let beef = bsv_rs::transaction::Beef::from_binary(out.beef.as_ref().unwrap()).unwrap();
        assert_eq!(
            beef.find_txid(&proofless_txid)
                .map(bsv_rs::transaction::BeefTx::has_proof),
            Some(true),
            "the old proofless tx now carries its proof"
        );
    }

    // ── S2 queue-durable admission (bsv-low 2026-08-29): Phase-3 faults ──
    //
    // The phantom class: under a D1 storm `submit` returned Ok(steak) while
    // its writes failed — the ack outlived the admission. These pins hold
    // the new contract: a fault is REPORTED, the faulted topic is NOT
    // recorded as applied, and a replay of the same bytes re-applies.

    use crate::storage::StorageError;
    use std::rc::Rc;

    /// `MemoryStorage` behind two fault switches. Every method delegates;
    /// the two the tests flip model a D1 write fault (`insert_output`) and
    /// a D1 read fault (`find_output` — the validation's previous-coin scan
    /// AND Phase 3's stale/consumed lookups).
    struct FaultingStorage {
        inner: MemoryStorage,
        fail_insert_output: Cell<bool>,
        fail_find_output: Cell<bool>,
    }

    impl FaultingStorage {
        fn new() -> Rc<Self> {
            Rc::new(Self {
                inner: MemoryStorage::new(),
                fail_insert_output: Cell::new(false),
                fail_find_output: Cell::new(false),
            })
        }
    }

    #[async_trait(?Send)]
    impl Storage for FaultingStorage {
        async fn put_deferred_graph(
            &self,
            record: &crate::gasp::DeferredGraph,
        ) -> Result<crate::gasp::DeferredGraphSave, StorageError> {
            self.inner.put_deferred_graph(record).await
        }
        async fn find_deferred_graphs(
            &self,
            host: &str,
            topic: &str,
        ) -> Result<Vec<crate::gasp::DeferredGraphKey>, StorageError> {
            self.inner.find_deferred_graphs(host, topic).await
        }
        async fn get_deferred_graph(
            &self,
            host: &str,
            topic: &str,
            outpoint: &str,
        ) -> Result<Option<crate::gasp::DeferredGraph>, StorageError> {
            self.inner.get_deferred_graph(host, topic, outpoint).await
        }
        async fn delete_deferred_graph(
            &self,
            host: &str,
            topic: &str,
            outpoint: &str,
        ) -> Result<(), StorageError> {
            self.inner
                .delete_deferred_graph(host, topic, outpoint)
                .await
        }
        async fn record_peer_sync_outcome(
            &self,
            host: &str,
            topic: &str,
            success: bool,
        ) -> Result<(), StorageError> {
            self.inner
                .record_peer_sync_outcome(host, topic, success)
                .await
        }
        async fn get_peer_sync_health(
            &self,
            host: &str,
            topic: &str,
        ) -> Result<crate::storage::PeerSyncHealth, StorageError> {
            self.inner.get_peer_sync_health(host, topic).await
        }
        async fn record_peer_sync_yield(
            &self,
            host: &str,
            topic: &str,
            yielded: bool,
        ) -> Result<crate::storage::PeerYieldStreak, StorageError> {
            self.inner
                .record_peer_sync_yield(host, topic, yielded)
                .await
        }
        async fn insert_output(&self, output: &Output) -> Result<(), StorageError> {
            if self.fail_insert_output.get() {
                return Err(StorageError::Database(
                    "D1_ERROR: storage overloaded".into(),
                ));
            }
            self.inner.insert_output(output).await
        }
        async fn delete_output(
            &self,
            txid: &str,
            output_index: u32,
            topic: &str,
        ) -> Result<(), StorageError> {
            self.inner.delete_output(txid, output_index, topic).await
        }
        async fn mark_utxo_as_spent(
            &self,
            txid: &str,
            output_index: u32,
            topic: &str,
        ) -> Result<(), StorageError> {
            self.inner
                .mark_utxo_as_spent(txid, output_index, topic)
                .await
        }
        async fn update_consumed_by(
            &self,
            txid: &str,
            output_index: u32,
            topic: &str,
            consumed_by: &[Outpoint],
        ) -> Result<(), StorageError> {
            self.inner
                .update_consumed_by(txid, output_index, topic, consumed_by)
                .await
        }
        async fn update_transaction_beef(
            &self,
            txid: &str,
            beef: &[u8],
        ) -> Result<(), StorageError> {
            self.inner.update_transaction_beef(txid, beef).await
        }
        async fn insert_applied_transaction(
            &self,
            tx: &AppliedTransaction,
        ) -> Result<(), StorageError> {
            self.inner.insert_applied_transaction(tx).await
        }
        async fn does_applied_transaction_exist(
            &self,
            tx: &AppliedTransaction,
        ) -> Result<bool, StorageError> {
            self.inner.does_applied_transaction_exist(tx).await
        }
        async fn delete_applied_transaction(
            &self,
            tx: &AppliedTransaction,
        ) -> Result<(), StorageError> {
            self.inner.delete_applied_transaction(tx).await
        }
        async fn find_output(
            &self,
            txid: &str,
            output_index: u32,
            topic: Option<&str>,
            spent: Option<bool>,
            include_beef: bool,
        ) -> Result<Option<Output>, StorageError> {
            if self.fail_find_output.get() {
                return Err(StorageError::Database("D1_ERROR: read timed out".into()));
            }
            self.inner
                .find_output(txid, output_index, topic, spent, include_beef)
                .await
        }
        async fn find_outputs_for_transaction(
            &self,
            txid: &str,
            include_beef: bool,
        ) -> Result<Vec<Output>, StorageError> {
            self.inner
                .find_outputs_for_transaction(txid, include_beef)
                .await
        }
        async fn find_utxos_for_topic(
            &self,
            topic: &str,
            since: Option<f64>,
            limit: Option<u64>,
            include_beef: bool,
        ) -> Result<Vec<Output>, StorageError> {
            self.inner
                .find_utxos_for_topic(topic, since, limit, include_beef)
                .await
        }
        async fn update_last_interaction(
            &self,
            host: &str,
            topic: &str,
            since: u64,
        ) -> Result<(), StorageError> {
            self.inner.update_last_interaction(host, topic, since).await
        }
        async fn get_last_interaction(&self, host: &str, topic: &str) -> Result<u64, StorageError> {
            self.inner.get_last_interaction(host, topic).await
        }
    }

    fn make_faulting_engine(admit_indices: Vec<u32>) -> (Engine, Rc<FaultingStorage>) {
        let storage = FaultingStorage::new();
        let mut managers: HashMap<String, Box<dyn TopicManagerTrait>> = HashMap::new();
        managers.insert(
            "tm_test".to_string(),
            Box::new(MockTopicManager::admitting(admit_indices)),
        );
        let mut lookup_services: HashMap<String, Box<dyn LookupServiceTrait>> = HashMap::new();
        lookup_services.insert("ls_test".to_string(), Box::new(MockLookupService::new()));
        let engine = Engine::new(
            managers,
            lookup_services,
            Box::new(Rc::clone(&storage)),
            None,
            EngineConfig::default(),
        );
        (engine, storage)
    }

    async fn applied(storage: &FaultingStorage) -> bool {
        storage
            .does_applied_transaction_exist(&AppliedTransaction {
                txid: TEST_TXID.to_string(),
                topic: "tm_test".to_string(),
            })
            .await
            .unwrap()
    }

    /// The old behaviour, pinned: a clean submit is durable, records the
    /// topic as applied, and the output is in storage.
    #[tokio::test]
    async fn clean_submit_is_durable_and_records_applied() {
        let (engine, storage) = make_faulting_engine(vec![0]);
        let (steak, report) = engine
            .submit_with_report(&test_tagged_beef(vec!["tm_test"]), SubmitMode::CurrentTx)
            .await
            .unwrap();
        assert_eq!(steak["tm_test"].outputs_to_admit, vec![0]);
        assert!(report.is_durable(), "{}", report.summary());
        assert_eq!(report.applied_topics, vec!["tm_test".to_string()]);
        assert!(applied(&storage).await);
        assert!(storage
            .find_output(TEST_TXID, 0, Some("tm_test"), None, false)
            .await
            .unwrap()
            .is_some());
    }

    /// THE PHANTOM, red→green: the insert fails, the steak still says
    /// "admitted" (the decision stands), but the report says NOT DURABLE and
    /// names the site — and the topic is NOT recorded as applied, so nothing
    /// downstream can treat the loss as final.
    #[tokio::test]
    async fn phase3_write_fault_is_reported_and_blocks_the_applied_record() {
        let (engine, storage) = make_faulting_engine(vec![0]);
        storage.fail_insert_output.set(true);
        let (steak, report) = engine
            .submit_with_report(&test_tagged_beef(vec!["tm_test"]), SubmitMode::CurrentTx)
            .await
            .unwrap();
        assert_eq!(
            steak["tm_test"].outputs_to_admit,
            vec![0],
            "the admission DECISION is unchanged by a write fault"
        );
        assert!(!report.is_durable());
        assert_eq!(report.faults.len(), 1, "{}", report.summary());
        assert_eq!(report.faults[0].topic, "tm_test");
        assert_eq!(report.faults[0].site, "insert_output");
        assert!(report.faults[0].error.contains("D1_ERROR"));
        assert!(report.applied_topics.is_empty());
        assert!(
            !applied(&storage).await,
            "a faulted topic must not be recorded as applied — the replay would be a dupe"
        );
        assert!(storage
            .find_output(TEST_TXID, 0, Some("tm_test"), None, false)
            .await
            .unwrap()
            .is_none());
    }

    /// The replay: same bytes, storage healthy again → re-validated (not a
    /// dupe), re-written, recorded. A THIRD submit is then the dupe it
    /// should be: nothing admitted, nothing to write, durable.
    #[tokio::test]
    async fn replay_after_a_fault_reapplies_and_records_applied() {
        let (engine, storage) = make_faulting_engine(vec![0]);
        storage.fail_insert_output.set(true);
        let (_, first) = engine
            .submit_with_report(&test_tagged_beef(vec!["tm_test"]), SubmitMode::CurrentTx)
            .await
            .unwrap();
        assert!(!first.is_durable());

        storage.fail_insert_output.set(false);
        let (steak, replay) = engine
            .submit_with_report(&test_tagged_beef(vec!["tm_test"]), SubmitMode::CurrentTx)
            .await
            .unwrap();
        assert_eq!(
            steak["tm_test"].outputs_to_admit,
            vec![0],
            "re-validated, not deduped"
        );
        assert!(replay.is_durable(), "{}", replay.summary());
        assert_eq!(replay.applied_topics, vec!["tm_test".to_string()]);
        assert!(applied(&storage).await);
        assert!(storage
            .find_output(TEST_TXID, 0, Some("tm_test"), None, false)
            .await
            .unwrap()
            .is_some());

        let (steak, third) = engine
            .submit_with_report(&test_tagged_beef(vec!["tm_test"]), SubmitMode::CurrentTx)
            .await
            .unwrap();
        assert!(
            steak["tm_test"].outputs_to_admit.is_empty(),
            "now a genuine dupe: nothing admitted"
        );
        assert!(third.is_durable() && third.applied_topics.is_empty());
    }

    /// The SPEND half of the phantom: a `find_output` fault during
    /// validation made a settle look like it consumed nothing, so the spend
    /// pointer was never written and the ack stood. Now the read fault is
    /// reported, the topic stays unrecorded, the previously-admitted coin
    /// is untouched — and the healthy replay consumes it.
    #[tokio::test]
    async fn validation_read_fault_is_reported_and_the_replay_consumes_the_coin() {
        let (engine, storage) = make_faulting_engine(vec![0]);
        // The subject's own input: seed the coin it spends as a previously
        // admitted tm_test output.
        let tx = Transaction::from_beef(&test_beef(), None).unwrap();
        let source_txid = tx.inputs[0].get_source_txid().unwrap();
        let source_vout = tx.inputs[0].source_output_index;
        storage
            .insert_output(&Output {
                txid: source_txid.clone(),
                output_index: source_vout,
                output_script: vec![0x51],
                satoshis: 1,
                topic: "tm_test".to_string(),
                spent: false,
                outputs_consumed: vec![],
                consumed_by: vec![],
                beef: None,
                block_height: None,
                score: Some(1.0),
            })
            .await
            .unwrap();

        storage.fail_find_output.set(true);
        let (_, faulted) = engine
            .submit_with_report(&test_tagged_beef(vec!["tm_test"]), SubmitMode::CurrentTx)
            .await
            .unwrap();
        assert!(!faulted.is_durable());
        assert!(
            faulted.faults.iter().any(|f| f.site == "find_output"),
            "{}",
            faulted.summary()
        );
        assert!(
            !applied(&storage).await,
            "unrecorded: the replay must re-read"
        );
        storage.fail_find_output.set(false);
        assert!(
            storage
                .find_output(&source_txid, source_vout, Some("tm_test"), None, false)
                .await
                .unwrap()
                .is_some(),
            "the coin the faulted pass could not see is still there, untouched"
        );

        let (_, replay) = engine
            .submit_with_report(&test_tagged_beef(vec!["tm_test"]), SubmitMode::CurrentTx)
            .await
            .unwrap();
        assert!(replay.is_durable(), "{}", replay.summary());
        assert!(applied(&storage).await);
        // The mock manager retains no coins, so the consumed coin is stale
        // and deleted — the observable proof the spend was PROCESSED.
        assert!(
            storage
                .find_output(&source_txid, source_vout, Some("tm_test"), None, false)
                .await
                .unwrap()
                .is_none(),
            "the healthy replay consumed the coin the faulted pass missed"
        );
    }

    /// bsv-low PLAN-PRE-LOOP4 §H4 (2026-09-06): a lookup service that missed
    /// its admit notification is told AGAIN from the engine's own stored
    /// outputs — one call per admitted output per service, the WholeTx body
    /// naming the subject — while `/submit` of the same bytes is deduped and
    /// tells nobody (the premise, RED-verified in the same test); a topic the
    /// engine never admitted this txid on yields 0 (the caller re-submits).
    #[tokio::test]
    async fn renotify_admitted_replays_the_admit_from_stored_outputs() {
        use std::cell::RefCell;
        use std::rc::Rc;

        struct CountingLs(Rc<RefCell<Vec<(String, u32, String)>>>, AdmissionMode);
        #[async_trait(?Send)]
        impl LookupServiceTrait for CountingLs {
            fn admission_mode(&self) -> AdmissionMode {
                self.1
            }
            fn spend_notification_mode(&self) -> SpendNotificationMode {
                SpendNotificationMode::None
            }
            async fn output_admitted_by_topic(
                &self,
                payload: &OutputAdmittedByTopic,
            ) -> Result<(), LookupServiceError> {
                let rec = match payload {
                    OutputAdmittedByTopic::LockingScript {
                        txid,
                        output_index,
                        topic,
                        ..
                    } => (txid.clone(), *output_index, topic.clone()),
                    OutputAdmittedByTopic::WholeTx {
                        atomic_beef,
                        output_index,
                        topic,
                        ..
                    } => {
                        let beef = Beef::from_binary(atomic_beef).expect("the WholeTx body parses");
                        (
                            beef.atomic_txid
                                .clone()
                                .expect("the WholeTx body NAMES its subject"),
                            *output_index,
                            topic.clone(),
                        )
                    }
                };
                self.0.borrow_mut().push(rec);
                Ok(())
            }
            async fn output_evicted(
                &self,
                _txid: &str,
                _output_index: u32,
            ) -> Result<(), LookupServiceError> {
                Ok(())
            }
            async fn lookup(
                &self,
                _question: &LookupQuestion,
            ) -> Result<LookupResult, LookupServiceError> {
                Ok(LookupResult::OutputList(Vec::new()))
            }
            async fn get_documentation(&self) -> String {
                "counting".to_string()
            }
            async fn get_metadata(&self) -> ServiceMetadata {
                ServiceMetadata {
                    name: "counting-ls".to_string(),
                    ..Default::default()
                }
            }
        }

        let mut managers: HashMap<String, Box<dyn TopicManagerTrait>> = HashMap::new();
        managers.insert(
            "tm_test".to_string(),
            Box::new(MockTopicManager::admitting(vec![0])),
        );
        let seen = Rc::new(RefCell::new(Vec::new()));
        let mut lookup_services: HashMap<String, Box<dyn LookupServiceTrait>> = HashMap::new();
        lookup_services.insert(
            "ls_whole".to_string(),
            Box::new(CountingLs(seen.clone(), AdmissionMode::WholeTx)),
        );
        lookup_services.insert(
            "ls_script".to_string(),
            Box::new(CountingLs(seen.clone(), AdmissionMode::LockingScript)),
        );
        let engine = Engine::new(
            managers,
            lookup_services,
            Box::new(MemoryStorage::new()),
            None,
            EngineConfig::default(),
        );

        let tagged = test_tagged_beef(vec!["tm_test"]);
        engine.submit(&tagged, SubmitMode::CurrentTx).await.unwrap();
        assert_eq!(seen.borrow().len(), 2, "one admit per service");
        let (txid, vout, _) = seen.borrow()[0].clone();
        assert_eq!(txid, TEST_TXID);

        // the premise, RED-verified: the same bytes again are DEDUPED — /submit can never re-notify
        let (_, report) = engine
            .submit_with_report(&tagged, SubmitMode::CurrentTx)
            .await
            .unwrap();
        assert_eq!(report.deduped_topics, vec!["tm_test".to_string()]);
        assert_eq!(seen.borrow().len(), 2, "dedup told nobody");

        // the verb: told again from the stored outputs, the WholeTx body naming the subject
        let r = engine.renotify_admitted(&txid, "tm_test").await.unwrap();
        assert_eq!((r.outputs, r.notified, r.faults.len()), (1, 2, 0));
        assert_eq!(r.vouts, vec![vout]);
        assert_eq!(seen.borrow().len(), 4);
        assert!(seen.borrow()[2..]
            .iter()
            .all(|(t, v, topic)| *t == txid && *v == vout && topic == "tm_test"));

        // a topic the engine never admitted this txid on: nothing to re-notify (re-submit instead)
        let r0 = engine.renotify_admitted(&txid, "tm_other").await.unwrap();
        assert_eq!((r0.outputs, r0.notified), (0, 0));
        assert_eq!(seen.borrow().len(), 4);

        // idempotent: a second re-notify tells everyone again, faults nothing
        let r2 = engine
            .renotify_admitted(&txid.to_ascii_uppercase(), "tm_test")
            .await
            .unwrap();
        assert_eq!((r2.outputs, r2.notified, r2.faults.len()), (1, 2, 0));
        assert_eq!(seen.borrow().len(), 6);
    }

    /// bsv-low PLAN-PRE-LOOP4 §H4: a PHANTOM applied row (the topic admitted
    /// NOTHING) dedups every re-submit of those bytes; forgetting it lets the
    /// same bytes be judged again — while a REAL admission's row is never
    /// forgotten and a missing row is nothing to forget.
    #[tokio::test]
    async fn forget_phantom_applied_unblocks_a_resubmit_but_never_a_real_admission() {
        // phantom: a TM that admits nothing still records the topic as applied
        let engine = make_engine(vec![]);
        let tagged = test_tagged_beef(vec!["tm_test"]);
        let (steak, r1) = engine
            .submit_with_report(&tagged, SubmitMode::CurrentTx)
            .await
            .unwrap();
        assert!(steak.get("tm_test").unwrap().outputs_to_admit.is_empty());
        assert_eq!(r1.applied_topics, vec!["tm_test".to_string()]);
        let (_, r2) = engine
            .submit_with_report(&tagged, SubmitMode::CurrentTx)
            .await
            .unwrap();
        assert_eq!(
            r2.deduped_topics,
            vec!["tm_test".to_string()],
            "the phantom row dedups the re-submit"
        );
        assert!(engine
            .forget_phantom_applied(TEST_TXID, "tm_test")
            .await
            .unwrap());
        let (_, r3) = engine
            .submit_with_report(&tagged, SubmitMode::CurrentTx)
            .await
            .unwrap();
        assert!(
            r3.deduped_topics.is_empty(),
            "judged again after the forget"
        );
        assert!(
            !engine
                .forget_phantom_applied(TEST_TXID, "tm_other")
                .await
                .unwrap(),
            "no row: nothing to forget"
        );

        // real: a TM that admits output 0 — its row is a real admission, never forgotten
        let real = make_engine(vec![0]);
        real.submit(&tagged, SubmitMode::CurrentTx).await.unwrap();
        assert!(!real
            .forget_phantom_applied(TEST_TXID, "tm_test")
            .await
            .unwrap());
        let (_, r4) = real
            .submit_with_report(&tagged, SubmitMode::CurrentTx)
            .await
            .unwrap();
        assert_eq!(
            r4.deduped_topics,
            vec!["tm_test".to_string()],
            "a real admission still dedups"
        );
    }

    // ── NL-6e: the SPV walk is linear in a BUMP's leaves (NL-8 W1) ─────

    /// Named and generous (a debug build on a loaded machine): the walk at
    /// bsv-rs 0.4.0 took 30 to 36 s at 4,096 leaves in release and gave no
    /// answer in 120 s at 8,192 (NL-8 W1).
    const WIDE_BUMP_WALK_BOUND: std::time::Duration = std::time::Duration::from_secs(10);

    /// The wide BUMP's height (NL-8's `wide k` row).
    const WIDE_HEIGHT: u32 = 800_001;

    /// `2^k` txids, display hex: the double SHA-256 of `i` (NL-8's probe).
    fn wide_leaves(k: u32) -> Vec<String> {
        (0..1u32 << k)
            .map(|i| {
                let mut id = bsv_rs::primitives::sha256d(&i.to_le_bytes()).to_vec();
                id.reverse();
                hex::encode(id)
            })
            .collect()
    }

    /// One BUMP at [`WIDE_HEIGHT`] whose level 0 carries `txids` as hashed
    /// leaves and whose `k - 1` upper levels are empty: every node above
    /// level 0 is computed from it. Its root, by one walk.
    fn wide_bump(txids: &[String]) -> (bsv_rs::transaction::MerklePath, String) {
        let k = txids.len().trailing_zeros() as usize;
        let mut levels = vec![Vec::new(); k];
        levels[0] = txids
            .iter()
            .enumerate()
            .map(|(i, id)| bsv_rs::transaction::MerklePathLeaf::new_txid(i as u64, id.clone()))
            .collect();
        let bump = bsv_rs::transaction::MerklePath::new(WIDE_HEIGHT, levels).unwrap();
        let root = bump.compute_root(None).unwrap();
        (bump, root)
    }

    /// NL-8 W1's bytes: a V1 BEEF of the one wide BUMP and no transaction
    /// (`wide_14` at `2^k` leaves, byte for byte the runner's probe).
    fn w1_bytes(k: u32) -> (Vec<u8>, String) {
        let (bump, root) = wide_bump(&wide_leaves(k));
        let mut beef = vec![0x01, 0x00, 0xbe, 0xef, 0x01];
        beef.extend_from_slice(&bump.to_binary());
        beef.push(0x00);
        (beef, root)
    }

    /// The entry, [`verify_spv_like_the_reference`], on its own thread under
    /// a tracker that carries `root` at [`WIDE_HEIGHT`]: its answer and its
    /// time, or a panic naming the bound.
    fn walk_within_bound(
        bytes: Vec<u8>,
        root: String,
        verify_scripts: bool,
        subject: String,
        what: &str,
    ) -> (Result<(), String>, std::time::Duration) {
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let mut tracker = bsv_rs::transaction::MockChainTracker::new(WIDE_HEIGHT + 10);
            tracker.add_root(WIDE_HEIGHT, root);
            let runtime = tokio::runtime::Builder::new_current_thread()
                .build()
                .unwrap();
            let started = std::time::Instant::now();
            let verdict = runtime.block_on(verify_spv_like_the_reference(
                Some(&tracker),
                verify_scripts,
                &bytes,
                &subject,
                DoorBudget::DEFAULT,
            ));
            let verdict = match verdict {
                Ok(None) => Ok(()),
                Ok(Some(stop)) => Err(format!("the walk could not run: {stop:?}")),
                Err(e) => Err(e.to_string()),
            };
            let _ = tx.send((verdict, started.elapsed()));
        });
        rx.recv_timeout(WIDE_BUMP_WALK_BOUND).unwrap_or_else(|_| {
            panic!("{what}: no answer from the walk within {WIDE_BUMP_WALK_BOUND:?}")
        })
    }

    /// The escape hatch's structural walk (`verify_scripts` false) on NL-8
    /// W1's bytes, 4,096 and 8,192 leaves: accepted, the one root asked of
    /// the tracker, well inside the bound.
    #[test]
    fn nl6e_the_structural_walk_is_linear_in_a_bump_s_leaves() {
        for k in [12u32, 13] {
            let (bytes, root) = w1_bytes(k);
            let what = format!("2^{k} leaves, {} bytes, structural", bytes.len());
            let (verdict, took) = walk_within_bound(bytes, root, false, String::new(), &what);
            println!(
                "NL-6e W1 {what}: {verdict:?} in {:.3} s",
                took.as_secs_f64()
            );
            assert_eq!(verdict, Ok(()), "{what}");
        }
    }

    /// The default walk (scripts run, `verify_scripts` true) over `2^k`
    /// proven parents in the one wide BUMP, each spent by a binary tree of
    /// two-input transactions whose root is the subject: every parent's
    /// root is the BUMP's, asked of the tracker, the inputs `2^(k+1) - 2`.
    fn proven_fan_in(k: u32) -> (Vec<u8>, String, String) {
        use bsv_rs::script::{LockingScript, UnlockingScript};
        use bsv_rs::transaction::{TransactionInput, TransactionOutput};
        let op_true = || LockingScript::from_binary(&[0x51]).unwrap();
        let spending = |txid: &str| {
            let mut input = TransactionInput::new(txid.to_string(), 0);
            input.unlocking_script = Some(UnlockingScript::from_binary(&[]).unwrap());
            input
        };
        let parents: Vec<Transaction> = (0..1u32 << k)
            .map(|i| {
                let mut tx = Transaction::new();
                // A coinbase's null outpoint, a distinct index each.
                let mut input = TransactionInput::new("00".repeat(32), u32::MAX - i);
                input.unlocking_script = Some(UnlockingScript::from_binary(&[0x51]).unwrap());
                tx.inputs.push(input);
                tx.outputs.push(TransactionOutput::new(1, op_true()));
                tx
            })
            .collect();
        let ids: Vec<String> = parents.iter().map(Transaction::id).collect();
        let (bump, root) = wide_bump(&ids);
        let mut beef = Beef::new();
        let at = beef.merge_bump(bump);
        for parent in &parents {
            beef.merge_raw_tx(parent.to_binary(), Some(at));
        }
        let mut layer = ids;
        while layer.len() > 1 {
            layer = layer
                .chunks(2)
                .map(|pair| {
                    let mut tx = Transaction::new();
                    tx.inputs.push(spending(&pair[0]));
                    tx.inputs.push(spending(&pair[1]));
                    tx.outputs.push(TransactionOutput::new(0, op_true()));
                    beef.merge_raw_tx(tx.to_binary(), None);
                    tx.id()
                })
                .collect();
        }
        (beef.to_binary(), root, layer.remove(0))
    }

    #[test]
    fn nl6e_the_script_walk_is_linear_in_a_bump_s_leaves() {
        for k in [12u32, 13] {
            let (bytes, root, subject) = proven_fan_in(k);
            let what = format!("2^{k} proven parents, {} bytes, scripts", bytes.len());
            let (verdict, took) = walk_within_bound(bytes, root, true, subject, &what);
            println!(
                "NL-6e fan-in {what}: {verdict:?} in {:.3} s",
                took.as_secs_f64()
            );
            assert_eq!(verdict, Ok(()), "{what}");
        }
    }
}