lgwks_bot 2.2.0

Capability-gated automation bots on a change-detecting ECS schedule: Observe, Evaluate, Execute, and Query, with an async runtime facade.
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
//! The four verbs on a `bevy_ecs` substrate.
//!
//! [`Bot`] executes a spec by polling every source on every tick and
//! evaluating every condition on the freshly polled value. That is correct and
//! it re-derives an answer it already had: a source that did not move is
//! evaluated anyway. This module keeps the same four verbs and the same
//! `(condition, action)` tuples, and moves the *execution* onto an ECS where the
//! condition is bevy's own change detection.
//!
//! # The mapping
//!
//! | Verb | On this substrate |
//! |---|---|
//! | `GrantSet` | the `Grants` resource: one authority per world |
//! | `Observe` | a `Chains` entry, polled by the `observe_fold` system |
//! | `Evaluate::check` | `Changed<Revision>` on the source entity |
//! | `Execute::execute_action` | the `fire_plan` system, whose effects run between schedule steps |
//! | `Bot::tick()` | [`EcsBot::tick_async`], one `Schedule::run` between two awaited phases |
//!
//! # One execution path, and who drives it
//!
//! A tick is four phases, and only the middle one is a synchronous schedule
//! step:
//!
//! 1. **observe** — every source is polled, in bounded waves, awaited on the
//!    caller's executor.
//! 2. **decide** — one `Schedule::run` folds those observations into the world
//!    (committing each value and bumping `Revision` where it moved) and records
//!    the effect program for this tick.
//! 3. **act** — the recorded effects run in declaration order, awaited on the
//!    caller's executor.
//! 4. **report** — the count and the first failure are written back.
//!
//! [`EcsBot::tick_async`] is the whole of it, and it is the way to run a bot
//! from async code: the verb futures are awaited *by* the caller's runtime, so
//! a source that waits on a timer, a socket, or a sibling task has a driver
//! making progress underneath it. [`EcsBot::tick`] is a synchronous adapter
//! over the same four phases for verbs that need no reactor; it is refused,
//! not hung, when an async runtime is already driving the calling thread.
//!
//! # One semantic delta, stated rather than discovered
//!
//! [`Bot::tick`] evaluates a condition on **every** tick.
//! `EcsBot::tick` evaluates it only on a tick where the observed value
//! **moved**. For a condition that stays true ("status is 500" while the
//! endpoint stays down) the first fires on every tick and the second fires
//! once, on the transition. That is the point of the substrate, and it is a
//! behaviour change rather than a re-implementation: a bot that must act on a
//! *held* state belongs on `Bot`, and a bot that acts on a *transition* belongs
//! here.
//!
//! # Work outlives the change filter
//!
//! `Changed<Revision>` says a chain is *eligible*; it is not a record of what
//! still has to happen. Committing the revision and then failing halfway marks
//! the source handled, so the entries the failure skipped are never reached on
//! an unchanged source, and a failure in the first chain stops every later
//! chain as well, because the loop that stops is outside the per-chain one.
//!
//! Eligible work therefore lives in its own structure — the ledger — keyed by
//! `(chain, entry)` and by the revision that made it due, and `fire` walks
//! *that* rather than the change set. The filter is consulted only to open a
//! transition; a chain with work outstanding is walked on every tick until the
//! work is settled, whether or not its source moves. One transition per chain
//! at a time: a source that moves again while its work is outstanding joins the
//! transition in progress, because the observed value is the only one the
//! substrate keeps (`Box<dyn Any>` is compared, not cloned) and a second
//! transition would replay effects the first already acknowledged.
//!
//! An entry is never skipped to reach a later one. The walk resumes at the
//! first entry that is not resolved and stops at the first it cannot settle, so
//! an effect that already happened is never replayed to get past a successor —
//! the failure mode where retrying a refused second entry duplicates the first
//! entry's merge. An entry that *may* have happened
//! ([`BotError::EffectIndeterminate`]) is held outright: it is attempted again
//! only when the caller supplies evidence, through `EcsBot::resolve_effect`.
//!
//! A tick is clean only when nothing is left holding a transition. When
//! something is, `EcsBot::tick` reports it — the entry, what is holding it, how
//! many entries are outstanding — so a clean subsequent tick cannot be read as
//! "the transition was handled". An error a source or an action produced keeps
//! precedence over that report, because it carries the typed variant a retry
//! classifier reads; the abandonment it caused is named by `EcsBot::pending`,
//! which lists every entry that is not finished, given-up entries included, with
//! the reason and the source revision. A tick that gives up on work is never
//! clean, and an entry it gave up on is never silently dropped.
//!
//! # A restart continues the record rather than the process
//!
//! [`EcsBot::tick`] is not a boundary the run has to survive: the journal is.
//! Every dispatch appends `IntentAdmitted` and `DispatchPrepared` *before* the
//! effect exists to hand over, so a process that dies mid-attempt leaves a
//! record of an attempt with no outcome behind it — and
//! [`EcsBot::into_journal`] is how a host carries that record into the next
//! process. Assembly folds in every attempt the record names, and the three
//! decisions it takes are deliberately different from one another:
//!
//! - **Outcome unknown** — nothing established whether the bytes arrived, so
//!   the action is *held*. The walk stops at it rather than beginning another
//!   attempt, the tick reports
//!   [`BotError::PendingTransition`], and
//!   the key a caller settles by is on the report.
//! - **Outcome landed** — the effect is done for the generation its key names,
//!   so the walk retires the entry rather than dispatching it again. That
//!   retirement is scoped to the generation: a source that moves opens the next
//!   one, and new work, which is the only thing that may legitimately re-run an
//!   acknowledged action.
//! - **Outcome missing or negative** — an admitted intent that was never handed
//!   over, or a delivery that was established not to have happened. Neither
//!   leaves anything held, so the entry is eligible again — under a *new*
//!   attempt identity, because the journal's ladder allows one walk per key and
//!   the attempt the record already holds cannot be minted twice.
//!
//! # Limits
//!
//! A panic that unwinds out of an action's future unwinds out of `fire` and out
//! of `tick` with it. The walk holds the chain's transition while it runs, so
//! that unwind loses the transition for the chain in flight — the entries it had
//! already resolved with it. Nothing in this module catches an unwind, and the
//! in-flight record it writes before an attempt (`EntryState::Unrecorded`) is
//! therefore durable for a tick that returns, not for a thread that panics. A
//! caller that catches an unwind around `tick` must treat that chain's work as
//! unknown rather than as handled.
//!
//! # What is measured, and what is deliberately not done
//!
//! Three findings from the measurement behind this module (`bevy_ecs` 0.19.1,
//! `default-features = false, features = ["std"]`), each with a control:
//!
//! - **`NonSend` is the only route for a verb.** `Component: Send + Sync +
//!   'static` is unconditional in this version and there is no `non_send`
//!   feature to relax it, so a `Box<dyn Any>` (which the verb erasure produces
//!   and which is not `Send`) cannot be a component. The observers, the
//!   entries and the observed values all live in `NonSend` resources, reachable
//!   only from an exclusive system. The crate's non-`Send` contract is
//!   preserved rather than tightened.
//! - **`Changed<T>` is visible to a second exclusive system in the same tick,
//!   and it is precise.** Against an input that holds still the change filter
//!   matched `[2, 0, 2, 0, 2]` (the ticks where the value actually moved),
//!   which is the whole reason a `Revision` marker exists rather than a
//!   "this system ran" flag.
//! - **Effects do not go through `Commands`.** `auto_insert_apply_deferred`
//!   defaults to `true` but inserts the sync point only where some system is
//!   ordered *after* the writer; a `Commands`-writing system with no successor
//!   has its queue dropped under a manually stepped `Schedule::run`, measured
//!   as 0 effects where 3 were expected. Adding a bare `ApplyDeferred` is not a
//!   fix either: unordered relative to the writer it runs first and defers the
//!   effect by a tick, giving 2 of 3. Both are silent. Here the effect is a
//!   direct resource write from an exclusive system, ordered by `.chain()`.
//!
//! # One path
//!
//! This is how a bot executes, not a candidate the caller may decline. There is
//! no `ecs` feature: `Bot` *is* this, and the project's build and test gate
//! compiles and tests it like any other code. A default-off flag would have left
//! it unexercised and unowned.
//!
//! # Build-time validation
//!
//! `EcsObserveBuilder::build` runs `Schedule::initialize()` with
//! `ambiguity_detection: LogLevel::Error`, so a schedule whose systems cannot be
//! totally ordered is a refusal at build rather than a silent misordering at
//! tick. An exclusive system cannot return an error, so a failure at *tick* time
//! is recorded in the `TickError` resource and surfaced by
//! `EcsBot::tick`: the same error ordering `Bot::tick` documents, where the
//! first error in declaration order is returned.

use std::any::Any;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::future::Future;
use std::num::{NonZeroU32, NonZeroU128};
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::task::{Context, Poll, Waker};
use std::thread;
use std::time::Duration;

// `self` is load-bearing: the `Component` and `Resource` derives expand to
// `bevy_ecs::…` paths, so the crate name has to be in scope at the use site even
// though every edge in this crate is written through the `lgwks_deps` facade.
use crate::effect::InputIdentity;
use lgwks_deps::bevy_ecs::{
    self,
    prelude::{Changed, Component, Entity, Resource, World},
    schedule::{
        IntoScheduleConfigs, LogLevel, Schedule, ScheduleBuildSettings, SingleThreadedExecutor,
    },
};
use lgwks_std::hash::{Digest, Hasher};

use crate::journal::frame::SaturatingFrom;
use crate::journal::owner::{lock, wait_timeout};

use super::broker::{Authority, Broker, DispatchError, prepare_dispatch};
use super::cap::{Deficit, Demand, Shortage};
#[cfg(feature = "ephemeral")]
use super::effect::MintError;
use super::effect::{
    ActionDigest, ActionId, AttemptId, EffectIdentity, EffectKey, EnvironmentEpoch, FlowRevision,
    Id128,
};
use super::error::{BotError, DispatchCertainty, Escaped, RetryClass};
use super::gate::GrantSet;
#[cfg(feature = "ephemeral")]
use super::journal::MemoryJournal;
use super::journal::{
    AttemptStatus, DurabilityPromise, DurableAck, EffectEvent, EffectJournal, EventKind,
    JournalError, JournalPosition, recover,
};
use super::registry::{DomainRegistry, Source};
use super::spec::{
    ActionSpec, Admission, BotSpec, ChainEntry, ChainSpec, Erased, Need, NeedSet, ObserveAny,
    Witness, typed_entry,
};
use super::verb::EffectLifetime;
use super::verb::RefreshReason;
use super::verb::{Evaluate, Execute, Observe};

// The one declared clock every deadline in this crate names (INV-BOT-30). Only
// its wall watchdog is read below — a source that stopped answering is not
// waiting for time, so a logical counter a caller can advance is the wrong
// authority for it — but it is reached through the crate's clock rather than
// through a free-floating `Instant`, which is what makes the elapsed time that
// cancelled a poll traceable to a named authority.
use crate::clock::Clock;

/// The per-stage tick profiler. Compiled out entirely without the default-off
/// `profile` feature: every charge site in this file sits behind the same
/// `cfg`, so a build without it reads no clock and does no per-stage arithmetic.
#[cfg(feature = "profile")]
mod profile;
#[cfg(feature = "profile")]
use profile::Charge;
#[cfg(feature = "profile")]
pub use profile::{TickProfile, TickStage};

// ── The effect path: identity, fencing, and the write-ahead record ─────────

/// The domain separator for an [`ActionId`] derived from a bot's structure.
///
/// A separator rather than a bare concatenation, because the fields hashed into
/// an identity are variable-length strings and a run of them with no framing is
/// a value two different bots can collide on.
const ACTION_ID_DOMAIN: &[u8] = b"lgwks.bot.action-id.v2";

/// The domain separator for an [`ActionDigest`] derived from an admitted input.
const ACTION_DIGEST_DOMAIN: &[u8] = b"lgwks.bot.action-digest.v2";

/// The domain separator for an admitted input's content identity.
///
/// `v2` replaced the `v1` stream, which hashed the compiler-provided
/// `type_name` of the output type. `type_name` is diagnostic and unstable
/// across toolchains, so `v2` binds the [`InputIdentity::SCHEMA_ID`] instead
/// and the two streams are different identities by construction (issue #118).
const OUTPUT_IDENTITY_DOMAIN: &[u8] = b"lgwks.bot.input-identity.v2";

/// The refusal for a journal that already holds a *different* outcome for `key`
/// than the one being settled.
///
/// One constructor for both places that compare a recorded outcome with the
/// evidence in hand, so they cannot name different orderings for one conflict.
fn changed_outcome(key: EffectKey) -> JournalError {
    JournalError::OutOfOrder {
        key: Box::new(key),
        expected: Some(EventKind::Verified),
        attempted: EventKind::OutcomeObserved,
    }
}

/// Hash a sequence of byte fields into the estate's content-identity digest.
///
/// Each field is length-prefixed with its `u64` little-endian width before the
/// bytes themselves, so a variable-length name cannot slide into the next field
/// and produce the same digest for a different parse. A domain separator
/// identifies the format; it does not frame the fields inside it. Indices are
/// always `u64::to_le_bytes` rather than `usize`, so a 32-bit and a 64-bit
/// target derive the same identity for the same bot (issue #101).
fn hash_parts(parts: &[&[u8]]) -> Digest {
    let mut hasher = Hasher::new();
    for part in parts {
        // Length-framed: a stream over several variable-length parts must
        // depend on the parts, not only on their concatenation (issue #118).
        hasher.write_framed(part);
    }
    hasher.finalize()
}

/// A `usize` index as a portable `u64`.
///
/// `usize::to_le_bytes` is 4 bytes on a 32-bit target and 8 on a 64-bit one,
/// so the same bot derived different identities on each. Every index that
/// enters a digest goes through here.
fn portable_index(index: usize) -> u64 {
    u64::saturating_from(index)
}

/// The fallback identity for a binding that cannot name itself.
fn derive_input_stamp(stamp: u64) -> [u8; 16] {
    let digest = hash_parts(&[b"lgwks.bot.input-stamp.v1", &stamp.to_le_bytes()]);
    let mut wide = [0_u8; 16];
    wide.copy_from_slice(&digest.as_bytes()[..16]);
    wide
}

/// Fold a digest into a non-zero 128-bit identifier.
///
/// The all-zero identifier is not a valid one (see [`IdError`]), and a hash has
/// no such exclusion, so a derivation that landed on zero would produce an
/// identity the parser would refuse to read back. The zero case is mapped to
/// [`NonZeroU128::MIN`] rather than refused, because a derivation that can fail
/// is a derivation every caller has to handle, and the collision it introduces
/// is one in 2^128.
///
/// [`IdError`]: crate::effect::IdError
fn id_from_digest(digest: &Digest) -> Id128 {
    let bytes = digest.as_bytes();
    let mut wide = [0_u8; 16];
    for (slot, byte) in wide.iter_mut().zip(bytes.iter()) {
        *slot = *byte;
    }
    match NonZeroU128::new(u128::from_be_bytes(wide)) {
        Some(identity) => Id128::from_nonzero(identity),
        None => Id128::from_nonzero(NonZeroU128::MIN),
    }
}

/// The logical intent of one entry of one chain.
///
/// Derived rather than declared, because the substrate is the only thing that
/// knows a chain's position, and position is what a settlement must survive an
/// edit elsewhere in the document to. The derivation reads the bot's name, the
/// entry's position, and the action's own domain identifier, so two entries
/// with the same domain in the same chain are still two intents.
///
/// `ActionId` is not a content digest, and this is not one either: [`ActionDigest`]
/// is what binds the input, and this binds *which action* it is. Deriving it
/// from the action's own `domain_id` is the closest the erased `ExecuteAny`
/// comes to naming what it does.
fn derive_action_id(bot: &str, chain: usize, entry: usize, domain: &str) -> ActionId {
    ActionId::new(id_from_digest(&hash_parts(&[
        ACTION_ID_DOMAIN,
        bot.as_bytes(),
        &portable_index(chain).to_le_bytes(),
        &portable_index(entry).to_le_bytes(),
        domain.as_bytes(),
    ])))
}

/// The exact admitted input one entry was dispatched from.
///
/// The ECS substrate has no payload bytes to hash: a transition's binding is an
/// erased `Box<dyn Any>` and nothing here asks it to be `Hash`. Content
/// equality is not event identity either — two distinct commands with the same
/// payload must stay distinguishable — so the digest binds the *admitted input
/// identity*: a monotonic stamp minted when the observation was admitted and
/// continued across a restart from the journal's tail, not the process-local
/// `Revision` counter, which reopens at 1 after every reconstruction (issue
/// #101).
///
/// Two attempts within one admitted input share a digest, which is what makes
/// a retry a retry. A new admission gets a new stamp even when the value is
/// equal or the revision counter has wrapped back to 1, which is what stops a
/// restarted bot from reading new work as already applied.
fn derive_action_digest(
    flow: FlowRevision,
    chain: usize,
    entry: usize,
    input: &[u8; 16],
) -> ActionDigest {
    ActionDigest::new(hash_parts(&[
        ACTION_DIGEST_DOMAIN,
        flow.digest().as_bytes(),
        &portable_index(chain).to_le_bytes(),
        &portable_index(entry).to_le_bytes(),
        input,
    ]))
}

/// The effect identity and the two adapters a dispatch is recorded through.
///
/// Handed to [`EcsBuilder::with_effects`], and required: there is no default
/// and no way to build a bot without one. A default would be a default
/// *identity*, and an identity a caller did not choose is one they cannot
/// recover against — which is precisely the state that makes a restart resend a
/// merge.
///
/// The three pieces are separate arguments rather than one because they fail
/// differently. A journal with no durability refuses at the boundary; a broker
/// with the wrong environment refuses to authorize; an identity naming the
/// wrong run makes every recovered key foreign. Fusing them into one value
/// would let a caller construct a scope it cannot reason about piece by piece.
pub struct EffectScope {
    /// Which run this is, which environment it acts on, and which flow revision
    /// it came from.
    identity: EffectIdentity,
    /// The environment generations a dispatch is fenced against.
    broker: Broker,
    /// Where a dispatch is written down before it leaves the process.
    journal: Box<dyn EffectJournal>,
}

/// Why an ephemeral scope could not be built.
///
/// Two arms, because building one crosses two independent refusals: the
/// operating system's entropy source, and the broker's registration of the
/// environment the identity was minted against. Neither converts into the
/// other, and flattening them would name the wrong failure.
#[cfg(feature = "ephemeral")]
#[derive(Debug)]
#[non_exhaustive]
pub enum EphemeralError {
    /// A run or environment identifier could not be minted.
    Mint(MintError),
    /// The broker refused to register the minted environment.
    ///
    /// Unreachable through this constructor, which registers exactly one
    /// freshly minted id into an empty broker, and present because
    /// [`Broker::register`] has a refusal channel and this crate has no
    /// `unwrap` to spend on a proof it cannot state to the compiler.
    Broker(super::broker::BrokerError),
}

#[cfg(feature = "ephemeral")]
impl fmt::Display for EphemeralError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // `*self` and `ref`, for the reason `JournalError` gives: the patterns
        // then carry the enum's own type and `pattern_type_mismatch` is
        // satisfied without a dereference at each field.
        match *self {
            Self::Mint(ref cause) => write!(f, "could not mint an ephemeral identity: {cause}"),
            Self::Broker(ref cause) => {
                write!(f, "could not register the ephemeral environment: {cause}")
            }
        }
    }
}

#[cfg(feature = "ephemeral")]
impl std::error::Error for EphemeralError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match *self {
            Self::Mint(ref cause) => Some(cause),
            Self::Broker(ref cause) => Some(cause),
        }
    }
}

#[cfg(feature = "ephemeral")]
impl From<MintError> for EphemeralError {
    fn from(cause: MintError) -> Self {
        Self::Mint(cause)
    }
}

/// Printed as the journal's promise and position rather than as the journal.
///
/// [`EffectJournal`] is an object-safe trait with no `Debug` bound, and adding
/// one to serve a `{:?}` would push the burden onto every implementation for no
/// gain. What a reader needs is which journal this is and how far it is
/// committed, and both of those the trait already answers.
impl fmt::Debug for EffectScope {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EffectScope")
            .field("identity", &self.identity)
            .field("broker", &self.broker)
            .field("durability", &self.journal.durability())
            .field("tail", &self.journal.tail())
            .finish()
    }
}

impl EffectScope {
    /// Record the identity, the fence and the journal a bot dispatches under.
    ///
    /// A caller with no host identity to supply — a test, an example, or work
    /// whose effects stay in this process — wants `EffectScope::ephemeral()`
    /// (feature `ephemeral`), which mints the identity and pairs it with an
    /// in-memory journal. It is not a shorter spelling of this: the journal it
    /// supplies is one [`EffectJournal::admit_external_handoff`] refuses, so the
    /// two are different capabilities rather than two ways to do one.
    ///
    /// Spelled as a code span rather than a link because the method is behind
    /// that feature, and a `--no-default-features` build has no item to link to
    /// — which the rustdoc gate refuses rather than tolerating.
    #[must_use]
    pub fn new(identity: EffectIdentity, broker: Broker, journal: Box<dyn EffectJournal>) -> Self {
        Self {
            identity,
            broker,
            journal,
        }
    }

    /// A scope for a run whose effects never leave the process.
    ///
    /// The one constructor a caller reaches for when there is no host, no
    /// persisted history and no flow document: a test, an example, or work
    /// whose effects stay inside this process. It mints a fresh run and
    /// environment from OS entropy, registers that environment, and pairs them
    /// with an in-memory journal.
    ///
    /// **The scope is safe to hand to real code because the journal refuses to
    /// be the record behind an external handoff.** [`MemoryJournal`] reports
    /// [`DurabilityPromise::Ephemeral`], and
    /// [`EffectJournal::admit_external_handoff`] returns
    /// [`JournalError::PromiseUnmet`] for it — so a dispatch that would leave
    /// the process fails at the boundary rather than proceeding on a record
    /// that cannot survive the process it was written in. That refusal is what
    /// makes this a capability rather than a testing shortcut: it is the
    /// difference between "no journal" and "a journal that tells you it is not
    /// enough".
    ///
    /// The three pieces [`EffectScope::new`] takes separately are still three
    /// pieces — this supplies all three rather than fusing them, so a caller
    /// that outgrows the ephemeral case can read each one back out
    /// ([`identity`](Self::identity), [`broker`](Self::broker),
    /// [`into_journal`](Self::into_journal)) and move to a durable journal
    /// without rebuilding the identity.
    ///
    /// # Errors
    ///
    /// [`EphemeralError::Mint`] when the operating system's entropy source
    /// could not be read, and [`EphemeralError::Broker`] if the broker refused
    /// the minted environment.
    ///
    /// [`DurabilityPromise::Ephemeral`]: crate::journal::DurabilityPromise::Ephemeral
    /// [`EffectJournal::admit_external_handoff`]: crate::journal::EffectJournal::admit_external_handoff
    /// [`JournalError::PromiseUnmet`]: crate::journal::JournalError::PromiseUnmet
    #[cfg(feature = "ephemeral")]
    pub fn ephemeral() -> Result<Self, EphemeralError> {
        let identity = EffectIdentity::ephemeral()?;
        let mut broker = Broker::new();
        broker
            .register(identity.environment())
            .map_err(EphemeralError::Broker)?;
        Ok(Self::new(identity, broker, Box::new(MemoryJournal::new())))
    }

    /// The host's three run-level facts.
    #[must_use]
    pub const fn identity(&self) -> EffectIdentity {
        self.identity
    }

    /// The environment broker this scope fences against.
    #[must_use]
    pub const fn broker(&self) -> &Broker {
        &self.broker
    }

    /// The journal a dispatch is appended to.
    #[must_use]
    pub fn journal(&self) -> &dyn EffectJournal {
        &*self.journal
    }

    /// The journal, to append through.
    ///
    /// `&mut self` rather than interior mutability: [`EffectJournal`] fences
    /// writers within one process through its receiver, and a shared handle
    /// that could append from two places at once would hand that fence back.
    #[must_use]
    pub fn journal_mut(&mut self) -> &mut dyn EffectJournal {
        &mut *self.journal
    }

    /// Take the journal back.
    ///
    /// What a host calls on its way out, so the record outlives the bot that
    /// wrote it. See [`EcsBot::into_journal`].
    #[must_use]
    pub fn into_journal(self) -> Box<dyn EffectJournal> {
        self.journal
    }
}

/// The effect path as the kernel holds it, with the recovered state folded in.
///
/// Private, and deliberately not the public [`EffectScope`]: the scope is what
/// a host declares, and this is what the kernel does with it — including the
/// one piece of state the host cannot supply, which is what the journal already
/// says about attempts this bot has not made yet.
struct Effects {
    /// What the host declared.
    scope: EffectScope,
    /// The committed position represented by this controller's recovery fold.
    ///
    /// This advances only from acknowledgements this controller accepted. A
    /// fresh tail would launder another controller's writes into stale state.
    tail: JournalPosition,
    /// Attempts the journal records as dispatched with no outcome, and which
    /// nothing has settled since.
    ///
    /// Seeded once, at assembly, from [`crate::journal::recover`]. Held as keys
    /// rather than as a count because settling one has to name it, and an
    /// attempt that is only a number in a total cannot be named.
    unsettled: Vec<EffectKey>,
    /// Durable outcomes whose positioned receipt has not been verified.
    recording: Vec<RecordedOutcome>,
    /// Durability required by outcomes this process has admitted.
    ///
    /// This is intentionally process-local. The v1 journal wire contract does
    /// not encode an admitted grade, so recovery falls back to the journal's
    /// declared durability rather than changing persisted event bytes.
    requirements: Vec<(EffectKey, DurabilityPromise)>,
    /// The most recently applied key for each action, keyed by action.
    ///
    /// Written when an attempt is settled `Applied`, and seeded at assembly
    /// from the attempts [`crate::journal::recover`] reads back as applied or
    /// verified, and read by the walk before it dispatches: the record says the
    /// effect landed, so the entry it was about is done *for the generation the
    /// key names*. A source that moves opens a new generation, and new work,
    /// which is the one thing that may legitimately re-run an acknowledged
    /// action.
    ///
    /// Held as the *latest* key per action, not as every key ever applied: the
    /// contract identity question ("does the value the run now sees match the
    /// one the last applied episode carried?") is a question about the last
    /// episode for that action, and keeping older ones would both grow
    /// unboundedly and mis-answer it. One entry per action for the life of the
    /// controller is the retention horizon.
    ///
    /// Held as whole keys rather than as `(action, revision)` pairs because a
    /// key carries the generation as a digest, and a recovered key has no
    /// integer revision to pair with it — the digest is one-way. Comparing the
    /// digest the run would mint for its current revision against the digest it
    /// holds answers the same question, and it answers it for an
    /// acknowledgement this process never made.
    applied_latest: HashMap<ActionId, EffectKey>,
    /// The event identities that have landed, as `(action, digest)`.
    ///
    /// An *event* identity answers a different question from the contract
    /// identity: a redelivery of the same event retires however many other
    /// episodes came between (issue #101), so membership over the tagged
    /// history is the right shape. Stored as the digest rather than the whole
    /// key because the digest is exactly what the question compares — the
    /// attempt number is deliberately not part of it.
    ///
    /// The set is bounded by the distinct `(action, digest)` pairs the run has
    /// applied, which is the journal's own deduplication horizon; older event
    /// identities are not evicted, because doing so would let a redelivery of
    /// an older event re-run (#129). This is the same retention the previous
    /// `Vec<EffectKey>` had; the change is that both questions are now answered
    /// in constant time instead of by scanning a growing vector, which was
    /// Θ(N²) over a run that applied N distinct keys.
    applied_events: HashSet<(ActionId, ActionDigest)>,
    /// The latest attempt the journal records for each action it names.
    ///
    /// Seeded once, at assembly, from [`crate::journal::recover`], and read
    /// when the attempt after it is minted. A restart is not a fresh run: the
    /// journal's ladder allows one walk of `IntentAdmitted → DispatchPrepared →
    /// OutcomeObserved → Verified` per key, so minting an attempt the journal
    /// already records reproduces the key it was recorded under and the append
    /// is refused as out of order. Continuing a run therefore means continuing
    /// its attempt sequence, and the number to continue from is in the record.
    attempted: Vec<(ActionId, AttemptId)>,
}

/// A recovered outcome that remains blocked until its journal receipt can be
/// bound to the exact recorded event.
struct RecordedOutcome {
    /// The exact effect attempt whose outcome was recorded.
    key: EffectKey,
    /// What that record says happened.
    evidence: EffectEvidence,
    /// Why the durable receipt could not be accepted during recovery.
    cause: JournalError,
}

impl Effects {
    /// A scope with nothing recovered yet.
    fn new(scope: EffectScope, tail: JournalPosition) -> Self {
        Self {
            scope,
            tail,
            unsettled: Vec::new(),
            recording: Vec::new(),
            requirements: Vec::new(),
            applied_latest: HashMap::new(),
            applied_events: HashSet::new(),
            attempted: Vec::new(),
        }
    }

    /// Note that `key`'s effect is recorded as landed.
    ///
    /// The one place both indexes move, so the two answers the walk asks of
    /// them cannot drift: the contract identity keeps the latest key per
    /// action, and the event identity keeps the `(action, digest)` membership.
    /// Idempotent, because an outcome may be settled once live and once by a
    /// reopen.
    fn note_applied(&mut self, key: EffectKey) {
        self.applied_events.insert((key.action(), key.digest()));
        self.applied_latest.insert(key.action(), key);
    }

    /// The position, evidence, and typed journal refusal behind one held
    /// outcome. Keeping the error typed avoids collapsing recovery failures
    /// into an indistinguishable pending state.
    fn recording_for(&self, action: ActionId) -> Option<&RecordedOutcome> {
        self.recording
            .iter()
            .find(|entry| entry.key.action() == action)
    }

    /// The host's three run-level facts.
    const fn identity(&self) -> EffectIdentity {
        self.scope.identity()
    }

    /// The environment broker this run's dispatches are fenced against.
    const fn broker(&self) -> &Broker {
        self.scope.broker()
    }

    /// Give the scope's journal back.
    fn into_journal(self) -> Box<dyn EffectJournal> {
        self.scope.into_journal()
    }

    /// Obtain the warrant for `key` and record the attempt as prepared.
    ///
    /// One method rather than two calls at the dispatch site, because the two
    /// borrows it needs — the broker to authorize and the journal to append —
    /// are two fields of one scope, and a call site that reached through
    /// `&self` for one and `&mut self` for the other would have to restructure
    /// itself to prove they do not overlap. The split is stated once, here.
    ///
    /// # Errors
    ///
    /// [`DispatchError::Broker`] when the environment refuses, and
    /// [`DispatchError::Journal`] when the append is refused.
    async fn prepare(
        &mut self,
        key: EffectKey,
        lifetime: EffectLifetime,
    ) -> Result<Authority, DispatchError> {
        // The durability admission is on the actual handoff path, not a
        // helper a test can call: an external effect must not leave on a
        // record that cannot outlive the process (issue #100).
        let required = match lifetime {
            EffectLifetime::Local => DurabilityPromise::Ephemeral,
            EffectLifetime::External => {
                self.scope
                    .journal()
                    .admit_external_handoff()
                    .map_err(DispatchError::Journal)?;
                // Reserve the whole handoff — intent, preparation and the
                // settlement that lands only after the effect has left the
                // process — before the first rung is written. A journal that
                // admitted the first two and refused the third would leave an
                // attempt that cannot be settled without deleting unresolved
                // evidence (#122 item 2 / #156).
                self.scope
                    .journal()
                    .reserve_handoff_capacity(3)
                    .map_err(DispatchError::Journal)?;
                DurabilityPromise::ProcessCrash
            }
        };
        // Intent first. Its acknowledgment is the first durability fact on the
        // handoff path: a store that cannot outlive the process is refused here,
        // before `DispatchPrepared` exists for recovery to misread as a live
        // dispatch (issue #100).
        let intent = EffectEvent::IntentAdmitted { key };
        let intent_ack = self.append_async(&intent).await?;
        self.note_journal_attempt(key.action(), key.attempt());
        if !intent_ack.promise().meets(required) {
            let refusal = Err(DispatchError::Journal(JournalError::PromiseUnmet {
                required,
                offered: intent_ack.promise(),
            }));
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "prepare: returning an error to the caller");
            return refusal;
        }
        self.accept_position(&intent, intent_ack.position())?;
        let expected_tail = self.tail;
        let scope = &mut self.scope;
        let (authority, ack) =
            prepare_dispatch(&scope.broker, &mut *scope.journal, expected_tail, key)
                .await?
                .into_parts();
        // The acknowledgment, not the advertisement. A journal that offers
        // less on this append than the handoff requires is refused even when
        // its `durability()` claimed enough.
        if !ack.promise().meets(required) {
            // The prepare record may already have committed under a weaker
            // promise. Do not append a best-effort `NotApplied`: its receipt
            // would be just as unverified and could turn an ambiguous durable
            // state into a false no-handoff claim. Recovery must hold it as
            // unknown until an operator establishes the outcome.
            let refusal = Err(DispatchError::Journal(JournalError::PromiseUnmet {
                required,
                offered: ack.promise(),
            }));
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "prepare: returning an error to the caller");
            return refusal;
        }
        self.accept_position(&EffectEvent::DispatchPrepared { key }, ack.position())?;
        self.requirements.push((key, required));
        Ok(authority)
    }

    /// The generation the broker currently holds for this run's environment.
    ///
    /// `None` when the broker has never been told about the environment. That
    /// is a declared state and not an accident: a broker that owns no
    /// environment mints no authority, which is the refusal
    /// [`prepare_dispatch`] reports as [`BrokerError::UnknownEnvironment`].
    ///
    /// [`BrokerError::UnknownEnvironment`]: crate::broker::BrokerError::UnknownEnvironment
    fn epoch(&self) -> Option<EnvironmentEpoch> {
        self.scope.broker().epoch(self.identity().environment())
    }

    /// The key for one attempt of one entry, or `None` when the broker does not
    /// own the environment this run acts on.
    fn key(
        &self,
        action: ActionId,
        chain: usize,
        entry: usize,
        input: [u8; 16],
        attempt: AttemptId,
    ) -> Option<EffectKey> {
        Some(self.identity().key(
            action,
            attempt,
            derive_action_digest(self.identity().flow(), chain, entry, &input),
            self.epoch()?,
        ))
    }

    /// Continue the run's journal if it has reached its watermark.
    ///
    /// Asked on the shipped append path rather than by a caller a test wrote,
    /// because a lifecycle policy nobody consults is a policy that does not exist
    /// (issue #267). The question is one call and one answer on every append: a
    /// journal that does not continue says so and the append proceeds exactly as
    /// it always did, which is why adding this changed no existing behaviour.
    ///
    /// The whole controller state moves with the journal, and that is the point:
    /// `unsettled`, `recording`, `applied_latest` and `attempted` are this
    /// controller's fold of the history, and the successor carries the same facts
    /// in its checkpoint, so the two agree by construction. Only the *fence* moves
    /// and it moves to the successor's own tail, which is the position after its
    /// seal frame — the append that follows is the successor's second event, and
    /// it is fenced on the successor's chain rather than the predecessor's.
    ///
    /// # Errors
    ///
    /// Whatever the continuation reports. A journal that cannot continue at this
    /// size refuses the *continuation*, not the append, and the append then lands
    /// in the journal it was always going to land in — which is what leaves the
    /// ladder's own reservation the last line of defence rather than the first.
    fn continue_if_due(&mut self) -> Result<(), JournalError> {
        if !self.scope.journal().continuation_watermark()?.is_due() {
            return Ok(());
        }
        let successor = match self.scope.journal_mut().continue_as_new()? {
            Some(successor) => successor,
            None => return Ok(()),
        };
        let adopted = successor.tail();
        self.scope.journal = successor;
        self.tail = adopted;
        Ok(())
    }

    /// Append one fact, fencing on the tail represented by this controller's
    /// recovery fold.
    ///
    /// A refusal is never retried with a newly-read tail: another controller
    /// may have created an unknown effect that this controller has not folded.
    ///
    /// # Errors
    ///
    /// Whatever the journal refuses.
    fn append(&mut self, event: &EffectEvent) -> Result<DurableAck, JournalError> {
        self.continue_if_due()?;
        self.scope
            .journal_mut()
            .compare_and_append(self.tail, event)
    }

    /// The same append, for a caller on an executor.
    ///
    /// The two doors differ only in how they wait, so which one a caller uses
    /// is a statement about that caller and not about the append. A dispatch
    /// path is on an executor, where a journal whose durability path blocks
    /// would charge the device's latency to everything else on the thread.
    ///
    /// # Errors
    ///
    /// Whatever the journal refuses.
    async fn append_async(&mut self, event: &EffectEvent) -> Result<DurableAck, JournalError> {
        self.continue_if_due()?;
        self.scope
            .journal_mut()
            .compare_and_append_async(self.tail, event)
            .await
    }

    /// Advance the fold fence only after the journal confirms the exact
    /// acknowledged position is still current. An adapter-supplied position is
    /// not authority by itself.
    fn accept_position(
        &mut self,
        event: &EffectEvent,
        position: JournalPosition,
    ) -> Result<(), JournalError> {
        self.event_position(event, position)?;
        let actual = self.scope.journal().tail();
        if actual != position {
            let refusal = Err(JournalError::TailMismatch {
                expected: position,
                actual,
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "accept_position: returning an error to the caller");
            return refusal;
        }
        self.tail = position;
        Ok(())
    }

    /// Whether an attempt on `action` is recorded as dispatched with no
    /// outcome, and nothing has settled it.
    ///
    /// This is the question a dispatch asks before it resends anything, and the
    /// answer that stops it. An unknown outcome is not permission to try again:
    /// nothing established that the bytes did not arrive.
    fn blocks(&self, action: ActionId) -> bool {
        self.unsettled.iter().any(|key| key.action() == action)
            || self.recording_for(action).is_some()
    }

    /// The unsettled key for `action`, when there is one.
    fn unsettled_for(&self, action: ActionId) -> Option<EffectKey> {
        self.unsettled
            .iter()
            .find(|key| key.action() == action)
            .copied()
    }

    /// Whether `action` was acknowledged applied for the generation `revision`
    /// of `(chain, entry)`.
    ///
    /// The comparison is between the digest the run would mint for its current
    /// revision and the digest a held key carries, rather than between two
    /// integers, because the held key may have come from a process that is
    /// gone: the digest is what the record has, so the digest is what the
    /// question is asked in.
    fn applied_in(
        &self,
        action: ActionId,
        chain: usize,
        entry: usize,
        input: [u8; 16],
        event: bool,
    ) -> bool {
        let digest = derive_action_digest(self.identity().flow(), chain, entry, &input);
        if event {
            // The identity names an event. A returning one is the same event
            // again: a redelivery of work that already landed, and it retires
            // however many other episodes came between (issue #101).
            return self.applied_events.contains(&(action, digest));
        }
        // The identity names only content. A restart that still sees the value
        // the last applied episode carried retires — that is the #101 property
        // content identity exists for. A later transition *back* to it after a
        // different value is a new episode of work and must run (issue #129):
        // a `0 → 1 → 0` watch fires three times, not twice.
        //
        // "Latest for this action" is "latest for this entry": `ActionId` is
        // derived from the bot name, the chain, the entry and the domain, so
        // one entry has one action and one action has one entry.
        self.applied_latest
            .get(&action)
            .is_some_and(|key| key.digest() == digest)
    }

    /// The attempt the journal already records for `action`, when it names one.
    ///
    /// The highest such attempt rather than the last seen, although the fold
    /// that seeds this reaches them in ascending order: an ordering assumption
    /// that a later record shape could break is not worth the two lines it
    /// saves, and the answer being wrong is a refused append rather than a
    /// loud failure.
    fn recorded_attempt(&self, action: ActionId) -> Option<AttemptId> {
        self.attempted
            .iter()
            .find(|entry| entry.0 == action)
            .map(|entry| entry.1)
    }

    /// Note that the journal already records `attempt` for `action`.
    fn note_journal_attempt(&mut self, action: ActionId, attempt: AttemptId) {
        match self.attempted.iter_mut().find(|entry| entry.0 == action) {
            Some(slot) => {
                if attempt.get() > slot.1.get() {
                    slot.1 = attempt;
                }
            }
            None => self.attempted.push((action, attempt)),
        }
    }

    /// Settle one recovered attempt, appending the outcome that settles it.
    ///
    /// The append lands first: the journal is the record, and a bot that
    /// dropped the key from its own list and then crashed before writing the
    /// outcome would come back with the same unknown it just cleared.
    ///
    /// # Errors
    ///
    /// Whatever the journal refuses.
    fn settle_recovered(
        &mut self,
        key: EffectKey,
        evidence: EffectEvidence,
    ) -> Result<(), JournalError> {
        self.ensure_outcome(key, evidence)?;
        self.unsettled.retain(|held| *held != key);
        Ok(())
    }

    /// Upgrade a recovered outcome receipt without appending or re-entering
    /// the action that produced it.
    fn settle_recording(
        &mut self,
        key: EffectKey,
        evidence: EffectEvidence,
    ) -> Result<(), JournalError> {
        self.confirm_recorded_outcome(key, evidence)?;
        self.recording.retain(|entry| entry.key != key);
        self.fold_outcome(key, evidence);
        Ok(())
    }

    /// Return the recorded position only when it holds the exact outcome.
    fn outcome_position(
        &self,
        key: EffectKey,
        evidence: EffectEvidence,
    ) -> Result<JournalPosition, JournalError> {
        let event = EffectEvent::OutcomeObserved { key, evidence };
        let Some((position, recorded)) = self.scope.journal().outcome_at(key)? else {
            let refusal = Err(JournalError::OutOfOrder {
                key: Box::new(key),
                expected: Some(EventKind::OutcomeObserved),
                attempted: EventKind::OutcomeObserved,
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "outcome_position: returning an error to the caller");
            return refusal;
        };
        if recorded != evidence {
            let refusal = Err(changed_outcome(key));
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "outcome_position: the journal holds a different outcome");
            return refusal;
        }
        self.event_position(&event, position)?;
        Ok(position)
    }

    /// Require the acknowledged position to hold the exact event.
    ///
    /// A tail equality check alone proves only that *something* occupies the
    /// acknowledged position. Binding the event prevents an adapter from
    /// laundering a concurrent writer's tail into this controller's fold.
    fn event_position(
        &self,
        expected: &EffectEvent,
        position: JournalPosition,
    ) -> Result<(), JournalError> {
        let Some(entry) = self.scope.journal().committed_entry(position)? else {
            let refusal = Err(JournalError::OutOfOrder {
                key: Box::new(expected.key()),
                expected: Some(expected.kind()),
                attempted: expected.kind(),
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "event_position: returning an error to the caller");
            return refusal;
        };
        if entry.event() != expected {
            let refusal = Err(JournalError::EntryMismatch {
                position,
                expected: Box::new(*expected),
                actual: Box::new(*entry.event()),
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "event_position: returning an error to the caller");
            return refusal;
        }
        Ok(())
    }

    /// The outcome already committed for `key`, when there is one.
    ///
    /// The durable half of idempotent settlement: a repeat after reconstruction
    /// has no live `AttemptRecord` to consult, and answering `NoSuchWork` there
    /// is how the same evidence stops being a safe retry across a restart.
    ///
    /// # Errors
    ///
    /// Whatever the journal refuses when read. An unreadable journal is not an
    /// absent outcome: collapsing the two is how a transient storage failure
    /// becomes a terminal "this work never existed" (issue #123).
    fn outcome_for(&self, key: &EffectKey) -> Result<Option<EffectEvidence>, JournalError> {
        Ok(self
            .scope
            .journal()
            .outcome_at(*key)?
            .map(|(_, evidence)| evidence))
    }

    /// Require the receipt for an outcome to meet the grade admitted for its
    /// attempt. A weak append can have occupied the ladder already; the
    /// journal's explicit receipt operation is the only safe retry in that
    /// case.
    ///
    /// The receipt binds to the keyed outcome, not to whatever the
    /// acknowledgment names: an ack for a position that holds no outcome for
    /// this key is a [`JournalError::ReceiptMismatch`], never an acceptance.
    fn confirm_outcome(
        &mut self,
        key: EffectKey,
        evidence: EffectEvidence,
        required: DurabilityPromise,
        acknowledgment: DurableAck,
    ) -> Result<(), JournalError> {
        let position = self.outcome_position(key, evidence)?;
        if acknowledgment.position() != position {
            let refusal = Err(JournalError::ReceiptMismatch {
                expected: position,
                actual: acknowledgment.position(),
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "confirm_outcome: returning an error to the caller");
            return refusal;
        }
        if acknowledgment.promise().meets(required) {
            return Ok(());
        }
        self.obtain_receipt(key, evidence, position, required)
    }

    /// Ask the journal for its own receipt for the outcome at `position` and
    /// require it to name that position at the grade `required`.
    ///
    /// The one receipt check both [`Self::confirm_outcome`] (a weak append whose
    /// acknowledgment fell short) and [`Self::confirm_recorded_outcome`] (recovery
    /// of an outcome whose acknowledgment is gone) end in, so the two cannot
    /// disagree about what a receipt must prove.
    fn obtain_receipt(
        &mut self,
        key: EffectKey,
        evidence: EffectEvidence,
        position: JournalPosition,
        required: DurabilityPromise,
    ) -> Result<(), JournalError> {
        let receipt = self
            .scope
            .journal_mut()
            .confirm_outcome(key, evidence, position, required)?;
        if receipt.position() != position {
            let refusal = Err(JournalError::ReceiptMismatch {
                expected: position,
                actual: receipt.position(),
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "obtain_receipt: the receipt names another position");
            return refusal;
        }
        if receipt.promise().meets(required) {
            Ok(())
        } else {
            Err(JournalError::PromiseUnmet {
                required,
                offered: receipt.promise(),
            })
        }
    }

    /// Fold a receipted outcome into the local state.
    fn fold_outcome(&mut self, key: EffectKey, evidence: EffectEvidence) {
        self.requirements.retain(|entry| entry.0 != key);
        self.note_journal_attempt(key.action(), key.attempt());
        if evidence == EffectEvidence::Applied {
            self.note_applied(key);
        }
    }

    /// Verify a previously committed outcome before recovery treats it as
    /// settled. A durable adapter must provide positioned readback; otherwise
    /// the action remains blocked rather than being re-entered.
    ///
    /// An ephemeral journal skips the receipt operation: readback is the
    /// strongest proof its grade can offer, and the default
    /// [`EffectJournal::confirm_outcome`] refuses exactly because readback
    /// bytes prove nothing about survival. For a journal that promises to
    /// survive anything, the record must be attested, not merely present.
    fn confirm_recorded_outcome(
        &mut self,
        key: EffectKey,
        evidence: EffectEvidence,
    ) -> Result<(), JournalError> {
        let required = self.scope.journal().durability();
        if required == DurabilityPromise::Ephemeral {
            return Ok(());
        }
        let position = self.outcome_position(key, evidence)?;
        self.obtain_receipt(key, evidence, position, required)
    }

    /// Settle an outcome the journal already holds.
    ///
    /// The committed record is the fact; what is left is the receipt the
    /// attempt was admitted under. The journal's own grade must meet it — a
    /// weaker store is refused rather than settled below the grade the
    /// dispatch was admitted with — and a store that grades itself above
    /// ephemeral must re-attest through its receipt operation, because
    /// readback proves only that bytes are present, not that they will
    /// survive what the grade promises.
    ///
    /// # Errors
    ///
    /// [`JournalError::ReceiptUnavailable`] when the journal's grade is below
    /// `required` or it has no receipt operation, and whatever the readback or
    /// the receipt operation refuses.
    fn settle_committed_outcome(
        &mut self,
        key: EffectKey,
        evidence: EffectEvidence,
        required: DurabilityPromise,
    ) -> Result<(), JournalError> {
        let offered = self.scope.journal().durability();
        if !offered.meets(required) {
            let refusal = Err(JournalError::ReceiptUnavailable { required });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "settle_committed_outcome: returning an error to the caller");
            return refusal;
        }
        if offered != DurabilityPromise::Ephemeral {
            self.confirm_recorded_outcome(key, evidence)?;
        }
        self.accept_position(
            &EffectEvent::OutcomeObserved { key, evidence },
            self.outcome_position(key, evidence)?,
        )?;
        self.fold_outcome(key, evidence);
        Ok(())
    }

    /// Record an outcome for `key` if one is not already committed, and fold
    /// it into the in-memory applied set.
    ///
    /// Idempotent: a repeat of the same evidence does not append twice. The
    /// ladder's next step after `OutcomeObserved` is `Verified`, so an
    /// `OutOfOrder` that expected `Verified` (or nothing) means this exact
    /// record is already in the journal and the call is a success. This is the
    /// one settlement write, shared by the live and recovered paths so a
    /// restart cannot resurrect an attempt a live resolve already settled.
    ///
    /// # Errors
    ///
    /// Whatever the journal refuses, other than the idempotent repeat above.
    fn ensure_outcome(
        &mut self,
        key: EffectKey,
        evidence: EffectEvidence,
    ) -> Result<(), JournalError> {
        // A key with no requirement of its own is held to the journal's grade:
        // that is the promise every other key in the scope is held to.
        let required = match self.requirements.iter().find(|entry| entry.0 == key) {
            Some(&(_, declared)) => declared,
            None => self.scope.journal().durability(),
        };
        if let Some(recorded) = self.outcome_for(&key)? {
            if recorded != evidence {
                let refusal = Err(changed_outcome(key));
                lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "ensure_outcome: the journal holds a different outcome");
                return refusal;
            }
            // The record is already in the journal. The only open question is
            // the receipt: the original append's acknowledgment is not in hand
            // on this path, so the journal's own receipt operation is what
            // settles a graded attempt (issue #118).
            return self.settle_committed_outcome(key, evidence, required);
        }
        match self.append(&EffectEvent::OutcomeObserved { key, evidence }) {
            Ok(acknowledgment) => self.record_new_outcome(key, evidence, required, acknowledgment),
            Err(JournalError::OutOfOrder { expected, .. })
                if expected == Some(EventKind::Verified) || expected.is_none() =>
            {
                // Idempotent success only when the *same* evidence is already
                // recorded. A ladder-complete `OutOfOrder` alone is not proof of
                // which outcome landed, and treating it as success is how a
                // contradictory `Applied` gets acknowledged (issue #106).
                match self.outcome_for(&key)? {
                    Some(recorded) if recorded == evidence => {
                        // The original append acknowledgment is unavailable
                        // after an out-of-order retry. The journal's receipt
                        // operation, not a minted replacement, is what
                        // settles a graded attempt.
                        self.settle_committed_outcome(key, evidence, required)
                    }
                    _ => Err(JournalError::OutOfOrder {
                        key: Box::new(key),
                        expected,
                        attempted: EventKind::OutcomeObserved,
                    }),
                }
            }
            Err(cause @ JournalError::OutcomeUnknown { .. }) => {
                // The store may hold the event; the reply was lost. Read back
                // before anything else: a matching record means the effect and
                // its record both landed, and the attempt settles instead of
                // reporting an ambiguity the next retry can never resolve.
                match self.outcome_for(&key)? {
                    Some(recorded) if recorded == evidence => {
                        self.settle_committed_outcome(key, evidence, required)
                    }
                    Some(_) => Err(JournalError::OutOfOrder {
                        key: Box::new(key),
                        expected: Some(EventKind::Verified),
                        attempted: EventKind::OutcomeObserved,
                    }),
                    // Nothing landed. The ambiguous failure is the honest
                    // report: the caller is post-effect and must surface
                    // `EffectUnrecorded` with `Occurred` certainty, and a
                    // recovery pass reconciles from the journal's own replay.
                    None => Err(cause),
                }
            }
            Err(cause) => {
                // A refusal that left the journal unchanged. Surface it now:
                // the caller is post-effect and must report `EffectUnrecorded`,
                // not a clean settle.
                Err(cause)
            }
        }
    }
}

impl Effects {
    /// Records a freshly appended outcome and folds it into the in-memory view.
    ///
    /// A helper rather than three statements in the arm: confirming the outcome,
    /// accepting its position and folding it are one transition, and a reader of
    /// `ensure_outcome` had to know that all three happen before the outcome
    /// counts. The other two arms settle the same outcome by a different route,
    /// so the three are now one named step with one exit.
    fn record_new_outcome(
        &mut self,
        key: EffectKey,
        evidence: EffectEvidence,
        required: DurabilityPromise,
        acknowledgment: DurableAck,
    ) -> Result<(), JournalError> {
        self.confirm_outcome(key, evidence, required, acknowledgment)?;
        let position = self.outcome_position(key, evidence)?;
        self.accept_position(&EffectEvent::OutcomeObserved { key, evidence }, position)?;
        self.fold_outcome(key, evidence);
        Ok(())
    }
}

impl fmt::Debug for Effects {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Effects")
            .field("identity", &self.identity())
            .field("journal", &self.scope.journal().durability())
            .field("unsettled", &self.unsettled.len())
            .field("applied", &self.applied_events.len())
            .field("attempted", &self.attempted.len())
            .finish()
    }
}

// ── Components: identity and the change marker are separate ────────────────

/// A source's identity in the world.
///
/// Written once at spawn and never again. `docs/bot-on-ecs.md` §4 is the reason
/// this is not fused with the observed value: a component that carries both is
/// marked changed by every poll, and `Changed<T>` degenerates to "always true".
#[derive(Component, Debug, Clone)]
pub(crate) struct SourceId {
    /// The chain's index in declaration order; the key into `Chains` and
    /// `Observed`.
    pub(crate) chain: usize,
    /// The observer's own `domain_id()`, for diagnostics.
    domain: String,
}

impl SourceId {
    /// The observed source's domain identifier (e.g. `"net::endpoint"`).
    pub(crate) fn domain(&self) -> &str {
        &self.domain
    }
}

/// The change marker, bumped only when the observed value actually differs.
///
/// This is the component a condition filters on. It is one component for every
/// domain rather than one per domain, because the *value* is heterogeneous and
/// only the fact of its movement is shared, which keeps the archetype count
/// bounded, as `docs/bot-on-ecs.md` §4 requires.
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) struct Revision(u64);

// ── Resources ──────────────────────────────────────────────────────────────

/// The capability proof, as a world resource: one authority per world, no
/// ambient singleton.
#[derive(Resource, Debug)]
struct Grants(GrantSet);

/// Effects fired on the most recent tick.
#[derive(Resource, Debug, Default)]
struct Fired(usize);

/// The first tick-time failure, if any.
///
/// An exclusive system returns `()` and cannot propagate, so the error is
/// parked here and `EcsBot::tick` takes it. This is not a workaround for a
/// missing feature: it is the shape that keeps the failure ordered, because the
/// systems stop at the first error and the driver reports that one.
#[derive(Resource, Debug, Default)]
struct TickError(Option<BotError>);

/// The source entities in chain order.
#[derive(Resource, Debug, Default)]
struct Order(Vec<Entity>);

/// The observation phase's reusable buffers.
///
/// Every buffer here was a fresh heap allocation on every tick, and each of them
/// was paid by a tick that changed nothing: a quiet tick allocated a
/// `Vec<Option<RefreshReason>>` the size of the world, a `Vec<usize>` for stalls
/// that stayed empty, and a `Vec<(usize, &EcsChain)>` holding the whole wave
/// before deciding that none of the wave had to be polled. A substrate that asks
/// "has anything moved?" once per chain per tick and then allocates several
/// times per chain to ask it is not measuring the question.
///
/// So the buffers live here, are taken out for the phase, and go back with their
/// capacity: the first tick pays for them and no tick after pays again. The
/// contents are cleared every tick and never retained — a scratch that kept its
/// entries would be a cache, and what these hold is per-tick state whose whole
/// meaning is that it does not survive.
#[derive(Resource, Debug, Default)]
struct PollScratch {
    /// One entry per chain: what that chain's source declared about its own
    /// caching, read once per tick.
    declared: Vec<Option<RefreshReason>>,
    /// The chains whose poll the wave gave up on, in declaration order.
    stalled: Vec<usize>,
    /// The current wave's own indices that have to be polled.
    slots: Vec<usize>,
}

/// The change ticks: the revision each chain's committed value was read at, and
/// the revision each source reported on this tick.
///
/// Two buffers rather than one because they answer two different questions, and
/// conflating them is the mistake that makes a poll look like a commit: `seen` is
/// what the substrate **holds**, and moves only where a value was committed;
/// `polled` is what the source **said** on the tick the value was read. A poll
/// that failed, was cancelled at its deadline, or produced a value equal to the
/// one already held writes `polled` and leaves `seen` alone, so the next tick
/// asks again — the fingerprint-commit rule (#99 / INV-BOT-5) applied to a change
/// tick rather than to a digest.
#[derive(Debug, Default)]
struct ChangeTicks {
    /// The revision of the value the substrate currently holds, per chain.
    seen: Vec<Option<u64>>,
    /// The revision each source reported on this tick, per chain.
    polled: Vec<Option<u64>>,
}

impl ChangeTicks {
    /// Whether `chain`'s source reported the revision its committed value was
    /// read at, so the poll can be skipped.
    ///
    /// Equality is the whole comparison. A revision that wraps, or regresses, is a
    /// *different* revision and therefore a change: there is no ordering here that
    /// a wrap could invalidate, and a source is free to use a saturating counter,
    /// a timestamp in its own units, or a content digest as its revision.
    fn quiet(&self, chain: usize, reported: Option<u64>) -> bool {
        reported.is_some() && self.seen.get(chain).copied().flatten() == reported
    }

    /// Commit the revision a value was read at, and only then.
    ///
    /// Called from the commit pass of [`observe_fold`] and nowhere else, which is
    /// what makes the rule a fact about one place rather than an intention.
    fn commit(&mut self, chain: usize, polled: Option<u64>) {
        if let Some(slot) = self.seen.get_mut(chain) {
            *slot = polled;
        }
    }
}

/// The decision phase's per-tick scratch: which chains moved, what the walk will
/// do with each chain's live transition, and the admitted input each binding
/// takes.
///
/// A world resource rather than a local, because it is per-tick scratch and the
/// point of scratch is that it is allocated once. Built as `vec![false; count]`
/// inside the decision system, this was a fresh zeroed allocation every tick —
/// one of a set of them, added together, that made the schedule's own bookkeeping
/// the larger half of a tick's cost.
///
/// One resource for all three rather than three, because they are resized
/// together: a plan that grows its chain count is a bot whose chain count grew,
/// and three buffers resized independently could hold three different widths for
/// one tick.
#[derive(Default)]
struct AdmitScratch {
    /// Which chains the change filter reported as moved.
    moving: Vec<bool>,
    /// What the walk will do with each chain, in declaration order.
    kinds: Vec<AdmitKind>,
    /// The admitted-input identity each binding takes, `None` where it binds none.
    inputs: Vec<Option<AdmittedInput>>,
}

/// The decision pass's scratch, taken out whole so the walk can read and write it
/// while the world is borrowed for the query.
///
/// The one step rather than three because the borrow is the whole reason:
/// `fire_plan` holds `&mut World`, and a mutable borrow of a single resource
/// cannot survive the immutable borrow the change query needs. One `mem::take`
/// moves all three buffers and keeps all three allocations.
impl AdmitScratch {
    /// Take the scratch out of the world, resized to `count` chains.
    fn take(world: &mut World, count: usize) -> Self {
        let mut scratch = std::mem::take(&mut *world.non_send_mut::<AdmitScratch>());
        scratch.moving.clear();
        scratch.moving.resize(count, false);
        scratch.kinds.clear();
        scratch.kinds.resize(count, AdmitKind::Idle);
        scratch.inputs.clear();
        scratch.inputs.resize(count, None);
        scratch
    }
}

/// The retry policy in force: one authority per world, like `Grants`.
#[derive(Resource, Debug)]
struct Policy(RetryPolicy);

/// The chains whose cached baseline cannot be trusted, and why.
///
/// One flag per chain, indexed exactly as [`Chains`] is, and one entry per tick
/// per chain — so this is bounded by the chain count for the life of the bot and
/// cannot grow with the number of ticks. The lifecycle is deliberately one tick
/// long: a chain marked here is polled with `None` handed to it as its
/// baseline, so whatever the source reports *is* committed as its new baseline,
/// and the flag is spent. A flag that outlived the forced poll would keep the
/// baseline out of the comparison indefinitely, which is the permanent quiet
/// state this resource exists to prevent — a slower version of the defect.
///
/// Spent rather than cleared for the same reason: a chain whose forced poll
/// *failed* has committed nothing, so its baseline is still whatever it was,
/// and the next tick must be forced again. Clearing the flag there would return
/// the bot to comparing against the unsound baseline it just failed to replace.
#[derive(Debug, Default)]
struct Invalidated {
    /// The reason each chain declared, or `None` where it declared nothing.
    reasons: Vec<Option<RefreshReason>>,
}

/// The bot's declared per-poll deadline, as the commit step reads it.
///
/// A resource beside `EcsBot::poll_deadline` rather than a second source of
/// truth: `observe_fold` is a schedule step and can only reach the world, so the
/// value it needs to put on a typed cancellation has to be there. It is inserted
/// from the same field the observation phase reads, so the number on the error and
/// the number that bounded the poll cannot differ.
#[derive(Debug, Clone, Copy, Resource)]
struct PollBudget(Duration);

impl Invalidated {
    /// Mark `chain` invalid for `reason`, keeping the reason it already had.
    ///
    /// First-write-wins rather than last-write-wins, because the driver walks the
    /// chains in declaration order and a report that varied with poll resolution
    /// order would not be comparable across two runs of one seed. One reason per
    /// chain is what makes the report a statement about the run rather than
    /// about how its sources happened to resolve.
    fn mark(&mut self, chain: usize, reason: RefreshReason) {
        if let Some(slot) = self.reasons.get_mut(chain)
            && slot.is_none()
        {
            *slot = Some(reason);
        }
    }

    /// Whether `chain` must be polled without a baseline this tick.
    fn is_invalid(&self, chain: usize) -> bool {
        self.reasons
            .get(chain)
            .is_some_and(|reason| reason.is_some())
    }
}

/// One chain's entry on a tick report: a baseline the source itself declared
/// unsound, and the reason it named.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ForcedRefresh {
    /// The chain whose cached baseline was refused.
    chain: usize,
    /// The source's own domain identifier, read through `domain`.
    domain: String,
    /// The reason, read through `reason`.
    reason: RefreshReason,
}

impl ForcedRefresh {
    /// The chain whose cached baseline was refused.
    ///
    /// The chain's index in declaration order, which is what `pending()` and the
    /// settlement reports name too.
    #[must_use]
    pub const fn chain(&self) -> usize {
        self.chain
    }

    /// The source's own domain identifier.
    ///
    /// The same spelling `Observe::domain_id` returns, so a report is readable
    /// without the caller having to hold the declaration order.
    #[must_use]
    pub fn domain(&self) -> &str {
        &self.domain
    }

    /// Why the source declared its baseline unsound.
    #[must_use]
    pub const fn reason(&self) -> RefreshReason {
        self.reason
    }
}

/// One source whose poll this tick cancelled at its per-poll deadline.
///
/// Reported rather than dropped, and beside [`ForcedRefresh`] rather than folded
/// into it, because the two are different facts with different repairs: a forced
/// refresh is a source that *told* the substrate its baseline was unsound, and a
/// stall is a source that *stopped answering*. The first is fixed by the domain
/// reconnecting; the second is bounded by the deadline, and a bot that reported
/// one as the other would send a reader to the wrong place.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StalledSource {
    /// The chain whose poll was cancelled, read through `chain`.
    chain: usize,
    /// The source's own domain identifier, read through `domain`.
    domain: String,
    /// The budget that was applied, read through `deadline`.
    deadline: Duration,
}

impl StalledSource {
    /// The chain whose poll was cancelled.
    ///
    /// The chain's index in declaration order, which is what `pending()` and the
    /// settlement reports name too, so one index identifies a chain across every
    /// report this bot produces.
    #[must_use]
    pub const fn chain(&self) -> usize {
        self.chain
    }

    /// The source's own domain identifier.
    ///
    /// The same spelling `Observe::domain_id` returns, so a caller triaging a
    /// stall can name the domain without holding the declaration order — which is
    /// the whole reason the report carries it.
    #[must_use]
    pub fn domain(&self) -> &str {
        &self.domain
    }

    /// The per-poll budget that was applied when this poll was cancelled.
    #[must_use]
    pub const fn deadline(&self) -> Duration {
        self.deadline
    }
}

/// What one tick observed about its own sources, beside the effects it fired.
///
/// The count of fired effects answers "what did this tick do"; this answers
/// "what did it have to look at again, and why", which is a different question
/// and the one a caller needs when a bot has gone quiet. A tick that fired
/// nothing because every source legitimately held still is a healthy tick. A
/// tick that fired nothing because a source's baseline stopped being a fact is
/// a bug the count cannot see, and this is where it becomes visible.
///
/// Read through [`EcsBot::tick_report`] rather than off the tick's return
/// value, because the tick's `Result` carries an *error* and this carries what
/// was true about the sources either way: a tick that failed still observed, and
/// a caller triaging the failure needs to know whether the sources were the
/// reason.
#[derive(Debug, Clone, Default, PartialEq, Eq, Resource)]
pub struct TickReport {
    /// Effects that fired on this tick, read through `fired`.
    fired: usize,
    /// The chains whose baseline this tick refused, read through `forced`.
    forced: Vec<ForcedRefresh>,
    /// The observations this tick passed over, read through `superseded`.
    superseded: Vec<SupersededObservation>,
    /// The sources this tick stopped waiting for, read through `stalled`.
    stalled: Vec<StalledSource>,
    /// Deadline watchdogs this tick started, read through `watchdogs`.
    watchdogs: u32,
}

impl TickReport {
    /// Effects that fired on this tick.
    #[must_use]
    pub const fn fired(&self) -> usize {
        self.fired
    }

    /// Chains whose cached baseline this tick refused and re-read.
    ///
    /// In chain order, at most one entry per chain: the first reason the tick
    /// recorded for a chain, which is the one whose forced read has not landed.
    /// Empty when every source legitimately held still — which is the answer a
    /// caller most needs to be able to distinguish from the next one.
    #[must_use]
    pub fn forced(&self) -> &[ForcedRefresh] {
        &self.forced
    }

    /// Intermediate observations replaced before any entry acted on them.
    ///
    /// In chain order, at most one entry per chain. Reported here rather than
    /// as a fired effect or as a retired one, because it is neither: the value
    /// was never due. Counting it as work done would overstate what the tick
    /// did, and counting it as work retired would understate how many values the
    /// run passed over.
    #[must_use]
    pub fn superseded(&self) -> &[SupersededObservation] {
        &self.superseded
    }

    /// Whether this tick re-read anything it had decided it could keep.
    #[must_use]
    pub fn forced_any(&self) -> bool {
        !self.forced.is_empty()
    }

    /// Whether this tick passed over an intermediate observation.
    #[must_use]
    pub fn superseded_any(&self) -> bool {
        !self.superseded.is_empty()
    }

    /// Sources whose poll this tick cancelled at the per-poll deadline.
    ///
    /// In chain order, at most one entry per chain. Every one of them committed
    /// nothing, so a caller reconciling "what did the tick see" against the fired
    /// count must read this beside `fired` rather than instead of it: the chains
    /// named here are the ones whose absence from the effects is explained, not
    /// the ones that had nothing to say.
    ///
    /// Empty is the ordinary answer, and it is distinguishable from a tick that
    /// never happened because this is published by the tick that ran, whatever
    /// that tick's own result was.
    #[must_use]
    pub fn stalled(&self) -> &[StalledSource] {
        &self.stalled
    }

    /// Whether this tick gave up on any source.
    #[must_use]
    pub fn stalled_any(&self) -> bool {
        !self.stalled.is_empty()
    }

    /// Deadline watchdogs this tick started.
    ///
    /// An OS thread is a real cost on a host with a real thread ceiling, so the
    /// count belongs in the operator's view of the tick beside the stall it may
    /// have produced. It is zero for the ordinary tick — every source answered
    /// on its first poll, so no poll ever needed watching — and at most one per
    /// observation wave that had a source still pending, because a wave shares
    /// one deadline and therefore one watcher.
    ///
    /// A watchdog that could not be started is not counted here: the count is
    /// what the host actually started, and a source reported stalled beside a
    /// zero is the one honest shape that combination can have.
    #[must_use]
    pub const fn watchdogs(&self) -> u32 {
        self.watchdogs
    }
}

/// One intermediate observation the substrate passed over in latest-state mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SupersededObservation {
    /// The chain, read through `chain`.
    chain: usize,
    /// The revision, read through `revision`.
    revision: u64,
}

impl SupersededObservation {
    /// The chain whose value was replaced.
    #[must_use]
    pub const fn chain(&self) -> usize {
        self.chain
    }

    /// The revision the replaced value was committed under.
    ///
    /// The revision of the *replaced* value, not of the one that took its place:
    /// what a caller wants to correlate is "the generation for revision 4 never
    /// ran", and revision 4 is the one this names.
    #[must_use]
    pub const fn revision(&self) -> u64 {
        self.revision
    }
}

/// Whether each chain's committed observation has been admitted into a
/// generation yet, and under which revision.
///
/// One entry per chain, so the answer is per-chain constant time rather than a
/// walk of the transitions. The distinction it records is the one that decides
/// what a replaced value *was*:
///
/// - **Admitted.** The value is sitting in the slot because the generation that
///   ran on it has finished and handed it back. Replacing it loses nothing: it
///   has already been acted on.
/// - **Not admitted.** The value is sitting in the slot because a generation was
///   still being walked when it arrived, so it could not be admitted yet — and a
///   newer one arrived before the walk finished. This value will *never* be
///   acted on, because the substrate admits only the newest observation once the
///   walk releases the chain. Replacing it passes over an intermediate state,
///   which is what latest-state mode means and what has to be reported.
///
/// Without this, the two are indistinguishable from the outside and the second
/// is silently dropped: a caller watching a counter see it jump 1 → 2 → 3 has no
/// way to learn that 2 was never observed as a state, only that it was never
/// acted on. Those are different facts and only one of them is a loss.
#[derive(Debug, Default)]
struct Committed {
    /// Per chain: has the value in the observation slot been admitted, and
    /// under which revision was it committed.
    slots: Vec<SlotAdmission>,
}

/// What one chain's committed observation is waiting for.
///
/// Three states rather than one boolean, because "was replaced before it was
/// acted on" and "has never been observed at all" both read as `false` in the
/// two-state form, and conflating them reports the *first* observation of every
/// chain as a pass-over. That is not cosmetic: it would make a fresh bot claim
/// it had skipped a state it had never seen.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
enum SlotState {
    /// Nothing has been committed for this chain yet.
    #[default]
    Nothing,
    /// A value is committed and a generation has run over it.
    Admitted,
    /// A value is committed and no generation has run over it.
    Unacted,
}

/// What one chain's committed observation is waiting for.
#[derive(Debug, Clone, Copy, Default)]
struct SlotAdmission {
    /// Where the chain's committed value stands.
    state: SlotState,
    /// The revision the value in the slot was committed under.
    revision: u64,
}

impl Committed {
    /// Note that `chain` committed a value under `revision`, not yet admitted.
    fn commit(&mut self, chain: usize, revision: u64) {
        if let Some(slot) = self.slots.get_mut(chain) {
            slot.state = SlotState::Unacted;
            slot.revision = revision;
        }
    }

    /// Note that a generation has been opened over `chain`'s committed value.
    ///
    /// Called from the handover, where the binding leaves the transition and
    /// becomes the slot's standing baseline. The value is then *acted on*, and
    /// replacing it later is not a supersession.
    fn admit(&mut self, chain: usize) {
        if let Some(slot) = self.slots.get_mut(chain) {
            slot.state = SlotState::Admitted;
        }
    }

    /// The admission of `chain`'s committed value, for the supersession check.
    ///
    /// `None` for a chain this bot does not have: the slots are sized to the
    /// chains at build, so that is a caller's index error, and it is answered as
    /// absent rather than as a chain that has committed nothing.
    fn slot(&self, chain: usize) -> Option<SlotAdmission> {
        self.slots.get(chain).copied()
    }
}

// ── Non-send state: the verbs and the values ───────────────────────────────

/// One observation chain, holding the same erased halves a
/// [`Chain`] does.
pub(crate) struct EcsChain {
    /// The observer. `Box<dyn ObserveAny>`'s `poll_any` is not `Send`, which is
    /// why this cannot live in a component.
    source: Box<dyn ObserveAny>,
    /// Equality for this observer's output, captured from the `PartialEq` bound
    /// on `EcsBuilder::observe`. Change detection needs to tell "the same
    /// value again" from "a new value", and the erased `Box<dyn Any>` cannot
    /// answer that on its own.
    same: fn(&dyn Any, &dyn Any) -> bool,
    /// The admitted-input identity of an erased binding, captured from
    /// `S::Output: InputIdentity` where the type was still a parameter.
    identify: fn(&dyn Any) -> AdmittedInput,
    /// The `(condition, action)` tuples, in declaration order.
    entries: Vec<ChainEntry>,
    /// What type this chain's source produces, taken where `S::Output` was
    /// still a type parameter and checked at every rendezvous.
    ///
    /// The chain is the *claim*: it is what the condition and the action were
    /// built against. The value that arrives each tick carries its own witness,
    /// and the rendezvous compares them. Neither half can be checked alone —
    /// both are erased — so the pair is the proof.
    witness: Witness,
}

impl EcsChain {
    /// Assemble a chain from a registry-built source and its erased entries.
    ///
    /// The materializer's seam, and the only place a chain's metadata is taken
    /// from something other than a concrete `S` parameter. The four pieces are
    /// captured by [`Source::new`] at the one point where
    /// `S::Output` was still a type parameter, so a chain built this way is the
    /// same value a native chain erases to — the tick path cannot tell them
    /// apart, which is exactly T25's claim.
    fn from_registry(source: Source, entries: Vec<ChainEntry>) -> Self {
        let (inner, same, identify, witness) = source.into_parts();
        Self {
            source: inner,
            same,
            identify,
            witness,
            entries,
        }
    }
}

/// Every chain, in declaration order.
#[derive(Default)]
struct Chains(Vec<EcsChain>);

/// The observed value per chain, from the most recent successful poll.
///
/// Paired to [`Chains`] by index, and by index only: a vector position carries
/// no type. Nothing here proves that `Observed[i]` belongs to `Chains[i]`, which
/// is why each value keeps its [`Witness`] and the fold compares it against the
/// chain's before committing anything.
#[derive(Default)]
struct Observed(Vec<Option<Erased>>);

// ── Staging between the awaited phases and the schedule steps ──────────────
//
// The verb futures are non-`Send` and may need an executor, so they are awaited
// by the driver *outside* the schedule. What crosses into the schedule is
// therefore data, in declaration order, and the two resources below are that
// handover. Both are overwritten wholesale at the point they are consumed, so
// a tick that is dropped between phases leaves nothing behind for the next one.

/// The results of the observation phase, staged for `observe_fold`.
///
/// In chain order, one entry per chain, exactly as `poll_sources` collected
/// them: the fold commits them positionally, so a result that arrived early
/// cannot be committed to the wrong chain.
/// An `Ok(None)` is not "no observation": it is the source's answer that the
/// value it just produced is **equal** to the baseline it was handed, so the
/// substrate keeps the value it already holds. Only `Ok(Some(_))` carries a new
/// payload, and only those are boxed.
#[derive(Default)]
struct Polled(Vec<Result<Option<Erased>, BotError>>);

/// Which chains moved on this tick, one flag per chain.
///
/// Per-tick scratch, like [`Moving`], and a resource for the same reason: it is
/// rebuilt on every tick of every bot and a rebuilt buffer is an allocation.
///
/// Named `Moved` and not `Changed` because `Changed` in this module is bevy's
/// query filter, and shadowing it would silently retarget every
/// `Changed<Revision>` in the file at this struct.
#[derive(Default)]
struct Moved(Vec<bool>);

/// What the decision phase decided for one entry it reached.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Decision {
    /// The condition held, so the entry is attempted.
    ///
    /// It does not say *which* attempt this will be. The number belongs to the
    /// ledger, which is the only thing that can keep it monotonic across a
    /// settlement, and it is handed back by [`Ledger::begin`]. Deriving it here
    /// from [`EntryState`] gave a settled entry the number one all over again,
    /// so two attempts at one address could answer to the same name.
    Attempt,
    /// The condition did not hold, so the entry is recorded as skipped and the
    /// walk moves past it. Recorded rather than dropped: an entry whose
    /// condition is false owes nothing, and saying so is what lets a chain
    /// settle and stop being walked.
    Skip,
}

/// One entry the decision phase reached.
struct Step {
    /// Index into [`Chains`].
    chain: usize,
    /// Index into that chain's `entries`, in declaration order.
    entry: usize,
    /// What the walk decided for it.
    decision: Decision,
}

/// The effect program the decision phase recorded, plus the condition failures
/// it met on the way.
///
/// A failure is carried here rather than parked in [`TickError`] because it
/// happened at a *position* in the walk rather than at the end of it: the
/// [`Step`]s alongside it are exactly the effects the walk reached before that
/// position, and they still run. Whichever failure comes first in walk order is
/// the one the tick reports, which is the ordering the synchronous loop had when
/// it evaluated a condition and ran an action in the same iteration.
///
/// One failure per chain rather than one for the tick, because a condition that
/// cannot be evaluated stops its own chain: the chains after it are still
/// walked, and a failing action earlier in a chain is a more specific report than
/// a failing condition later in the same one. That is also why the failures are
/// indexed rather than ordered — the `chain` field of each [`Step`] is the order
/// they are reported in.
#[derive(Default)]
struct Plan {
    /// The decisions to apply, in declaration order: one chain's entries in
    /// walk order, then the next chain's.
    steps: Vec<Step>,
    /// The condition failure each chain's walk met, indexed by chain. A chain
    /// whose walk met none has `None`, and an action failure recorded by the
    /// driver displaces the condition failure of the chain it happened in.
    failures: Vec<Option<BotError>>,
}

/// Upper bound on sources polled simultaneously by one tick. A source poll may
/// occupy one `spawn_blocking` thread, so this caps the blocking-thread fan-out
/// regardless of how many chains a spec declares. Chains beyond the cap are
/// polled in additional waves.
///
/// Also the width of the deadline watchdog: a wave is one unit of waiting, so a
/// wave has one watcher and the number of threads a tick can spend on the
/// deadline is the number of waves rather than the number of chains.
const MAX_IN_FLIGHT_POLLS: usize = 32;

/// How long one source poll may take before the tick stops waiting for it.
///
/// `MAX_IN_FLIGHT_POLLS` above bounds how many sources are polled at once; this
/// bounds how long the tick waits for any one of them. Without it a source that
/// never resolves holds the whole tick — the observation wave is joined through
/// `lgwks_std::task::join_all_boxed`, which polls on the calling thread and
/// returns only when the wave has resolved — and every other chain's action is
/// held behind a source nobody can make progress for. That is T06's slow-source
/// half, and it was the one claim this substrate could not make.
///
/// Thirty seconds, and the reasoning is about what the number has to be rather
/// than about taste. It is long enough that a source reading a socket, a
/// `spawn_blocking` thread, or an ordinary remote call finishes first, so an
/// ordinary tick is never cut short by it; and it is short enough that "the
/// source is wedged" is a fact a caller waits one poll budget to observe rather
/// than a change observed at the next deploy. [`MAX_POLL_DEADLINE`] is the
/// ceiling a caller may raise it to, and the builder refuses anything past it.
pub const DEFAULT_POLL_DEADLINE: Duration = Duration::from_secs(30);

/// The largest per-poll deadline [`EcsBuilder::with_poll_deadline`] will grant.
///
/// A ceiling rather than an unconstrained field, because the deadline is the one
/// bound between a wedged source and a bot that never ticks again. A caller who
/// needs longer than this is making a statement about their whole fan-out, and
/// the refusal is where that statement belongs.
pub const MAX_POLL_DEADLINE: Duration = Duration::from_secs(600);

/// One observation wave's deadline watchdog, shared with every poll in it.
///
/// Two halves under two primitives rather than a set of atomics, because the
/// invariant is an *ordering* between three writes across two threads and a
/// lock is what makes "install the waker, then read the flag" one indivisible
/// step. With atomics the same sequence needs a re-check after every publish,
/// and the window that produces is exactly the lost wakeup that hangs a tick.
///
/// One per **wave**, not per poll. Every poll in a wave starts together under
/// the same budget, so the wave has one deadline to watch and one thread to
/// watch it with: a bot of *n* chains spent a thread per chain per tick before,
/// and a wave whose sources all answered on their first poll had nothing to
/// watch at all. The per-poll *report* is unchanged — a poll is still named
/// stalled, with its own chain index — because what a watcher does is set a flag
/// every poll in the wave reads, not decide any one poll's fate.
#[derive(Debug)]
struct PollWatchdog {
    /// What the two threads share.
    ///
    /// Shared *by* `Arc` rather than moved into the reaper, because both sides
    /// read and write it: the polls install wakers and register as pending while
    /// the reaper is waiting on the same flag that decides whether it is still
    /// live. A copy on each side is two clocks with one name.
    state: Arc<Mutex<WatchdogState>>,
    /// How the reaper waits, and how the wave ends that wait early.
    ///
    /// A condition variable rather than a sleep, because a wave that resolves
    /// must not leave a thread parked for the rest of its budget: that is the
    /// cost this was built to remove, not to move.
    settled: Arc<Condvar>,
    /// The reaper's handle, owned by the wave that started it.
    ///
    /// Its own lock rather than a field of the guarded state, because the wave
    /// takes it while the guarded state is *not* held, and nesting one mutex
    /// inside another would be an acquisition order every reader has to hold in
    /// their head for a handle two stores touch.
    reaper: Mutex<Option<thread::JoinHandle<()>>>,
}

impl PollWatchdog {
    /// A watchdog for one wave of `members` polls under `deadline`.
    ///
    /// The width is taken at construction because the reaper decides the wave is
    /// over by comparing a resolved count against it, and a width it had to read
    /// out of shared state would be one more thing the two threads could
    /// disagree about.
    fn new(deadline: Duration, members: usize) -> Self {
        Self {
            state: Arc::new(Mutex::new(WatchdogState {
                members,
                resolved: 0,
                expired: false,
                released: false,
                deadline,
                pending: vec![false; members],
                wakers: (0..members).map(|_| None).collect(),
            })),
            settled: Arc::new(Condvar::new()),
            reaper: Mutex::new(None),
        }
    }

    /// Mark one poll of this wave as finished.
    ///
    /// Once per poll, and by the *last* poll the wave is over and the reaper is
    /// released — written and notified inside one critical section, because
    /// setting `released` without the notification is the lost wakeup that leaves
    /// a thread parked for the rest of the budget on a wave nobody waits for.
    fn poll_finished(&self) {
        let mut state = lock(&self.state);
        state.resolved = state.resolved.saturating_add(1);
        if state.resolved >= state.members {
            state.released = true;
            self.settled.notify_all();
        }
    }

    /// Note that `slot` may still have to be waited for.
    ///
    /// Set once, under the same lock the poll read `expired` under, so a reaper
    /// firing on that very turn cannot decide the wave was over while this poll
    /// was still outstanding.
    fn poll_pending(&self, slot: usize) {
        let mut state = lock(&self.state);
        if let Some(pending) = state.pending.get_mut(slot) {
            *pending = true;
        }
    }

    /// Whether the wave's deadline has already passed.
    fn expired(&self) -> bool {
        lock(&self.state).expired
    }

    /// Start the wave's reaper, unless one is running, the wave is over, or
    /// nothing in it is still unresolved.
    ///
    /// Returns `false` only when the host refused the thread *and* some poll is
    /// still unresolved. The caller reports that as a stall for the poll that
    /// asked and the wave stops, rather than waiting for a deadline nobody is
    /// watching — which is the failure this watchdog exists to prevent, so a
    /// substrate that cannot watch must not pretend it is watching.
    ///
    /// Lazy, because a poll that resolved on its first turn never reaches this
    /// with anything to watch: `true` with no thread started is the ordinary
    /// answer. Once per wave, because every poll in a wave shares one deadline
    /// and one thread watching it is the whole of the bound.
    fn start(&self, clock: &Clock, armed: &AtomicBool) -> bool {
        // Serialized on the handle's own lock for the whole decision *and* the
        // spawn, so "already started" is only ever answered for a thread that
        // really exists. A second poll arriving while the first is still
        // spawning waits for the fact rather than reading an optimistic flag,
        // and a refused spawn cannot leave a poll parked against a thread that
        // never started. The lock order is reaper → state here and nowhere the
        // reverse, and the reaper thread itself takes neither.
        let mut owned = lock(&self.reaper);
        if owned.is_some() {
            return true;
        }
        {
            let state = lock(&self.state);
            // A wave with nothing pending — every source answered on its first
            // poll — has nothing to watch, and an expired or released wave is
            // already over: neither starts a thread.
            if state.expired || state.released || !state.pending.iter().any(|held| *held) {
                return true;
            }
        }
        let shared = WatchdogShared {
            deadline: lock(&self.state).deadline,
            state: Arc::clone(&self.state),
            settled: Arc::clone(&self.settled),
        };
        // `std::thread::Builder` rather than the `std::thread::spawn` this
        // workspace bans: the handle is stored in the wave and joined by the wave,
        // so the thread is owned for its whole life rather than being
        // fire-and-forget with an invisible panic.
        let built = thread::Builder::new()
            .name("lgwks-poll-deadline".into())
            .spawn({
                let clock = clock.clone();
                move || reaper(&clock, &shared)
            });
        match built {
            Ok(handle) => {
                *owned = Some(handle);
                // The wave-level mirror the report reads, set only on the path
                // that really did start one, so a zero in the report is an honest
                // statement that no thread was started.
                armed.store(true, Ordering::Relaxed);
                true
            }
            // Not stored, so the next poll that goes Pending tries again rather
            // than concluding from one refusal that the wave is already watched.
            Err(_) => false,
        }
    }

    /// Join the reaper if one was started.
    ///
    /// Split from the wave's own teardown because the join has to *happen* before
    /// the wave reads its polls' outcomes — that ordering is what makes a
    /// resolved wave leave no thread parked behind it.
    fn join(&self) {
        let handle = lock(&self.reaper).take();
        if let Some(handle) = handle {
            // A reaper panic is not this wave's outcome to report: the polls'
            // own answers are the observation, and the thread has either done its
            // work or given up. Joining rather than detaching is what keeps the
            // thread owned to the wave that started it.
            let _joined = handle.join();
        }
    }
}

/// The guarded half of [`PollWatchdog`].
#[derive(Debug, Default)]
struct WatchdogState {
    /// Whether the wave's deadline has passed. Read on the polling thread,
    /// written by the reaper.
    expired: bool,
    /// Whether every poll in the wave has finished, so the reaper has nothing
    /// left to do.
    ///
    /// Distinct from the resolved count, because reaching the width is what sets
    /// this and reading the count is not reading the fact.
    released: bool,
    /// How many polls in the wave have finished.
    resolved: usize,
    /// How many polls the wave has.
    members: usize,
    /// Whether each slot's poll may still have to be waited for.
    ///
    /// One entry per poll, indexed by the slot its waker occupies, rather than a
    /// count: the question that matters before a thread is started is *which*
    /// polls are outstanding, because that is the same index the wakers are
    /// stored at, and a count a poll could decrement twice would answer it wrong.
    pending: Vec<bool>,
    /// The budget this wave is watched against.
    deadline: Duration,
    /// The wave's tasks to wake when the deadline passes.
    ///
    /// One slot per poll, left installed across the reaper's wait rather than
    /// cleared before it: clearing is what loses the wakeup. The reaper clears a
    /// slot on the way *out* by taking it, and a poll installs its own on every
    /// turn, so the one case that must not happen — a deadline expiring against a
    /// poll already parked with its slot empty — cannot be constructed.
    wakers: Vec<Option<Waker>>,
}

/// What a spawned reaper runs on: the budget and the two halves both sides
/// share.
struct WatchdogShared {
    /// The budget this wave is watched against.
    deadline: Duration,
    /// What the two threads share.
    state: Arc<Mutex<WatchdogState>>,
    /// How the reaper waits, and how the wave ends that wait early.
    settled: Arc<Condvar>,
}

/// Watch one wave's deadline and wake every poll still in it when it passes.
///
/// The remaining budget is recomputed on every pass rather than slept once, so
/// the deadline is honoured to the quantum rather than to a multiple of it, and
/// a spurious wake — which a condition variable is free to produce — costs one
/// extra turn rather than a missed deadline.
///
/// The wakers are *not* cleared before the wait, and `released` is *not* set
/// without the notification. Those are the two halves of the same mistake: a
/// poll installs its waker on the turn that finds `expired` false and then
/// parks, so a reaper that cleared the slots on the way into its wait would
/// expire against empty ones; and a reaper that published `released` before
/// notifying would sleep out the whole budget on a wave that had already
/// returned. Both are avoided by making the notification happen while the lock
/// is held, which is what `settled.notify_all()` inside the same critical
/// section as the write buys.
fn reaper(clock: &Clock, watchdog: &WatchdogShared) {
    let fired = clock.wall_watchdog();
    let mut state = lock(&watchdog.state);
    loop {
        // A wave that finished before this thread reached its first wait must
        // not be waited for. `released` is set and notified by the last poll's
        // `Drop`; a notification that lands before the reaper waits is a wakeup
        // a condition variable does not replay, so a per-poll watchdog that was
        // spawned *before* the poll never saw the race, while a wave-level one
        // spawned *during* the poll does — the source that yields and answers
        // on its very next turn resolves in less time than this thread takes to
        // start. Checked under the same guard `wait_timeout` releases
        // atomically, so no poll can set `released` between this check and the
        // wait.
        if state.released {
            return;
        }
        let remaining = watchdog.deadline.saturating_sub(fired.elapsed());
        if remaining.is_zero() {
            state.expired = true;
            // Woken with the lock held, because each waker must be taken here: a
            // poll that installs one immediately afterwards would otherwise park
            // against a slot nobody holds.
            for slot in &mut state.wakers {
                if let Some(waker) = slot.take() {
                    waker.wake();
                }
            }
            return;
        }
        // Waited on a condition variable, never on a sleep. A poll that installs
        // a waker while the reaper is parked against the *same* condition wakes
        // it (`poll_finished` notifies inside its critical section), so a wave
        // that resolved is not paid for with a thread parked out the rest of the
        // budget; and a poll that installs a waker *after* the reaper's last
        // check is one the reaper can still reach, because the waker slots are
        // left installed across the wait rather than cleared before it. Clearing
        // a slot on the way into the wait is the mistake this comment exists for:
        // it loses the wakeup on exactly the turn the wave needs it, and the
        // symptom is a tick that never returns.
        let (woken, _) = wait_timeout(&watchdog.settled, state, remaining);
        state = woken;
        if state.expired || state.released {
            return;
        }
    }
}

/// One source poll's half of a wave: the future, its chain index, and the slot
/// its waker occupies.
///
/// A named struct rather than positional arguments because the one thing a
/// caller must not get wrong is *which* wave a poll belongs to, and a parameter
/// list is where that goes wrong.
struct WavePoll<'wave> {
    /// The chain this poll reads, named in its own report.
    chain: usize,
    /// The wave's deadline watchdog.
    watchdog: &'wave PollWatchdog,
    /// This poll's position in the wave's waker slots.
    slot: usize,
    /// Whether the waker for this poll is installed in its slot.
    ///
    /// Part of the poll rather than the guarded state, so "install, then read"
    /// can be *one* critical section: reading it back out of shared state would
    /// need a second lock acquisition, and the window between the two is the
    /// lost wakeup this whole structure exists to close.
    installed: bool,
    /// The source's own poll.
    ///
    /// Borrowed from the world's chains for the wave's lifetime rather than
    /// `'static`, because the chain is erased in place and the poll is not: a
    /// `'static` box would have to own a copy of the source it is reading, and
    /// the substrate's promise is that it polls *the* source the caller declared.
    poll: Pin<Box<dyn Future<Output = Result<Option<Erased>, BotError>> + 'wave>>,
}

impl WavePoll<'_> {
    /// The typed stall this poll reports when it cannot be waited for any more.
    ///
    /// A whole poll result rather than a bare error, because every caller of it
    /// is a `Poll::Ready` arm of this poll's own turn: a stall is what the
    /// source's slot holds, and a caller that had to wrap it would be the second
    /// place that shape is written.
    fn stalled(&self, deadline: Duration) -> Result<Option<Erased>, BotError> {
        Err(BotError::PollStalled {
            chain: self.chain,
            deadline,
        })
    }

    /// Turn this poll once under the wave's deadline.
    ///
    /// Install, register, read `expired`, and poll are sequenced so that no arm
    /// can park against a deadline nobody is watching and no deadline can expire
    /// against a poll whose waker is not installed. The two registrations are the
    /// half that is easy to get wrong and impossible to notice: a poll that
    /// registered as pending *after* the reaper checked would never be woken, and
    /// a poll that started a thread *after* the reaper decided the wave was
    /// released would wait forever on a thread that has already gone.
    fn turn(
        &mut self,
        cx: &mut Context<'_>,
        clock: &Clock,
        armed: &AtomicBool,
        deadline: Duration,
    ) -> Poll<Result<Option<Erased>, BotError>> {
        {
            let mut state = lock(&self.watchdog.state);
            if state.expired {
                return Poll::Ready(self.stalled(deadline));
            }
            // Whether the installed waker is one the executor will recognise. A
            // poll that has not installed one yet, or whose installed waker
            // belongs to a different task, has to write again — and writing the
            // *same* waker on every turn would be a clone per turn for nothing.
            let stale = if self.installed {
                state
                    .wakers
                    .get(self.slot)
                    .and_then(|slot| slot.as_ref())
                    .is_none_or(|installed| !installed.will_wake(cx.waker()))
            } else {
                true
            };
            if let (true, Some(slot)) = (stale, state.wakers.get_mut(self.slot)) {
                *slot = Some(cx.waker().clone());
                self.installed = true;
            }
        }
        match self.poll.as_mut().poll(cx) {
            // Polled before a late expiry is consulted, so a poll that resolved
            // in the same turn the deadline passed still answers with what it
            // read. A cancellation landing on a poll that was about to finish is
            // indistinguishable from one that never was going to, and only the
            // value is a fact. A poll that answers on its first turn — the
            // ordinary one — returns here without ever having started a thread,
            // which is the whole of the lazy half.
            Poll::Ready(outcome) => Poll::Ready(outcome),
            Poll::Pending => {
                // Registered before the wave is armed, so the reaper's first
                // look at the wave already sees this poll as outstanding. The
                // registration and the `expired` read below are two critical
                // sections rather than one, and that is safe here in a way it is
                // not above: `start` takes the same lock, so a reaper cannot be
                // running to fire between them until this poll has registered.
                self.watchdog.poll_pending(self.slot);
                // Started only now, because a wave with nothing pending has
                // nothing to watch. The first poll in the wave to go Pending is
                // the one that spends the thread, and a wave whose every source
                // answered spends none — the ordinary tick. Registering first and
                // arming second is what makes a wave that will never be woken
                // again, a wedged source, still bounded: the reaper exists before
                // this turn returns `Pending`, so the deadline can still fire and
                // wake it. A spawn the host refuses reports this poll stalled and
                // leaves every already-resolved poll in the wave with its answer,
                // because a poll that answered never reaches this arm.
                if !self.watchdog.start(clock, armed) {
                    return Poll::Ready(self.stalled(deadline));
                }
                if self.watchdog.expired() {
                    Poll::Ready(self.stalled(deadline))
                } else {
                    Poll::Pending
                }
            }
        }
    }
}

impl Drop for WavePoll<'_> {
    /// Count this poll as finished under the wave's lock.
    ///
    /// A `Drop` rather than a call at the end of the poll body, because a poll
    /// future dropped *before* it resolves — a tick cancelled mid-wave — is no
    /// longer going to ask, and a counter that missed it would leave a reaper
    /// parked for the rest of the budget on a wave nobody is waiting for.
    fn drop(&mut self) {
        self.watchdog.poll_finished();
    }
}

/// Run one wave's polls under a shared `deadline`, reporting a typed stall per
/// poll rather than waiting forever.
///
/// This is the whole of T06's slow-source half, and it is one function because
/// there is exactly one place in this crate where a source poll is awaited and
/// exactly one place that can therefore bound it. Putting the bound anywhere
/// else would mean a second place that could forget it.
///
/// # Why the *watchdog* half of the declared clock
///
/// The crate's one declared clock ([`crate::rt::clock::Clock`], INV-BOT-30) has
/// two halves, and this takes the one that is always on: a real-time watchdog
/// that keeps running when the logical counter is frozen. That is the correct
/// authority here, and the reason is in the clock's own contract — a source that
/// stopped answering is not waiting for time to pass, it has stopped making
/// progress entirely. A logical deadline would either expire against a poll that
/// was merely slow (because a test advanced the clock) or wait on the wedged one
/// forever (because nothing advanced it).
///
/// The declaration is still load-bearing: the watchdog is obtained *through* a
/// [`crate::rt::clock::Clock`], so the elapsed time that cancelled these polls
/// traces back to a clock the crate named rather than to a free-floating
/// `Instant` someone sampled at a call site.
///
/// # What "cancelled" means
///
/// A poll future is dropped where it stands. It committed nothing, so its
/// chain's baseline and its forced-refresh mark are exactly as they were, and
/// the next tick re-polls it — the same rule a failed poll already follows, and
/// for the same reason: the value this poll was supposed to replace is still
/// there. Dropping a future is cooperative, so a poll that already handed work
/// to `spawn_blocking` has its handle released and its thread runs to
/// completion; that is the documented behaviour of the estate's executor, and it
/// is why the stall report is about *this bot's* observation and not about the
/// source's side effects.
///
/// A sibling poll in the same wave is not stopped: the chains beside a wedged
/// source still commit and act in the same tick. The budget bounds the *wave's*
/// wait rather than each poll's separately, and the difference that makes is
/// bounded by the cost of starting the wave — every poll begins together, so
/// there is no second budget to spend and no poll can be cancelled twice.
async fn bounded_wave(
    deadline: Duration,
    watchdog: &PollWatchdog,
    polls: impl IntoIterator<Item = WavePoll<'_>>,
) -> (Vec<Result<Option<Erased>, BotError>>, bool) {
    let clock = Clock::wall();
    // The wave-level mirror the report reads, set only on the path that really
    // did start a reaper, so a report beside a zero is an honest statement that
    // no thread was started.
    let armed = AtomicBool::new(false);

    let joined = lgwks_std::task::join_all_boxed(polls.into_iter().map(|mut poll| {
        let clock = clock.clone();
        let armed = &armed;
        Box::pin(std::future::poll_fn(move |cx: &mut Context<'_>| {
            poll.turn(cx, &clock, armed, deadline)
        }))
    }));
    let results = joined.await;
    // Joined before the results are read, so a wave that resolved leaves no
    // thread parked behind it and an expired wave has its reaper reaped before
    // the caller acts on what it decided. The watchdog is the wave's own — the
    // one its polls borrowed — so there is exactly one handle in this scope and
    // no thread can be started and left unjoined.
    watchdog.join();
    (results, armed.load(Ordering::Relaxed))
}

/// Compare two erased outputs as `S::Output`.
///
/// A downcast that fails is reported as *different* rather than equal: treating
/// an unreadable value as unchanged would silently suppress an effect, and the
/// failure mode this whole substrate is built to avoid is an effect that does
/// not happen with nothing to show for it.
/// The admitted-input identity of an observation, and how a returning one reads.
///
/// The two fields answer two different questions (issue #129). `identity` is
/// the content identity a digest binds: the same value of the same type derives
/// the same bytes (so a restart retires work that already landed), and a
/// different value derives different ones (so a restart does not read new work
/// as already applied). `event` says whether those bytes name an *event*
/// rather than only content — see [`InputIdentity::names_an_event`].
///
/// Keeping them apart is what lets a state watch `0 → 1 → 0` fire three times
/// while a redelivered [`EventId`] still retires.
#[derive(Clone, Copy)]
pub(crate) struct AdmittedInput {
    /// The content identity a dispatch digest binds.
    identity: [u8; 16],
    /// Whether `identity` names an event rather than only content.
    event: bool,
}

/// The admitted-input identity of an erased binding.
///
/// A type-qualified content identity: the same value of the same type always
/// derives the same bytes (so a restart retires work that already landed), and
/// a different value derives different ones (so a restart does not read new
/// work as already applied). Two *events* with equal content must still be
/// distinguishable, which is the caller's to express via
/// [`EventId`] or their own [`InputIdentity`] impl —
/// content equality alone is not event identity (issue #101).
pub(crate) fn identify_output<S>(value: &dyn Any) -> AdmittedInput
where
    S: Observe,
    S::Output: InputIdentity + 'static,
{
    let mut hasher = Hasher::new();
    hasher
        .write_framed(OUTPUT_IDENTITY_DOMAIN)
        .write_framed(<S::Output as InputIdentity>::SCHEMA_ID);
    let event = match value.downcast_ref::<S::Output>() {
        Some(typed) => {
            typed.write_identity(&mut hasher);
            typed.names_an_event()
        }
        None => {
            // A downcast that fails means the binding is not what this chain
            // claims. Hash the miss rather than returning a default: a constant
            // identity would make every mismatched binding look like the same
            // admitted input. Reported as content-only, so the stricter of the
            // two retire readings applies and a mismatch is not quietly retired.
            hasher.write_framed(b"downcast-miss");
            false
        }
    };
    let digest = hasher.finalize();
    let mut wide = [0_u8; 16];
    wide.copy_from_slice(&digest.as_bytes()[..16]);
    AdmittedInput {
        identity: wide,
        event,
    }
}

/// Compare two erased outputs as `S::Output`.
///
/// A downcast that fails is reported as *different* rather than equal: treating
/// an unreadable value as unchanged would silently suppress an effect, and the
/// failure mode this whole substrate is built to avoid is an effect that does
/// not happen with nothing to show for it.
pub(crate) fn same_output<S>(left: &dyn Any, right: &dyn Any) -> bool
where
    S: Observe + 'static,
    S::Output: PartialEq + InputIdentity + 'static,
{
    match (
        left.downcast_ref::<S::Output>(),
        right.downcast_ref::<S::Output>(),
    ) {
        (Some(left), Some(right)) => left == right,
        _ => false,
    }
}

/// Whether the tick is parked, so its steps commit and run nothing.
///
/// A **domain** failure parks a tick: the substrate could not act on what a chain
/// told it, and the tick's contract is that such a tick commits nothing and fires
/// nothing. A **cancelled** poll does not, and that distinction is the whole of
/// T06's slow-source half. A source that stopped answering said nothing, so the
/// chains beside it have real observations to commit — withholding them because
/// one unrelated source was slow is exactly the starvation the per-poll deadline
/// exists to prevent.
///
/// The report still names every cancelled chain, and the tick still returns the
/// typed cancellation; what it does not do is stop the bot.
fn parked(world: &World) -> bool {
    world.get_resource::<TickError>().is_some_and(|error| {
        error
            .0
            .as_ref()
            .is_some_and(|error| !matches!(error, BotError::PollStalled { .. }))
    })
}

// ── The work ledger: eligible work, separate from change detection ─────────

/// One `(chain, entry)` slot of a chain.
///
/// An address, not an identity, and the distinction is the whole of what
/// [`PendingWork`] exists to carry. A slot is reused by every generation over
/// its chain and by every attempt within one, so two `WorkId`s comparing equal
/// says only that the *address* is the same — never that the work standing
/// there is. It names a place in a report; it does not settle one.
///
/// It is deliberately not constructible outside this crate. That is not what
/// makes settlement safe — a [`PendingWork`] is what does — but a caller that
/// could mint one could name work it never observed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct WorkId {
    /// The chain's index, in declaration order.
    chain: usize,
    /// The entry's index within its chain.
    entry: usize,
}

impl WorkId {
    /// The chain's index, in declaration order.
    #[must_use]
    pub const fn chain(self) -> usize {
        self.chain
    }

    /// The entry's index within its chain.
    #[must_use]
    pub const fn entry(self) -> usize {
        self.entry
    }
}

/// Why an entry was given up on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AbandonReason {
    /// The attempt budget for this entry is spent. The effect definitely did
    /// not happen on any of the attempts made; nothing further is attempted
    /// without evidence, which `EcsBot::resolve_effect` supplies.
    AttemptsExhausted {
        /// How many attempts were made.
        attempts: u32,
    },
    /// The failure is one no retry can fix: a refused capability, a type
    /// mismatch behind an erased verb, a malformed action input. Retrying would
    /// spend an attempt to learn the same answer.
    Terminal,
}

/// What is holding one entry of a transition back.
///
/// The `Running` state the ledger tracks is called [`Self::Unrecorded`] here:
/// at rest — which is the only time a caller can observe it — "an attempt is
/// in flight" and "an attempt began and no outcome was ever recorded" are the
/// same fact, and the second is the one that decides what happens next.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum TransitionHold {
    /// Never attempted. An entry ahead of it is unresolved, and the chain's
    /// declared order is part of what it means.
    NotStarted,
    /// An attempt began and no outcome was recorded — the tick that started it
    /// ended without one. Held exactly as an unknown outcome is: the effect may
    /// be live, so it is never attempted again without evidence.
    Unrecorded,
    /// An attempt on this entry's action was recorded as dispatched earlier in
    /// this run, and no outcome was ever recorded for it.
    ///
    /// Distinct from [`Self::Unrecorded`], which is an attempt *this* process
    /// began and whose outcome the same process never wrote, and from
    /// [`Self::OutcomeUnknown`], which is an attempt it ran and watched become
    /// indeterminate. This one was found, not made: the bot was assembled
    /// against a journal that already said the bytes may be live, and the
    /// substrate will not begin another attempt on that action until a caller
    /// settles it. The key to settle it with is
    /// [`PendingWork::key`].
    UnsettledByRecovery {
        /// The action whose earlier attempt never settled.
        action: ActionId,
    },
    /// The effect definitely did not happen, and the attempt budget remains.
    Failed {
        /// Attempts made so far, including the failed one.
        attempts: u32,
        /// The budget this entry is allowed.
        budget: u32,
        /// The failure the attempt produced.
        cause: String,
    },
    /// The effect may or may not have happened. Never attempted again without
    /// evidence.
    OutcomeUnknown {
        /// Attempts made so far, including the indeterminate one.
        attempts: u32,
        /// Why the outcome could not be settled.
        cause: String,
    },
    /// The action produced a known outcome and the journal refused to record
    /// it. Only the append is retried; the action is never re-entered.
    RecordingFailed {
        /// What the action did — the occurrence is a fact.
        evidence: EffectEvidence,
        /// Why the last append was refused.
        cause: String,
    },
    /// Given up on, and reported rather than dropped.
    Abandoned {
        /// Why it was given up on.
        reason: AbandonReason,
        /// The failure that ended it.
        cause: String,
    },
}

impl fmt::Display for TransitionHold {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // The scrutinee is `*self`, so each pattern's type is the enum's own
        // type rather than a reference to it, and the causes are bound by
        // `ref`. They are rendered through `Escaped`, which is what keeps a
        // foreign payload from forging a log record; the pass is idempotent
        // (see `error::Escaped`), so a cause that arrived already escaped is
        // rendered exactly once.
        match *self {
            Self::NotStarted => f.write_str("not attempted: an entry ahead of it is unresolved"),
            Self::Unrecorded => {
                f.write_str("an attempt began and no outcome was recorded: the effect may be live")
            }
            Self::UnsettledByRecovery { action } => write!(
                f,
                "may have happened: an earlier attempt on action {action} was dispatched \
                 and nothing recorded its outcome, so nothing is sent again until it is \
                 settled"
            ),
            Self::Failed {
                attempts,
                budget,
                ref cause,
            } => write!(
                f,
                "did not happen: attempt {attempts} of {budget} failed with {}",
                Escaped(cause)
            ),
            Self::OutcomeUnknown {
                attempts,
                ref cause,
            } => write!(
                f,
                "may have happened: attempt {attempts} was indeterminate ({})",
                Escaped(cause)
            ),
            Self::RecordingFailed {
                evidence,
                ref cause,
            } => write!(
                f,
                "the effect is {evidence} and only its record is missing: {}. \
                 The journal append is retried; the action is not",
                Escaped(cause)
            ),
            Self::Abandoned { reason, ref cause } => match reason {
                AbandonReason::AttemptsExhausted { attempts } => write!(
                    f,
                    "given up on after {attempts} attempts: {}",
                    Escaped(cause)
                ),
                AbandonReason::Terminal => {
                    write!(f, "given up on, no retry can fix: {}", Escaped(cause))
                }
            },
        }
    }
}

/// One entry of a transition that is not finished, and the attempt it is about.
///
/// This is the report a caller reads, and [`Self::key`] is what a settlement is
/// made against. The two are one value because they are two halves of one fact:
/// the address ([`WorkId`]) tells a caller *where* to look in its own books and
/// the key tells the substrate *which* attempt, over *which* observed input, the
/// evidence is about.
///
/// The key is why settlement takes this value's key rather than the slot. A
/// chain retries within one generation, so `NotApplied` for the first attempt
/// makes the entry eligible again and a second attempt runs against the same
/// address over the same binding. A report about the first attempt that is
/// *delivered twice* — which settlement is explicitly designed to tolerate,
/// because a caller that never saw its first delivery acknowledged has to be
/// able to repeat it — would otherwise land on the second attempt and make an
/// attempt whose effect may be live eligible to run a third time. Naming the
/// attempt is what separates "send that again" from "that was about work that is
/// over".
///
/// [`Self::key`] is `None` for an entry that has never been attempted. There is
/// then nothing for evidence to settle, and the absence is the same absence
/// rather than a zero attempt that would have to be special-cased at every
/// settlement site.
///
/// The fields are private and there is no public constructor, so a caller can
/// only ever settle work it read from [`EcsBot::pending`]. That is a seal, not
/// a formality: it makes "settle an attempt I invented" unrepresentable rather
/// than merely refused.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PendingWork {
    /// Which entry this is.
    id: WorkId,
    /// The attempt this entry is on, and the four facts that name it.
    ///
    /// `None` when the entry has not been attempted, which is the only state
    /// that has no attempt identity to hand out.
    ///
    /// Boxed because a key is a fixed-width identity — seven fields, 128 bytes
    /// — and this type is embedded in [`BotError::PendingTransition`], which is
    /// returned by value from every tick that leaves work unfinished. Held
    /// inline, one key would put that error over the size at which the
    /// `result_large_err` lint fires for every caller in the workspace; the
    /// indirection costs one allocation on a path that already produces a
    /// report, and buys back the error's size for all of them.
    ///
    /// [`BotError::PendingTransition`]: crate::BotError::PendingTransition
    key: Option<Box<EffectKey>>,
    /// What is holding it.
    hold: TransitionHold,
}

impl PendingWork {
    /// Which entry this is.
    ///
    /// The address in the bot's own declarations, not an identity: a slot is
    /// reused by every generation over its chain, so two reports comparing
    /// equal here say only that the *place* is the same. [`Self::key`] is what
    /// names the work.
    #[must_use]
    pub const fn id(&self) -> WorkId {
        self.id
    }

    /// The attempt this entry is on, when there has been one.
    ///
    /// This is the value [`EcsBot::resolve_effect`] takes. It carries the run,
    /// the action, the attempt, the flow, the binding, the environment and the
    /// generation, and all seven are compared before anything is read or
    /// written — which is what makes the delivery safe to repeat.
    ///
    /// `None` means nothing has been attempted on this entry yet, so there is
    /// no attempt for evidence to be about.
    #[must_use]
    pub fn key(&self) -> Option<EffectKey> {
        self.key.as_deref().copied()
    }

    /// What is holding it back.
    #[must_use]
    pub const fn hold(&self) -> &TransitionHold {
        &self.hold
    }
}

impl fmt::Display for PendingWork {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Written in two passes rather than through an intermediate `String`:
        // this renders on every tick that leaves work unfinished, and a
        // diagnostic that allocates twice to say which entry is stuck is a cost
        // paid on the path that is already the unhappy one.
        write!(f, "chain {} entry {} (", self.id.chain(), self.id.entry())?;
        match self.key.as_deref() {
            Some(key) => write!(
                f,
                "attempt {}, binding {}",
                key.attempt().get(),
                key.digest()
            )?,
            None => f.write_str("no attempt yet")?,
        }
        write!(f, "): {}", self.hold)
    }
}

/// What a caller knows about an effect the substrate could not settle.
///
/// Two arms, because there are two facts a caller can establish, and the
/// decision that matters — attempt it again or not — follows from which one
/// they are. "Unknown and staying unknown" is not evidence and has no arm: an
/// entry in that state stays reported, which is the honest outcome.
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    Hash,
    lgwks_std::wire::Archive,
    lgwks_std::wire::Serialize,
    lgwks_std::wire::Deserialize,
)]
#[rkyv(attr(non_exhaustive), crate = lgwks_std::wire::rkyv, compare(PartialEq), derive(Debug))]
#[non_exhaustive]
pub enum EffectEvidence {
    /// The effect happened. The entry is acknowledged and never attempted
    /// again.
    Applied,
    /// The effect did not happen. This is the evidence a retry requires: the
    /// entry becomes eligible for an attempt again, with a fresh budget,
    /// because a new fact is not a repeat of the attempt that failed.
    NotApplied,
}

/// Renders the fact the caller established, not the enum arm, because these
/// appear in refusal messages a person reads to decide whether their own
/// observation was wrong: `applied` and `not applied` are what they were asked
/// for, and `Applied`/`NotApplied` would make them translate.
///
/// Lives here rather than in `error.rs` for the same reason
/// [`PendingWork`]'s does — the type owns its rendering, so a later variant
/// cannot be interpolated anywhere unhandled.
impl fmt::Display for EffectEvidence {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Matched through a dereference rather than through the reference: the
        // type is `Copy`, and `clippy::pattern_type_mismatch` is forbidden in
        // this workspace.
        f.write_str(match *self {
            Self::Applied => "applied",
            Self::NotApplied => "not applied",
        })
    }
}

/// How many times an entry whose effect definitely did not happen is attempted.
///
/// A policy rather than a constant, because the right number is a property of
/// the action: a merge that transiently refuses wants several attempts, a
/// process launch wants one. There is no measured basis for a default, so
/// [`Self::DEFAULT`] is a declared guess and is named as one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RetryPolicy {
    /// Attempts per entry, the first included. Non-zero: an entry that may
    /// never be attempted is not a policy, it is pre-abandoned work.
    max_attempts: NonZeroU32,
}

impl RetryPolicy {
    /// One attempt per entry: the first definite failure abandons it.
    pub const ONE_ATTEMPT: Self = Self {
        max_attempts: NonZeroU32::MIN,
    };

    /// The declared default: three attempts per entry, counting the first.
    pub const DEFAULT: Self = Self {
        // Total rather than panicking: a `const` has no error channel and
        // `unwrap` is refused crate-wide. The `None` arm is unreachable, since
        // three is not zero.
        max_attempts: match NonZeroU32::new(3) {
            Some(three) => three,
            None => NonZeroU32::MIN,
        },
    };

    /// A policy allowing `max_attempts` attempts per entry.
    #[must_use]
    pub const fn new(max_attempts: NonZeroU32) -> Self {
        Self { max_attempts }
    }

    /// Attempts allowed per entry.
    #[must_use]
    pub const fn max_attempts(self) -> u32 {
        self.max_attempts.get()
    }
}

/// The state of one entry within a transition.
#[derive(Debug, Clone)]
enum EntryState {
    /// Never attempted. An entry ahead of it may be holding it back.
    NotStarted,
    /// An attempt is under way, or was begun and its outcome never recorded.
    /// This is the issue's `Running`, named for the fact that survives the
    /// call.
    Unrecorded,
    /// The action ran and returned.
    Succeeded,
    /// The condition was false when it was evaluated against the value.
    Skipped,
    /// The effect definitely did not happen ([`BotError::DomainError`]), and
    /// attempts remain in the budget.
    DefinitelyFailed {
        /// Attempts made so far.
        attempts: u32,
        /// The failure.
        cause: String,
    },
    /// The effect may or may not have happened
    /// ([`BotError::EffectIndeterminate`]).
    OutcomeUnknown {
        /// Attempts made so far.
        attempts: u32,
        /// Why the outcome could not be settled.
        cause: String,
    },
    /// The action produced a known outcome and the journal refused to record
    /// it ([`BotError::EffectUnrecorded`]).
    ///
    /// Held for an **append-only** retry. The action is never re-entered: the
    /// occurrence is already a fact, and a second dispatch would turn that
    /// fact into a duplicate. The key and the evidence travel with the state so
    /// the next tick can write exactly the record that failed to land.
    RecordingFailed {
        /// The attempt identity the append is for.
        key: EffectKey,
        /// What the action did.
        evidence: EffectEvidence,
        /// Why the last append was refused.
        cause: String,
        /// Attempts made so far, including the one that produced the outcome.
        attempts: u32,
    },
    /// Given up on, and reported.
    Abandoned {
        /// Why.
        reason: AbandonReason,
        /// The failure that ended it.
        cause: String,
    },
}

impl EntryState {
    /// Whether the entry still needs something: an attempt, evidence, or the
    /// entry ahead of it to be resolved.
    fn is_open(&self) -> bool {
        matches!(
            self,
            Self::NotStarted
                | Self::Unrecorded
                | Self::DefinitelyFailed { .. }
                | Self::OutcomeUnknown { .. }
                | Self::RecordingFailed { .. }
        )
    }

    /// Whether the entry was given up on: terminal for this transition, and
    /// reported rather than dropped.
    fn is_abandoned(&self) -> bool {
        matches!(self, Self::Abandoned { .. })
    }

    /// How this entry reads to a caller, `None` when it is resolved and has
    /// nothing to report.
    fn hold(&self, budget: u32) -> Option<TransitionHold> {
        match *self {
            Self::Succeeded | Self::Skipped => None,
            Self::NotStarted => Some(TransitionHold::NotStarted),
            Self::Unrecorded => Some(TransitionHold::Unrecorded),
            Self::DefinitelyFailed {
                attempts,
                ref cause,
            } => Some(TransitionHold::Failed {
                attempts,
                budget,
                cause: cause.clone(),
            }),
            Self::OutcomeUnknown {
                attempts,
                ref cause,
            } => Some(TransitionHold::OutcomeUnknown {
                attempts,
                cause: cause.clone(),
            }),
            Self::RecordingFailed {
                ref evidence,
                ref cause,
                ..
            } => Some(TransitionHold::RecordingFailed {
                evidence: *evidence,
                cause: cause.clone(),
            }),
            Self::Abandoned { reason, ref cause } => Some(TransitionHold::Abandoned {
                reason,
                cause: cause.clone(),
            }),
        }
    }
}

/// What the ledger knows about the attempts made on one entry of one
/// generation.
///
/// Kept beside [`EntryState`] rather than inside it, because the state is
/// overwritten by every settlement and every failure and this is not: an entry
/// settled `NotApplied` and attempted again is a *later* attempt at the same
/// address, and the ordinal is what says so.
#[derive(Debug, Clone, Copy, Default)]
struct AttemptRecord {
    /// The latest attempt begun on this entry in this generation, or `None`
    /// while none has been.
    ///
    /// Monotonic by construction: only [`Ledger::begin_attempt`] moves it, and
    /// nothing resets it while the transition stands. It is the entry's attempt
    /// identity, and it is what a [`PendingWork`] hands out — an identity
    /// rather than a count, so the number a caller is handed and the number a
    /// settlement compares against are the same value rather than two
    /// derivations of one.
    begun: Option<AttemptId>,
    /// The attempt the latest settlement was about, and what it said.
    ///
    /// The ordinal is stored rather than assumed to be the latest, because a
    /// settlement is what *permits* the next attempt: recording it against
    /// whichever attempt happened to be current when a repeat arrived is how a
    /// report about one attempt comes to authorise another.
    settled: Option<SettledAttempt>,
}

/// The attempt one settlement was about, and the evidence it carried.
#[derive(Debug, Clone, Copy)]
struct SettledAttempt {
    /// The attempt the evidence was submitted for.
    attempt: AttemptId,
    /// What the evidence said.
    evidence: EffectEvidence,
}

/// The work of one source transition: one state per entry of its chain.
///
/// Deliberately neither `Clone` nor a derived `Debug`: it owns the observed
/// payload it is bound to, and that payload is erased. Copying a transition
/// would quietly copy the payload with it — the very copy the sources are not
/// required to support — and printing one would demand `Debug` of a type the
/// source never promised it for. The manual [`fmt::Debug`] below renders the
/// binding as its presence, which is the part a reader of a log wants.
struct Transition {
    /// The revision that opened it, for the caller-facing revision report.
    ///
    /// Not the digest input: this counter is process-local and reopens at 1
    /// after every reconstruction. [`Self::input`] is what a digest binds.
    revision: u64,
    /// The admitted input identity this transition is bound to.
    ///
    /// A content identity extracted from the observation when it was admitted
    /// (issue #101), so a restart that sees the same input retires work that
    /// already landed and a restart that sees a different one does not.
    input: [u8; 16],
    /// Whether [`Self::input`] names an event rather than only content.
    ///
    /// Settled at admission from [`InputIdentity::names_an_event`] and carried
    /// so a later retire check reads a returning identity the way the type
    /// says to read it (issue #129).
    event: bool,
    /// One state per entry of the chain, in declaration order.
    entries: Vec<EntryState>,
    /// What the ledger knows about the attempts made on each entry, for the
    /// generation [`Self::revision`] names, indexed as [`Self::entries`] is.
    ///
    /// Two facts live here, and each answers a question [`EntryState`] cannot.
    /// The settlement is what makes evidence idempotent and a contradiction
    /// refusable: `Applied` and an attempt that returned `Ok` both land on
    /// [`EntryState::Succeeded`], and `NotApplied` and an entry that has not
    /// been reached both land on [`EntryState::NotStarted`], so without it a
    /// caller whose first delivery was ambiguous cannot safely repeat it. The
    /// attempt ordinal is what makes the entry's attempts *numerable*: a
    /// settled entry walks back to [`EntryState::NotStarted`], which carries no
    /// count, so a number read off the state alone would restart at one and two
    /// different attempts would answer to the same name.
    ///
    /// Per generation: both are reset when a transition is opened, because a
    /// settlement is a statement about one attempt within one generation and
    /// neither fact carries into the next.
    attempts: Vec<AttemptRecord>,
    /// The observed payload this transition is bound to.
    ///
    /// The binding is the whole point of the field. One transition is one
    /// generation of work over a chain, and every entry of it — the conditions
    /// that are evaluated and the actions that are run — must see the value the
    /// generation was opened under. Reading the newest observation instead
    /// splits a transition across two inputs: an entry that was acknowledged
    /// against the old value is retried against the new one, and the run ends
    /// up reporting an effect of the new value that was actually produced from
    /// the old.
    ///
    /// It is *moved* here out of the observation slot rather than copied from
    /// it, which is why nothing in this module asks a source's `Output` to be
    /// `Clone`. The observation slot is empty for exactly as long as a live
    /// transition owns the value, and [`observe_fold`] reads the binding back
    /// when it needs to know what the chain last acted on.
    ///
    /// `None` only for a transition opened while nothing had been observed —
    /// there is then no payload to bind, and the entries are held rather than
    /// evaluated against a value nobody read.
    value: Option<Erased>,
}

impl fmt::Debug for Transition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Transition")
            .field("revision", &self.revision)
            .field("entries", &self.entries)
            .field("attempts", &self.attempts)
            .field("bound", &self.value.is_some())
            .finish()
    }
}

impl Transition {
    /// The latest attempt begun on `entry`, or `None` when this transition has
    /// no such entry or none has been begun.
    ///
    /// Read through here rather than off [`EntryState`] so that the identity a
    /// caller is handed and the identity settlement checks are the same one: a
    /// settled entry walks back to `NotStarted`, which carries no attempt, and
    /// an identity derived from the state would restart at the first one.
    fn attempt_of(&self, entry: usize) -> Option<AttemptId> {
        self.attempts.get(entry).and_then(|record| record.begun)
    }

    /// A transition with every entry outstanding, bound to `value`.
    fn opened(input: AdmittedInput, revision: u64, entries: usize, value: Option<Erased>) -> Self {
        Self {
            revision,
            input: input.identity,
            event: input.event,
            entries: vec![EntryState::NotStarted; entries],
            attempts: vec![AttemptRecord::default(); entries],
            value,
        }
    }

    /// Continue into a new revision, from a transition with nothing open.
    ///
    /// Every entry is outstanding again for the new value, *except* the ones
    /// given up on: those are terminal until evidence revives them, and
    /// carrying their record forward is what keeps a lost effect reported
    /// instead of silently dropped the moment the source moves.
    fn resumed(
        input: AdmittedInput,
        revision: u64,
        previous: &Self,
        value: Option<Erased>,
    ) -> Self {
        Self {
            revision,
            input: input.identity,
            event: input.event,
            entries: previous
                .entries
                .iter()
                .map(|state| match *state {
                    EntryState::Abandoned { reason, ref cause } => EntryState::Abandoned {
                        reason,
                        cause: cause.clone(),
                    },
                    _ => EntryState::NotStarted,
                })
                .collect(),
            // Attempts as well as settlements: both are statements about one
            // attempt within one generation, and this is a new generation.
            attempts: vec![AttemptRecord::default(); previous.entries.len()],
            value,
        }
    }

    /// Whether any entry is still unresolved.
    fn has_open(&self) -> bool {
        self.entries.iter().any(EntryState::is_open)
    }

    /// Whether the ledger must keep this transition: it has work to do, or a
    /// fact to report.
    fn is_retained(&self) -> bool {
        self.entries
            .iter()
            .any(|state| state.is_open() || state.is_abandoned())
    }
}

/// What a settlement did to the ledger.
///
/// Six answers, because a caller's next move differs for each: [`Decided`] and
/// [`Duplicate`] are both success, and the other four are four distinct
/// refusals that must not be collapsed into one. Only [`NoSuchWork`] means
/// "there is no held effect for this action"; a caller told that about an action
/// it has a `PendingWork` for is being told its evidence is stale or
/// contradictory, which is a different repair.
///
/// Each refusal carries the address it was about, worked out where the ledger
/// already had it. A refusal that made the caller look the entry up again would
/// have to answer what to do when the lookup fails, and there is no honest
/// answer: the ledger just knew, and a second query is a chance for the two
/// answers to differ.
///
/// [`Decided`]: Settled::Decided
/// [`Duplicate`]: Settled::Duplicate
/// [`NoSuchWork`]: Settled::NoSuchWork
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Settled {
    /// The key's generation's entry was outstanding, and this evidence is now
    /// its outcome.
    Decided,
    /// The key's generation was already given exactly this evidence for this
    /// entry. A caller that could not tell whether its first delivery landed
    /// repeats it and must not be punished for the repetition, nor may the
    /// repeat move the entry a second time.
    Duplicate,
    /// The key names a binding that is not the one in the slot now: the work
    /// the caller is reporting on was superseded, and the live transition is
    /// about a different attempt over a different observed input.
    Superseded {
        /// The entry the action is declared on.
        id: WorkId,
        /// The binding the slot holds now.
        current: ActionDigest,
    },
    /// The named attempt is not the one outstanding on that entry: a later
    /// attempt has been begun since the caller read the work.
    ///
    /// Distinct from [`Self::Superseded`], which is about the generation, and
    /// the distinction is the point of carrying an attempt at all. The
    /// generation can be the one the caller named and the attempt still be
    /// gone — that is the retry-inside-one-generation case — and accepting the
    /// report there would apply it to an attempt the caller never observed.
    StaleAttempt {
        /// The entry the action is declared on.
        id: WorkId,
        /// The attempt the evidence was about.
        reported: AttemptId,
        /// The attempt the entry is on now.
        outstanding: AttemptId,
    },
    /// The named generation's entry is settled, and this evidence says the
    /// opposite of what settled it.
    Contradicted {
        /// The entry the action is declared on.
        id: WorkId,
        /// The evidence already recorded for this generation.
        settled: EffectEvidence,
    },
    /// The key has no work to settle: either the action is not declared here at
    /// all, or it is declared at an entry whose outcome is already decided.
    ///
    /// The address is absent only in the first case, which is why it is an
    /// `Option` rather than a fabricated slot: a caller told "no such work, at
    /// chain 0 entry 0" would be reading a place the key never named.
    NoSuchWork {
        /// The entry the action is declared on, when it is declared at all.
        id: Option<WorkId>,
    },
}

/// The eligible work of the bot, keyed by chain.
///
/// One transition per chain, and never one per revision: an entry's work cannot
/// be re-derived from the change filter, and two transitions for one chain
/// would replay an acknowledged effect on the older one to reach an entry the
/// newer one skipped. Bounded by construction — at most one state per entry of
/// the spec, so the ledger cannot grow with the number of ticks.
///
/// A non-send resource rather than a plain one, because a transition owns the
/// observed payload it is bound to and `Box<dyn Any>` is neither `Send` nor
/// `Sync`. The binding travels *inside* the transition deliberately: a second
/// structure holding the payloads would have to be kept in step with this one
/// through every `take`, `put`, `begin`, `skip` and `fail`, and the first path
/// that forgot would silently re-bind a live transition to the wrong value.
#[derive(Debug)]
struct Ledger {
    /// One live transition per chain, in declaration order.
    transitions: Vec<Option<Transition>>,
    /// The next admitted-input identity to mint.
    ///
    /// Seeded from the journal tail so a reconstructed bot cannot reissue a
    /// stamp an earlier process already bound a dispatch to.
    next_input: u64,
    /// The action each entry of each chain runs, in declaration order.
    ///
    /// Derived once, at assembly, from the declarations — the bot's name, the
    /// chain's index, the entry's index and the action's own domain — rather
    /// than re-derived per attempt. Two derivations of one identity are two
    /// identities the moment they disagree, and an action identity that drifted
    /// between the key a dispatch was recorded under and the key a settlement
    /// names is a settlement that never lands.
    actions: Vec<Vec<ActionId>>,
    /// The effect path: the identity, the fence and the journal, plus what
    /// recovery found in them.
    effects: Effects,
}

impl Ledger {
    /// A ledger with one idle slot per chain, no work recorded, and the
    /// declared action identities indexed as the chains are.
    fn new(actions: Vec<Vec<ActionId>>, effects: Effects, next_input: u64) -> Self {
        Self {
            transitions: (0..actions.len()).map(|_| None).collect(),
            actions,
            effects,
            next_input,
        }
    }

    /// Mint the fallback admitted-input identity.
    ///
    /// Used only when a binding cannot supply an [`InputIdentity`]. The
    /// watermark is seeded from the journal tail at assembly and only ever
    /// grows, so a restart cannot reissue a stamp an earlier process bound a
    /// dispatch to (issue #101). An identified binding supplies its content
    /// identity instead; that identity is unique per distinct value, which is
    /// not the same as unique per admitted episode (issue #129).
    fn mint_input(&mut self) -> [u8; 16] {
        let stamp = self.next_input;
        self.next_input = self.next_input.saturating_add(1);
        derive_input_stamp(stamp)
    }

    /// The action one entry runs, when the ledger has that entry.
    fn action_of(&self, id: WorkId) -> Option<ActionId> {
        self.actions.get(id.chain())?.get(id.entry()).copied()
    }

    /// Give the journal back, leaving the ledger unusable.
    ///
    /// The undo of the move `assemble` made, and the only way a record outlives
    /// the bot that wrote it.
    fn into_journal(self) -> Box<dyn EffectJournal> {
        self.effects.into_journal()
    }

    /// The generation a chain's live transition was opened at, when it has one.
    ///
    /// What a caller needs to ask whether an acknowledgement covers the work in
    /// front of it: an `Applied` verdict retires its action for one generation
    /// and no other, so the comparison is between the acknowledgement's
    /// generation and this one.
    fn generation(&self, chain: usize) -> Option<([u8; 16], bool)> {
        self.transitions
            .get(chain)
            .and_then(Option::as_ref)
            .map(|transition| (transition.input, transition.event))
    }

    /// The entry an action is declared on, when the ledger has one.
    ///
    /// The action is what a key carries and an address is what the ledger is
    /// indexed by, so this is the translation settlement runs first. It is a
    /// search rather than a map because the declaration is bounded by the spec
    /// — a handful of entries, scanned at most once per settlement and once per
    /// recovery — and a second index kept in step with `actions` is a second
    /// place for the two to disagree.
    fn locate(&self, action: ActionId) -> Option<WorkId> {
        for (chain, entries) in self.actions.iter().enumerate() {
            if let Some(entry) = entries.iter().position(|declared| *declared == action) {
                return Some(WorkId { chain, entry });
            }
        }
        None
    }

    /// Take a chain's transition out, leaving its slot empty. The walk needs it
    /// owned: the ledger is mutated while the chains, the observed values and
    /// the granted authority are borrowed from the same world.
    fn take(&mut self, chain: usize) -> Option<Transition> {
        self.transitions.get_mut(chain).and_then(Option::take)
    }

    /// Put a chain's transition back, `None` when nothing is retained.
    fn put(&mut self, chain: usize, transition: Option<Transition>) {
        if let Some(slot) = self.transitions.get_mut(chain) {
            *slot = transition;
        }
    }

    /// The entry a [`WorkId`] names, when the ledger holds it.
    fn entry_state(&self, id: WorkId) -> Option<&EntryState> {
        self.transitions
            .get(id.chain())
            .and_then(Option::as_ref)
            .and_then(|transition| transition.entries.get(id.entry()))
    }

    /// The entry a [`WorkId`] names, when the ledger holds it.
    fn entry_mut(&mut self, id: WorkId) -> Option<&mut EntryState> {
        self.transitions
            .get_mut(id.chain())
            .and_then(Option::as_mut)
            .and_then(|transition| transition.entries.get_mut(id.entry()))
    }

    /// Record that an attempt on this entry is about to be made, *before* it is
    /// awaited.
    ///
    /// This is the write-ahead half of the ledger, and it is why the driver
    /// writes to the world between awaits at all: a tick dropped while the effect
    /// is in flight leaves this record behind, and "an attempt began and no
    /// outcome was recorded" is held exactly as an unknown outcome is. Without
    /// it, a dropped tick would leave a `NotStarted` entry behind and the next
    /// tick would replay an effect that may already be live.
    ///
    /// `Err` when the entry is not in a state an attempt can start from, when
    /// the action identity is unknown, or when the journal or the broker
    /// refused — which means the world moved behind the schedule's back.
    ///
    /// The two writes happen here, in this order, and neither can be moved
    /// later. `IntentAdmitted` is the decision to act, and `DispatchPrepared` is
    /// the warrant: both are committed *before* the caller builds the future that
    /// reaches the external system. A crash anywhere after this returns leaves a
    /// journal that says "this attempt was prepared and nothing recorded what
    /// became of it", which recovery reads as an unknown rather than as a
    /// never-sent — the exact distinction a duplicate merge turns on.
    ///
    /// The warrant is handed back rather than consumed here because the handoff
    /// is the caller's: it runs after the payload the attempt acts on is in
    /// hand, and it presents the warrant at [`Broker::revalidate`] on the way in.
    async fn begin_attempt(
        &mut self,
        id: WorkId,
        lifetime: EffectLifetime,
    ) -> Result<(EffectKey, Authority), BotError> {
        let no_such_work = || BotError::NoSuchWork { work: id };
        let action = self.action_of(id).ok_or_else(no_such_work)?;
        // Refused before anything is written, and refused for the reason
        // recovery exists: an attempt on this action is recorded as dispatched
        // with no outcome, so the bytes may already be live. Beginning another
        // one is the blind resend, and the guard is here rather than at the top
        // of the walk so it cannot be bypassed by a second caller.
        if self.effects.blocks(action) {
            let refusal = Err(BotError::EffectUnsettled { action });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "begin_attempt: returning an error to the caller");
            return refusal;
        }
        let transition = self
            .transitions
            .get_mut(id.chain())
            .and_then(Option::as_mut)
            .ok_or_else(no_such_work)?;
        let state = transition
            .entries
            .get_mut(id.entry())
            .ok_or_else(no_such_work)?;
        if !matches!(
            *state,
            EntryState::NotStarted | EntryState::DefinitelyFailed { .. }
        ) {
            let refusal = Err(no_such_work());
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "begin_attempt: returning an error to the caller");
            return refusal;
        }
        let record = transition
            .attempts
            .get_mut(id.entry())
            .ok_or_else(no_such_work)?;
        // The attempt identity is minted here and nowhere else, which is what
        // makes it monotonic within the generation: `FIRST` for an entry that
        // has never been attempted, otherwise the successor of the last one. An
        // exhausted chain of successes is refused rather than wrapped, because
        // an identity that came round again would name two attempts.
        //
        // "Never been attempted" means *this run has not attempted it*, and the
        // two are not the same question after a restart. A transition is opened
        // fresh, so its record starts empty however far the journal got, and
        // minting attempt one again would name the attempt the record already
        // holds — which the journal refuses, and which is the refuse-forever
        // dead end a settled `NotApplied` would otherwise lead into. The
        // journal's own latest attempt for the action is therefore the floor,
        // and the successor of that floor is what this mints.
        let attempt = match record.begun {
            Some(previous) => previous
                .checked_next()
                .ok_or(BotError::EffectUnsettled { action })?,
            None => match self.effects.recorded_attempt(action) {
                Some(recorded) => recorded
                    .checked_next()
                    .ok_or(BotError::EffectUnsettled { action })?,
                None => AttemptId::FIRST,
            },
        };
        // Journal first, memory second. `record.begun` and `EntryState` are
        // moved only after the write-ahead pair is committed and its
        // acknowledgments are strong enough: a refusal before that point leaves
        // the entry as it was, instead of a false `Unrecorded` barrier for a
        // handoff that never left (issue #100).
        let input = transition.input;
        let key = self
            .effects
            .key(action, id.chain(), id.entry(), input, attempt)
            .ok_or(BotError::EffectUnsettled { action })?;
        let authority = self
            .effects
            .prepare(key, lifetime)
            .await
            .map_err(|cause| BotError::EffectRefused { cause })?;
        let transition = self
            .transitions
            .get_mut(id.chain())
            .and_then(Option::as_mut)
            .ok_or_else(no_such_work)?;
        let record = transition
            .attempts
            .get_mut(id.entry())
            .ok_or_else(no_such_work)?;
        record.begun = Some(attempt);
        if let Some(state) = transition.entries.get_mut(id.entry()) {
            *state = EntryState::Unrecorded;
        }
        Ok((key, authority))
    }

    /// Record that the entry's condition did not hold, so it owes nothing.
    fn skip(&mut self, id: WorkId) -> bool {
        let Some(state) = self.entry_mut(id) else {
            return false;
        };
        if !matches!(
            *state,
            EntryState::NotStarted | EntryState::DefinitelyFailed { .. }
        ) {
            return false;
        }
        *state = EntryState::Skipped;
        true
    }

    /// Record that the attempt returned without error.
    fn succeed(&mut self, id: WorkId) -> bool {
        let Some(state) = self.entry_mut(id) else {
            return false;
        };
        if !matches!(*state, EntryState::Unrecorded) {
            return false;
        }
        *state = EntryState::Succeeded;
        true
    }

    /// The key, evidence and attempt count of an entry held for an append-only
    /// retry, when there is one.
    fn recording_failed(
        &self,
        id: WorkId,
    ) -> Option<(crate::effect::EffectKey, EffectEvidence, u32)> {
        match *self.entry_state(id)? {
            EntryState::RecordingFailed {
                key,
                evidence,
                attempts,
                ..
            } => Some((key, evidence, attempts)),
            _ => None,
        }
    }

    /// Refresh a [`EntryState::RecordingFailed`] hold after another refused
    /// append, without touching the action or the attempt identity.
    fn hold_recording(&mut self, id: WorkId, evidence: EffectEvidence, error: &BotError) -> bool {
        let Some(state) = self.entry_mut(id) else {
            return false;
        };
        let EntryState::RecordingFailed {
            ref mut cause,
            evidence: ref mut held,
            ..
        } = *state
        else {
            return false;
        };
        *cause = error.to_string();
        *held = evidence;
        true
    }

    /// Close an entry whose outcome is known and whose record has now landed.
    ///
    /// `Applied` retires the entry. `NotApplied` leaves it eligible for a fresh
    /// attempt under the budget — a new attempt is a response to "the effect
    /// did not happen", not a retry of the recording failure.
    fn finish_recording(
        &mut self,
        id: WorkId,
        evidence: EffectEvidence,
        attempts: u32,
        budget: u32,
    ) -> bool {
        let Some(state) = self.entry_mut(id) else {
            return false;
        };
        if !matches!(*state, EntryState::RecordingFailed { .. }) {
            return false;
        }
        *state = match evidence {
            EffectEvidence::Applied => EntryState::Succeeded,
            EffectEvidence::NotApplied => {
                if attempts < budget {
                    EntryState::DefinitelyFailed {
                        attempts,
                        cause: "effect not applied; its record landed on retry".into(),
                    }
                } else {
                    EntryState::Abandoned {
                        reason: AbandonReason::AttemptsExhausted { attempts },
                        cause: "effect not applied; its record landed on retry".into(),
                    }
                }
            }
        };
        true
    }

    /// Record what a failed attempt means for the entry it was made on.
    ///
    /// The attempt arrives as the identity the key carries rather than as a
    /// count, because the count [`EntryState::DefinitelyFailed`] renders is a
    /// `u32` and the identity is not. The conversion is saturating rather than
    /// wrapping: an attempt ordinal past `u32::MAX` would take the maximum,
    /// which reports an entry as further along than it is, and that is the
    /// direction a retry budget can absorb.
    fn fail(&mut self, id: WorkId, error: &BotError, attempt: AttemptId, budget: u32) -> bool {
        let attempts = u32::saturating_from(attempt.get());
        let Some(state) = self.entry_mut(id) else {
            return false;
        };
        // Only an attempt in flight can fail: an outcome recorded for an entry
        // that was never begun is not this tick's to write.
        if !matches!(*state, EntryState::Unrecorded) {
            return false;
        }
        *state = failure_state(error, attempts, budget);
        true
    }

    /// Settle an attempt whose effect may or may not have happened.
    ///
    /// The caller hands over the [`EffectKey`] it read from
    /// [`PendingWork::key`], and nothing is read or written until that key's own
    /// facts match the ledger's: the run and the flow it acts under, the action
    /// that locates the entry, the binding the entry currently holds, and the
    /// attempt the entry is on.
    ///
    /// This is not a formality. A chain has one transition at a time and a slot
    /// is reused by every generation over it, so an action that matches says
    /// only that the *address* is the same. A report computed against one
    /// generation's binding and delivered after the slot was re-opened under the
    /// next would be accepted against work the caller has never seen: `Applied`
    /// would acknowledge an effect produced from an input that is gone, and
    /// `NotApplied` — worse, because it authorises a retry — would make an
    /// unknown attempt eligible to run against the new one.
    ///
    /// The binding is the digest, and it carries both halves of that check at
    /// once: it is derived from the generation's revision *and* from the entry
    /// it belongs to, so a key for one entry cannot be spent on another and a
    /// key for one generation cannot be spent on the next. Comparing it is what
    /// makes supersession a fact about the observed input rather than about a
    /// counter that a restarted process would begin again at one.
    ///
    /// The attempt closes the same hole one level down, where the binding does
    /// not help. An entry is retried *within* a generation: settling it
    /// `NotApplied` makes it eligible, and the next tick begins the next attempt
    /// over the same binding. A repeat of the earlier report — which must be
    /// tolerated, because a caller that never saw its first delivery
    /// acknowledged has to be able to send it again — is indistinguishable from
    /// a fresh one unless the attempt is named, and accepting it would reset an
    /// in-flight attempt to eligible.
    ///
    /// Returns a decision rather than a bool, because the answers lead a caller
    /// to different next actions and several of them are not errors.
    /// Validate an evidence report without changing any state.
    ///
    /// The whole of [`settle`](Self::settle)'s decision, minus the mutation.
    /// `resolve_effect` runs this first so the settlement fact can be journaled
    /// before the entry is allowed to move: a live settle that only touched
    /// memory is resurrected by recovery as an unknown (issue #106).
    fn classify_settlement(
        &self,
        key: &EffectKey,
        evidence: EffectEvidence,
    ) -> Result<Settled, JournalError> {
        let Some(id) = self.locate(key.action()) else {
            return Ok(Settled::NoSuchWork { id: None });
        };
        // The run and the flow are the identity this ledger speaks for. A key
        // from another run is not this ledger's to settle, and answering it with
        // any of the finer refusals would suggest the evidence nearly applied.
        let identity = self.effects.identity();
        if key.run() != identity.run()
            || key.flow() != identity.flow()
            || key.environment() != identity.environment()
        {
            return Ok(Settled::NoSuchWork { id: None });
        }
        let Some(transition) = self.transitions.get(id.chain()).and_then(Option::as_ref) else {
            return self.durable_or_missing(key, id, evidence);
        };
        // The binding first, before the attempt is even looked up: a key that
        // names the right action inside a generation that is gone is exactly the
        // case this exists to refuse.
        let live = derive_action_digest(identity.flow(), id.chain(), id.entry(), &transition.input);
        if key.digest() != live {
            return Ok(Settled::Superseded { id, current: live });
        }
        let Some(record) = transition.attempts.get(id.entry()).copied() else {
            return self.durable_or_missing(key, id, evidence);
        };
        // The durable record is authoritative about *what the outcome is*. A
        // mismatch is a contradiction whatever the live slot says. A match is
        // deliberately not answered here: a live settleable slot still has to
        // be moved — an abandoned entry reopened by confirmation that its
        // effect did not land is exactly that — and answering `Duplicate`
        // before the move is how the reopen stops happening (issue #106).
        if let Some(recorded) = self.effects.outcome_for(key)?
            && recorded != evidence
        {
            return Ok(Settled::Contradicted {
                id,
                settled: recorded,
            });
        }
        let settleable = matches!(
            transition.entries.get(id.entry()),
            Some(
                EntryState::Unrecorded
                    | EntryState::OutcomeUnknown { .. }
                    | EntryState::Abandoned { .. }
            )
        );
        if !settleable {
            // Decided: an entry that ran, one whose condition was false, one
            // that has not been attempted yet, and one with a live budget all
            // have an answer, and evidence supplied after the fact cannot
            // contradict an attempt whose outcome was recorded.
            //
            // But an answer this *generation* was already given is not a
            // contradiction, it is the same answer twice, and a caller whose
            // first delivery it never saw an outcome for has to be able to
            // repeat it. Only the record distinguishes that from a fresh claim
            // about an entry that was never settled.
            // The record answers for the attempt it was made about and no
            // other. An entry can be decided while the record is about an
            // earlier attempt — an entry settled and then failed again is on
            // its second attempt with the first one's record still beside it —
            // and reading that record as an answer about *this* attempt is how
            // a report about attempt 2 comes back as a duplicate of attempt 1.
            return match record.settled {
                Some(previous)
                    if previous.attempt == key.attempt() && previous.evidence == evidence =>
                {
                    Ok(Settled::Duplicate)
                }
                Some(previous) if previous.attempt == key.attempt() => Ok(Settled::Contradicted {
                    id,
                    settled: previous.evidence,
                }),
                Some(_) | None => self.durable_or_missing(key, id, evidence),
            };
        }
        // Then the attempt, and this is the half that the slot and the
        // generation together do not cover. Within one generation an entry is
        // retried: settling it `NotApplied` makes it eligible and `begin` moves
        // it to the next attempt at the same address under the same revision. A
        // repeat of the earlier report — which has to be tolerated, because a
        // caller that never saw its first delivery acknowledged must be able to
        // send it again — would otherwise read as a statement about the attempt
        // now outstanding, and `NotApplied` would make an attempt whose effect
        // may be live eligible to run a third time.
        //
        // Placed after the decided case rather than before it, because a
        // decided entry is where the repeat is *supposed* to land: it is only
        // the live entry whose attempt has to match.
        // An entry with nothing begun cannot be settleable, so the `None` arm
        // is unreachable; it is answered with the same refusal as an entry the
        // ledger does not hold rather than being asserted away.
        let Some(outstanding) = record.begun else {
            return Ok(Settled::NoSuchWork { id: Some(id) });
        };
        if key.attempt() != outstanding {
            return Ok(Settled::StaleAttempt {
                id,
                reported: key.attempt(),
                outstanding,
            });
        }
        Ok(Settled::Decided)
    }

    /// The journal's answer when the live slot has none left to move.
    ///
    /// A reconstructed bot has no in-memory record to consult, and a caller
    /// repeating an acknowledgement it never saw land has no live attempt
    /// either. The durable fact is then the only answer (issue #106 scenario
    /// 3): the same evidence twice is [`Settled::Duplicate`], the other
    /// evidence is [`Settled::Contradicted`], and only a key the journal never
    /// recorded is [`Settled::NoSuchWork`]. Answering `NoSuchWork` for a
    /// settlement the journal already holds is how the same evidence stops
    /// being a safe retry across a restart.
    ///
    /// A journal that cannot be read answers neither: the error is propagated
    /// so an unreadable record is never recast as "the work never existed"
    /// (issue #123).
    fn durable_or_missing(
        &self,
        key: &EffectKey,
        id: WorkId,
        evidence: EffectEvidence,
    ) -> Result<Settled, JournalError> {
        Ok(match self.effects.outcome_for(key)? {
            Some(recorded) if recorded == evidence => Settled::Duplicate,
            Some(recorded) => Settled::Contradicted {
                id,
                settled: recorded,
            },
            None => Settled::NoSuchWork { id: Some(id) },
        })
    }

    /// Apply a settlement [`classify_settlement`](Self::classify_settlement)
    /// answered [`Decided`](Settled::Decided) for.
    ///
    /// Called only after the settlement fact is committed, so the entry never
    /// moves on evidence the journal does not hold.
    fn apply_settlement(&mut self, key: &EffectKey, evidence: EffectEvidence) {
        let Some(id) = self.locate(key.action()) else {
            return;
        };
        let Some(transition) = self
            .transitions
            .get_mut(id.chain())
            .and_then(Option::as_mut)
        else {
            return;
        };
        let Some(record) = transition.attempts.get(id.entry()).copied() else {
            return;
        };
        let Some(outstanding) = record.begun else {
            return;
        };
        let next = match evidence {
            EffectEvidence::Applied => EntryState::Succeeded,
            EffectEvidence::NotApplied => EntryState::NotStarted,
        };
        if let Some(state) = transition.entries.get_mut(id.entry()) {
            *state = next;
        }
        if let Some(slot) = transition.attempts.get_mut(id.entry()) {
            // Recorded against the attempt the evidence was *about*, never
            // against whichever is current: this record is what decides
            // whether a later report is a repeat, and a record that drifted
            // onto the next attempt would make two different attempts look
            // like one.
            slot.settled = Some(SettledAttempt {
                attempt: outstanding,
                evidence,
            });
        }
    }

    /// The payload the chain's live transition is bound to, if it has one.
    ///
    /// The binding is on loan from the observation slot, which is empty while
    /// the transition holds it, so this is the only way to read back what the
    /// chain last acted on. Two callers need that and they need it for the same
    /// reason: the change filter, which cannot compare a new poll against a
    /// slot that has nothing in it, and the executor, which must run an entry
    /// against the value its transition was opened under rather than against
    /// whatever has arrived since.
    fn bound(&self, chain: usize) -> Option<&Erased> {
        self.transitions
            .get(chain)
            .and_then(Option::as_ref)
            .and_then(|transition| transition.value.as_ref())
    }

    /// The key for the attempt an entry is currently on, when it has one.
    ///
    /// `None` for an entry never attempted, and for a chain or entry the ledger
    /// does not hold. Both are the same answer to the caller — there is no
    /// attempt identity to hand out — and one absence rather than two keeps the
    /// settlement sites from having to tell them apart.
    fn key_of(&self, chain: usize, entry: usize, transition: &Transition) -> Option<EffectKey> {
        let id = WorkId { chain, entry };
        self.effects.key(
            self.action_of(id)?,
            chain,
            entry,
            transition.input,
            transition.attempt_of(entry)?,
        )
    }

    /// Every entry that is still unresolved, in `(chain, entry)` order.
    ///
    /// One fold, and every report that used to disagree is rendered from it:
    /// [`Self::first_unresolved`] is the first item, [`Self::pending`] is the
    /// whole list, and [`Self::unresolved_count`] is its length.
    ///
    /// "Unresolved" is open *or* abandoned, and the second half is load-bearing.
    /// An abandoned entry asks nothing of the substrate — it will not be
    /// attempted again and no evidence is owed by the tick — so a scan that
    /// looked only for open entries walked straight past it and reported a clean
    /// tick. But abandoned work is not handled work: [`Self::pending`] names it,
    /// and a caller that read `Ok` as "the chain is done" was reading the
    /// opposite of what the ledger held. It is also a prerequisite that is *not*
    /// satisfied, so the entries behind it are unresolved through it.
    ///
    /// A recovered attempt nothing has settled is reported for its declared
    /// work whether or not a transition exists: the barrier is durable and does
    /// not wait for a poll, so a bot assembled against a journal that already
    /// says the bytes may be live is stuck before its first observation (issue
    /// #104). It is reported *instead of* the entry's own hold, because two
    /// reports for one entry would read as two problems — and it is why the
    /// three reports now agree: a skipped unknown used to produce `Ok` from
    /// `tick` while `pending` still named it.
    fn unresolved(&self, budget: u32) -> Vec<PendingWork> {
        let mut unresolved = Vec::new();
        for chain in 0..self.actions.len().max(self.transitions.len()) {
            // The declared actions and the live transition can disagree in
            // width: a world mutated behind the builder's back is a real
            // state, and a scan that trusted only one of the two walked past
            // work the other one holds.
            let declared = self.actions.get(chain).map_or(0, Vec::len);
            let held = self
                .transitions
                .get(chain)
                .and_then(Option::as_ref)
                .map_or(0, |transition| transition.entries.len());
            for entry in 0..declared.max(held) {
                let id = WorkId { chain, entry };
                if let Some(key) = self
                    .action_of(id)
                    .and_then(|action| self.effects.unsettled_for(action))
                {
                    let action = key.action();
                    unresolved.push(PendingWork {
                        id,
                        key: Some(Box::new(key)),
                        hold: TransitionHold::UnsettledByRecovery { action },
                    });
                    continue;
                }
                if let Some(recording) = self
                    .action_of(id)
                    .and_then(|action| self.effects.recording_for(action))
                {
                    unresolved.push(PendingWork {
                        id,
                        key: Some(Box::new(recording.key)),
                        hold: TransitionHold::RecordingFailed {
                            evidence: recording.evidence,
                            cause: recording.cause.to_string(),
                        },
                    });
                    continue;
                }
                let Some(transition) = self.transitions.get(chain).and_then(Option::as_ref) else {
                    continue;
                };
                let Some(state) = transition.entries.get(entry) else {
                    continue;
                };
                if !(state.is_open() || state.is_abandoned()) {
                    continue;
                }
                // Unreachable in practice: an open or abandoned state always
                // renders a hold.
                let Some(hold) = state.hold(budget) else {
                    continue;
                };
                unresolved.push(PendingWork {
                    id,
                    key: self.key_of(chain, entry, transition).map(Box::new),
                    hold,
                });
            }
        }
        unresolved
    }

    /// The first entry that is unresolved, in `(chain, entry)` order: the
    /// abandonment in front of its successors, the recovered unknown in front
    /// of a fresh attempt, the open entry itself otherwise. Taking the first
    /// in declaration order is deliberate: the barrier is the entry that
    /// explains every successor blocked behind it, so naming it is naming the
    /// reason.
    fn first_unresolved(&self, budget: u32) -> Option<PendingWork> {
        self.unresolved(budget).into_iter().next()
    }

    /// Every entry that is not finished, in `(chain, entry)` order: open,
    /// given up on and still reported, or held by a recovered unknown.
    fn pending(&self, budget: u32) -> Vec<PendingWork> {
        self.unresolved(budget)
    }

    /// How many entries are still unresolved, across every chain.
    ///
    /// Counted the same way [`Self::first_unresolved`] scans, because the two
    /// are rendered together in [`BotError::PendingTransition`]: a count that
    /// omitted abandoned entries would report a non-zero entry alongside an
    /// "0 outstanding", which reads as the one thing the pair is there to rule
    /// out — a chain that is somehow both stuck and finished. A recovered
    /// unknown is counted for the same reason: it is what is holding the work.
    fn unresolved_count(&self, budget: u32) -> usize {
        self.unresolved(budget).len()
    }
}

/// The revision the chain's source last moved to, or zero if it never has.
fn revision_of(world: &World, chain: usize) -> u64 {
    world
        .resource::<Order>()
        .0
        .get(chain)
        .and_then(|entity| world.get::<Revision>(*entity))
        .map_or(0, |revision| revision.0)
}

/// Move the newest observation for `chain` out of its slot.
///
/// Moved, not copied. A source's `Output` carries no `Clone` bound and this is
/// the reason it does not need one: the value is not wanted in two places at
/// once. Once a transition is bound to it, the transition is what speaks for
/// it, and the slot being empty is not a loss — it is the record that the value
/// is out on loan, which [`observe_fold`] reads back through the binding.
///
/// The take is also what admits the value: a generation is being opened over
/// exactly this payload, so a later commit that overtakes it is superseding work
/// that is already owed and being done, not work that is still unclaimed. Marking
/// it here rather than on the handover is what makes a value that a *held*
/// generation is holding count as acted-on — the handover happens only once the
/// transition is finally dropped, which for an entry awaiting evidence is never
/// on the tick the pass-over occurs.
fn take_observed(world: &mut World, chain: usize) -> Option<Erased> {
    let taken = world
        .non_send_mut::<Observed>()
        .0
        .get_mut(chain)
        .and_then(Option::take);
    if taken.is_some() {
        world.non_send_mut::<Committed>().admit(chain);
    }
    taken
}

/// Whether the newest observation for `chain` should be admitted over the
/// payload a retained transition is bound to.
///
/// The comparison is the chain's own, the same one the change filter uses, so
/// "moved" means one thing in this substrate rather than two. It stands in for
/// a `Changed<Revision>` test rather than supplementing one: a movement that
/// arrives while the transition is open does bump the revision, but the change
/// filter is consumed on the tick it is seen, so by the time the transition
/// drains there is nothing left to consult — the observation itself is the only
/// surviving record that the source moved at all.
fn admits(world: &World, chain: usize, bound: Option<&Erased>) -> bool {
    let seen = world.non_send::<Observed>();
    let Some(next) = seen.0.get(chain).and_then(|slot| slot.as_ref()) else {
        // Nothing to admit. An empty slot beside a transition that has nothing
        // open is not a movement, and reading it as one would reopen the chain
        // on every tick and run its entries forever.
        return false;
    };
    let Some(bound) = bound else {
        // Bound to nothing, and now there is something: that is a movement.
        return true;
    };
    let chains = world.non_send::<Chains>();
    chains
        .0
        .get(chain)
        .is_some_and(|chain| !(chain.same)(bound.as_any(), next.as_any()))
}

/// What the decision pass decided for one chain, before it walks any of them.
///
/// The value is computed in one batched pass over every chain — see
/// [`plan_admissions`] — so the walk that follows reads a decision rather than
/// making one. That is what lets the two halves of change detection be measured
/// apart (which chains moved, and which admitted inputs are new) and it is also
/// what keeps the admitted-input stamps in declaration order: the pass walks
/// chains by index, exactly as the walk this replaces did.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AdmitKind {
    /// Keep the live transition exactly as it stands. No observation is taken
    /// and no input is minted: the entries still running were acknowledged
    /// against the payload the transition holds.
    Keep,
    /// Resume into a new revision over the newest observation, bound to
    /// [`AdmittedInput`].
    Resume,
    /// Open a fresh transition over the newest observation, bound to
    /// [`AdmittedInput`]. Only reachable for a chain that has no live
    /// transition.
    Open,
    /// Nothing to walk: no transition is held and the source did not move.
    Idle,
}

/// A chain's batched decision: its [`AdmitKind`] and the input it binds to.
#[derive(Clone, Copy)]
enum Admit {
    /// Keep the live transition, or have nothing to walk.
    Keep,
    /// Resume or open, bound to this admitted input.
    Bind(AdmittedInput),
}

impl Admit {
    /// Compose a chain's decision from the two passes that produced it.
    ///
    /// A kind that needs an input the fingerprint pass did not derive reads as
    /// [`Self::Keep`] rather than as a fabricated one: a transition bound to an
    /// input nobody derived would mint dispatch identities that cannot be
    /// recovered against, and keeping the previous transition is the safe answer
    /// because the next tick re-plans from the same observations.
    fn bind(kind: AdmitKind, input: Option<AdmittedInput>) -> Self {
        match (kind, input) {
            (AdmitKind::Resume | AdmitKind::Open, Some(input)) => Self::Bind(input),
            _ => Self::Keep,
        }
    }
}

/// Decide every chain's [`AdmitKind`] in one pass, in declaration order.
///
/// Two questions per chain, and the answers are cached rather than recomputed
/// inside the walk: whether the `Changed<Revision>` query reported the chain as
/// moved, and whether the newest observation is admitted over the payload a
/// retained transition holds. The second is the value comparison, and it is the
/// expensive one — computing it here and reading it there is what keeps the walk
/// from paying for it twice.
///
/// The `has_open` test is read here and again by the walk, and it is a scan of
/// one transition's entry states rather than a comparison of values, so the
/// repeat costs less than the caching saves.
fn plan_admissions(world: &World, moving: &[bool], kinds: &mut [AdmitKind]) {
    for (chain, kind) in kinds.iter_mut().enumerate() {
        let ledger = world.non_send::<Ledger>();
        let held = ledger.transitions.get(chain).and_then(Option::as_ref);
        *kind = match held {
            Some(transition) if transition.has_open() => AdmitKind::Keep,
            Some(transition) => {
                if admits(world, chain, transition.value.as_ref()) {
                    AdmitKind::Resume
                } else {
                    AdmitKind::Keep
                }
            }
            // A transition is opened **over an observation** or not at all. The
            // change filter alone is not enough to open one: a component is
            // "changed" from the moment it is spawned, so a freshly assembled bot
            // reports every chain as moved with no committed observation behind
            // it, and a transition bound to nothing is never walked — its entries
            // stay `NotStarted` and the tick reports all of them pending.
            //
            // The change-tick skip is what makes this reachable rather than
            // theoretical: a quiet source commits nothing, so its slot stays empty
            // however many ticks the filter keeps calling it moved.
            None if moving.get(chain).copied().is_some_and(|held| held)
                && world
                    .non_send::<Observed>()
                    .0
                    .get(chain)
                    .is_some_and(|slot| slot.is_some()) =>
            {
                AdmitKind::Open
            }
            None => AdmitKind::Idle,
        };
    }
}

/// Derive the admitted-input identity for every chain whose kind binds one.
///
/// One batch, in two halves. The first half holds the world shared and reads the
/// value each identity is derived from; the second holds it exclusively and mints
/// the content-free fallback stamp for the chains whose binding cannot supply
/// one. The split is why the stamps are still consumed in declaration order: the
/// fallback is what a dispatch digest binds when nothing else can be, and two
/// derivations of one identity are two identities the moment they disagree.
fn plan_inputs(world: &mut World, kinds: &[AdmitKind], inputs: &mut [Option<AdmittedInput>]) {
    let binds = |kind: &AdmitKind| matches!(kind, AdmitKind::Resume | AdmitKind::Open);
    {
        let chains = world.non_send::<Chains>();
        let observed = world.non_send::<Observed>();
        for (chain, kind) in kinds.iter().enumerate() {
            if !binds(kind) {
                continue;
            }
            let (Some(held), Some(value)) = (
                chains.0.get(chain),
                observed.0.get(chain).and_then(|slot| slot.as_ref()),
            ) else {
                continue;
            };
            if let Some(slot) = inputs.get_mut(chain) {
                *slot = Some((held.identify)(value.as_any()));
            }
        }
    }
    let mut ledger = world.non_send_mut::<Ledger>();
    for (chain, kind) in kinds.iter().enumerate() {
        if !binds(kind) {
            continue;
        }
        if inputs.get(chain).is_some_and(Option::is_none) {
            // A fallback stamp is content-free, so it can never name an event.
            let minted = AdmittedInput {
                identity: ledger.mint_input(),
                event: false,
            };
            if let Some(slot) = inputs.get_mut(chain) {
                *slot = Some(minted);
            }
        }
    }
}

/// The transition a chain should be walking this tick, if any.
///
/// The decision is [`Admit`]'s, computed for every chain in one batched pass
/// rather than made here per chain: that is what makes the change detection and
/// the identity derivation two separately measurable stages, and it keeps the
/// admitted-input stamps in declaration order.
///
/// Opening and resuming are where the payload is bound, and both *take* it out
/// of the observation slot. That is the mechanism that keeps a transition on
/// one input: the entries it evaluates and runs read the binding, so a value
/// that arrives mid-transition cannot reach them, however many ticks the
/// transition takes to drain. The admission itself is then deferred rather than
/// dropped — the newer observation is still sitting in the slot, and the tick
/// after the transition stops being retained is the tick it becomes work.
fn resume(
    world: &mut World,
    chain: usize,
    admit: Admit,
    held: Option<Transition>,
) -> Option<Transition> {
    match (admit, held) {
        // Outstanding work keeps the payload it was opened under. A newer
        // observation is not admitted here, and deliberately: the entries
        // still running were acknowledged against this one.
        (Admit::Keep, Some(transition)) => Some(transition),
        (Admit::Keep, None) => None,
        (Admit::Bind(input), Some(transition)) => {
            let value = take_observed(world, chain);
            Some(Transition::resumed(
                input,
                revision_of(world, chain),
                &transition,
                value,
            ))
        }
        (Admit::Bind(input), None) => {
            let entries = world
                .non_send::<Chains>()
                .0
                .get(chain)
                .map_or(0, |chain| chain.entries.len());
            let value = take_observed(world, chain);
            Some(Transition::opened(
                input,
                revision_of(world, chain),
                entries,
                value,
            ))
        }
    }
}

/// What a failed attempt means for the entry it was made on.
///
/// The three cases are the three things a caller has to be able to tell apart
/// afterwards: a retry is a retry, a retry may be a duplicate, and a retry is
/// pointless because the failure is not something another attempt can change. The
/// budget is consulted only for the first of them.
///
/// The classification is [`BotError::retry_class`] and nothing else. The error's
/// *variant* is not the question: `DomainError` is where a permanent refusal, a
/// connection that never opened, and a wiring defect all used to land, and they
/// want three different answers. Reading the rendered `cause` to tell them apart
/// is worse still — it makes a retry policy depend on the wording of a message.
/// The producer states what the failure establishes about the effect, the
/// certainty carries it here, and this function is a total map over that.
fn failure_state(error: &BotError, attempts: u32, budget: u32) -> EntryState {
    // A post-effect recording failure is not a dispatch failure and is not
    // abandoned: the occurrence is already known, and the only work left is the
    // append. Mapped here rather than through `RetryClass` so `Never` keeps its
    // meaning of "this failure will not change on a retry of the *action*".
    if let BotError::EffectUnrecorded {
        ref key,
        ref evidence,
        ref cause,
    } = *error
    {
        return EntryState::RecordingFailed {
            key: **key,
            evidence: *evidence,
            cause: cause.to_string(),
            attempts,
        };
    }
    let cause = error.to_string();
    match error.retry_class() {
        // The effect definitely did not happen: a retry is a retry, and the
        // budget bounds it.
        RetryClass::Safe if attempts < budget => EntryState::DefinitelyFailed { attempts, cause },
        RetryClass::Safe => EntryState::Abandoned {
            reason: AbandonReason::AttemptsExhausted { attempts },
            cause,
        },
        // It may have happened. Never attempted again without evidence, whatever
        // the budget says.
        RetryClass::RequiresEvidence => EntryState::OutcomeUnknown { attempts, cause },
        // No retry fixes a refused capability, a parse refusal, or a type
        // mismatch — and the budget is untouched, so the disposition reports
        // what actually happened rather than "we ran out of attempts".
        RetryClass::Never => EntryState::Abandoned {
            reason: AbandonReason::Terminal,
            cause,
        },
    }
}

// ── Systems ────────────────────────────────────────────────────────────────

/// Observe, fold half: commit the polled values, then bump `Revision` for the
/// sources that moved.
///
/// Exclusive because the verbs are non-`Send`. Every source has already been
/// polled and awaited by the driver by the time this runs, so all that is left
/// is the commit — and a poll that failed is reported *before* any `Revision`
/// is written, which is `Bot::tick`'s documented error ordering: the first
/// error in declaration order, with no source left half-updated.
///
/// That the polls themselves happen outside is what makes a timer- or
/// socket-backed source work: this system is a synchronous step, and a source
/// awaiting a reactor inside it would have no reactor making progress.
fn observe_fold(world: &mut World) {
    if parked(world) {
        return;
    }

    let mut polled = std::mem::take(&mut world.non_send_mut::<Polled>().0);

    // Two passes over the results, and neither allocates. The first inspects
    // every result and commits nothing, which is what makes a failed tick leave
    // the world exactly as it was; the second applies the movements the first
    // cleared.
    //
    // The passes are separate for the same reason `collect::<Result<Vec<_>,_>>`
    // was here before: the first error in declaration order is the one `tick`
    // reports, and finding it may not have written a `Revision` or replaced an
    // observation on the way. Building the values into a fresh `Vec` to do that
    // — which is what the collect did — is an allocation per tick bought for
    // nothing, since the values already sit in a buffer that outlives the call.

    // Pass one: the first error, in declaration order. The failing slot is
    // replaced with a benign `Ok(None)` and the error moved out, because
    // `BotError` is the caller's evidence and is deliberately not `Clone` —
    // copying it to report it would let a caller settle an effect against a
    // duplicate of the failure rather than the failure itself.
    //
    // A cancelled poll is **not** one of those errors, and that is the whole
    // difference between the two rows it could otherwise be confused for. A
    // source that refused reported a fact about itself, so the tick that heard
    // it has nothing to commit and reports the failure. A source that stopped
    // answering told the substrate nothing at all, so the chains *beside* it
    // still have real observations to commit — the same rule that already lets
    // one chain's failing action leave the effects before it live. Treating the
    // cancellation as a failure here would mean one wedged source stopped every
    // chain on the bot from committing for as long as it stayed wedged, which is
    // precisely the starvation this deadline exists to prevent.
    let mut first_error = None;
    let mut first_stall = None;
    for (index, result) in polled.iter_mut().enumerate() {
        let stalled = matches!(result, Err(BotError::PollStalled { .. }));
        if stalled {
            first_stall.get_or_insert(index);
            *result = Ok(None);
        } else if result.is_err() && first_error.is_none() {
            first_error = std::mem::replace(result, Ok(None)).err();
        }
    }
    // One stall is reported and the rest are already named in the tick report, so
    // the tick's own `Result` carries a single typed cancellation the way it
    // carries a single first domain failure. The report is the complete list; this
    // is the one a caller matching on the variant can act on.
    match (first_stall, first_error) {
        // A cancellation is reported and the commit *proceeds*: the chains beside
        // the wedged one have real observations, and withholding them is the
        // starvation this deadline exists to prevent.
        (Some(chain), _) => {
            world.resource_mut::<TickError>().0 = Some(BotError::PollStalled {
                chain,
                deadline: world.resource::<PollBudget>().0,
            });
        }
        // A domain failure stops the commit, as it always did: the tick's contract
        // is that a tick which could not act on what a chain said commits nothing.
        (None, Some(error)) => {
            world.resource_mut::<TickError>().0 = Some(error);
            put_polled(world, polled);
            return;
        }
        (None, None) => {}
    }

    // The rendezvous. The results arrived in chain order because `poll_sources`
    // appended them that way, and the pairing from here on is by index — a
    // vector position, which carries no type. The witness is what proves the
    // two halves still agree, and it is checked *before* anything is committed
    // or compared, so a mis-pairing cannot reach a downcast.
    //
    // A miss is a defect in this crate — a chain whose index no longer names the
    // source it was built with — not a domain failure and not something a retry
    // can change. It is reported as `TypeMismatch`, which is classified terminal,
    // so it does not spend a budget; and it commits nothing, so the world is left
    // exactly as the previous tick left it.
    //
    // Only a value that moved is inspected. A source that answered "equal"
    // allocated nothing and has no witness to offer — and needs none: to answer
    // that, it had to downcast the baseline to its own output type, which is a
    // stricter proof of the pairing than comparing two names.
    {
        let chains = world.non_send::<Chains>();
        let mismatch = polled.iter().enumerate().find_map(|(index, result)| {
            let next = result.as_ref().ok()?.as_ref()?;
            let chain = chains.0.get(index)?;
            (!chain.witness.agrees_with(next.witness)).then_some(BotError::TypeMismatch {
                site: "observe_fold rendezvous",
                chain: Some(index),
                expected: chain.witness.name(),
                observed: next.witness.name(),
            })
        });
        if let Some(error) = mismatch {
            world.resource_mut::<TickError>().0 = Some(error);
            put_polled(world, polled);
            return;
        }
    }

    // Pass two: commit. A slot that takes a value has moved; a slot left empty
    // has not, and the value the substrate already held for that chain stays
    // exactly where it is.
    //
    // Holding the older value is not a compromise, it is the rule the substrate
    // already follows one step later: `admits` refuses to let a newer
    // observation displace the payload a retained transition is bound to when
    // the two compare equal, and `resume` keeps that binding. A chain whose
    // values compare equal is a chain whose payload has not changed, and the
    // observation the entries were selected against is the one they still run
    // against.
    //
    // The consequence to know about: `PartialEq` that is narrower than identity
    // — a type that compares only a status field and ignores a timestamp — will
    // now hold the *earlier* of two equal values rather than the later one. That
    // is the same value the action was already going to receive through the
    // binding, so nothing an effect observes changes; but a caller reading the
    // observation back after an equal-valued tick gets the older instance. A
    // type whose equality is not its identity should not be a chain's output
    // type, and this is the point where that shows up.
    let mut changed = std::mem::take(&mut world.non_send_mut::<Moved>().0);
    changed.clear();
    changed.resize(polled.len(), false);
    let mut superseded: Vec<SupersededObservation> = Vec::new();
    // The change tick commits **here and only here**: beside the arm that put a
    // new value in the slot. A tick that parked, stopped on a failure, or left a
    // result equal to the value it already held reaches none of it, so the
    // revision stays where it was and the next tick asks again — the
    // fingerprint-commit rule (#99 / INV-BOT-5) applied to a change tick rather
    // than to a digest.
    let revisions = std::mem::take(&mut world.non_send_mut::<ChangeTicks>().polled);
    {
        let mut observed = world.non_send_mut::<Observed>();
        for (index, result) in polled.iter_mut().enumerate() {
            let moved = result
                .as_mut()
                .ok()
                .and_then(Option::take)
                .is_some_and(|value| {
                    if let Some(slot) = observed.0.get_mut(index) {
                        *slot = Some(value);
                        return true;
                    }
                    false
                });
            if let Some(flag) = changed.get_mut(index) {
                *flag = moved;
            }
        }
    }
    // A second pass, with the observation slot released, so the commit reads the
    // same `changed` the revision walk below reads. One flag is one chain: a
    // chain that took a value commits the revision that value was read at, and
    // every other chain's revision stays exactly where it was.
    for index in 0..changed.len() {
        if changed.get(index).copied().is_some_and(|held| held) {
            let reported = revisions.get(index).copied().flatten();
            world.non_send_mut::<ChangeTicks>().commit(index, reported);
        }
    }
    world.non_send_mut::<ChangeTicks>().polled = revisions;
    put_polled(world, polled);

    // Walked by index rather than over a cloned `Order`: the entity is one
    // `copy` away and the clone was a heap allocation per tick to avoid it.
    for (index, moved) in changed.iter().copied().enumerate() {
        if !moved {
            continue;
        }
        let Some(entity) = world.resource::<Order>().0.get(index).copied() else {
            continue;
        };
        if let Some(mut revision) = world.get_mut::<Revision>(entity) {
            revision.0 = revision.0.wrapping_add(1);
        }
    }

    // The revision the *replaced* value was committed under, read before the
    // bump above. A value superseded by this tick carries the revision it was
    // committed at, which is what a caller needs to line the pass-over up with
    // the generation that did or did not run on it.
    //
    // Only `Unacted` is a pass-over. `Nothing` is a first observation, which
    // replaced nothing; `Admitted` is a value a generation already ran on, which
    // also replaced nothing that was still owed. Reading either of those as a
    // pass-over would make a healthy bot claim it had skipped a state.
    for index in changed
        .iter()
        .copied()
        .enumerate()
        .filter_map(|(index, moved)| moved.then_some(index))
    {
        if let Some(previous) = world.non_send::<Committed>().slot(index)
            && previous.state == SlotState::Unacted
        {
            superseded.push(SupersededObservation {
                chain: index,
                revision: previous.revision,
            });
        }
        let revision = revision_of(world, index);
        world.non_send_mut::<Committed>().commit(index, revision);
        // The mark is spent by the read it forced, and only by it. This is the
        // point at which a forced poll has provably committed a value, so the
        // baseline this tick holds is one the source produced rather than one the
        // source disowned. A tick that never reaches here — parked, or stopped on
        // a rendezvous miss — leaves the mark standing, which is the correct
        // outcome for a refresh that did not land.
        if let Some(slot) = world.non_send_mut::<Invalidated>().reasons.get_mut(index) {
            *slot = None;
        }
    }
    world.resource_mut::<TickReport>().superseded = superseded;
    world.non_send_mut::<Moved>().0 = changed;
}

/// Put the staging buffer back, capacity and all.
///
/// The counterpart to the `mem::take` at the top of [`observe_fold`]. Handing
/// the same allocation back is the point: a staging area rebuilt per tick is an
/// allocation per tick, and the observation phase is the one phase guaranteed to
/// run on every tick of every bot.
fn put_polled(world: &mut World, polled: Vec<Result<Option<Erased>, BotError>>) {
    world.non_send_mut::<Polled>().0 = polled;
}

/// Fire, decide half: walk the eligible work of every chain, in declaration
/// order, and record the effects this tick should run.
///
/// The capability check is not repeated when the effect runs: `run_any` mints a
/// fresh `Auth` from the retained `GrantSet`, which is where the proof belongs.
///
/// The load-bearing word is *retained*. `assemble` clones the set into the world
/// as `Grants(grants.clone())` and nothing revokes it, so this substrate offers
/// exactly the snapshot boundary `Bot` documents and not a live lease: changing
/// or dropping the caller's `GrantSet` after build cannot narrow a bot that is
/// already running. An earlier version of this comment claimed the opposite.
///
/// Conditions are evaluated here, in the schedule, and the effects they select
/// are run by the driver afterwards. That is a reordering of *when* each verb
/// runs, not of which effects happen or in what order: a condition takes only
/// the observed value (`Evaluate::check` has no other input) and so cannot
/// observe an action's effect, which makes the selected list a pure function of
/// the observations. The plan is therefore the exact effect program the
/// synchronous loop would have walked.
///
/// What is walked is the *ledger*, not the change set. `Changed<Revision>`
/// decides only which chains *open* a transition; a chain whose ledger entry is
/// outstanding is walked whether or not it moved, which is what keeps an
/// unattempted effect from being lost when its source holds still. A failure
/// stops its own chain rather than every chain after it, so the chains behind a
/// failing one still record their work.
fn fire_plan(world: &mut World) {
    // The plan's buffers are moved out and put back rather than refilled. This
    // used to clear the plan and then assign it a freshly collected `Vec` for
    // each field — so the `clear` bought nothing and every tick paid two heap
    // allocations per chain to rebuild buffers it was about to overwrite. The
    // buffers are scratch: allocated once, cleared (which keeps capacity), and
    // reused until the chain count actually changes.
    let (mut steps, mut failures) = take_plan_buffers(world);
    steps.clear();
    failures.clear();

    if parked(world) {
        put_plan_buffers(world, steps, failures);
        return;
    }

    let count = world.non_send::<Chains>().0.len();

    // A flag per chain rather than a search of the moved set: the walk below is
    // in declaration order, and membership has to be answerable in constant time
    // for that order to be the one that decides what runs.
    //
    // Taken out of the world because the query below borrows the world
    // immutably; `clear` + `resize` keeps the allocation, where the
    // `vec![false; count]` this replaces made a new zeroed one every tick. The
    // intermediate `Vec<usize>` of moved chains is gone with it: filling the
    // flags directly from the query is one pass instead of two and allocates
    // nothing.
    //
    // The admission plan rides in the same resource, because it is the same
    // per-tick scratch for the same phase and a second resource for it would be
    // a second place for the two halves of change detection to be resized
    // independently.
    let mut scratch = AdmitScratch::take(world, count);
    let AdmitScratch {
        ref mut moving,
        ref mut kinds,
        ref mut inputs,
    } = scratch;

    // Which chains moved, and whether each newest observation is admitted over
    // the payload a retained transition holds. Both are change detection outside
    // the poll, and both are answered here for every chain at once so the walk
    // below reads a decision rather than making one.
    #[cfg(feature = "profile")]
    let compare_charge = Charge::new(TickStage::Compare);
    {
        let mut query = world.query_filtered::<&SourceId, Changed<Revision>>();
        for id in query.iter(world) {
            if let Some(flag) = moving.get_mut(id.chain) {
                *flag = true;
            }
        }
    }
    plan_admissions(world, moving, kinds);
    #[cfg(feature = "profile")]
    drop(compare_charge);

    // The admitted-input identity of every value a chain will bind, derived in
    // one batch so the stamps stay in declaration order.
    #[cfg(feature = "profile")]
    let fingerprint_charge = Charge::new(TickStage::Fingerprint);
    plan_inputs(world, kinds, inputs);
    #[cfg(feature = "profile")]
    drop(fingerprint_charge);

    failures.resize_with(count, || None);

    #[cfg(feature = "profile")]
    let decide_charge = Charge::new(TickStage::Decide);
    for index in 0..count {
        let held = world.non_send_mut::<Ledger>().take(index);
        let admit = Admit::bind(
            // A chain the compare pass did not reach is idle, which is the same
            // answer the buffer's own initial value carries.
            match kinds.get(index).copied() {
                Some(kind) => kind,
                None => AdmitKind::Idle,
            },
            inputs.get(index).copied().flatten(),
        );
        let Some(mut transition) = resume(world, index, admit, held) else {
            continue;
        };

        // The borrow of the world for the walk is scoped: `Ledger::take` above
        // and `Ledger::put` below each need it mutably, while the walk needs the
        // chains and the transition's binding immutably. Nothing is written to
        // the transition here — every state that depends on an attempt is
        // written by the driver, which is the only place that knows the outcome.
        {
            let chains = world.non_send::<Chains>();
            let ledger = world.non_send::<Ledger>();
            if let (Some(chain), Some(value), Some(failure)) = (
                chains.0.get(index),
                transition.value.as_ref(),
                failures.get_mut(index),
            ) {
                plan_chain(
                    chain,
                    &transition,
                    value,
                    index,
                    ledger,
                    &mut steps,
                    failure,
                );
            }
            // No chain, or a transition bound to nothing: the work is kept,
            // not discarded. A transition is opened only for a source that was
            // polled, so a chain with no value bound to it is a world that was
            // mutated behind the schedule's back.
        }

        // ── The handover that keeps the last-seen value alive ─────────────
        //
        // A transition holds its payload out on loan: `Transition::opened`
        // *takes* it out of `Observed`, and while the transition is retained
        // that binding is where the chain's newest value lives. When the
        // transition is finished and dropped instead, the binding goes with
        // it — and unless it is handed back, the chain is left with no
        // baseline at all. The next tick would then compare a fresh
        // observation against nothing, read every source as moved, re-open
        // every chain and fire every entry again, forever.
        //
        // That is not a slowdown, it is the substrate running work it had
        // already done: the fairness gate in `bench/` reports it as the bot
        // firing 896,000 effects where the hand-rolled baseline fires 17,920
        // for identical input. The value goes back only when the slot is
        // empty, because a slot the observation phase filled this tick holds a
        // newer value than the one being handed back.
        let retained = transition.is_retained();
        let returned = if retained {
            None
        } else {
            std::mem::take(&mut transition.value)
        };
        world
            .non_send_mut::<Ledger>()
            .put(index, if retained { Some(transition) } else { None });
        if let Some(returned) = returned {
            // Handed back only when the slot is empty, because a slot the
            // observation phase filled this tick holds a newer value than the
            // one being returned. Nothing to mark here: the value was admitted
            // when its generation took it out of the slot, and a value standing
            // in the slot again is *still* admitted — it has been acted on.
            let mut observed = world.non_send_mut::<Observed>();
            if let Some(slot) = observed.0.get_mut(index).filter(|slot| slot.is_none()) {
                *slot = Some(returned);
            }
        }
    }

    #[cfg(feature = "profile")]
    drop(decide_charge);
    *world.non_send_mut::<AdmitScratch>() = scratch;
    put_plan_buffers(world, steps, failures);
}

/// Take the plan's two buffers, leaving empty ones behind.
///
/// They are taken rather than borrowed so the decision walk can push into them
/// while the world is borrowed immutably for the chains and the transition
/// bindings. Empty `Vec`s are left in their place, so a tick that dies before
/// putting them back stages nothing.
fn take_plan_buffers(world: &mut World) -> (Vec<Step>, Vec<Option<BotError>>) {
    let mut plan = world.non_send_mut::<Plan>();
    (
        std::mem::take(&mut plan.steps),
        std::mem::take(&mut plan.failures),
    )
}

/// Put the plan's buffers back, capacity and all.
///
/// The counterpart to [`take_plan_buffers`]. Handing the same allocations back
/// is the whole point: a plan rebuilt from empty every tick allocates once per
/// chain for each of its two fields, which is the cost this pair exists to
/// remove.
fn put_plan_buffers(world: &mut World, steps: Vec<Step>, failures: Vec<Option<BotError>>) {
    let mut plan = world.non_send_mut::<Plan>();
    plan.steps = steps;
    plan.failures = failures;
}

/// Record the decisions one chain's walk reaches, in entry order.
///
/// Only the decisions a walk can make without attempting anything are taken
/// here: an entry the walk is finished with, and an entry it reached whose
/// condition did not hold. Everything that depends on an attempt — marking the
/// entry in flight, and what its outcome means — is left to the driver, which is
/// the only place that knows it.
///
/// A skipped entry is recorded as a [`Decision::Skip`] rather than written to the
/// ledger here so that the condition behind it is evaluated against the value the
/// attempt will actually see. An entry the walk never reaches because an earlier
/// action failed keeps the state that makes it reachable, instead of being marked
/// decided by a condition evaluated ahead of the failure that stopped the walk
/// before it.
fn plan_chain(
    chain: &EcsChain,
    transition: &Transition,
    value: &Erased,
    index: usize,
    ledger: &Ledger,
    steps: &mut Vec<Step>,
    failure: &mut Option<BotError>,
) {
    for (entry_index, entry) in chain.entries.iter().enumerate() {
        let Some(state) = transition.entries.get(entry_index) else {
            continue;
        };
        // A recovered unknown is a barrier *before* the condition is read.
        // The current observation is not evidence that the earlier effect did
        // not occur, so a false condition may not skip the entry and a true
        // one may not re-enter it; either way the successor does not run
        // (issue #104).
        if ledger
            .action_of(WorkId {
                chain: index,
                entry: entry_index,
            })
            .is_some_and(|action| ledger.effects.blocks(action))
        {
            break;
        }
        match *state {
            // Decided, and the chain continues past it: an entry that ran, and
            // one whose condition was false. Both are facts about the entry that
            // leave the entry behind it with nothing standing in its way.
            EntryState::Succeeded | EntryState::Skipped => continue,
            // Given up on, and a *barrier* to everything behind it. This is the
            // line between declaration order and success dependency, and it is
            // the one this walk used to get wrong: an entry in a chain is a
            // prerequisite of the next, so an abandonment is the strongest
            // possible statement that the entry behind it must not run — the
            // draft was never reserved, so there is nothing to send. Continuing
            // past it completed a command whose prerequisite had been given up
            // on.
            //
            // The successors are not lost or forgotten by stopping here. They
            // stay `NotStarted`, so [`Ledger::pending`] keeps reporting them and
            // the tick that finds them names the abandonment in front of them.
            // The way past it is evidence: `NotApplied` revives the entry, and
            // the successors with it.
            EntryState::Abandoned { .. } => break,
            // Held: the effect may be live and only evidence settles that. A
            // later entry is not run ahead of it.
            EntryState::Unrecorded | EntryState::OutcomeUnknown { .. } => break,
            // A known outcome whose record is missing is walked: the retry is
            // an append, not a dispatch, and `run_chain` takes that path.
            EntryState::RecordingFailed { .. } => {}
            EntryState::NotStarted | EntryState::DefinitelyFailed { .. } => {}
        }

        // The condition reads the value as it stands *now*, which is why an
        // outstanding transition is walked on a tick where the source held
        // still: the value it has not been evaluated against is the one from the
        // movement that joined the transition.
        match entry.condition.check_any(value) {
            Ok(true) => {}
            Ok(false) => {
                steps.push(Step {
                    chain: index,
                    entry: entry_index,
                    decision: Decision::Skip,
                });
                continue;
            }
            Err(error) => {
                // A condition that cannot be evaluated has decided nothing about
                // the effect: the entry stays where it is, this chain stops, and
                // the tick reports the error. Nothing is abandoned, because
                // nothing was attempted. Recorded at most once per chain, since
                // the walk stops here.
                *failure = Some(error);
                break;
            }
        }

        steps.push(Step {
            chain: index,
            entry: entry_index,
            decision: Decision::Attempt,
        });
    }
}

/// Build the schedule this substrate runs, with the two settings that make its
/// order a property of the graph rather than of thread arrival.
fn schedule() -> Schedule {
    let mut schedule = Schedule::default();
    // Explicit, not inherited: the multithreaded executor admits any system
    // whose access set is disjoint from the running set, so which of two
    // non-conflicting systems runs first is not fixed.
    schedule.set_executor(SingleThreadedExecutor::default());
    schedule.set_build_settings(ScheduleBuildSettings {
        ambiguity_detection: LogLevel::Error,
        ..Default::default()
    });
    // `.chain()` is the declared order: commit the observations, then decide
    // the effects.
    schedule.add_systems((observe_fold, fire_plan).chain());
    schedule
}

/// Initialize and validate a schedule, turning a build failure into a
/// [`BotError`]. Factored out so the refusal is testable without constructing a
/// bot whose schedule happens to be ambiguous.
fn validate(schedule: &mut Schedule, world: &mut World) -> Result<(), BotError> {
    schedule
        .initialize(world)
        .map(|_| ())
        .map_err(|error| BotError::DomainError {
            domain: "ecs::schedule".into(),
            certainty: DispatchCertainty::Refused,
            // `ScheduleBuildError` carries an inherent `to_string(&self, graph,
            // world)` that shadows `Display::to_string`; the inherent one is the
            // one that resolves system names against the graph.
            cause: error.to_string(schedule.graph(), world),
        })
}

// ── The bot ────────────────────────────────────────────────────────────────

/// A bot executing on a `bevy_ecs` world.
///
/// Stepped by hand: one tick is one [`EcsBot::tick_async`], which is one
/// `Schedule::run` between the awaited observe and act phases. No framework owns
/// a loop, and no `App::run` is ever called.
pub struct EcsBot {
    /// The name the spec declared.
    name: String,
    /// The world the schedule runs against.
    world: World,
    /// The validated schedule.
    schedule: Schedule,
    /// How long one source poll may take before the tick stops waiting for it.
    ///
    /// A field rather than a resource because nothing in the schedule reads it:
    /// it bounds the observation phase alone, and a resource would put a second
    /// writer next to the phase that owns it. The declared default is
    /// [`DEFAULT_POLL_DEADLINE`] and the builder's override is the only other
    /// value a bot can carry.
    poll_deadline: Duration,
}

impl EcsBot {
    /// Start building a named bot on this substrate.
    #[must_use]
    pub fn builder(name: impl Into<String>) -> EcsBuilder {
        EcsBuilder {
            name: name.into(),
            chains: Vec::new(),
            policy: RetryPolicy::DEFAULT,
            effects: None,
            poll_deadline: DEFAULT_POLL_DEADLINE,
        }
    }

    /// Materialize a runnable bot from a serializable spec and a registry.
    ///
    /// This is `from_spec`, and it is deliberately the *same* bot the builder
    /// chain produces: the spec's sources and actions are built through the
    /// registry, erased into chains, and handed to the same `assemble` step
    /// that [`ObserveBuilder::build`](crate::spec::ObserveBuilder::build)
    /// reaches with a natively declared chain. There is no second interpreter
    /// and no second execution path, so a materialized bot and a native one
    /// built from the same domains produce the same operation trace (T25).
    ///
    /// # Authority
    ///
    /// A spec cannot grant itself anything. Capabilities come only from the
    /// `grants` argument: the registry supplies constructors, never authority,
    /// and every erased verb still checks its own caps at the call site against
    /// the proof the bot mints from this set. This is what makes it safe to
    /// accept a spec from wire data at all — naming a domain buys no reach.
    ///
    /// # All-or-nothing admission
    ///
    /// Nothing runs and nothing is half-built. Every presently knowable unmet
    /// need is collected in one [`NeedSet`] — an unknown source or action
    /// domain, a constructor that rejects its target, a missing capability, an
    /// unknown condition — each attributed to the chain (and action) that needs
    /// it, and the whole materialization is refused with [`Admission::Needs`].
    /// A malformed document or registry is refused with [`Admission::Refused`]
    /// before any need is computed. Because the refusal happens before the
    /// builder runs, no source is polled and no action executes.
    ///
    /// # Errors
    ///
    /// [`Admission::Refused`] for a registry with a duplicate identifier, an
    /// unsupported [`version`](BotSpec::version), an empty chain list, or the
    /// builder's own admission (which an all-admitted spec does not reach);
    /// [`Admission::Needs`] for the complete report of unmet needs.
    ///
    /// # Example
    ///
    /// ```rust
    /// use lgwks_bot::broker::Broker;
    /// use lgwks_bot::effect::{EnvironmentId, FlowRevision, RunId};
    /// use lgwks_bot::journal::MemoryJournal;
    /// use lgwks_bot::spec::{Bot, BotSpec, EffectIdentity, EffectScope};
    /// use lgwks_bot::{
    ///     Action, Auth, BotError, Cap, EffectLifetime, Execute, GrantSet, Observe, Source, domains,
    /// };
    ///
    /// /// A source that reports the count its target parsed to.
    /// struct Counter(u16);
    /// impl Counter {
    ///     fn from_target(target: &str) -> Result<Source, BotError> {
    ///         match target.parse::<u16>() {
    ///             Ok(count) => Ok(Source::new(Self(count))),
    ///             Err(error) => Err(BotError::IncompleteSpec {
    ///                 field: "target",
    ///                 cause: error.to_string(),
    ///             }),
    ///         }
    ///     }
    /// }
    /// impl Observe for Counter {
    ///     type Output = u16;
    ///     fn required_caps(&self) -> &[Cap] { &[] }
    ///     async fn poll(&self, call: (Auth, ())) -> Result<u16, BotError> {
    ///         call.0.check(&[])?;
    ///         Ok(self.0)
    ///     }
    ///     fn domain_id(&self) -> &str { "doc::counter" }
    /// }
    ///
    /// /// An action that accepts a count.
    /// struct Page;
    /// impl Page {
    ///     fn from_target(target: &str) -> Result<Action, BotError> {
    ///         let _ = target;
    ///         Ok(Action::new(Self))
    ///     }
    /// }
    /// impl Execute for Page {
    ///     type Input = u16;
    ///     type Output = ();
    ///     fn required_caps(&self) -> &[Cap] { &[] }
    ///     fn effect_lifetime(&self) -> EffectLifetime { EffectLifetime::Local }
    ///     async fn execute_action(&self, call: (Auth, &u16)) -> Result<(), BotError> {
    ///         call.0.check(&[])?;
    ///         Ok(())
    ///     }
    ///     fn domain_id(&self) -> &str { "doc::page" }
    /// }
    ///
    /// domains! {
    ///     /// The domains this example runs.
    ///     pub DOMAINS {
    ///         observe { "doc::counter" => Counter::from_target, }
    ///         execute { "doc::page" => Page::from_target, }
    ///     }
    /// }
    ///
    /// let spec = BotSpec::from_json(
    ///     r#"{"version":1,"name":"doc",
    ///         "chains":[{"source":"doc::counter","target":"3",
    ///                    "on":[["always",{"domain":"doc::page","target":""}]]}]}"#,
    /// )?;
    ///
    /// let environment = EnvironmentId::from_hex("2122232425262728292a2b2c2d2e2f30")?;
    /// let mut broker = Broker::new();
    /// broker.register(environment)?;
    /// let effects = EffectScope::new(
    ///     EffectIdentity::new(
    ///         RunId::from_hex("0102030405060708090a0b0c0d0e0f10")?,
    ///         environment,
    ///         FlowRevision::from_tagged(
    ///             "blake3_256",
    ///             "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
    ///         )?,
    ///     ),
    ///     broker,
    ///     Box::new(MemoryJournal::new()),
    /// );
    ///
    /// let mut bot = Bot::from_spec(&spec, &DOMAINS, &GrantSet::empty(), effects)?;
    /// assert_eq!(bot.tick()?, 1);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn from_spec(
        spec: &BotSpec,
        registry: &DomainRegistry,
        grants: &GrantSet,
        effects: EffectScope,
    ) -> Result<Self, Admission> {
        // A registry that declares one identifier twice cannot be dispatched
        // against: lookup would depend on declaration order. Refused before any
        // chain is walked, because the repair is the registry's, not the
        // document's.
        registry.validate().map_err(Admission::Refused)?;
        if spec.version != BotSpec::CURRENT_VERSION {
            let refusal = Err(Admission::Refused(BotError::UnsupportedSpecVersion {
                found: spec.version,
                supported: BotSpec::CURRENT_VERSION,
            }));
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "from_spec: returning an error to the caller");
            return refusal;
        }
        // A materialized bot with nothing to observe is almost always a
        // truncated document rather than an intentional one; the builder
        // tolerates it, the materializer does not.
        if spec.chains.is_empty() {
            let refusal = Err(Admission::Refused(BotError::IncompleteSpec {
                field: "chains",
                cause: String::from("the document declares no observation chains at all"),
            }));
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "from_spec: returning an error to the caller");
            return refusal;
        }

        // One pass over every chain, collecting *every* need rather than
        // stopping at the first. Each chain that fully resolves contributes its
        // erased form; a chain with any need contributes to the report and no
        // chain at all. The two lists cannot disagree: `needs` non-empty means
        // the build below is never reached.
        let mut needs: Vec<Need> = Vec::new();
        let mut chains: Vec<EcsChain> = Vec::with_capacity(spec.chains.len());
        for (chain_index, chain) in spec.chains.iter().enumerate() {
            if let Some(built) = materialize_chain(chain_index, chain, registry, grants, &mut needs)
            {
                chains.push(built);
            }
        }
        if !needs.is_empty() {
            let refusal = Err(Admission::Needs(NeedSet::new(needs)));
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "from_spec: returning an error to the caller");
            return refusal;
        }

        // The same `assemble` a native bot reaches, through the same builder.
        let mut builder = Self::builder(spec.name.clone());
        for chain in chains {
            builder = builder.chain(chain);
        }
        builder
            .with_effects(effects)
            .build(grants)
            .map_err(Admission::Refused)
    }

    /// Take the journal back out of the bot.
    ///
    /// `None` when the ledger is not in the world, which is the state after a
    /// previous call already took it. What a host calls on its way out, so the
    /// record outlives the process that wrote it — and what a restart test
    /// calls to hand the same journal to a second bot.
    #[must_use]
    pub fn into_journal(mut self) -> Option<Box<dyn EffectJournal>> {
        self.world
            .remove_non_send::<Ledger>()
            .map(Ledger::into_journal)
    }

    /// The name the spec declared.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Effects fired on the most recent tick.
    #[must_use]
    pub fn fired(&self) -> usize {
        self.world.resource::<Fired>().0
    }

    /// The world, for tests and instrumentation. Read-only: mutating it behind
    /// the schedule's back would break the ordering the build validated.
    #[must_use]
    pub fn world(&self) -> &World {
        &self.world
    }

    /// The `Revision` of every source, in chain order.
    #[must_use]
    pub fn revisions(&self) -> Vec<u64> {
        let order = self.world.resource::<Order>().0.clone();
        order
            .iter()
            .filter_map(|entity| self.world.get::<Revision>(*entity))
            .map(|revision| revision.0)
            .collect()
    }

    /// The observed sources' domain identifiers, in chain order.
    ///
    /// Replaces the old `chains()` accessor: what a caller wanted from it was
    /// "what is this bot watching", and that is identity, not the erased
    /// observer objects.
    #[must_use]
    pub fn source_domains(&self) -> Vec<String> {
        let order = self.world.resource::<Order>().0.clone();
        order
            .iter()
            .filter_map(|entity| self.world.get::<SourceId>(*entity))
            .map(|id| id.domain().to_owned())
            .collect()
    }

    /// Run one tick, awaiting the verb futures on the caller's executor.
    ///
    /// Returns the number of actions that fired. The bot is `mut` because a
    /// tick advances its world.
    ///
    /// # What this is for
    ///
    /// This is the tick to call from async code, and the reason is that the
    /// verb futures are awaited **by the caller's runtime** rather than by a
    /// thread parked inside a synchronous system. A source that waits on
    /// `rt::time`, on a socket, on a channel fed by a sibling task, or on
    /// anything else that needs a driver resolves while this future is pending,
    /// because the runtime that owns it is the one driving.
    ///
    /// # Phases
    ///
    /// 1. every source is polled in bounded waves of `MAX_IN_FLIGHT_POLLS`,
    ///    concurrently, in declaration order;
    /// 2. one `Schedule::run` commits those observations, detects which values
    ///    moved, and records the effect program (`observe_fold`, `fire_plan`),
    ///    walking the ledger's outstanding work rather than the change set;
    /// 3. the recorded effects run one at a time, in declaration order, and each
    ///    entry is written into the ledger as it goes;
    /// 4. the count, the first failure, and any entry still held are reported.
    ///
    /// The middle two phases are what keep this deterministic: the schedule is
    /// a total order validated at build, the observations are folded
    /// positionally, and the effect program is fixed before any effect runs.
    ///
    /// # Failure
    ///
    /// A poll that failed fires nothing (no `Revision` was written), while an
    /// action that failed leaves the effects before it live and returns the first
    /// error. A condition that fails stops its own chain where it failed, so the
    /// effects that chain's walk had already reached still run — the plan carries
    /// the decisions and the chains after it are still walked, and the tick
    /// reports the first failure in declaration order. `Err` therefore means "this
    /// run did not finish", never "nothing happened".
    ///
    /// The failure keeps precedence over the pending report when a tick has both,
    /// because it carries the typed variant a retry classifier reads: an
    /// [`BotError::EffectIndeterminate`] written into a string would stop being
    /// the distinction the whole error type exists to draw. So the tick that gives
    /// up on an entry reports the error that caused it, and the abandonment —
    /// never a silent drop — is reported by [`Self::pending`], which names every
    /// abandoned entry, its reason, and its source revision for as long as it
    /// stands.
    ///
    /// # Cancellation
    ///
    /// Dropping this future before it resolves cancels the tick at the point it
    /// was dropped. Between phases 2 and 3 that loses the effects phase 2
    /// selected, and the next tick does not re-fire them: the revisions were
    /// committed in phase 2, so the sources no longer read as moved. This is the
    /// same "unattempted work is lost, not queued" rule the failure path
    /// documents, and it is stated rather than discovered because it is the price
    /// of a tick that is a future.
    ///
    /// Dropping it *during* phase 3 is the case the ledger exists for. An entry
    /// whose attempt was in flight was written to the ledger before the effect
    /// was awaited, so the next tick finds it held as
    /// [`TransitionHold::Unrecorded`] — "an attempt began and no outcome was
    /// recorded" — and does not replay it. An entry whose turn had not come is
    /// left `NotStarted`, so it is walked again. Which of the two an entry is
    /// depends only on whether the effect was awaited, which is the same fact the
    /// caller is missing; the difference is that the substrate no longer has to
    /// guess.
    ///
    /// # Errors
    ///
    /// The first domain failure of the tick, in the order described above, or
    /// [`BotError::PendingTransition`] when nothing failed and work is still held.
    pub async fn tick_async(&mut self) -> Result<usize, BotError> {
        self.begin_tick();

        // The staging buffers are moved out, refilled and put back, so the
        // observation phase reuses one allocation across every tick rather than
        // building a fresh vector per tick. They are taken rather than borrowed
        // because `poll_sources` borrows the world immutably across its awaits
        // and a mutable borrow of a resource cannot be held across them.
        let mut polled = std::mem::take(&mut self.world.non_send_mut::<Polled>().0);
        polled.clear();
        // The revisions the sources reported, taken out with the rest of the
        // observation phase's scratch: this method holds `&self` across every
        // poll, so it cannot write the world it is reading.
        let mut revisions = std::mem::take(&mut self.world.non_send_mut::<ChangeTicks>().polled);
        // Taken rather than borrowed for the same reason `revisions` is, and
        // because the observation phase is the tick's only writer of these
        // buffers. It goes back with its capacity, which is the entire point:
        // a quiet tick fills the buffers, publishes them, and hands them to the
        // next tick instead of asking the allocator for them again.
        let mut scratch = {
            let mut guard = self.world.non_send_mut::<PollScratch>();
            std::mem::take(&mut *guard)
        };
        #[cfg(feature = "profile")]
        let poll_charge = Charge::new(TickStage::Poll);
        let watchdogs = self
            .poll_sources(&mut polled, &mut revisions, &mut scratch)
            .await;
        #[cfg(feature = "profile")]
        drop(poll_charge);
        self.world.non_send_mut::<Polled>().0 = polled;
        // Handed back before the schedule runs, because `observe_fold` commits
        // each chain's revision from it and that commit is the whole rule.
        self.world.non_send_mut::<ChangeTicks>().polled = revisions;

        // Published before the schedule runs, so the report describes this tick's
        // observation phase even when the schedule step stops on a failure and
        // the effects phase never runs. A caller reading the report after a
        // failed tick is exactly the caller who needs to know a source had
        // already declared its cache unsound when it failed.
        self.record_invalidations(&scratch.declared);
        self.publish_refreshes();
        self.publish_stalls(&scratch.stalled, watchdogs);
        *self.world.non_send_mut::<PollScratch>() = scratch;

        #[cfg(feature = "profile")]
        let schedule_charge = Charge::new(TickStage::Schedule);
        self.schedule.run(&mut self.world);
        #[cfg(feature = "profile")]
        drop(schedule_charge);

        // Taken rather than borrowed: the effects are awaited below, and a
        // borrow of the plan would outlive the schedule that wrote it. An empty
        // plan is left behind, so a tick dropped here stages nothing.
        let plan = {
            let mut guard = self.world.non_send_mut::<Plan>();
            std::mem::take(&mut *guard)
        };
        let Plan {
            mut steps,
            mut failures,
        } = plan;
        let budget = self.world.resource::<Policy>().0.max_attempts();
        #[cfg(feature = "profile")]
        let act_charge = Charge::new(TickStage::Act);
        let (fired, failure) = self.run_steps(&steps, &mut failures, budget).await;
        #[cfg(feature = "profile")]
        drop(act_charge);

        // Handed back with their capacity, not dropped. The plan is taken out of
        // the world to run because the driver needs it mutably while it awaits,
        // and a buffer that is taken out and then dropped is a buffer the next
        // tick has to allocate again — which is exactly what made a tick cost a
        // heap allocation per chain before it ran a single effect.
        steps.clear();
        failures.clear();
        put_plan_buffers(&mut self.world, steps, failures);

        self.world.resource_mut::<Fired>().0 = fired;
        self.world.resource_mut::<TickReport>().fired = fired;
        if let Some(error) = failure {
            self.world.resource_mut::<TickError>().0 = Some(error);
        }

        if let Some(error) = self.world.resource_mut::<TickError>().0.take() {
            let refusal = Err(error);
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "tick_async: returning an error to the caller");
            return refusal;
        }

        // A tick that reported no failure is not necessarily a tick with nothing
        // left. An entry the substrate cannot settle on its own — an attempt in
        // flight whose outcome was never recorded, an effect that may be live, or
        // one the budget gave up on — is held, and a held entry is reported
        // rather than passed over in silence: a caller that read a clean `Ok` as
        // "the transition was handled" would be reading something that is not
        // true. That includes an abandonment, which is the case this used to
        // miss: it asks the tick for nothing, so it looks finished from inside
        // the walk, but it is work nobody resolved.
        let ledger = self.world.non_send::<Ledger>();
        match ledger.first_unresolved(budget) {
            Some(work) => Err(BotError::PendingTransition {
                work,
                outstanding: ledger.unresolved_count(budget),
            }),
            None => Ok(self.world.resource::<Fired>().0),
        }
    }

    /// One tick, with each stage of it measured.
    ///
    /// The same [`tick_async`](Self::tick_async) on the same four phases, with the
    /// per-stage instrument armed around it; the `Result` is the identical value
    /// that call would have returned. Nothing here is a reimplementation of the
    /// tick, so a profile is a decomposition of the real path rather than of a
    /// model of it.
    ///
    /// # The instrument is not free, and this is how its cost is known
    ///
    /// Measuring six stages costs seven clock reads. A caller that wants both a
    /// wall time and a profile therefore times the *same* workload through both
    /// doors and takes the difference as the instrument's cost on that tick —
    /// which is what `bench/` does, and the only way the two figures can be read
    /// together. The **shares** the profile reports are the claim it supports;
    /// the absolute per-stage times carry the instrument.
    ///
    /// Stages are a partition of the tick and nest in one direction: the
    /// schedule step wraps the stages inside it, so [`TickStage::Schedule`] is
    /// the *residual* — the dispatch of the two systems plus the commit
    /// bookkeeping inside `observe_fold` that nothing else claims.
    #[cfg(feature = "profile")]
    pub async fn tick_profiled(&mut self) -> (Result<usize, BotError>, TickProfile) {
        profile::begin();
        let outcome = self.tick_async().await;
        (outcome, profile::end())
    }

    /// Run one tick on this thread, without an async runtime.
    ///
    /// # Scope
    ///
    /// This is the adapter for **runtime-independent futures**: polls and
    /// actions that complete without a timer or an I/O driver. Immediate
    /// futures, `lgwks_std::task::spawn_blocking` work, and a channel fed by
    /// another thread all belong here; it drives the same four phases as
    /// [`EcsBot::tick_async`] with `lgwks_std::task::block_on`, which parks
    /// this thread until they resolve.
    ///
    /// A verb that needs this crate's timer (`rt::time`) or a driver cannot run
    /// here, because there is no reactor for it to register with: on this
    /// adapter `rt::time::sleep` reaches the runtime-context panic its own
    /// documentation names. Await [`EcsBot::tick_async`] from inside a runtime
    /// instead.
    ///
    /// # The refusal
    ///
    /// [`BotError::TickInsideRuntime`] when an async runtime is already driving
    /// the calling thread. Parking a thread that owns a runtime's driver is not
    /// a slow tick, it is a deadlock — the timer never fires, the socket never
    /// reports ready, and the tick never returns — so the one thing this
    /// adapter must not do is what its name suggests. The check is made here
    /// rather than left to the caller because the calling mode is not knowable
    /// from the verb API.
    ///
    /// This refuses even on a runtime with several worker threads, where
    /// parking one worker may happen to work. Which thread the caller was
    /// handed is not knowable from here, and a deadlock that appears only on
    /// the current-thread runtime is the failure this exists to prevent rather
    /// than to mask.
    ///
    /// # Errors
    ///
    /// [`BotError::TickInsideRuntime`] as above, or the first domain failure of
    /// the tick.
    pub fn tick(&mut self) -> Result<usize, BotError> {
        #[cfg(feature = "rt")]
        if lgwks_deps::tokio::runtime::Handle::try_current().is_ok() {
            let refusal = Err(BotError::TickInsideRuntime);
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "tick: returning an error to the caller");
            return refusal;
        }
        lgwks_std::task::block_on(self.tick_async())
    }

    /// Reset the per-tick scratch, so a tick starts from the same state however
    /// the previous one ended.
    ///
    /// The staged observations and the effect program are not cleared here:
    /// both are overwritten wholesale by the phase that produces them, which is
    /// what makes a *dropped* tick safe as well as a completed one.
    fn begin_tick(&mut self) {
        self.world.resource_mut::<Fired>().0 = 0;
        self.world.resource_mut::<TickError>().0 = None;
        // The previous tick's report is history, not this tick's. Overwritten
        // rather than appended so a caller reading it before the next tick sees
        // the tick it just ran and not a union of every tick the bot has ever
        // run — which would answer "was a refresh ever forced", a different and
        // much less useful question.
        *self.world.resource_mut::<TickReport>() = TickReport::default();
    }

    /// What the most recent tick observed about its own sources.
    ///
    /// The companion to [`Self::tick`]'s return value rather than a second
    /// channel into the same fact: the count says what fired, this says what the
    /// bot had to re-read to decide, and a bot that has gone quiet is exactly
    /// where only the first of those is uninformative.
    ///
    /// Reports the last tick that ran, whatever its result. A tick that returned
    /// `Err` still observed, and the caller triaging the error needs to know
    /// whether a declared cache failure is behind it. Reading this before the
    /// first tick returns the empty report, which says no source was forced —
    /// true, and true for a tick that never happened.
    #[must_use]
    pub fn tick_report(&self) -> TickReport {
        self.world.resource::<TickReport>().clone()
    }

    /// Poll every source, `MAX_IN_FLIGHT_POLLS` at a time, awaiting each wave
    /// on the caller's executor, appending to `polled`.
    ///
    /// Bounded waves, joined concurrently: a source poll may occupy one
    /// `spawn_blocking` thread, so polling them one at a time would make a tick
    /// as slow as the sum of its sources rather than as slow as its slowest.
    /// The wave cap is what keeps that from becoming unbounded blocking-thread
    /// fan-out. Determinism is unaffected: the results are collected in
    /// declaration order whatever order they resolve in.
    ///
    /// # Bounded in time as well as in width
    ///
    /// Each poll runs under [`bounded_poll`], which gives it
    /// [`Self::poll_deadline`] of *real* elapsed time before the wave drops it.
    /// Without that, the fan-out cap is the only bound this phase has and a
    /// source that never resolves holds the tick forever — which is T06's
    /// slow-source half, and it was the one claim this substrate could not make.
    ///
    /// The bound is measured on the wall watchdog half of the crate's one
    /// declared clock ([`crate::rt::clock::Clock`], INV-BOT-30) rather than on
    /// its logical counter, because a source that stopped answering is not
    /// waiting for time to pass: it has stopped making progress entirely, and a
    /// logical clock a caller can advance would either fire the deadline for a
    /// poll that was merely slow or wait on the wedged one forever. What the
    /// clock names is the *source* of the elapsed time, so a reader can ask
    /// which clock governed the cancellation.
    ///
    /// A cancelled poll commits nothing, keeps its chain's baseline and its
    /// forced-refresh mark standing, and is reported through
    /// [`TickReport::stalled`]. Its siblings in the wave are not stopped: the
    /// deadline is per poll, so the chains beside a wedged one still commit and
    /// act in the same tick.
    ///
    /// # Why the output is a parameter
    ///
    /// `polled` is the caller's buffer, already cleared and already holding the
    /// capacity of the previous tick's results. Returning a fresh `Vec` instead
    /// would make the observation phase allocate its staging area every tick,
    /// which is one of the costs this substrate is measured on. The caller owns
    /// the buffer because it also owns the resource the buffer lives in; this
    /// function only borrows the world.
    ///
    /// # What each source is handed
    ///
    /// Each source is given the payload the substrate currently holds for its
    /// chain — the newest committed observation, or the binding of a transition
    /// that owns it — so the source itself can answer "did I move?" against a
    /// concrete value, before anything is boxed. A source that returned
    /// `Ok(None)` did not move, and nothing is allocated for it.
    ///
    /// A source that declared its cache unsound is handed **`None`** instead,
    /// whatever the substrate holds. That is the whole of the forced refresh:
    /// with a baseline in hand the source can answer "equal to this" and the
    /// substrate keeps a value it now knows is wrong. With `None` there is
    /// nothing to be equal to, so the poll is a read and its value becomes the
    /// new baseline — and because a read is a read, the chain also *moved*, so
    /// the change filter re-evaluates the entries against the value that is
    /// actually current rather than against the one the failure left behind.
    ///
    /// # The change-tick skip, and what it is not
    ///
    /// A source that implements [`Observe::revision`](crate::verb::Observe::revision)
    /// and reports the revision its committed value was read at is **not polled
    /// at all**. No future is built, no value is boxed, nothing is allocated, and
    /// the wave is narrower by however many sources are quiet. The check is one
    /// `&self` call and one integer comparison.
    ///
    /// The skip is suppressed for a chain that declared its baseline unsound,
    /// which is the case where believing a revision would be exactly wrong: the
    /// substrate has been told its held value is not what the source would report
    /// now, and a revision is a claim about the value rather than a repair of it.
    ///
    /// # Where the reason comes from
    ///
    /// Read from the source itself, after its poll resolves, never guessed by
    /// this function: the substrate cannot know whether a domain's transport is
    /// up or its queue overflowed, and a heuristic would be a guess about
    /// somebody else's transport. A source that declares nothing is a source
    /// with nothing to declare.
    ///
    /// # What it returns
    ///
    /// The chains whose baseline this tick could not trust: one entry per chain,
    /// in declaration order, `None` where the chain declared nothing; the chains
    /// whose poll the wave gave up on, in the same order; and how many deadline
    /// threads those waves started. Handed back rather than written to the world
    /// here, so `&self` stays a shared borrow across every poll. A `&mut World`
    /// would have to be held while each poll future is alive, and holding it
    /// across awaits to publish three words is exactly the shape that lets one
    /// phase's ordering become another's.
    async fn poll_sources(
        &self,
        polled: &mut Vec<Result<Option<Erased>, BotError>>,
        revisions: &mut Vec<Option<u64>>,
        scratch: &mut PollScratch,
    ) -> u32 {
        let count = self.world.non_send::<Chains>().0.len();
        polled.clear();
        polled.resize_with(count, || Ok(None));
        revisions.clear();
        revisions.resize(count, None);

        // What each chain declares about its own caching, one entry per chain and
        // read once per tick. Copied out of the world rather than borrowed across
        // the polls: the marks are written after the polls resolve, and the
        // closures below borrow the world's sources immutably for their whole
        // life.
        self.declared_refresh(&mut scratch.declared, count);
        // The chains whose poll was cancelled, in declaration order. Collected
        // here rather than published by the caller because the poll phase is the
        // only place that knows which poll was cut short, and the report must be
        // published before the schedule step runs on the strength of this tick's
        // observation — a tick that then failed still has to say which source it
        // gave up on.
        scratch.stalled.clear();
        let PollScratch {
            ref mut declared,
            ref mut stalled,
            ref mut slots,
        } = *scratch;
        // The deadline threads this tick actually started, one per wave that had
        // a poll left pending. Published beside the stalls they may have caused,
        // because a caller triaging a wedged source wants to know whether the bot
        // spent a thread on it and how many.
        let mut watchdogs = 0_u32;

        // One guard for the whole phase, held across every await, rather than a
        // fresh `Vec` of `(chain, source)` pairs per wave. The old code copied the
        // wave out because `join_all_boxed` takes an iterator of futures and each
        // of those borrows the world, and the borrow was thought to need an owner
        // rather than a guard: it does not. `Chains` is borrowed shared, nothing
        // in this function is mutably borrowed, and no system runs while a poll is
        // pending — so the guard *is* the owner, and the wave's pairs cost nothing.
        let chains = self.world.non_send::<Chains>();
        for wave_index in 0..count.div_ceil(MAX_IN_FLIGHT_POLLS) {
            let base = wave_index.saturating_mul(MAX_IN_FLIGHT_POLLS);
            let width = count.saturating_sub(base).min(MAX_IN_FLIGHT_POLLS);

            // Which chains in this wave must be polled. A chain is **skipped**
            // when it reported a revision equal to the one its committed value
            // was read at and did not declare its baseline unsound: it keeps its
            // slot in `polled` as `Ok(None)` — "this source did not move" — and no
            // future is built for it, which is the whole saving.
            //
            // The indices are the *wave's* own slots, not positions in `polls`,
            // so each `WavePoll::slot` is still its own index in the wave's wakers
            // and the results below land on the chains that produced them.
            slots.clear();
            {
                let ticks = self.world.non_send::<ChangeTicks>();
                for slot in 0..width {
                    let index = base.saturating_add(slot);
                    let Some(chain) = chains.0.get(index) else {
                        continue;
                    };
                    let unsound = declared
                        .get(index)
                        .copied()
                        .flatten()
                        .is_some_and(|reason| reason.invalidates_baseline());
                    let reported = chain.source.revision();
                    if let Some(slot) = revisions.get_mut(index) {
                        *slot = reported;
                    }
                    // `None` from a source that cannot report a revision is never
                    // quiet: that is the value-comparison path, and it runs on
                    // every tick as it always has.
                    if !(ticks.quiet(index, reported) && !unsound) {
                        slots.push(slot);
                    }
                }
            }

            // A wave whose every source was skipped is a tick that asked and was
            // told nothing had moved. There is no future to join, no deadline to
            // keep, and no watcher to arm — the watchdog is two `Arc`s and its
            // state is a `Mutex`, so arming one for a wave with no members to
            // watch was a thread's worth of bookkeeping spent on the answer
            // "nothing happened".
            if slots.is_empty() {
                continue;
            }

            // One watchdog for the wave rather than one per poll, and one
            // deadline the whole wave shares: `bounded_wave` owns it and reports
            // whether it really did start a thread, which is the number the tick
            // report names. Its width is the number of polls that will actually
            // run.
            let wave_watchdog = PollWatchdog::new(self.poll_deadline, slots.len());
            let (results, armed) = {
                // Scoped to the wave, because each poll borrows that wave's
                // watchdog and a buffer outliving the watchdog would be a buffer
                // holding dangling borrows. Built from `drain(..)` into the wave
                // rather than moved, so a bot with more chains than fit in one
                // wave reuses one allocation across its waves.
                let mut polls: Vec<WavePoll<'_>> = Vec::new();
                for &slot in slots.iter() {
                    {
                        let index = base.saturating_add(slot);
                        let chain = &chains.0[index];
                        let seen = self.world.non_send::<Observed>();
                        let ledger = self.world.non_send::<Ledger>();
                        let grants = self.world.resource::<Grants>();
                        // `None` here means *the source declared nothing*, which
                        // is the ordinary case and must hand the baseline over —
                        // so the two are separated by an explicit test, not by an
                        // `and_then` over the option. `and_then` treats "no
                        // declaration" and "declares nothing usable" as the same
                        // `None` and drops the baseline in the first case, which
                        // is how every poll started reading as a fresh read and
                        // every tick looked like a movement.
                        let unsound = declared
                            .get(index)
                            .copied()
                            .flatten()
                            .is_some_and(|reason| reason.invalidates_baseline());
                        let baseline = if unsound {
                            None
                        } else {
                            seen.0
                                .get(index)
                                .and_then(|slot| slot.as_ref())
                                .or_else(|| ledger.bound(index))
                        };
                        polls.push(WavePoll {
                            chain: index,
                            slot,
                            installed: false,
                            poll: Box::pin(chain.source.poll_any(&grants.0, baseline)),
                            watchdog: &wave_watchdog,
                        });
                    }
                }
                bounded_wave(self.poll_deadline, &wave_watchdog, polls.drain(..)).await
            };
            watchdogs = watchdogs.saturating_add(u32::from(armed));

            // Zipped against the slots that were polled, not against the wave:
            // `results` has one entry per built future, so pairing it with the
            // wave would put every result after the first skip on the wrong
            // chain — a mis-pairing the rendezvous would then refuse as a type
            // mismatch, or, worse, commit one chain's value to another's.
            for (&slot, result) in slots.iter().zip(results) {
                let index = base.saturating_add(slot);
                let Some(slot) = polled.get_mut(index) else {
                    continue;
                };
                if matches!(result, Err(BotError::PollStalled { .. })) {
                    stalled.push(index);
                }
                *slot = result;
            }
        }

        // A poll that failed never reached the value that would have been
        // compared, so its baseline is exactly as unsound as it was and the mark
        // has to outlive this tick. A poll that succeeded is read once more,
        // after it resolved: a source that reached its failure *inside* the poll
        // has only now recorded it, and asking before the poll would have asked
        // about the previous tick's state.
        for (index, reason) in declared.iter_mut().enumerate() {
            let Some(chain) = chains.0.get(index) else {
                continue;
            };
            match (
                chain.source.cache_state(),
                polled.get(index).map(Result::is_ok),
            ) {
                (Some(declared_now), Some(true)) => *reason = Some(declared_now),
                // A failed poll carries no value at all, so the reason the source
                // would have named is not the one that matters: nothing was read,
                // and the baseline this tick did not replace is still standing.
                // The mark stays whatever it already was, and defaults to
                // `Disconnected` for a chain that had declared nothing, because a
                // source that could not be read is a source whose transport is at
                // least unavailable.
                (_, Some(false)) if reason.is_none() => {
                    *reason = Some(RefreshReason::Disconnected);
                }
                _ => {}
            }
        }
        // The `Some(false)` arm above is exactly what a cancelled poll reaches,
        // and that is deliberate: a stalled poll read nothing, so its baseline is
        // as unsound as it was and the mark has to outlive this tick, which is
        // the same rule a failed poll already follows. Clearing the mark on a
        // stall would re-read the source against the very baseline the stall
        // left standing, which is the quiet state INV-BOT-120 exists to rule
        // out.
        //
        // Sorted rather than in wave-completion order: a chain's index is its
        // identity everywhere else in this crate, and a report whose order
        // depended on which wave finished first could not be compared across two
        // runs of one seed.
        stalled.sort_unstable();
        watchdogs
    }

    /// What each of `count` chains declares about its own caching right now.
    ///
    /// Read once per tick, in declaration order, and copied out so the callers
    /// can hold it across the polls without borrowing the world. A chain that
    /// declared a reason last tick and nothing this tick is not cleared here:
    /// the mark is the substrate's record that the baseline it forced a read for
    /// was never successfully replaced, and clearing it on silence would be the
    /// permanent quiet state, one cause at a time.
    fn declared_refresh(&self, declared: &mut Vec<Option<RefreshReason>>, count: usize) {
        let chains = self.world.non_send::<Chains>();
        let invalidated = self.world.non_send::<Invalidated>();
        declared.clear();
        declared.resize(count, None);
        for (index, chain) in chains.0.iter().enumerate() {
            // A chain already marked this tick keeps the mark it has: re-reading
            // it would let a later poll within the same tick overwrite the reason
            // the report names with one that happened afterwards.
            if invalidated.is_invalid(index) {
                continue;
            }
            if let Some(reason) = chain.source.cache_state() {
                declared[index] = Some(reason);
            }
        }
    }

    /// Write this tick's marks into the world, so the schedule step and the
    /// report read the same record the observation phase produced.
    ///
    /// A mark that is already standing keeps the reason it has. That is the
    /// difference between "this source is currently unsound" and "this source's
    /// baseline has not been successfully replaced since it first declared
    /// itself unsound", and only the second one is worth re-reading a caller: a
    /// source that reconnects and then overflows on the very next tick reported
    /// two different facts, and the report names the first because the first is
    /// the one whose forced read has not landed yet.
    fn record_invalidations(&mut self, declared: &[Option<RefreshReason>]) {
        let mut invalidated = self.world.non_send_mut::<Invalidated>();
        for (chain, reason) in declared.iter().enumerate() {
            if let Some(reason) = *reason {
                invalidated.mark(chain, reason);
            }
        }
    }

    /// Copy this tick's invalidated marks onto the tick report, in chain order.
    ///
    /// Declaration order rather than mark order, for the reason
    /// [`Invalidated::mark`] already gives: the report is compared across two
    /// runs of one seed, and an order that varied with poll resolution would
    /// make the comparison meaningless.
    fn publish_refreshes(&mut self) {
        // Built as a whole vector and then moved in, rather than pushed a row
        // at a time: building it needs two shared borrows of the world (the
        // marks and the source identities) and writing it needs a mutable one,
        // and bevy's access rules cannot express "shared, shared, then mutable"
        // through a chain of borrows on one `self`. One assignment at the end is
        // also cheaper than a `clear` followed by a push per chain.
        let forced: Vec<ForcedRefresh> = {
            let invalidated = self.world.non_send::<Invalidated>();
            let order = self.world.resource::<Order>();
            invalidated
                .reasons
                .iter()
                .enumerate()
                .filter_map(|(chain, reason)| {
                    let reason = (*reason)?;
                    let domain = order
                        .0
                        .get(chain)
                        .and_then(|entity| self.world.get::<SourceId>(*entity))
                        .map_or_else(String::new, |id| id.domain().to_owned());
                    Some(ForcedRefresh {
                        chain,
                        domain,
                        reason,
                    })
                })
                .collect()
        };
        self.world.resource_mut::<TickReport>().forced = forced;
    }

    /// Copy this tick's cancelled polls onto the tick report, in chain order.
    ///
    /// The same build-then-assign shape as [`Self::publish_refreshes`] and the
    /// same reason: naming a chain's domain needs two shared borrows of the world
    /// and writing the report needs a mutable one.
    fn publish_stalls(&mut self, stalled: &[usize], watchdogs: u32) {
        let rows: Vec<StalledSource> = {
            let order = self.world.resource::<Order>();
            stalled
                .iter()
                .map(|chain| {
                    let domain = order
                        .0
                        .get(*chain)
                        .and_then(|entity| self.world.get::<SourceId>(*entity))
                        .map_or_else(String::new, |id| id.domain().to_owned());
                    StalledSource {
                        chain: *chain,
                        domain,
                        deadline: self.poll_deadline,
                    }
                })
                .collect()
        };
        let mut report = self.world.resource_mut::<TickReport>();
        report.stalled = rows;
        report.watchdogs = watchdogs;
    }

    /// Run the effects the decision phase selected, in the order it selected
    /// them, awaiting each on the caller's executor.
    ///
    /// Returns the number that fired and the first failure in declaration order,
    /// or `None` when nothing failed.
    ///
    /// Every chain is run on its own, because a failure stops its own chain rather
    /// than every chain after it: the chains behind a failing one still run and
    /// still record their work. Iterating chains rather than steps is also what
    /// keeps a chain that recorded *no* step from being skipped: a condition the
    /// walk could not evaluate stops that chain before it records anything, and
    /// its failure is still the tick's to report. The failure of the first chain
    /// in declaration order that has one is that report, which is the ordering the
    /// synchronous walk had.
    ///
    /// States are written to the ledger as the walk reaches them — an attempt in
    /// flight *before* its effect is awaited, and its outcome after — so a tick
    /// dropped in the middle holds what it had begun instead of leaving a
    /// `NotStarted` entry for the next tick to replay.
    async fn run_steps(
        &mut self,
        steps: &[Step],
        failures: &mut [Option<BotError>],
        budget: u32,
    ) -> (usize, Option<BotError>) {
        let mut fired: usize = 0;
        let mut failure: Option<BotError> = None;
        let mut start = 0;
        for chain in 0..failures.len() {
            // `steps` is in `(chain, entry)` walk order, so the steps of `chain`
            // are the run at `start` — and a chain that recorded none contributes
            // the empty run, because its first step is a later chain's.
            let end = steps[start..]
                .iter()
                .position(|step| step.chain != chain)
                .map_or(steps.len(), |offset| start.saturating_add(offset));
            let run = match steps.get(start) {
                Some(step) if step.chain == chain => &steps[start..end],
                _ => &[],
            };

            // Taken, so the condition failure belongs to the chain it was recorded
            // for and cannot be reported for a chain that never reached it.
            let condition_failure = failures.get_mut(chain).and_then(Option::take);
            let (chain_fired, chain_failure) = self.run_chain(run, condition_failure, budget).await;
            fired = fired.saturating_add(chain_fired);
            // Chain order, so "the first error in declaration order" is the one a
            // caller gets, exactly as the synchronous walk had it — except that
            // the chains after it still ran.
            if failure.is_none() {
                failure = chain_failure;
            }
            start = end;
        }
        (fired, failure)
    }

    /// Apply one chain's walk, in entry order, awaiting each attempt.
    ///
    /// A [`Decision::Skip`] is applied without an attempt. A
    /// [`Decision::Attempt`] is written to the ledger as in flight, awaited, and
    /// then recorded. The run stops at the first failure, leaving the entries
    /// behind it exactly as they were, so an acknowledged effect is never
    /// replayed to reach a successor.
    ///
    /// The report falls back to the condition failure the decision phase recorded
    /// for this chain when no attempt of its own failed: a condition the walk
    /// could not evaluate is a failure of the chain it is in, and the decisions
    /// before it are exactly the effects the walk had already cleared.
    async fn run_chain(
        &mut self,
        steps: &[Step],
        condition_failure: Option<BotError>,
        budget: u32,
    ) -> (usize, Option<BotError>) {
        let mut fired: usize = 0;
        let mut failure: Option<BotError> = None;
        for step in steps {
            let work = WorkId {
                chain: step.chain,
                entry: step.entry,
            };
            if matches!(step.decision, Decision::Skip) {
                // A Skip is the plan's answer to a false condition, and a
                // recovered unknown outranks that answer: marking the entry
                // `Skipped` is how the unknown got buried and its successor
                // ran (issue #104). The chain stops instead, and the entry
                // stays where it was.
                let blocked = {
                    let ledger = self.world.non_send::<Ledger>();
                    ledger
                        .action_of(work)
                        .is_some_and(|action| ledger.effects.blocks(action))
                };
                if blocked {
                    break;
                }
                self.world.non_send_mut::<Ledger>().skip(work);
                continue;
            }

            // A known outcome whose record is missing: retry the append and
            // never re-enter the action. This is the whole of issue #102's
            // repair on the recovery side — the occurrence is already a fact,
            // so a second dispatch would be a duplicate, and the only thing
            // left to do is write the record that failed to land.
            if let Some((key, evidence, attempts)) =
                self.world.non_send::<Ledger>().recording_failed(work)
            {
                let result = self
                    .world
                    .non_send_mut::<Ledger>()
                    .effects
                    .ensure_outcome(key, evidence);
                match result {
                    Ok(()) => {
                        if self
                            .world
                            .non_send_mut::<Ledger>()
                            .finish_recording(work, evidence, attempts, budget)
                            && evidence == EffectEvidence::Applied
                        {
                            fired = fired.saturating_add(1);
                        }
                        continue;
                    }
                    Err(cause) => {
                        let error = BotError::EffectUnrecorded {
                            key: Box::new(key),
                            evidence,
                            cause: Box::new(DispatchError::Journal(cause)),
                        };
                        self.world
                            .non_send_mut::<Ledger>()
                            .hold_recording(work, evidence, &error);
                        failure = Some(error);
                        break;
                    }
                }
            }

            // Two questions the ledger answers before anything is sent, and
            // they lead to different places. An action an acknowledgement has
            // retired for this generation is *done*, so the walk steps over it
            // exactly as it steps over a false condition: the effect landed, and
            // the generation is the one it landed in. An action an unsettled
            // recovered attempt stands against is *held*, so the walk stops:
            // nothing established that the bytes did not arrive, and the report
            // a caller needs is the one `first_unresolved` renders from the same
            // fact.
            if let Some(action) = self.world.non_send::<Ledger>().action_of(work) {
                let ledger = self.world.non_send::<Ledger>();
                if ledger.generation(step.chain).is_some_and(|(input, event)| {
                    ledger
                        .effects
                        .applied_in(action, step.chain, step.entry, input, event)
                }) {
                    // Retired, not merely stepped over. An entry whose effect
                    // landed owes nothing for this generation, and leaving it
                    // outstanding would report finished work as pending for as
                    // long as the generation lasts.
                    self.world.non_send_mut::<Ledger>().skip(work);
                    continue;
                }
                if ledger.effects.blocks(action) {
                    break;
                }
            }

            // Written *before* the attempt, not after: a tick dropped while the
            // effect is in flight leaves this behind, and a record that says
            // "dispatched, outcome unknown" is what makes the next tick hold the
            // effect instead of replaying it. Both the intent and the prepared
            // dispatch are committed here, so a crash after this line recovers
            // as an unknown rather than as a never-sent. A panic unwinding out
            // of the action is a limit this substrate does not close, and it is
            // stated in the module documentation.
            //
            // The key comes back *from* the ledger rather than being derived
            // beside it. The attempt a caller is handed and the attempt
            // settlement checks have to be one identity, and two derivations of
            // one identity are two identities the moment they disagree.
            let lifetime = self
                .world
                .non_send::<Chains>()
                .0
                .get(step.chain)
                .and_then(|chain| chain.entries.get(step.entry))
                .map_or(EffectLifetime::External, |entry| {
                    entry.action.effect_lifetime()
                });
            let (key, authority) = match self
                .world
                .non_send_mut::<Ledger>()
                .begin_attempt(work, lifetime)
                .await
            {
                Ok(pair) => pair,
                Err(error) => {
                    // The entry is not in a state an attempt can start from, or
                    // a guard refused it. Either way nothing left the process,
                    // and the run stops here rather than guessing what the entry
                    // now means.
                    failure = Some(error);
                    break;
                }
            };

            // The generation check, at the handoff rather than at the mint.
            // Authorization and handing over are two instants, and a replacement
            // landing between them leaves a warrant that was minted legitimately
            // and is now stale; a check that only ran at mint time would let it
            // through. Nothing is awaited before this, so the warrant is
            // presented as close to the handoff as the substrate can put it.
            if let Err(cause) = self
                .world
                .non_send::<Ledger>()
                .effects
                .broker()
                .revalidate(&authority)
            {
                let error = BotError::EffectRefused {
                    cause: DispatchError::Broker(cause),
                };
                self.world
                    .non_send_mut::<Ledger>()
                    .fail(work, &error, key.attempt(), budget);
                failure = Some(error);
                break;
            }

            // Scoped, so the world is borrowed immutably only across the await
            // and the ledger is reachable mutably on either side of it.
            //
            // The value is the transition's binding, not the newest observation.
            // That is the whole of the invariant: this entry was *selected*
            // against the payload its transition was opened under, so it has to
            // be *run* against that same payload. Reading the observation slot
            // here is how a chain comes to refuse against one input and then
            // retry against another, combining two command inputs into one
            // transition's effects. The slot is empty for as long as the binding
            // is out on loan, so there is nothing to reach for by accident.
            let outcome = {
                let chains = self.world.non_send::<Chains>();
                let grants = self.world.resource::<Grants>();
                let bound = self.world.non_send::<Ledger>().bound(step.chain);
                match (chains.0.get(step.chain), bound) {
                    (Some(chain), Some(value)) => match chain.entries.get(step.entry) {
                        Some(entry) => Some(entry.action.run_any(&grants.0, value).await),
                        None => None,
                    },
                    // No chain, or a transition bound to nothing: the entry
                    // stays held by the record written above rather than being
                    // guessed at.
                    _ => None,
                }
            };

            let Some(outcome) = outcome else {
                break;
            };
            // The outcome is written down for the two cases where it is a fact,
            // and deliberately not for the third. `Applied` and `NotApplied` are
            // answers; an indeterminate effect is the *absence* of one, and
            // appending `NotApplied` for it would record a fact the substrate
            // does not have — which is exactly how a recovery path comes to
            // believe a merge did not land.
            let observed = match outcome {
                Ok(_) => Some(EffectEvidence::Applied),
                Err(ref error) => match error.dispatch_certainty() {
                    DispatchCertainty::Refused | DispatchCertainty::NotDelivered => {
                        Some(EffectEvidence::NotApplied)
                    }
                    DispatchCertainty::Unsettled => None,
                    // An action cannot report `Occurred` as its own failure —
                    // that certainty belongs to a post-effect recording
                    // failure. Nothing is appended for it, because the
                    // substrate does not have the fact that arm would record.
                    DispatchCertainty::Occurred => None,
                },
            };
            if let Some(evidence) = observed
                && let Err(cause) = self
                    .world
                    .non_send_mut::<Ledger>()
                    .effects
                    .ensure_outcome(key, evidence)
            {
                // Post-effect: the action already returned and `evidence` is a
                // fact. This is a recording failure, not a pre-dispatch
                // refusal — `EffectRefused` would tell a controller that
                // nothing left the process and that it may replan, which
                // duplicates a known outcome.
                let error = BotError::EffectUnrecorded {
                    key: Box::new(key),
                    evidence,
                    cause: Box::new(DispatchError::Journal(cause)),
                };
                self.world
                    .non_send_mut::<Ledger>()
                    .fail(work, &error, key.attempt(), budget);
                failure = Some(error);
                break;
            }
            match outcome {
                Ok(_) => {
                    if self.world.non_send_mut::<Ledger>().succeed(work) {
                        fired = fired.saturating_add(1);
                    }
                }
                Err(error) => {
                    self.world
                        .non_send_mut::<Ledger>()
                        .fail(work, &error, key.attempt(), budget);
                    failure = Some(error);
                    break;
                }
            }
        }
        // An action failure happens *earlier* in walk order than a condition
        // failure that follows it, so it is the more specific report.
        (fired, failure.or(condition_failure))
    }

    /// Every entry that is not finished, in `(chain, entry)` order.
    ///
    /// Two kinds are reported and [`TransitionHold`] distinguishes them: an
    /// entry still being held — waiting for an attempt or for evidence — and
    /// one given up on, which stays listed so lost work has a name after the
    /// tick that lost it. An empty result means the last transition is fully
    /// handled.
    #[must_use]
    pub fn pending(&self) -> Vec<PendingWork> {
        let budget = self.world.resource::<Policy>().0.max_attempts();
        self.world.non_send::<Ledger>().pending(budget)
    }

    /// Settle an entry whose effect may or may not have happened.
    ///
    /// A held entry is one the substrate cannot decide about on its own, and
    /// retrying it blind is how a bot duplicates a merge, a message, or a
    /// launch. Supply what you know — [`EffectEvidence::Applied`] acknowledges
    /// the effect, [`EffectEvidence::NotApplied`] makes the entry eligible for
    /// an attempt again — and the entry moves.
    ///
    /// An entry that was given up on accepts evidence too, which is how a
    /// caller revives work the attempt budget abandoned.
    ///
    /// The evidence is submitted against the [`PendingWork`] it is about,
    /// rather than against a slot: the value carries the address, the
    /// generation and the attempt, and all three are compared before anything
    /// is read or written. That is what makes the delivery safe to retry — a
    /// caller that never saw its first report acknowledged can send the same
    /// one again and have it answered idempotently, rather than applied a
    /// second time.
    ///
    /// # Errors
    ///
    /// [`BotError::NoSuchWork`] when the entry is not held: it ran, its
    /// condition was false, it has not been reached yet, or its chain holds no
    /// transition at all. Evidence cannot contradict an attempt whose outcome
    /// was recorded, and accepting it silently would let a caller believe an
    /// effect was acknowledged when nothing was.
    ///
    /// [`BotError::EvidenceSuperseded`] when the chain holds a transition whose
    /// revision is not the one the work was read from — the work the caller is
    /// reporting on was superseded, and nothing was changed. Re-read
    /// [`pending`](Self::pending) and report against the generation that is
    /// there now.
    ///
    /// [`BotError::EvidenceStaleAttempt`] when the generation still holds but
    /// the entry has moved on to a later attempt since. The report is about an
    /// attempt that is over, so there is nothing for it to decide; re-read
    /// [`pending`](Self::pending) to see the attempt that is outstanding.
    ///
    /// [`BotError::EvidenceContradicted`] when this generation's entry was
    /// already settled with the opposite evidence. Nothing was changed:
    /// [`Applied`](EffectEvidence::Applied) does not become
    /// [`NotApplied`](EffectEvidence::NotApplied), or the reverse, after the
    /// fact. Repeating the *same* evidence is not a contradiction and succeeds
    /// idempotently, so a caller that never saw its first delivery through can
    /// safely send it again.
    pub fn resolve_effect(
        &mut self,
        key: &EffectKey,
        evidence: EffectEvidence,
    ) -> Result<(), BotError> {
        // A recovered attempt is settled first, and the order is the whole of
        // deliverable F05's second half: a key the journal records as dispatched
        // with no outcome belongs to no live transition, so the ledger's own
        // settlement has nothing to match it against and would answer
        // `NoSuchWork`. It is the one case where "settle it" is the repair for a
        // refusal the substrate itself raised.
        let recovered = self
            .world
            .non_send::<Ledger>()
            .effects
            .unsettled_for(key.action())
            .is_some_and(|held| held == *key);
        if recovered {
            // The generation the acknowledgement covers is the key's own. An
            // `Applied` verdict retires the action for the generation that key
            // names and no other, so a source that moves afterwards gets new
            // work — which is what a new generation *is* — while the generation
            // the effect was produced from never runs it again. Reading the
            // generation off the key rather than off the entry's live
            // transition is what makes this reach the recovered case: a
            // recovered attempt belongs to no live transition, so the entry
            // holds no revision to take it from.
            return self
                .world
                .non_send_mut::<Ledger>()
                .effects
                .settle_recovered(*key, evidence)
                .map_err(|cause| BotError::EffectRefused {
                    cause: DispatchError::Journal(cause),
                });
        }
        let recording = self
            .world
            .non_send::<Ledger>()
            .effects
            .recording_for(key.action())
            .is_some_and(|held| held.key == *key && held.evidence == evidence);
        if recording {
            return self
                .world
                .non_send_mut::<Ledger>()
                .effects
                .settle_recording(*key, evidence)
                .map_err(|cause| BotError::EffectUnrecorded {
                    key: Box::new(*key),
                    evidence,
                    cause: Box::new(DispatchError::Journal(cause)),
                });
        }
        match self
            .world
            .non_send::<Ledger>()
            .classify_settlement(key, evidence)
        {
            // A journal that could not be read is not a settlement fact and
            // must not be reported as one. Nothing has been mutated: the call
            // is a classification, and the caller may repeat it once reads
            // come back (issue #123).
            Err(cause) => Err(BotError::EffectRefused {
                cause: DispatchError::Journal(cause),
            }),
            // Both are success, and deliberately one arm after the journal
            // write: to the caller, a repeat that landed a second time is the
            // same fact as one that landed the first. The append happens
            // *before* either is acknowledged, so a restart cannot resurrect an
            // attempt this process already settled (issue #106).
            Ok(verdict @ (Settled::Decided | Settled::Duplicate)) => {
                self.world
                    .non_send_mut::<Ledger>()
                    .effects
                    .ensure_outcome(*key, evidence)
                    .map_err(|cause| BotError::EffectUnrecorded {
                        key: Box::new(*key),
                        evidence,
                        cause: Box::new(DispatchError::Journal(cause)),
                    })?;
                if verdict == Settled::Decided {
                    self.world
                        .non_send_mut::<Ledger>()
                        .apply_settlement(key, evidence);
                }
                Ok(())
            }
            Ok(Settled::Superseded { id, current }) => Err(BotError::EvidenceSuperseded {
                work: id,
                named: key.digest(),
                current,
            }),
            Ok(Settled::StaleAttempt {
                id,
                reported,
                outstanding,
            }) => Err(BotError::EvidenceStaleAttempt {
                work: id,
                reported,
                outstanding,
            }),
            Ok(Settled::Contradicted { id, settled }) => Err(BotError::EvidenceContradicted {
                work: id,
                settled,
                submitted: evidence,
            }),
            Ok(Settled::NoSuchWork { id: Some(id) }) => Err(BotError::NoSuchWork { work: id }),
            Ok(Settled::NoSuchWork { id: None }) => Err(BotError::ActionNotDeclared {
                action: key.action(),
            }),
        }
    }
}

/// Resolve one spec chain into an erased chain, or record every need it has.
///
/// Returns `None` when the chain contributed any need, so the caller knows not
/// to build it; the needs are appended to `needs` in declaration order. The
/// walk is deliberately exhaustive: an unknown source stops the chain (nothing
/// downstream of a source this binary cannot build is knowable), but a known
/// source with an unknown action still has its condition and its capability
/// requirements checked, because those are facts about the document rather than
/// about the missing action.
fn materialize_chain(
    chain_index: usize,
    chain: &ChainSpec,
    registry: &DomainRegistry,
    grants: &GrantSet,
    needs: &mut Vec<Need>,
) -> Option<EcsChain> {
    let before = needs.len();

    let Some(source_ctor) = registry.source(&chain.source) else {
        needs.push(Need::UnknownSource {
            chain: chain_index,
            domain: chain.source.clone(),
        });
        return None;
    };
    let source = match source_ctor(&chain.target) {
        Ok(source) => source,
        Err(cause) => {
            needs.push(Need::SourceTargetRejected {
                chain: chain_index,
                domain: chain.source.clone(),
                cause: cause.to_string(),
            });
            return None;
        }
    };
    for shortage in grants.uncovered(source.required_caps(), &Demand::new(chain.source.clone())) {
        needs.push(Need::MissingCapability {
            chain: chain_index,
            action: None,
            domain: chain.source.clone(),
            capability: shortage.required().clone(),
        });
    }

    let mut entries: Vec<ChainEntry> = Vec::with_capacity(chain.on.len());
    for (action_index, entry) in chain.on.iter().enumerate() {
        let condition_id: &String = &entry.0;
        let action_spec: &ActionSpec = &entry.1;
        let action = match registry.action(&action_spec.domain) {
            Some(ctor) => match ctor(&action_spec.target) {
                Ok(action) => Some(action),
                Err(cause) => {
                    needs.push(Need::ActionTargetRejected {
                        chain: chain_index,
                        action: action_index,
                        domain: action_spec.domain.clone(),
                        cause: cause.to_string(),
                    });
                    None
                }
            },
            None => {
                needs.push(Need::UnknownAction {
                    chain: chain_index,
                    action: action_index,
                    domain: action_spec.domain.clone(),
                });
                None
            }
        };
        if let Some(ref action) = action {
            for shortage in grants.uncovered(
                action.required_caps(),
                &Demand::new(action_spec.domain.clone()),
            ) {
                needs.push(Need::MissingCapability {
                    chain: chain_index,
                    action: Some(action_index),
                    domain: action_spec.domain.clone(),
                    capability: shortage.required().clone(),
                });
            }
        }
        let condition = match source.condition(condition_id) {
            Ok(condition) => Some(condition),
            Err(_) => {
                needs.push(Need::UnknownCondition {
                    chain: chain_index,
                    action: action_index,
                    condition: condition_id.clone(),
                });
                None
            }
        };
        if let (Some(action), Some(condition)) = (action, condition) {
            entries.push(ChainEntry::erased(
                condition.into_evaluate_any(),
                action.into_execute_any(),
            ));
        }
    }

    if needs.len() == before {
        Some(EcsChain::from_registry(source, entries))
    } else {
        None
    }
}

/// Builder for [`EcsBot`].
pub struct EcsBuilder {
    /// The bot name.
    name: String,
    /// Chains finished so far.
    chains: Vec<EcsChain>,
    /// The retry policy every entry will run under.
    policy: RetryPolicy,
    /// The identity, the fence and the journal every dispatch goes through.
    ///
    /// `None` until [`Self::with_effects`] supplies one, and `build` refuses
    /// while it is. There is no default: a default would be a default
    /// *identity*, and an identity a caller did not choose is one they cannot
    /// recover against — which is precisely the state that makes a restart
    /// resend a merge. A default-off variant of the same bot would be worse
    /// still, because nothing would exercise it.
    effects: Option<EffectScope>,
    /// How long one source poll may take before the tick stops waiting for it.
    ///
    /// A declared bound rather than a hidden one, so a caller who has been
    /// waiting on a wedged source can read the budget from the builder instead of
    /// discovering it as a mystery. Defaults to [`DEFAULT_POLL_DEADLINE`].
    poll_deadline: Duration,
}

impl EcsBuilder {
    /// Set how long one source poll may take before the tick stops waiting for it.
    ///
    /// The bound that makes T06's slow-source half true. A poll that misses it is
    /// dropped mid-flight, commits nothing, leaves its chain's baseline and its
    /// forced-refresh mark standing, and is reported in
    /// [`TickReport::stalled`] — so the chains beside it commit and act in the
    /// same tick rather than waiting on a source that will not answer.
    ///
    /// Bounded at both ends, because both ends are the same fact: a zero budget
    /// cancels every poll before its first poll, and a budget past
    /// [`MAX_POLL_DEADLINE`] is a caller asking for a bot that can still hang.
    /// Both are [`BotError`]s at [`build`](Self::build), not panics and not
    /// silently clamped values, because a clamp is indistinguishable from the
    /// budget the caller asked for.
    ///
    /// ```
    /// # use std::time::Duration;
    /// # use lgwks_bot::broker::Broker;
    /// # use lgwks_bot::effect::{EnvironmentId, FlowRevision, RunId};
    /// # use lgwks_bot::journal::MemoryJournal;
    /// # use lgwks_bot::spec::{EffectIdentity, EffectScope};
    /// # use lgwks_bot::{Bot, BotError, GrantSet};
    /// # fn effects() -> Result<EffectScope, Box<dyn std::error::Error>> {
    /// #     let environment = EnvironmentId::from_hex("2122232425262728292a2b2c2d2e2f30")?;
    /// #     let mut broker = Broker::new();
    /// #     broker.register(environment)?;
    /// #     let identity = EffectIdentity::new(
    /// #         RunId::from_hex("0102030405060708090a0b0c0d0e0f10")?,
    /// #         environment,
    /// #         FlowRevision::from_tagged(
    /// #             "blake3_256",
    /// #             "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
    /// #         )?,
    /// #     );
    /// #     Ok(EffectScope::new(identity, broker, Box::new(MemoryJournal::new())))
    /// # }
    /// let scope = effects()?;
    /// let refused = Bot::builder("zero")
    ///     .with_poll_deadline(Duration::ZERO)
    ///     .with_effects(scope)
    ///     .build(&GrantSet::empty());
    /// assert!(matches!(
    ///     refused,
    ///     Err(BotError::PollDeadlineUnbounded { .. })
    /// ));
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// Defaults to [`DEFAULT_POLL_DEADLINE`] for a caller that never calls this,
    /// which is what makes it a declared policy rather than a hidden constant.
    ///
    /// # Errors
    ///
    /// [`BotError::PollDeadlineUnbounded`] for [`Duration::ZERO`], and
    /// [`BotError::PollDeadlineExceeded`] for a budget above
    /// [`MAX_POLL_DEADLINE`]. Both surface from [`build`](Self::build), so this
    /// call itself cannot fail.
    #[must_use]
    pub fn with_poll_deadline(mut self, deadline: Duration) -> Self {
        self.poll_deadline = deadline;
        self
    }

    /// Set the retry budget for entries whose effect definitely did not happen.
    ///
    /// Additive and defaulted: a caller that never calls this gets
    /// [`RetryPolicy::DEFAULT`], which is what makes the budget a policy rather
    /// than a constant. Without it, "the work was given up on" would be a fact
    /// the caller could not influence, and a bot whose actions are idempotent
    /// would abandon work it could perfectly well retry.
    #[must_use]
    pub fn with_retry_policy(mut self, policy: RetryPolicy) -> Self {
        self.policy = policy;
        self
    }

    /// Bind the identity, the environment fence and the journal every dispatch
    /// goes through.
    ///
    /// Required: [`build`](Self::build) refuses without it, reporting
    /// [`BotError::IncompleteSpec`] with `field: "effects"`. That is the same
    /// idiom the name check uses, and it is deliberate rather than a typestate —
    /// a bot whose dispatch path is optional is a bot with two dispatch paths,
    /// and the estate does not keep two implementations of one job.
    #[must_use]
    pub fn with_effects(mut self, effects: EffectScope) -> Self {
        self.effects = Some(effects);
        self
    }

    /// Append a fully-erased chain, as a materializer builds one.
    ///
    /// The native path finishes a chain through
    /// [`ObserveBuilder::build`], which
    /// erases a concrete source and hands the result to
    /// [`EcsBot::assemble`]. This is the other seam into the same list: a chain
    /// whose source and entries are already erased, built from wire data by
    /// [`Bot::from_spec`]. Both reach `assemble`, so a
    /// materialized bot and a native one are the same value and share one
    /// execution path — there is no second interpreter here.
    ///
    /// Crate-internal: a caller outside cannot build an `EcsChain`, so this is
    /// not a second public builder.
    #[must_use]
    pub(crate) fn chain(mut self, chain: EcsChain) -> Self {
        self.chains.push(chain);
        self
    }

    /// Bind a source to observe.
    ///
    /// The source is *not* erased here. It stays a concrete `S` inside the
    /// returned builder for as long as the chain is being declared, so `on` can
    /// type its condition and its action against `S::Output`; the erasure
    /// happens in [`EcsObserveBuilder::observe`] and
    /// [`EcsObserveBuilder::build`], which are the two points where the chain
    /// stops being a declaration and becomes a chain.
    #[must_use]
    pub fn observe<S>(self, source: S) -> EcsObserveBuilder<S>
    where
        S: Observe,
    {
        EcsObserveBuilder {
            name: self.name,
            prior: self.chains,
            source,
            entries: Vec::new(),
            policy: self.policy,
            effects: self.effects,
            poll_deadline: self.poll_deadline,
        }
    }

    /// Build with no observation chains: a bot that only serves direct
    /// `Query` and `Execute` calls.
    ///
    /// # Errors
    ///
    /// Whatever [`EcsBuilder::with_poll_deadline`] documents, plus the same
    /// admission refusals every other build of a bot raises.
    pub fn build(self, grants: &GrantSet) -> Result<EcsBot, BotError> {
        EcsBot::assemble(
            self.name,
            self.chains,
            grants,
            self.policy,
            self.effects,
            self.poll_deadline,
        )
    }
}

impl<S: Observe> EcsObserveBuilder<S> {
    /// Bind the effect path, as [`EcsBuilder::with_effects`] does.
    ///
    /// Offered here as well so the call can sit anywhere in the declaration
    /// chain — after the last `on` as naturally as before the first `observe` —
    /// rather than only at the one point the builder happens to hand it over.
    #[must_use]
    pub fn with_effects(mut self, effects: EffectScope) -> Self {
        self.effects = Some(effects);
        self
    }

    /// Add a `(condition, action)` tuple to this chain.
    ///
    /// Both halves are typed against the source this chain is observing: the
    /// condition reads `S::Output`, and the action takes exactly it. There is no
    /// third type parameter, and that is the point — the shape this replaced had
    /// one (`on<C, A, T>`) which was tied to nothing at all, so a chain whose
    /// condition read one type and whose action expected another compiled, built,
    /// and failed at tick time with a downcast miss. A wiring defect that
    /// compiles is a defect that ships.
    ///
    /// The tuple's erasure is shared with the `Bot` executor rather than
    /// re-implemented, so the `Auth` issue, the downcast and the type-mismatch
    /// error cannot drift between the two substrates.
    ///
    /// # The rule this relies on
    ///
    /// Equal types across the chain is sound only because every verb so far
    /// consumes its input and produces a caller-visible one: [`Evaluate::check`]
    /// returns a `bool`, a pure predicate with no derived output, so
    /// `Source::Output == Condition::Input == Action::Input` is already the real
    /// semantics rather than a simplification of it.
    ///
    /// **No stage may introduce a caller-selected type parameter disconnected
    /// from its input.** A stage that transforms the value must carry the
    /// transformation as an associated type — `Transform<I>::Output` — so the
    /// next stage's input is a consequence of the previous one's output. A free
    /// parameter here is how this defect happened once, and it will happen again
    /// the first time a verb takes a type the chain does not determine.
    #[must_use]
    pub fn on<C, A>(mut self, condition: C, action: A) -> Self
    where
        S::Output: 'static,
        C: Evaluate<S::Output> + 'static,
        A: Execute<Input = S::Output> + 'static,
        A::Output: 'static,
    {
        self.entries
            .push(typed_entry::<C, A, S::Output>(condition, action));
        self
    }

    /// Finish this chain and start another.
    ///
    /// The erasure boundary for the chain being closed: `S` stops being a type
    /// parameter here, and the witness is taken in the same breath, while
    /// `S::Output` can still be named.
    ///
    /// The `PartialEq` bound is the substrate's one extra requirement, and it is
    /// semantic rather than incidental: the condition on this substrate *is*
    /// change detection, and a value that cannot be compared cannot be detected
    /// as changed. [`Bot::builder`](crate::Bot::builder) carries no such bound
    /// because its condition is re-evaluated every tick and needs no equality.
    #[must_use]
    pub fn observe<U>(self, source: U) -> EcsObserveBuilder<U>
    where
        S: 'static,
        S::Output: PartialEq + InputIdentity + 'static,
        U: Observe,
    {
        // Destructured rather than moved field by field: taking `prior` by
        // `mem::take` and then moving `source` out leaves `self` partially
        // moved, and the borrow checker will not let a method call finish the
        // chain in between.
        let Self {
            name,
            mut prior,
            source: previous,
            entries,
            policy,
            effects,
            poll_deadline,
        } = self;
        prior.push(EcsChain {
            source: Box::new(previous),
            same: same_output::<S>,
            identify: identify_output::<S>,
            witness: Witness::of::<S::Output>(),
            entries,
        });
        EcsObserveBuilder {
            name,
            prior,
            source,
            entries: Vec::new(),
            policy,
            effects,
            poll_deadline,
        }
    }

    /// Assemble the bot, admitting every capability and validating the schedule.
    ///
    /// The erasure boundary for the last chain, for the same reason as
    /// [`observe`](Self::observe), and the one call that turns a declaration into
    /// a running bot.
    pub fn build(self, grants: &GrantSet) -> Result<EcsBot, BotError>
    where
        S: 'static,
        S::Output: PartialEq + InputIdentity + 'static,
    {
        let Self {
            name,
            mut prior,
            source,
            entries,
            policy,
            effects,
            poll_deadline,
        } = self;
        prior.push(EcsChain {
            source: Box::new(source),
            same: same_output::<S>,
            identify: identify_output::<S>,
            witness: Witness::of::<S::Output>(),
            entries,
        });
        EcsBot::assemble(name, prior, grants, policy, effects, poll_deadline)
    }
}

/// A chain being assembled, holding its source as the concrete type it is.
///
/// Generic over the source so that [`on`](Self::on) can type a condition and an
/// action against `S::Output`. The type parameter is the chain's one claim about
/// its own wiring, and it is checked by the compiler rather than by a downcast:
/// a `(condition, action)` tuple attached here has both halves typed against the
/// source, so a chain that cannot work does not build.
///
/// `S` is erased at [`observe`](Self::observe) and [`build`](Self::build), which
/// are the only two points where the chain is finished. There is no third state
/// between "declaring a chain" and "a chain": the builder cannot be stored,
/// serialized, or passed to anything that expects an `EcsChain`, because it is
/// not one until the erasure runs.
pub struct EcsObserveBuilder<S> {
    /// Carried from [`EcsBuilder`]; the chain being built does not consume it.
    name: String,
    /// Carried from [`EcsBuilder`] alongside `name`. Taken by the terminal
    /// `build`, which is the only place it is needed.
    effects: Option<EffectScope>,
    /// Chains finished by an earlier `observe` call, in order.
    prior: Vec<EcsChain>,
    /// The source being bound, still concrete.
    source: S,
    /// Tuples attached so far, each already erased for storage.
    entries: Vec<ChainEntry>,
    /// Carried from [`EcsBuilder`] alongside `policy`.
    policy: RetryPolicy,
    /// Carried from [`EcsBuilder`] alongside `policy`.
    poll_deadline: Duration,
}

impl EcsBot {
    /// Validate and assemble. Shared by both terminal builder calls so
    /// admission cannot drift between them, the same rule
    /// [`spec::assemble`](crate::spec) follows for `Bot`.
    fn assemble(
        name: String,
        chains: Vec<EcsChain>,
        grants: &GrantSet,
        policy: RetryPolicy,
        effects: Option<EffectScope>,
        poll_deadline: Duration,
    ) -> Result<Self, BotError> {
        if name.is_empty() {
            let refusal = Err(BotError::IncompleteSpec {
                field: "name",
                cause: String::from("the bot was given an empty name"),
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "assemble: returning an error to the caller");
            return refusal;
        }
        // Refused before anything is built or polled, and for the same reason the
        // name is: a budget of zero cancels every poll before its first poll, so
        // a bot built with one observes nothing forever and reports every chain
        // as stalled. A refusal here names the number and the repair rather than
        // producing a bot whose every tick is a cancellation.
        if poll_deadline.is_zero() {
            let refusal = Err(BotError::PollDeadlineUnbounded {
                deadline: poll_deadline,
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "assemble: returning an error to the caller");
            return refusal;
        }
        if poll_deadline > MAX_POLL_DEADLINE {
            let refusal = Err(BotError::PollDeadlineExceeded {
                deadline: poll_deadline,
                ceiling: MAX_POLL_DEADLINE,
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "assemble: returning an error to the caller");
            return refusal;
        }
        // Refused before the capability gate, because a bot that cannot record
        // a dispatch is not a bot that is missing a capability — it is one that
        // was never given a dispatch path, and the repair is different.
        let Some(effects) = effects else {
            let refusal = Err(BotError::IncompleteSpec {
                field: "effects",
                cause: String::from(
                    "no effect scope was supplied, so a dispatch could not be recorded",
                ),
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "assemble: returning an error to the caller");
            return refusal;
        };
        // What recovery found, folded in before the world exists. A key naming
        // an action this bot does not declare is a foreign journal — the
        // record belongs to a different bot or a different revision of this
        // one — and it is refused here rather than ignored, because ignoring it
        // means dispatching an action whose earlier attempt the journal says
        // may be live.
        let committed = effects
            .journal()
            .committed()
            .map_err(|cause| BotError::EffectRefused {
                cause: DispatchError::Journal(cause),
            })?;
        let tail = effects.journal().tail();
        // A committed count that cannot be a sequence number means the journal
        // holds more events than the sequence can name, which is exhaustion.
        let recovered_events = match u64::try_from(committed.len()) {
            Ok(count) => count,
            Err(_too_many_events) => {
                let refusal = Err(BotError::EffectRefused {
                    cause: DispatchError::Journal(JournalError::Exhausted),
                });
                lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "assemble: returning an error to the caller");
                return refusal;
            }
        };
        if recovered_events != tail.sequence() {
            let refusal = Err(BotError::EffectRefused {
                cause: DispatchError::Journal(JournalError::SnapshotStale {
                    recovered_events,
                    committed_events: tail.sequence(),
                }),
            });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "assemble: returning an error to the caller");
            return refusal;
        }
        let recovered = recover(committed.iter());
        // The same admission gate `Bot::build` applies: a bot requiring a
        // capability it was not granted fails before it runs, not at tick.
        //
        // Every unmet requirement in the bot, from one pass, each attributed to
        // the domain that declared it. Admission that returned at the first one
        // made "what does this bot need" a loop: each answer revealed the next
        // question, so a bot short of four capabilities took four refusals to
        // diagnose and the fourth was the first time the caller had the whole
        // picture. The gate already computes the whole difference — it is the
        // required set minus the granted set — so it reports the whole of it,
        // and the caller has one list to act on rather than a sequence to
        // discover.
        let mut shortages: Vec<Shortage> = Vec::new();
        for chain in &chains {
            shortages.extend(grants.uncovered(
                chain.source.required_caps(),
                &Demand::new(chain.source.domain_id()),
            ));
            for entry in &chain.entries {
                shortages.extend(grants.uncovered(
                    entry.action.required_caps(),
                    &Demand::new(entry.action.domain_id()),
                ));
            }
        }
        if let Some(deficit) = Deficit::from_shortages(shortages) {
            let refusal = Err(BotError::CapabilityDenied { deficit });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "assemble: returning an error to the caller");
            return refusal;
        }

        let mut world = World::new();
        world.insert_resource(Grants(grants.clone()));
        world.insert_resource(Fired::default());
        world.insert_resource(TickError::default());
        world.insert_resource(Policy(policy));
        world.insert_resource(PollBudget(poll_deadline));

        let mut order = Vec::with_capacity(chains.len());
        for (index, chain) in chains.iter().enumerate() {
            order.push(
                world
                    .spawn((
                        SourceId {
                            chain: index,
                            domain: chain.source.domain_id().to_owned(),
                        },
                        Revision::default(),
                    ))
                    .id(),
            );
        }
        world.insert_resource(Order(order));

        let count = chains.len();
        // The declared action identity of every entry, derived once here and
        // indexed exactly as the chains are. `derive_action_id` is the single
        // producer of an `ActionId` in this crate: a second derivation anywhere
        // else would be a second identity for the same entry.
        let actions: Vec<Vec<ActionId>> = chains
            .iter()
            .enumerate()
            .map(|(chain, held)| {
                held.entries
                    .iter()
                    .enumerate()
                    .map(|(entry, declared)| {
                        derive_action_id(&name, chain, entry, declared.action.domain_id())
                    })
                    .collect()
            })
            .collect();
        // The next admitted-input identity continues past whatever the journal
        // already holds, so a reconstructed bot cannot reissue a stamp an
        // earlier process bound a dispatch to (issue #101).
        let next_input = tail.sequence().saturating_add(1);
        let mut ledger = Ledger::new(actions, Effects::new(effects, tail), next_input);
        // Every attempt the journal names, folded in. Not only the uncertain
        // ones: an attempt whose outcome is recorded is a fact about this run
        // too, and the two things this loop derives from it are what let a
        // restarted run continue instead of stopping at the first entry the
        // previous process touched.
        //
        //   - the attempt the action must mint next, because the journal has
        //     already walked its ladder for the attempts below it and a
        //     repeated `IntentAdmitted` for one of them is an out-of-order
        //     append rather than a dispatch;
        //   - the attempts whose effect landed, which the walk retires rather
        //     than dispatching again.
        for attempt in recovered.attempts() {
            let key = attempt.key();
            let Some(id) = ledger.locate(key.action()) else {
                let refusal = Err(BotError::ActionNotDeclared {
                    action: key.action(),
                });
                lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "assemble: returning an error to the caller");
                return refusal;
            };
            // The journal's key must name this run, this flow, and this
            // environment. A journal that holds keys from any of the others is
            // the foreign-journal case one step finer: the action matches, the
            // ownership identity does not, and folding it in would dispatch an
            // action whose earlier attempt belongs to a different bot (issue
            // #101).
            let identity = ledger.effects.identity();
            if key.run() != identity.run()
                || key.flow() != identity.flow()
                || key.environment() != identity.environment()
            {
                let refusal = Err(BotError::ActionNotDeclared {
                    action: key.action(),
                });
                lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "assemble: returning an error to the caller");
                return refusal;
            }
            let _ = id;
            ledger
                .effects
                .note_journal_attempt(key.action(), key.attempt());
            match attempt.status() {
                // A dispatch with no outcome. Nothing established that the
                // bytes did not arrive, so the action is held until a caller
                // settles it.
                AttemptStatus::OutcomeUnknown => ledger.effects.unsettled.push(key),
                // A durable journal needs a positioned receipt before replay
                // treats a known outcome as settled. The record alone may have
                // landed below its advertised grade.
                // A failed predicate is an effect that landed, so it is never
                // resent; the failure is read from the status, not from here.
                AttemptStatus::Applied
                | AttemptStatus::Verified
                | AttemptStatus::VerificationFailed => {
                    if ledger.effects.scope.journal().durability() == DurabilityPromise::Ephemeral {
                        ledger.effects.note_applied(key);
                    } else if let Err(cause) = ledger
                        .effects
                        .confirm_recorded_outcome(key, EffectEvidence::Applied)
                    {
                        ledger.effects.recording.push(RecordedOutcome {
                            key,
                            evidence: EffectEvidence::Applied,
                            cause,
                        });
                    } else {
                        ledger.effects.note_applied(key);
                    }
                }
                // Nothing to hold. `Prepared` means the intent was admitted and
                // nothing was handed over, and `NotApplied` means exactly that
                // the bytes did not arrive; both leave the entry free to be
                // attempted again, under the next attempt identity.
                AttemptStatus::Prepared => {}
                AttemptStatus::NotApplied => {
                    if ledger.effects.scope.journal().durability() != DurabilityPromise::Ephemeral
                        && let Err(cause) = ledger
                            .effects
                            .confirm_recorded_outcome(key, EffectEvidence::NotApplied)
                    {
                        ledger.effects.recording.push(RecordedOutcome {
                            key,
                            evidence: EffectEvidence::NotApplied,
                            cause,
                        });
                    }
                }
            }
        }
        world.insert_non_send(Chains(chains));
        // Not `vec![None; count]`: `Box<dyn Any>` is not `Clone`, so the
        // repeat-form macro cannot build this.
        world.insert_non_send(Observed((0..count).map(|_| None).collect()));
        // The eligible work of the bot, one idle slot per chain. Non-send,
        // because each transition owns the observed payload it is bound to.
        world.insert_non_send(ledger);
        // The two staging resources the awaited phases hand to the schedule.
        // Inserted here rather than at first use so every phase can name them
        // unconditionally: a phase that found one missing would have to decide
        // what that means, and there is no answer that is better than "this
        // cannot happen".
        world.insert_non_send(Polled::default());
        // The change ticks, sized here so neither buffer is ever resized on the
        // observation path. `seen` starts empty of revisions: a chain with no
        // committed value has nothing a source's revision could equal, so its
        // first tick is a poll like any other.
        world.insert_non_send(ChangeTicks {
            seen: vec![None; count],
            polled: vec![None; count],
        });
        // The change flags and the plan's buffers are per-tick scratch, inserted
        // here so the first tick allocates them once and every later tick reuses
        // the same allocations. Nothing else writes them.
        world.insert_non_send(AdmitScratch::default());
        world.insert_non_send(Moved::default());
        world.insert_non_send(Plan::default());
        // The observation phase's own scratch, empty on purpose: the first tick
        // sizes these to the world and every tick after reuses that capacity,
        // which is the whole of how a tick that changed nothing came to cost no
        // allocations at all.
        world.insert_non_send(PollScratch::default());
        // One slot per chain, sized here so the observation phase never resizes
        // it: a `resize` per tick would be an allocation the first time and a
        // capacity check every tick after, for a buffer whose length is the
        // chain count and is already known.
        world.insert_non_send(Invalidated {
            reasons: vec![None; count],
        });
        // Same shape and the same reason: the supersession check asks one
        // question per chain, and a walk of the transitions to answer it would
        // be a per-chain scan on every tick for a question that has one.
        world.insert_non_send(Committed {
            slots: vec![SlotAdmission::default(); count],
        });
        // A resource rather than a field on the bot, so the observation phase
        // and the schedule step — two functions that can only reach the world —
        // write one record and `tick_report` reads the same one they wrote.
        world.insert_resource(TickReport::default());

        let mut schedule = schedule();
        validate(&mut schedule, &mut world)?;

        Ok(Self {
            name,
            world,
            schedule,
            poll_deadline,
        })
    }
}

// ── `Debug` for the assembled bot and its two builders ─────────────────────
//
// Written as impls rather than derives because a derive line added above a type
// would renumber the citations the module's own docs make by line number, and
// because `EcsObserveBuilder<S>` and `EcsBuilder` hold `dyn` seams that no
// derive can cross. Each rendering reports the shape a caller can act on — the
// name, how many chains or entries are staged, the retry policy — and stops
// short of the engine's own state through `finish_non_exhaustive`, which marks
// the omission instead of hiding it.

impl core::fmt::Debug for EcsBot {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("EcsBot")
            .field("name", &self.name)
            .finish_non_exhaustive()
    }
}

impl core::fmt::Debug for EcsBuilder {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("EcsBuilder")
            .field("name", &self.name)
            .field("chains", &self.chains.len())
            .field("policy", &self.policy)
            .finish()
    }
}

impl<S> core::fmt::Debug for EcsObserveBuilder<S> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("EcsObserveBuilder")
            .field("name", &self.name)
            .field("prior", &self.prior.len())
            .field("entries", &self.entries.len())
            .field("policy", &self.policy)
            .finish_non_exhaustive()
    }
}

// ── Tests ──────────────────────────────────────────────────────────────────
//
// These run under the ordinary workspace test run: there is no feature to turn
// on, because a substrate whose tests only run when someone remembers a flag is
// a substrate whose guarantees are claims.

#[cfg(test)]
pub(super) mod tests {
    use std::cell::{Cell, RefCell};
    use std::future::Future;
    use std::marker::PhantomData;
    use std::rc::Rc;
    use std::task::{Context, Poll, Waker};

    use super::*;
    use crate::EventId;
    use crate::cap::{Auth, Cap, Demand};
    use crate::effect::{EnvironmentId, RunId};
    use crate::journal::{DurabilityPromise, DurableAck, JournalPosition, MemoryJournal};
    use std::io;

    type TestResult = Result<(), Box<dyn std::error::Error>>;

    /// A domain refusal from a test source, recorded before it is returned.
    ///
    /// Every fixture that refuses says the same three things — which domain, that
    /// nothing was delivered, and why — so they say it here once.
    fn domain_refusal<T>(domain: &str, cause: &str) -> Result<T, BotError> {
        let refusal = Err(BotError::DomainError {
            domain: domain.into(),
            certainty: DispatchCertainty::NotDelivered,
            cause: cause.into(),
        });
        lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "a test source refused its poll");
        refusal
    }

    /// A scripted source: yields the next value from `values` on each poll,
    /// and refuses a poll past the end of its script rather than inventing one.
    ///
    /// Deliberately `Rc`-based and therefore `!Send`, which is the property the
    /// verbs actually have and the reason this whole module routes through
    /// `NonSend` resources.
    struct Script {
        values: Rc<RefCell<Vec<u16>>>,
        cursor: Rc<Cell<usize>>,
        caps: Vec<Cap>,
    }

    impl Script {
        fn new(values: Vec<u16>) -> Self {
            Self {
                values: Rc::new(RefCell::new(values)),
                cursor: Rc::new(Cell::new(0)),
                caps: vec![Cap::net()],
            }
        }
    }

    impl Observe for Script {
        type Output = u16;

        fn required_caps(&self) -> &[Cap] {
            &self.caps
        }

        async fn poll(&self, call: (Auth, ())) -> Result<u16, BotError> {
            call.0.check(&self.caps)?;
            let index = self.cursor.get();
            self.cursor.set(index.saturating_add(1));
            match self.values.borrow().get(index).copied() {
                Some(value) => Ok(value),
                None => domain_refusal("test::script", "polled past the end of its script"),
            }
        }

        fn domain_id(&self) -> &str {
            "test::script"
        }
    }

    /// A source that reports one value and then holds it for every later poll.
    ///
    /// The counterpart to [`Script`], which advances on every call. A chain over
    /// a scripted source moves on every tick, so it cannot tell "the chain ran
    /// once" from "the chain runs every tick" — both look like work. This one
    /// moves exactly once and then stands still, which is the shape that makes a
    /// chain re-running settled work visible as a count rather than as a
    /// coincidence.
    struct Holds {
        value: u16,
        caps: Vec<Cap>,
    }

    impl Holds {
        fn new(value: u16) -> Self {
            Self {
                value,
                caps: vec![Cap::net()],
            }
        }
    }

    impl Observe for Holds {
        type Output = u16;

        fn required_caps(&self) -> &[Cap] {
            &self.caps
        }

        async fn poll(&self, call: (Auth, ())) -> Result<u16, BotError> {
            call.0.check(&self.caps)?;
            Ok(self.value)
        }

        fn domain_id(&self) -> &str {
            "test::holds"
        }
    }

    /// A source that counts how often it is asked for a value, and can answer
    /// "has anything moved?" without being asked at all.
    ///
    /// The counter is the point. `Holds` proves *what* a settled chain does;
    /// this proves *how much it costs* — specifically that a quiet tick does
    /// not call `poll`, which is the difference between the tick paying for a
    /// value and the tick paying for a `u128`.
    struct Counted {
        value: Rc<Cell<u16>>,
        polls: Rc<Cell<usize>>,
        caps: Vec<Cap>,
    }

    impl Counted {
        fn new(value: u16, polls: Rc<Cell<usize>>) -> Self {
            Self {
                value: Rc::new(Cell::new(value)),
                polls,
                caps: vec![Cap::net()],
            }
        }
    }

    impl Observe for Counted {
        type Output = u16;

        fn required_caps(&self) -> &[Cap] {
            &self.caps
        }

        async fn poll(&self, call: (Auth, ())) -> Result<u16, BotError> {
            call.0.check(&self.caps)?;
            self.polls.set(self.polls.get().saturating_add(1));
            Ok(self.value.get())
        }

        fn fingerprint(&self) -> Option<u128> {
            Some(u128::from(self.value.get()))
        }

        fn domain_id(&self) -> &str {
            "test::counted"
        }
    }

    /// A source that reports a change tick as well as a value.
    struct Rev {
        value: Rc<Cell<u64>>,
        rev: Rc<Cell<u64>>,
        polls: Rc<Cell<usize>>,
        caps: Vec<Cap>,
    }

    impl Observe for Rev {
        type Output = u64;

        fn required_caps(&self) -> &[Cap] {
            &self.caps
        }

        async fn poll(&self, call: (Auth, ())) -> Result<u64, BotError> {
            call.0.check(&self.caps)?;
            self.polls.set(self.polls.get().saturating_add(1));
            Ok(self.value.get())
        }

        fn revision(&self) -> Option<u64> {
            Some(self.rev.get())
        }

        fn domain_id(&self) -> &str {
            "test::rev"
        }
    }

    /// An action over a `u64`, counting its own calls.
    struct CountU64(Rc<Cell<usize>>);

    impl Execute for CountU64 {
        type Input = u64;
        type Output = ();

        fn required_caps(&self) -> &[Cap] {
            &[]
        }

        fn effect_lifetime(&self) -> EffectLifetime {
            EffectLifetime::Local
        }

        async fn execute_action(&self, call: (Auth, &u64)) -> Result<(), BotError> {
            call.0.check(&[])?;
            self.0.set(self.0.get().saturating_add(1));
            Ok(())
        }

        fn domain_id(&self) -> &'static str {
            "test::count_u64"
        }
    }

    #[test]
    fn a_change_tick_source_fires_once_per_movement_and_is_not_polled_otherwise() -> TestResult {
        let value = Rc::new(Cell::new(0u64));
        let rev = Rc::new(Cell::new(0u64));
        let polls = Rc::new(Cell::new(0usize));
        let counter = Rc::new(Cell::new(0usize));
        let mut bot = EcsBot::builder("revs")
            .observe(Rev {
                value: Rc::clone(&value),
                rev: Rc::clone(&rev),
                polls: Rc::clone(&polls),
                caps: Vec::new(),
            })
            .on(
                |value: &u64| value.is_multiple_of(2),
                CountU64(Rc::clone(&counter)),
            )
            .with_effects(test_effects()?)
            .build(&GrantSet::empty())?;
        let mut fired = Vec::new();
        for step in 0..6u64 {
            // The value and the revision move together, every other tick: the
            // promise `Observe::revision` asks for, kept in both directions.
            // Halving a `u64` by a literal cannot overflow or divide by zero,
            // so the refusal is a statement about that rather than a path a
            // reader has to imagine.
            let held = step
                .checked_div(2)
                .ok_or("halving a u64 by two cannot fail")?;
            value.set(held);
            rev.set(held);
            fired.push(bot.tick()?);
        }
        // The value steps 0, 0, 1, 1, 2, 2 and the revision steps with it. Tick 2
        // moves to an **odd** value, so the condition runs and answers false —
        // which is the half the skip must not lose: a movement is evaluated, and
        // only a tick that did not move is skipped.
        assert_eq!(
            fired,
            vec![1, 0, 0, 0, 1, 0],
            "one fire per even movement and nothing while the revision holds: {fired:?}"
        );
        assert_eq!(
            polls.get(),
            3,
            "a skipped chain is not polled at all, so three movements are three polls"
        );
        assert_eq!(
            bot.pending(),
            Vec::new(),
            "a value that moves must be acted on, and a chain with nothing outstanding \
             must not be reported"
        );
        Ok(())
    }

    /// A source that fails once its script runs out.
    struct Exhausting {
        remaining: Rc<Cell<usize>>,
        caps: Vec<Cap>,
    }

    impl Observe for Exhausting {
        type Output = u16;

        fn required_caps(&self) -> &[Cap] {
            &self.caps
        }

        async fn poll(&self, call: (Auth, ())) -> Result<u16, BotError> {
            call.0.check(&self.caps)?;
            let left = self.remaining.get();
            self.remaining.set(left.saturating_sub(1));
            if left == 0 {
                return domain_refusal("test::exhausting", "script exhausted");
            }
            Ok(200)
        }

        fn domain_id(&self) -> &str {
            "test::exhausting"
        }
    }

    /// A source with a digest that can fail on demand and counts its polls.
    ///
    /// The fingerprint is pure and answers even while `fail` is set, which is
    /// the contract `Observe::fingerprint` states and the shape that makes the
    /// sibling-poll bug reachable: the digest moves (or never committed), the
    /// poll runs and fails, and a cache that published the digest early would
    /// skip the source on every later tick.
    struct Switched {
        value: Rc<Cell<u16>>,
        fail: Rc<Cell<bool>>,
        polls: Rc<Cell<usize>>,
        caps: Vec<Cap>,
    }

    impl Switched {
        fn new(value: u16, fail: bool, polls: Rc<Cell<usize>>) -> Self {
            Self {
                value: Rc::new(Cell::new(value)),
                fail: Rc::new(Cell::new(fail)),
                polls,
                caps: vec![Cap::net()],
            }
        }
    }

    impl Observe for Switched {
        type Output = u16;

        fn required_caps(&self) -> &[Cap] {
            &self.caps
        }

        async fn poll(&self, call: (Auth, ())) -> Result<u16, BotError> {
            call.0.check(&self.caps)?;
            self.polls.set(self.polls.get().saturating_add(1));
            if self.fail.get() {
                return domain_refusal("test::switched", "switch is off");
            }
            Ok(self.value.get())
        }

        fn fingerprint(&self) -> Option<u128> {
            // No digest while the switch is off: a source that cannot produce a
            // value has none to offer a cheap key for, and `None` is the
            // contract's "must poll" answer. A stable digest across a failure
            // would let the cache skip the source and swallow the error.
            if self.fail.get() {
                None
            } else {
                Some(u128::from(self.value.get()))
            }
        }

        fn domain_id(&self) -> &str {
            "test::switched"
        }
    }

    /// A source that returns `Pending` once and then answers, with a digest.
    ///
    /// Exists so a tick can be dropped mid-poll without hanging the test: the
    /// first `poll` of the source's future parks, the caller drops the tick,
    /// and the second tick finds the yield already spent and completes.
    struct Yielding {
        value: u16,
        yielded: Rc<Cell<bool>>,
        polls: Rc<Cell<usize>>,
        caps: Vec<Cap>,
    }

    impl Yielding {
        fn new(value: u16, yielded: Rc<Cell<bool>>, polls: Rc<Cell<usize>>) -> Self {
            Self {
                value,
                yielded,
                polls,
                caps: vec![Cap::net()],
            }
        }
    }

    impl Observe for Yielding {
        type Output = u16;

        fn required_caps(&self) -> &[Cap] {
            &self.caps
        }

        async fn poll(&self, call: (Auth, ())) -> Result<u16, BotError> {
            call.0.check(&self.caps)?;
            self.polls.set(self.polls.get().saturating_add(1));
            let flag = Rc::clone(&self.yielded);
            std::future::poll_fn(move |cx| {
                if flag.get() {
                    Poll::Ready(())
                } else {
                    flag.set(true);
                    cx.waker().wake_by_ref();
                    Poll::Pending
                }
            })
            .await;
            Ok(self.value)
        }

        fn fingerprint(&self) -> Option<u128> {
            Some(u128::from(self.value))
        }

        fn domain_id(&self) -> &str {
            "test::yielding"
        }
    }

    /// A source whose poll deliberately spans two externally controlled state
    /// changes. Its digest remains an honest read of the live value; the test
    /// uses the pauses to place those reads around the A → B → A schedule.
    struct AbaSource {
        value: Rc<Cell<u16>>,
        phase: Rc<Cell<u8>>,
        polls: Rc<Cell<usize>>,
        caps: Vec<Cap>,
    }

    impl AbaSource {
        fn new(value: Rc<Cell<u16>>, phase: Rc<Cell<u8>>, polls: Rc<Cell<usize>>) -> Self {
            Self {
                value,
                phase,
                polls,
                caps: vec![Cap::net()],
            }
        }
    }

    impl Observe for AbaSource {
        type Output = u16;

        fn required_caps(&self) -> &[Cap] {
            &self.caps
        }

        async fn poll(&self, call: (Auth, ())) -> Result<u16, BotError> {
            call.0.check(&self.caps)?;
            self.polls.set(self.polls.get().saturating_add(1));
            let value = Rc::clone(&self.value);
            let phase = Rc::clone(&self.phase);
            let captured = Rc::new(Cell::new(0));
            let captured = std::future::poll_fn(move |cx| match phase.get() {
                0 => {
                    phase.set(1);
                    cx.waker().wake_by_ref();
                    Poll::Pending
                }
                1 => {
                    captured.set(value.get());
                    phase.set(2);
                    cx.waker().wake_by_ref();
                    Poll::Pending
                }
                _ => {
                    phase.set(0);
                    Poll::Ready(captured.get())
                }
            })
            .await;
            Ok(captured)
        }

        fn fingerprint(&self) -> Option<u128> {
            Some(u128::from(self.value.get()))
        }

        fn domain_id(&self) -> &str {
            "test::aba"
        }
    }

    /// An action that counts how many times it ran.
    struct Count(Rc<Cell<usize>>);

    impl Execute for Count {
        type Input = u16;
        type Output = ();

        fn required_caps(&self) -> &[Cap] {
            &[]
        }

        fn effect_lifetime(&self) -> EffectLifetime {
            EffectLifetime::Local
        }

        async fn execute_action(&self, call: (Auth, &u16)) -> Result<(), BotError> {
            call.0.check(&[])?;
            self.0.set(self.0.get().saturating_add(1));
            Ok(())
        }

        fn domain_id(&self) -> &str {
            "test::count"
        }
    }

    /// An action that records what it saw, so a test can assert on a
    /// *persistent* effect rather than on a call count.
    struct Record(Rc<RefCell<Vec<u16>>>);

    impl Execute for Record {
        type Input = u16;
        type Output = ();

        fn required_caps(&self) -> &[Cap] {
            &[]
        }

        fn effect_lifetime(&self) -> EffectLifetime {
            EffectLifetime::Local
        }

        async fn execute_action(&self, call: (Auth, &u16)) -> Result<(), BotError> {
            call.0.check(&[])?;
            self.0.borrow_mut().push(*call.1);
            Ok(())
        }

        fn domain_id(&self) -> &str {
            "test::record"
        }
    }

    /// An action that fails a fixed number of times and then records: the
    /// retry half of a chain, with a persistent effect to assert on.
    struct Flaky {
        remaining: Rc<Cell<usize>>,
        log: Rc<RefCell<Vec<u16>>>,
        kind: FlakyKind,
    }

    /// Which failure the action reports, because the two are not the same
    /// question and the substrate must treat them differently.
    #[derive(Clone, Copy)]
    enum FlakyKind {
        /// The effect definitely did not happen.
        Refused,
        /// The effect may or may not have happened.
        Indeterminate,
    }

    impl Execute for Flaky {
        type Input = u16;
        type Output = ();

        fn required_caps(&self) -> &[Cap] {
            &[]
        }

        fn effect_lifetime(&self) -> EffectLifetime {
            EffectLifetime::Local
        }

        async fn execute_action(&self, call: (Auth, &u16)) -> Result<(), BotError> {
            call.0.check(&[])?;
            let left = self.remaining.get();
            if left == 0 {
                self.log.borrow_mut().push(*call.1);
                return Ok(());
            }
            self.remaining.set(left.saturating_sub(1));
            Err(match self.kind {
                FlakyKind::Refused => BotError::DomainError {
                    domain: "test::flaky".into(),
                    certainty: DispatchCertainty::NotDelivered,
                    cause: "refused, and the effect did not happen".into(),
                },
                FlakyKind::Indeterminate => BotError::EffectIndeterminate {
                    domain: "test::flaky".into(),
                    cause: "the acknowledgment never arrived".into(),
                },
            })
        }

        fn domain_id(&self) -> &str {
            "test::flaky"
        }
    }

    /// The `(chain, entry)` identity of a pending report.
    fn identity(work: &PendingWork) -> (usize, usize) {
        (work.id().chain(), work.id().entry())
    }

    /// The identities of every pending report, in order.
    fn identities(bot: &EcsBot) -> Vec<(usize, usize)> {
        bot.pending().iter().map(identity).collect()
    }

    /// What is holding the first pending report, if anything is pending.
    fn first_hold(bot: &EcsBot) -> Option<TransitionHold> {
        bot.pending().first().map(|work| work.hold().clone())
    }

    /// An action that always refuses, counting the attempts it received, in
    /// one of the two shapes a refusal takes.
    struct Refuses {
        attempts: Rc<Cell<usize>>,
        domain: &'static str,
        certainty: DispatchCertainty,
        cause: &'static str,
    }

    impl Refuses {
        /// Refuses after the attempt without delivering anything: a failure a
        /// retry may cure.
        fn undelivered(attempts: Rc<Cell<usize>>) -> Self {
            Self {
                attempts,
                domain: "test::refuses",
                certainty: DispatchCertainty::NotDelivered,
                cause: "refused",
            }
        }

        /// Refuses permanently, before dispatch: the shape every "binding
        /// required" domain has.
        fn permanently(attempts: Rc<Cell<usize>>) -> Self {
            Self {
                attempts,
                domain: "test::permanent",
                certainty: DispatchCertainty::Refused,
                cause: "no binding is installed for this domain",
            }
        }
    }

    impl Execute for Refuses {
        type Input = u16;
        type Output = ();

        fn required_caps(&self) -> &[Cap] {
            &[]
        }

        fn effect_lifetime(&self) -> EffectLifetime {
            EffectLifetime::Local
        }

        async fn execute_action(&self, call: (Auth, &u16)) -> Result<(), BotError> {
            call.0.check(&[])?;
            self.attempts.set(self.attempts.get().saturating_add(1));
            Err(BotError::DomainError {
                domain: self.domain.into(),
                certainty: self.certainty,
                cause: self.cause.into(),
            })
        }

        fn domain_id(&self) -> &str {
            self.domain
        }
    }

    /// A condition that fails structurally rather than evaluating to `false`.
    ///
    /// Named apart from the refusing *action* above rather than sharing a name
    /// with it: the two refuse in different halves of a chain, one is a condition
    /// and one is an action, and a single name for both would make a call site
    /// that reads `.on(Refuses, ..)` ambiguous about which half it is asserting on.
    struct RefusesToEvaluate;

    impl Evaluate<u16> for RefusesToEvaluate {
        fn check(&self, observed: &u16) -> Result<bool, BotError> {
            Err(BotError::EvaluateError {
                cause: format!("this condition cannot decide about {observed}"),
            })
        }

        fn condition_id(&self) -> &str {
            "test::refuses"
        }
    }

    /// The action half of the same arrangement: `Count` requires nothing, so a
    /// test built on it can only ever put a source's requirements in front of
    /// the gate.
    struct NeedsCaps {
        caps: Vec<Cap>,
        domain: &'static str,
    }

    impl Execute for NeedsCaps {
        type Input = u16;
        type Output = ();

        fn required_caps(&self) -> &[Cap] {
            &self.caps
        }

        fn effect_lifetime(&self) -> EffectLifetime {
            EffectLifetime::Local
        }

        async fn execute_action(&self, call: (Auth, &u16)) -> Result<(), BotError> {
            call.0.check(&self.caps)?;
            Ok(())
        }

        fn domain_id(&self) -> &str {
            self.domain
        }
    }

    fn net_grants() -> GrantSet {
        GrantSet::empty().grant(Cap::net())
    }

    /// The attempt a report is about, for the tests that settle one.
    ///
    /// A `Result` rather than a bare key because an entry that has never been
    /// attempted has no attempt identity, and a test that asked for one anyway
    /// should say so rather than be handed a fabricated one.
    fn held_key(work: &PendingWork) -> Result<EffectKey, Box<dyn std::error::Error>> {
        work.key().ok_or_else(|| {
            format!(
                "chain {} entry {} has no attempt",
                work.id().chain(),
                work.id().entry()
            )
            .into()
        })
    }

    /// The run every test dispatches under.
    const TEST_RUN: &str = "0102030405060708090a0b0c0d0e0f10";
    /// The environment every test dispatches against.
    const TEST_ENV: &str = "2122232425262728292a2b2c2d2e2f30";
    /// The flow revision every test dispatches from.
    const TEST_FLOW: &str = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";

    /// A scope the tests dispatch under: one run, one environment at its first
    /// generation, and an in-memory journal.
    ///
    /// Returns a `Result` rather than panicking, because the crate forbids a
    /// panicking path anywhere — tests included — and a failure then names the
    /// cause rather than a line number inside a macro.
    ///
    /// The environment is registered because a broker that owns none mints no
    /// authority, so an unregistered one would make every dispatch refuse with
    /// `UnknownEnvironment` and no test would reach the path it is about.
    pub(crate) fn test_effects() -> Result<EffectScope, Box<dyn std::error::Error>> {
        test_effects_with(Box::new(MemoryJournal::new()))
    }

    /// A memory journal with injectable append faults, counting what it saw.
    ///
    /// One fixture for every journal fault these tests arm, wrapping
    /// [`MemoryJournal`] so the real ladder and chain checks stay underneath the
    /// injected fault:
    ///
    /// - refusing an append by event kind — issue #102's acceptance: an append
    ///   failure *after* the action ran is not a pre-dispatch refusal, and a
    ///   retry of the recording does not re-enter the action;
    /// - the two halves of the [`JournalError::OutcomeUnknown`] contract, each a
    ///   one-shot: commit-then-lost-reply (the record is in the store and the
    ///   caller settles by readback) and unknown-without-commit (nothing landed,
    ///   so the retry re-appends — safe precisely because the readback, not
    ///   hope, authorized it).
    ///
    /// [`Self::durable`] grades it as surviving a process crash and gives it the
    /// receipt operation a file-backed adapter has: it attests an outcome only
    /// when that outcome is actually in the store. The ephemeral form keeps the
    /// trait's refusal.
    struct FaultJournal {
        inner: Rc<RefCell<MemoryJournal>>,
        durable: bool,
        refuse_intent: Rc<Cell<bool>>,
        refuse_prepare: Rc<Cell<bool>>,
        refuse_outcome: Rc<Cell<bool>>,
        lose_reply_once: Rc<Cell<bool>>,
        unknown_once: Rc<Cell<bool>>,
        outcome_appends: Rc<Cell<usize>>,
    }

    impl FaultJournal {
        /// An ephemeral journal, graded as the memory journal it wraps.
        fn new() -> Self {
            Self::graded(false)
        }

        /// A journal graded to survive a process crash, with a receipt operation.
        fn durable() -> Self {
            Self::graded(true)
        }

        fn graded(durable: bool) -> Self {
            Self {
                inner: Rc::new(RefCell::new(MemoryJournal::new())),
                durable,
                refuse_intent: Rc::new(Cell::new(false)),
                refuse_prepare: Rc::new(Cell::new(false)),
                refuse_outcome: Rc::new(Cell::new(false)),
                lose_reply_once: Rc::new(Cell::new(false)),
                unknown_once: Rc::new(Cell::new(false)),
                outcome_appends: Rc::new(Cell::new(0)),
            }
        }

        fn refuse_outcome(&self) -> Rc<Cell<bool>> {
            Rc::clone(&self.refuse_outcome)
        }

        fn refuse_intent(&self) -> Rc<Cell<bool>> {
            Rc::clone(&self.refuse_intent)
        }

        fn refuse_prepare(&self) -> Rc<Cell<bool>> {
            Rc::clone(&self.refuse_prepare)
        }

        fn outcome_appends(&self) -> Rc<Cell<usize>> {
            Rc::clone(&self.outcome_appends)
        }

        /// One-shot: commit the next outcome append and lose its reply.
        fn lose_reply_once(&self) -> Rc<Cell<bool>> {
            Rc::clone(&self.lose_reply_once)
        }

        /// One-shot: the next outcome append reports an unknown outcome without
        /// committing anything.
        fn unknown_once(&self) -> Rc<Cell<bool>> {
            Rc::clone(&self.unknown_once)
        }

        fn store(&self) -> Rc<RefCell<MemoryJournal>> {
            Rc::clone(&self.inner)
        }
    }

    /// An injected journal failure, recorded before it is returned.
    fn injected<T>(error: JournalError) -> Result<T, JournalError> {
        let refusal = Err(error);
        lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "a test journal injected a fault");
        refusal
    }

    impl EffectJournal for FaultJournal {
        fn durability(&self) -> DurabilityPromise {
            if self.durable {
                DurabilityPromise::ProcessCrash
            } else {
                self.inner.borrow().durability()
            }
        }

        fn tail(&self) -> JournalPosition {
            self.inner.borrow().tail()
        }

        fn committed(&self) -> Result<Vec<EffectEvent>, JournalError> {
            // Qualified: `MemoryJournal` also has an inherent `committed` that
            // returns its raw entries, and that one would win method resolution.
            EffectJournal::committed(&*self.inner.borrow())
        }

        fn committed_entries(&self) -> Result<Vec<crate::journal::JournalEntry>, JournalError> {
            Ok(self.inner.borrow().committed().to_vec())
        }

        fn compare_and_append(
            &mut self,
            expected_tail: JournalPosition,
            event: &EffectEvent,
        ) -> Result<DurableAck, JournalError> {
            let is_outcome = matches!(event, EffectEvent::OutcomeObserved { .. });
            let refuse = match *event {
                EffectEvent::IntentAdmitted { .. } => self.refuse_intent.get(),
                EffectEvent::DispatchPrepared { .. } => self.refuse_prepare.get(),
                EffectEvent::OutcomeObserved { .. } => {
                    self.outcome_appends
                        .set(self.outcome_appends.get().saturating_add(1));
                    self.refuse_outcome.get()
                }
                EffectEvent::Verified { .. } => false,
            };
            if refuse {
                return injected(JournalError::Storage(io::Error::other(
                    "injected append refusal",
                )));
            }
            if is_outcome && self.unknown_once.take() {
                return injected(JournalError::OutcomeUnknown {
                    cause: io::Error::other("injected unknown outcome, nothing written"),
                });
            }
            let ack = self
                .inner
                .borrow_mut()
                .compare_and_append(expected_tail, event)?;
            if is_outcome && self.lose_reply_once.take() {
                // Conforming ambiguity: the event is in the store and the reply
                // is lost. `Storage` would claim the journal is unchanged, which
                // the committed event contradicts.
                return injected(JournalError::OutcomeUnknown {
                    cause: io::Error::other("injected post-commit lost reply"),
                });
            }
            Ok(ack)
        }

        fn confirm_outcome(
            &mut self,
            key: crate::effect::EffectKey,
            evidence: EffectEvidence,
            position: JournalPosition,
            required: DurabilityPromise,
        ) -> Result<DurableAck, JournalError> {
            let held = self.durable
                && EffectJournal::committed(&*self.inner.borrow())?.iter().any(
                    |event| matches!(*event, EffectEvent::OutcomeObserved { key: held, evidence: held_evidence }
                        if held == key && held_evidence == evidence),
                );
            if !held {
                return injected(JournalError::ReceiptUnavailable { required });
            }
            Ok(DurableAck::new(position, self.durability()))
        }
    }

    /// The error a tick that has to refuse returned.
    ///
    /// A tick that fires instead is a test failure, named by `reported` with the
    /// count it fired, so every refusal test fails the same way and reads only
    /// the assertions about the error it expected.
    fn refused(
        ticked: Result<usize, BotError>,
        reported: impl FnOnce(usize) -> String,
    ) -> Result<BotError, Box<dyn std::error::Error>> {
        match ticked {
            Ok(fired) => Err(reported(fired).into()),
            Err(error) => Ok(error),
        }
    }

    /// A bot whose one chain's first effect is indeterminate, logging every
    /// effect that ran into `log`: the shape the evidence tests settle by hand.
    fn indeterminate_once_bot(
        name: &str,
        log: &Rc<RefCell<Vec<u16>>>,
    ) -> Result<EcsBot, Box<dyn std::error::Error>> {
        Ok(EcsBot::builder(name)
            .observe(Script::new(vec![200, 200, 200]))
            .on(
                |value: &u16| *value >= 200,
                Flaky {
                    remaining: Rc::new(Cell::new(1)),
                    log: Rc::clone(log),
                    kind: FlakyKind::Indeterminate,
                },
            )
            .with_effects(test_effects()?)
            .build(&net_grants())?)
    }

    /// A bot over one settled source whose chain counts its runs into `runs`,
    /// recording through `effects`.
    ///
    /// The journal-fault tests differ in which fault they arm and when, not in
    /// the bot they arm it against, so the bot is built here once.
    fn counting_bot(
        name: &str,
        runs: &Rc<Cell<usize>>,
        effects: EffectScope,
    ) -> Result<EcsBot, Box<dyn std::error::Error>> {
        Ok(EcsBot::builder(name)
            .observe(Holds::new(200))
            .on(|value: &u16| *value >= 200, Count(Rc::clone(runs)))
            .with_effects(effects)
            .build(&net_grants())?)
    }

    #[test]
    fn hash_parts_frames_distinct_variable_length_splits() -> TestResult {
        let left = hash_parts(&[b"ab", b"c"]);
        let right = hash_parts(&[b"a", b"bc"]);
        assert_ne!(left, right, "distinct field splits must not collide");
        assert_eq!(left, hash_parts(&[b"ab", b"c"]));
        Ok(())
    }

    #[test]
    fn an_ambiguous_commit_then_error_is_idempotent() -> TestResult {
        let runs = Rc::new(Cell::new(0));
        let journal = FaultJournal::new();
        let lose_reply = journal.lose_reply_once();
        let store = journal.store();
        let mut bot = counting_bot(
            "ambiguous-commit",
            &runs,
            test_effects_with(Box::new(journal))?,
        )?;

        lose_reply.set(true);
        // The reply is lost, but the readback finds the record and the tick
        // settles in the same breath: an effect whose record is provably in
        // the journal is settled work, not an ambiguity to stall on.
        assert_eq!(bot.tick()?, 1);
        assert_eq!(runs.get(), 1);
        let committed = EffectJournal::committed(&*store.borrow())?;
        assert!(matches!(
            committed.last(),
            Some(EffectEvent::OutcomeObserved {
                evidence: EffectEvidence::Applied,
                ..
            })
        ));
        // A public repeat of the same evidence is the same fact, not a
        // refusal: the journal answers it from the committed record.
        let key = committed[0].key();
        bot.resolve_effect(&key, EffectEvidence::Applied)?;

        assert_eq!(bot.tick()?, 0);
        assert_eq!(runs.get(), 1, "retry must not dispatch the action again");
        assert!(bot.pending().is_empty());
        Ok(())
    }

    /// A journal whose positioned readback answers with a different event
    /// than the one the controller acknowledged: the shape a concurrent
    /// writer's tail swap has at the readback seam.
    struct SwappedEntryJournal {
        inner: MemoryJournal,
        swap: EffectEvent,
    }

    impl EffectJournal for SwappedEntryJournal {
        fn durability(&self) -> DurabilityPromise {
            self.inner.durability()
        }

        fn tail(&self) -> JournalPosition {
            self.inner.tail()
        }

        fn committed(&self) -> Result<Vec<EffectEvent>, JournalError> {
            EffectJournal::committed(&self.inner)
        }

        fn committed_entries(&self) -> Result<Vec<crate::journal::JournalEntry>, JournalError> {
            Ok(self.inner.committed().to_vec())
        }

        fn committed_entry(
            &self,
            position: JournalPosition,
        ) -> Result<Option<crate::journal::JournalEntry>, JournalError> {
            Ok(Some(crate::journal::JournalEntry::new(position, self.swap)))
        }

        fn compare_and_append(
            &mut self,
            expected_tail: JournalPosition,
            event: &EffectEvent,
        ) -> Result<DurableAck, JournalError> {
            self.inner.compare_and_append(expected_tail, event)
        }
    }

    /// A positioned readback that holds a different event is a mismatch,
    /// never an acknowledgement: binding the event to the position stops an
    /// adapter from laundering a concurrent writer's tail into this
    /// controller's fold (R05 wrong-event control; #122 item 2).
    #[test]
    fn a_position_holding_a_different_event_is_a_mismatch_not_an_acknowledgement() -> TestResult {
        let key = crate::effect::EffectIdentity::new(
            RunId::from_hex(TEST_RUN)?,
            EnvironmentId::from_hex(TEST_ENV)?,
            crate::effect::FlowRevision::from_tagged("blake3_256", TEST_FLOW)?,
        )
        .key(
            crate::effect::ActionId::from_hex("1112131415161718191a1b1c1d1e1f20")?,
            crate::effect::AttemptId::from_decimal("1")?,
            crate::effect::ActionDigest::from_tagged(
                "blake3_256",
                "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeffe0e1e2e3e4e5e6e7e8e9eaebecedeeef",
            )?,
            crate::effect::EnvironmentEpoch::from_decimal("1")?,
        );
        let admitted = EffectEvent::IntentAdmitted { key };
        let mut backing = MemoryJournal::new();
        let ack = backing.compare_and_append(backing.tail(), &admitted)?;
        let swapped = EffectEvent::DispatchPrepared { key };
        let scope = test_effects_with(Box::new(SwappedEntryJournal {
            inner: backing,
            swap: swapped,
        }))?;
        let mut effects = Effects::new(scope, ack.position());
        match effects.accept_position(&admitted, ack.position()) {
            Err(JournalError::EntryMismatch {
                position,
                expected,
                actual,
            }) => {
                assert_eq!(position, ack.position());
                assert_eq!(*expected, admitted);
                assert_eq!(*actual, swapped);
            }
            other => {
                return Err(format!(
                    "a swapped positioned entry must be EntryMismatch, got {other:?}"
                )
                .into());
            }
        }
        Ok(())
    }

    #[test]
    fn a_durable_retry_after_a_lost_reply_settles_instead_of_stalling() -> TestResult {
        let runs = Rc::new(Cell::new(0));
        let journal = FaultJournal::durable();
        let ambiguous_once = journal.lose_reply_once();
        let store = journal.store();
        let mut bot = counting_bot("lost-reply", &runs, test_effects_with(Box::new(journal))?)?;

        // Half one: the record landed, the reply did not. The readback finds
        // it, the journal attests its grade, and the tick settles in the same
        // breath — a receipt the journal can produce is not a reason to
        // stall, and never a reason to re-enter the action.
        ambiguous_once.set(true);
        assert_eq!(bot.tick()?, 1);
        assert_eq!(runs.get(), 1);
        let committed = EffectJournal::committed(&*store.borrow())?;
        assert!(
            matches!(
                committed.last(),
                Some(EffectEvent::OutcomeObserved {
                    evidence: EffectEvidence::Applied,
                    ..
                })
            ),
            "the store must hold the outcome whose reply was lost"
        );
        assert!(bot.pending().is_empty());

        // Half two: an unknown outcome where nothing landed. The readback
        // proves absence, the caller reports the occurrence, and the retry
        // re-appends — readback authorized it, the ladder stands behind it.
        // A separate bot: half one's `Applied` settlement retired that
        // generation, and a retired generation is owed no second append.
        let runs = Rc::new(Cell::new(0));
        let journal = FaultJournal::durable();
        let unknown_once = journal.unknown_once();
        let store = journal.store();
        let mut bot = counting_bot(
            "unknown-refused",
            &runs,
            test_effects_with(Box::new(journal))?,
        )?;

        unknown_once.set(true);
        match bot.tick() {
            Err(error @ BotError::EffectUnrecorded { .. }) => {
                assert_eq!(
                    error.dispatch_certainty(),
                    DispatchCertainty::Occurred,
                    "the effect happened; only its record's reply was lost: {error:?}"
                );
            }
            other => return Err(format!("expected a lost reply, got {other:?}").into()),
        }
        assert_eq!(runs.get(), 1);
        let committed = EffectJournal::committed(&*store.borrow())?;
        assert!(
            !committed
                .iter()
                .any(|event| matches!(event, EffectEvent::OutcomeObserved { .. })),
            "an unknown outcome without a commit must leave the ladder free"
        );
        assert_eq!(
            bot.tick()?,
            1,
            "the record lands on the recovery tick and counts as fired"
        );
        assert_eq!(runs.get(), 1, "a lost reply must never re-run the action");
        assert!(bot.pending().is_empty());
        Ok(())
    }

    /// Build an effect scope over a caller-supplied journal.
    fn test_effects_with(
        journal: Box<dyn EffectJournal>,
    ) -> Result<EffectScope, Box<dyn std::error::Error>> {
        let environment = EnvironmentId::from_hex(TEST_ENV)?;
        let mut broker = Broker::new();
        broker.register(environment)?;
        Ok(EffectScope::new(
            EffectIdentity::new(
                RunId::from_hex(TEST_RUN)?,
                environment,
                FlowRevision::from_tagged("blake3_256", TEST_FLOW)?,
            ),
            broker,
            journal,
        ))
    }

    /// A post-applied append failure is a recording failure with a known
    /// occurrence — never a pre-dispatch refusal, and never a re-dispatch.
    ///
    /// Acceptance: the action's marker exists exactly once after recovery, the
    /// returned certainty is `Occurred` (not `Refused`, not `NotDelivered`),
    /// the entry is held as `RecordingFailed`, and the append retry does not
    /// call the action again.
    #[test]
    fn a_post_applied_append_failure_is_a_recording_failure_not_a_refusal() -> TestResult {
        let runs = Rc::new(Cell::new(0));
        let journal = FaultJournal::new();
        let refuse_outcome = journal.refuse_outcome();
        let outcome_appends = journal.outcome_appends();
        let mut bot = counting_bot(
            "unrecorded-applied",
            &runs,
            test_effects_with(Box::new(journal))?,
        )?;

        refuse_outcome.set(true);
        let error = refused(bot.tick(), |fired| {
            format!("a refused outcome append was reported as {fired} fired")
        })?;
        assert!(
            matches!(error, BotError::EffectUnrecorded { .. }),
            "expected EffectUnrecorded, got {error:?}"
        );
        assert_eq!(
            error.dispatch_certainty(),
            DispatchCertainty::Occurred,
            "the effect happened: the certainty must not be Refused or NotDelivered"
        );
        assert_eq!(
            error.retry_class(),
            RetryClass::Never,
            "the action is never re-entered for a recording failure"
        );
        assert_eq!(runs.get(), 1, "the action ran exactly once");
        assert_eq!(
            outcome_appends.get(),
            1,
            "the outcome append was attempted once and refused"
        );
        assert!(
            matches!(
                first_hold(&bot),
                Some(TransitionHold::RecordingFailed { .. })
            ),
            "the entry is held for an append-only retry: {:?}",
            first_hold(&bot)
        );

        // Clear the fault. The recovery tick retries the *append* and must not
        // call the action again.
        refuse_outcome.set(false);
        assert_eq!(
            bot.tick()?,
            1,
            "the append lands and the recovered effect is counted as fired"
        );
        assert_eq!(
            runs.get(),
            1,
            "a retry of recording must not re-enter the action"
        );
        assert_eq!(
            outcome_appends.get(),
            2,
            "the outcome append was retried exactly once"
        );
        assert!(
            bot.pending().is_empty(),
            "the entry is resolved once its record lands: {:?}",
            bot.pending()
        );
        Ok(())
    }

    /// The same split after a definitely-not-applied effect: the occurrence is
    /// `NotApplied`, the error is still `EffectUnrecorded`, and the action is
    /// still not re-entered while the record is missing.
    #[test]
    fn a_post_failure_append_failure_keeps_the_not_applied_fact() -> TestResult {
        let runs = Rc::new(Cell::new(0));
        let journal = FaultJournal::new();
        let refuse_outcome = journal.refuse_outcome();
        let mut bot = EcsBot::builder("unrecorded-not-applied")
            .observe(Holds::new(200))
            .on(
                |value: &u16| *value >= 200,
                Refuses::undelivered(Rc::clone(&runs)),
            )
            .with_effects(test_effects_with(Box::new(journal))?)
            .build(&net_grants())?;

        refuse_outcome.set(true);
        let error = refused(bot.tick(), |fired| {
            format!("a refused outcome append was reported as {fired} fired")
        })?;
        assert!(
            matches!(
                error,
                BotError::EffectUnrecorded {
                    evidence: EffectEvidence::NotApplied,
                    ..
                }
            ),
            "expected EffectUnrecorded carrying NotApplied, got {error:?}"
        );
        assert_eq!(
            error.dispatch_certainty(),
            DispatchCertainty::NotDelivered,
            "the effect definitely did not happen"
        );
        assert_eq!(
            error.retry_class(),
            RetryClass::Never,
            "a recording failure never re-enters the action"
        );
        assert_eq!(runs.get(), 1, "the action ran exactly once");
        assert!(
            matches!(
                first_hold(&bot),
                Some(TransitionHold::RecordingFailed { .. })
            ),
            "the entry is held for an append-only retry: {:?}",
            first_hold(&bot)
        );

        refuse_outcome.set(false);
        // The append lands. The effect is known not-applied, so the entry
        // becomes eligible for a *fresh* attempt under the budget — that is a
        // response to "it did not happen", not a retry of the recording
        // failure. It is still open work, so the tick reports it rather than
        // claiming a clean finish.
        let error = refused(bot.tick(), |fired| {
            format!("an open entry was reported as {fired} fired")
        })?;
        assert!(
            matches!(error, BotError::PendingTransition { .. }),
            "expected the still-open entry, got {error:?}"
        );
        assert_eq!(
            runs.get(),
            1,
            "the append retry must not re-enter the action"
        );
        assert!(
            matches!(
                first_hold(&bot),
                Some(TransitionHold::Failed { attempts: 1, .. })
            ),
            "the entry is eligible again under the budget: {:?}",
            first_hold(&bot)
        );
        Ok(())
    }

    /// Append failures *before* the action are still pre-dispatch refusals.
    ///
    /// The negative control for the two tests above: `Refused` is the right
    /// answer when nothing left the process, and this is what keeps the new
    /// variant from swallowing that case.
    #[test]
    fn an_append_failure_before_the_action_is_still_a_pre_dispatch_refusal() -> TestResult {
        let runs = Rc::new(Cell::new(0));

        // Before intent.
        let journal = FaultJournal::new();
        let refuse_intent = journal.refuse_intent();
        let mut bot = counting_bot(
            "refuse-intent",
            &runs,
            test_effects_with(Box::new(journal))?,
        )?;
        refuse_intent.set(true);
        let error = refused(bot.tick(), |fired| {
            format!("a refused intent append was reported as {fired} fired")
        })?;
        assert!(
            matches!(error, BotError::EffectRefused { .. }),
            "expected EffectRefused before intent, got {error:?}"
        );
        assert_eq!(error.dispatch_certainty(), DispatchCertainty::Refused);
        assert_eq!(runs.get(), 0, "the action never ran");

        // Before preparation.
        let journal = FaultJournal::new();
        let refuse_prepare = journal.refuse_prepare();
        let mut bot = counting_bot(
            "refuse-prepare",
            &runs,
            test_effects_with(Box::new(journal))?,
        )?;
        refuse_prepare.set(true);
        let error = refused(bot.tick(), |fired| {
            format!("a refused prepare append was reported as {fired} fired")
        })?;
        assert!(
            matches!(error, BotError::EffectRefused { .. }),
            "expected EffectRefused before preparation, got {error:?}"
        );
        assert_eq!(error.dispatch_certainty(), DispatchCertainty::Refused);
        assert_eq!(runs.get(), 0, "the action never ran");
        Ok(())
    }

    /// The sequence every test uses: two ticks of 200, two of 503, one of 200.
    /// It holds still for a tick at a time, which is what makes a change filter
    /// falsifiable: a sequence that moved on every tick would make "changed"
    /// and "ran" indistinguishable.
    const SCRIPT: [u16; 5] = [200, 200, 503, 503, 200];

    #[test]
    fn a_condition_fires_only_on_the_tick_its_source_moves() -> TestResult {
        let counter = Rc::new(Cell::new(0));
        let mut bot = EcsBot::builder("scripted")
            .observe(Script::new(SCRIPT.to_vec()))
            .on(|value: &u16| *value >= 500, Count(Rc::clone(&counter)))
            .with_effects(test_effects()?)
            .build(&net_grants())?;

        let mut fired = Vec::new();
        let mut revisions = Vec::new();
        for _ in 0..5 {
            fired.push(bot.tick()?);
            revisions.push(
                bot.revisions()
                    .first()
                    .copied()
                    .ok_or("a bot with one chain reports one revision")?,
            );
        }

        // `Revision` moves on the ticks the value actually moved: the first
        // poll, the step to 503, and the step back to 200.
        assert_eq!(
            revisions,
            vec![1, 1, 2, 2, 3],
            "Revision must track value movement, not system execution"
        );
        // 503 is held for two ticks; the condition is true on both, and the
        // effect runs once, on the transition.
        assert_eq!(fired, vec![0, 0, 1, 0, 0]);
        assert_eq!(counter.get(), 1);
        Ok(())
    }

    /// A chain whose source settles must settle.
    ///
    /// This is the regression for a defect found by `bench/`'s fairness gate and
    /// by nothing else: the bot fired 896,000 effects where the hand-rolled
    /// baseline fired 17,920 for identical input, a 50x over-run that every
    /// test in this crate passed through.
    ///
    /// The cause was a lost baseline. A transition *takes* the observed value out
    /// of its slot, and while the transition is retained that binding is where
    /// the chain's newest value lives. When the transition finished and was
    /// dropped instead, the value went with it, leaving the chain with nothing to
    /// compare against. The next tick read "no baseline" as "the source moved",
    /// re-opened the chain and fired the entry again — and again, every tick
    /// after, forever.
    ///
    /// So the assertion is not "it fired" but "it fired **once**", over a run
    /// long enough that a per-tick re-fire is unmistakable. `Holds` is what makes
    /// it decidable: a source that advances every poll cannot tell a chain that
    /// settled from a chain that is still working.
    #[test]
    fn a_settled_chain_does_not_fire_again_on_every_later_tick() -> TestResult {
        let counter = Rc::new(Cell::new(0));
        let mut bot = counting_bot("held", &counter, test_effects()?)?;

        // The first tick is the movement: the chain opens and the effect runs.
        assert_eq!(bot.tick()?, 1, "the movement opens the chain");

        // Twenty more ticks in which nothing whatever happens. A lost baseline
        // shows up here as `1` rather than `0` on the second tick and every one
        // after it.
        for tick in 0_u32..20 {
            assert_eq!(
                bot.tick()?,
                0,
                "tick {}: the source held still, so the chain had nothing to run",
                tick.saturating_add(2)
            );
        }

        assert_eq!(
            counter.get(),
            1,
            "the effect is owed once per movement, not once per tick"
        );
        // The revision is the substrate's own record of movement, and it is the
        // other half of the same claim: one movement, one bump.
        assert_eq!(
            bot.revisions().first().copied(),
            Some(1),
            "Revision counts movements, so a settled chain's is still 1"
        );
        Ok(())
    }

    /// A detached digest cannot prove that an async poll returned the same
    /// snapshot. The bot must continue to poll until an observer can bind its
    /// revision to the returned value in one operation.
    #[test]
    fn a_source_with_a_detached_digest_is_polled_while_it_holds_still() -> TestResult {
        let polls = Rc::new(Cell::new(0));
        let counter = Rc::new(Cell::new(0));
        let mut bot = EcsBot::builder("lazy")
            .observe(Counted::new(200, Rc::clone(&polls)))
            .on(|value: &u16| *value >= 200, Count(Rc::clone(&counter)))
            .with_effects(test_effects()?)
            .build(&net_grants())?;

        assert_eq!(bot.tick()?, 1, "the first tick polls");
        assert_eq!(polls.get(), 1, "and polls exactly once");

        for tick in 0_u32..20 {
            assert_eq!(
                bot.tick()?,
                0,
                "tick {}: nothing moved",
                tick.saturating_add(2)
            );
        }
        assert_eq!(
            polls.get(),
            21,
            "a detached digest cannot suppress a later async poll"
        );
        assert_eq!(counter.get(), 1, "and must not fire the effect again");
        Ok(())
    }

    /// An A → B → A source race must not leave B held while stable A is skipped.
    ///
    /// The first tick reads the legacy fingerprint at A, lets the observer
    /// sample B, returns the live source to A, and only then admits B. The next
    /// tick has to poll and deliver A. The retired cache used the earlier A
    /// fingerprint for B, saw A as quiet on the next tick, and left B held.
    #[test]
    fn a_detached_digest_cannot_suppress_the_final_stable_aba_state() -> TestResult {
        let value = Rc::new(Cell::new(0));
        let phase = Rc::new(Cell::new(0));
        let polls = Rc::new(Cell::new(0));
        let seen = Rc::new(RefCell::new(Vec::new()));
        let mut bot = EcsBot::builder("aba")
            .observe(AbaSource::new(
                Rc::clone(&value),
                Rc::clone(&phase),
                Rc::clone(&polls),
            ))
            .on(|_: &u16| true, Record(Rc::clone(&seen)))
            .with_effects(test_effects()?)
            .build(&net_grants())?;

        let mut tick = Box::pin(bot.tick_async());
        let waker = Waker::noop();
        let mut cx = Context::from_waker(waker);
        if !matches!(tick.as_mut().poll(&mut cx), Poll::Pending) {
            return Err("the first poll must pause before sampling B".into());
        }
        value.set(1);
        if !matches!(tick.as_mut().poll(&mut cx), Poll::Pending) {
            return Err("the source must pause after sampling B".into());
        }
        value.set(0);
        match tick.as_mut().poll(&mut cx) {
            Poll::Ready(Ok(fired)) => assert_eq!(fired, 1, "the sampled B action fires"),
            Poll::Ready(Err(error)) => return Err(format!("the B tick failed: {error}").into()),
            Poll::Pending => return Err("the third poll must admit the sampled B value".into()),
        }
        drop(tick);
        assert_eq!(*seen.borrow(), vec![1], "the first tick delivers sampled B");

        assert_eq!(bot.tick()?, 1, "the next tick must observe stable A");
        assert_eq!(
            *seen.borrow(),
            vec![1, 0],
            "stable A is delivered instead of being suppressed by B's stale digest"
        );
        assert_eq!(polls.get(), 2, "both B and the final stable A were polled");
        Ok(())
    }

    /// Value comparison still avoids another effect when a source holds still.
    #[test]
    fn a_source_value_that_moves_is_polled_again_and_fires() -> TestResult {
        let polls = Rc::new(Cell::new(0));
        let counter = Rc::new(Cell::new(0));
        let source = Counted::new(200, Rc::clone(&polls));
        let value = Rc::clone(&source.value);
        let mut bot = EcsBot::builder("lazy-moving")
            .observe(source)
            .on(|value: &u16| *value >= 200, Count(Rc::clone(&counter)))
            .with_effects(test_effects()?)
            .build(&net_grants())?;

        assert_eq!(bot.tick()?, 1, "the first value fires");
        assert_eq!(bot.tick()?, 0, "and holds");
        assert_eq!(
            polls.get(),
            2,
            "the second tick polls and compares its value"
        );

        value.set(503);
        assert_eq!(bot.tick()?, 1, "the movement is seen, not skipped");
        assert_eq!(
            polls.get(),
            3,
            "the tick paid for a value to see the movement"
        );

        assert_eq!(bot.tick()?, 0, "and settles again");
        assert_eq!(polls.get(), 4, "the stable value is polled and compared");
        assert_eq!(counter.get(), 2, "two movements, two effects");
        Ok(())
    }

    /// A source without a digest keeps the same value-comparison behavior.
    #[test]
    fn a_source_without_a_digest_is_polled_every_tick() -> TestResult {
        let counter = Rc::new(Cell::new(0));
        let mut bot = counting_bot("unguarded", &counter, test_effects()?)?;

        assert_eq!(bot.tick()?, 1);
        for _ in 0..5 {
            assert_eq!(bot.tick()?, 0);
        }
        // Every tick polls; the effect still fires once because the value did
        // not move.
        assert_eq!(
            counter.get(),
            1,
            "the value decides the chain, not the digest"
        );
        Ok(())
    }

    #[test]
    fn building_without_the_grant_is_refused() -> TestResult {
        let counter = Rc::new(Cell::new(0));
        match EcsBot::builder("ungranted")
            .observe(Script::new(SCRIPT.to_vec()))
            .on(|value: &u16| *value >= 500, Count(counter))
            .with_effects(test_effects()?)
            .build(&GrantSet::empty())
        {
            Ok(_) => Err("a source requiring `bot.net` built without it".into()),
            Err(error) => {
                assert!(
                    matches!(error, BotError::CapabilityDenied { .. }),
                    "expected CapabilityDenied, got {error:?}"
                );
                Ok(())
            }
        }
    }

    /// Admission as one answer rather than a loop.
    ///
    /// This bot is short of `bot.net` on its source and `bot.fs` on its action.
    /// Admission that returned at the first unmet requirement told the caller
    /// `bot.net`, and `bot.fs` only appeared on the next build — so a person
    /// repairing a bot discovered its requirements one refusal at a time. The
    /// gate already knows both; one refusal now carries both, and each says
    /// which domain declared it.
    #[test]
    fn admission_names_every_unmet_requirement_and_the_domain_that_declared_it() -> TestResult {
        match EcsBot::builder("short")
            .observe(Holds::new(1))
            .on(
                |value: &u16| *value > 0,
                NeedsCaps {
                    caps: vec![Cap::fs()],
                    domain: "test::writes",
                },
            )
            .with_effects(test_effects()?)
            .build(&GrantSet::empty())
        {
            Ok(_) => Err("a bot requiring two ungranted capabilities built".into()),
            Err(BotError::CapabilityDenied { deficit }) => {
                let named: Vec<(&str, Option<&str>)> = deficit
                    .shortages()
                    .map(|shortage| {
                        (
                            shortage.required().as_str(),
                            shortage.demand().map(Demand::domain),
                        )
                    })
                    .collect();
                assert_eq!(
                    named,
                    vec![
                        (Cap::NET, Some("test::holds")),
                        (Cap::FS, Some("test::writes")),
                    ],
                    "one refusal must name both requirements and both domains: {deficit}"
                );
                // And the repair is one call, not one per refusal.
                assert!(
                    deficit
                        .to_grant_set()
                        .admit(&[Cap::net(), Cap::fs()])
                        .is_ok(),
                    "the deficit must derive the whole repair: {deficit}"
                );
                Ok(())
            }
            Err(other) => Err(format!("expected a capability denial, got {other:?}").into()),
        }
    }

    #[test]
    fn a_poll_error_is_returned_and_commits_nothing() -> TestResult {
        let counter = Rc::new(Cell::new(0));
        let mut bot = EcsBot::builder("exhausting")
            .observe(Exhausting {
                remaining: Rc::new(Cell::new(1)),
                caps: vec![Cap::net()],
            })
            .on(|value: &u16| *value >= 500, Count(Rc::clone(&counter)))
            .with_effects(test_effects()?)
            .build(&net_grants())?;

        assert_eq!(
            bot.tick()?,
            0,
            "the first poll answers 200 and fires nothing"
        );
        let after_success = bot.revisions();

        // The second poll fails. The tick reports it, and the observed value
        // from the first tick must survive: a failed tick leaves the world as
        // it was rather than half-updated.
        let error = refused(bot.tick(), |_| {
            String::from("a failing poll was reported as a successful tick")
        })?;
        assert!(
            matches!(error, BotError::DomainError { .. }),
            "expected the observer's own error, got {error:?}"
        );
        assert_eq!(
            bot.revisions(),
            after_success,
            "a failed tick must not commit a new Revision"
        );
        assert_eq!(
            counter.get(),
            0,
            "a failed poll fires nothing: the action must not have run"
        );
        Ok(())
    }

    /// A failed sibling poll must not teach the fingerprint cache about a
    /// value the fold refused to hold.
    ///
    /// The counterexample, stated as issue #99 states it: A reports payload `1`
    /// with digest `Some(1)` and B fails its first poll. The first tick fires
    /// nothing under the all-or-nothing observation contract. Before the
    /// repair A's digest was published anyway, so the second tick read A as
    /// quiet and skipped it despite holding no committed payload — A's action
    /// never ran unless A changed again.
    #[test]
    fn a_failed_sibling_does_not_publish_the_successful_sources_digest() -> TestResult {
        let left_polls = Rc::new(Cell::new(0));
        let right_polls = Rc::new(Cell::new(0));
        let seen = Rc::new(RefCell::new(Vec::new()));
        let left = Switched::new(1, false, Rc::clone(&left_polls));
        let mid = Switched::new(9, true, Rc::clone(&right_polls));
        let mid_fail = Rc::clone(&mid.fail);
        let mut bot = EcsBot::builder("sibling")
            .observe(left)
            .on(|value: &u16| *value >= 1, Record(Rc::clone(&seen)))
            .observe(mid)
            .on(
                |value: &u16| *value >= 9,
                Record(Rc::new(RefCell::new(Vec::new()))),
            )
            .with_effects(test_effects()?)
            .build(&net_grants())?;

        let error = refused(bot.tick(), |fired| {
            format!("a failing sibling was reported as {fired} fired")
        })?;
        assert!(
            matches!(error, BotError::DomainError { .. }),
            "expected the sibling's own error, got {error:?}"
        );
        assert!(
            seen.borrow().is_empty(),
            "the failed fold must not commit A's payload"
        );
        assert_eq!(left_polls.get(), 1, "A was polled once on the first tick");
        assert_eq!(right_polls.get(), 1, "and so was B");

        mid_fail.set(false);
        assert_eq!(bot.tick()?, 2, "both chains recover and both actions fire");
        assert_eq!(
            *seen.borrow(),
            vec![1],
            "A's uncommitted payload is committed on recovery, with 1 as its input"
        );
        assert_eq!(
            left_polls.get(),
            2,
            "A is polled again: its digest must not have been published early"
        );
        assert_eq!(right_polls.get(), 2, "B recovers on a poll of its own");
        Ok(())
    }

    /// The second half of issue #99's public scenario: a *previously committed*
    /// value changes while a sibling fails, and the recovery must keep the
    /// transition to the new value rather than the older committed one.
    #[test]
    fn a_committed_source_that_moves_during_a_sibling_failure_is_not_lost() -> TestResult {
        let left_polls = Rc::new(Cell::new(0));
        let right_polls = Rc::new(Cell::new(0));
        let seen = Rc::new(RefCell::new(Vec::new()));
        let left = Switched::new(0, false, Rc::clone(&left_polls));
        let left_value = Rc::clone(&left.value);
        let mid = Switched::new(9, false, Rc::clone(&right_polls));
        let mid_fail = Rc::clone(&mid.fail);
        let mut bot = EcsBot::builder("recovery")
            .observe(left)
            .on(|value: &u16| *value >= 1, Record(Rc::clone(&seen)))
            .observe(mid)
            .on(|_: &u16| true, Record(Rc::new(RefCell::new(Vec::new()))))
            .with_effects(test_effects()?)
            .build(&net_grants())?;

        assert_eq!(bot.tick()?, 1, "the first tick commits A=0 and B=9");
        assert_eq!(
            *seen.borrow(),
            Vec::<u16>::new(),
            "A=0 does not meet its condition"
        );
        assert_eq!(left_polls.get(), 1);

        left_value.set(1);
        mid_fail.set(true);
        let error = refused(bot.tick(), |fired| {
            format!("a failing sibling was reported as {fired} fired")
        })?;
        assert!(
            matches!(error, BotError::DomainError { .. }),
            "expected the sibling's own error, got {error:?}"
        );
        assert!(
            seen.borrow().is_empty(),
            "the failed fold must not commit A=1"
        );

        mid_fail.set(false);
        assert_eq!(
            bot.tick()?,
            1,
            "recovery commits A's move; B is unchanged and fires nothing"
        );
        assert_eq!(
            *seen.borrow(),
            vec![1],
            "the transition to 1 is retained, not the older committed 0"
        );
        assert_eq!(
            left_polls.get(),
            3,
            "A is polled on the failing tick and again on recovery"
        );
        Ok(())
    }

    /// Several siblings fail on one tick; every successful source must still
    /// deliver its payload once the fold can commit.
    #[test]
    fn several_failed_siblings_do_not_suppress_the_sources_that_succeeded() -> TestResult {
        let polls_left = Rc::new(Cell::new(0));
        let polls_mid = Rc::new(Cell::new(0));
        let polls_right = Rc::new(Cell::new(0));
        let seen_left = Rc::new(RefCell::new(Vec::new()));
        let seen_right = Rc::new(RefCell::new(Vec::new()));
        let left = Switched::new(1, false, Rc::clone(&polls_left));
        let mid = Switched::new(2, true, Rc::clone(&polls_mid));
        let right = Switched::new(3, false, Rc::clone(&polls_right));
        // A second failing source, so "the first error wins" is not the only
        // thing the fold is being asked to survive.
        let far = Switched::new(4, true, Rc::new(Cell::new(0)));
        let mid_fail = Rc::clone(&mid.fail);
        let far_fail = Rc::clone(&far.fail);
        let mut bot = EcsBot::builder("multi-fail")
            .observe(left)
            .on(|value: &u16| *value >= 1, Record(Rc::clone(&seen_left)))
            .observe(mid)
            .on(|_: &u16| true, Record(Rc::new(RefCell::new(Vec::new()))))
            .observe(right)
            .on(|value: &u16| *value >= 3, Record(Rc::clone(&seen_right)))
            .observe(far)
            .on(|_: &u16| true, Record(Rc::new(RefCell::new(Vec::new()))))
            .with_effects(test_effects()?)
            .build(&net_grants())?;

        if let Ok(fired) = bot.tick() {
            return Err(format!("failed siblings were reported as {fired} fired").into());
        }
        assert!(
            seen_left.borrow().is_empty(),
            "nothing commits on a failed fold"
        );
        assert!(
            seen_right.borrow().is_empty(),
            "nothing commits on a failed fold"
        );
        assert_eq!(polls_left.get(), 1);
        assert_eq!(polls_right.get(), 1);

        mid_fail.set(false);
        far_fail.set(false);
        assert_eq!(bot.tick()?, 4, "every chain recovers and fires");
        assert_eq!(*seen_left.borrow(), vec![1], "A delivers its payload");
        assert_eq!(*seen_right.borrow(), vec![3], "C delivers its payload");
        assert_eq!(
            polls_left.get(),
            2,
            "A was re-polled after the aborted fold"
        );
        assert_eq!(
            polls_right.get(),
            2,
            "C was re-polled after the aborted fold"
        );
        Ok(())
    }

    /// A tick dropped mid-poll leaves the next tick able to observe normally.
    #[test]
    fn cancelling_a_poll_leaves_the_next_observation_usable() -> TestResult {
        let polls = Rc::new(Cell::new(0));
        let seen = Rc::new(RefCell::new(Vec::new()));
        let yielded = Rc::new(Cell::new(false));
        let source = Yielding::new(200, Rc::clone(&yielded), Rc::clone(&polls));
        let mut bot = EcsBot::builder("cancel")
            .observe(source)
            .on(|value: &u16| *value >= 200, Record(Rc::clone(&seen)))
            .with_effects(test_effects()?)
            .build(&net_grants())?;

        // Drive the tick until the source parks, then drop it on the floor.
        {
            let mut tick = Box::pin(bot.tick_async());
            let waker = Waker::noop();
            let mut cx = Context::from_waker(waker);
            match tick.as_mut().poll(&mut cx) {
                Poll::Ready(_) => {
                    return Err("the yielding source resolved before it was cancelled".into());
                }
                Poll::Pending => {}
            }
            drop(tick);
        }
        assert!(seen.borrow().is_empty(), "a cancelled tick commits nothing");

        assert_eq!(bot.tick()?, 1, "the recovery tick completes and fires");
        assert_eq!(*seen.borrow(), vec![200], "with the payload as its input");
        assert_eq!(
            polls.get(),
            2,
            "the source is polled once per tick across the cancel"
        );

        assert_eq!(bot.tick()?, 0, "and the next tick compares the same value");
        assert_eq!(polls.get(), 3, "the next tick polls after a cancellation");
        Ok(())
    }

    /// A retained transition keeps its immutable input across a sibling failure
    /// that admits a newer candidate and then aborts.
    ///
    /// Acceptance case 4 of issue #99. The held entry is bound to the payload
    /// it was opened under. A later tick moves the source and fails on a
    /// sibling; the fold refuses that tick wholesale. After recovery the
    /// binding must still be the older payload, and the newer value must not
    /// have been folded into it — and must not have been lost either.
    #[test]
    fn a_held_transition_keeps_its_input_across_a_sibling_failure() -> TestResult {
        let logs = Rc::new(RefCell::new(Vec::new()));
        let mid_polls = Rc::new(Cell::new(0));
        let mid = Switched::new(9, false, Rc::clone(&mid_polls));
        let mid_fail = Rc::clone(&mid.fail);
        let left = Holds::new(200);
        let mut bot = EcsBot::builder("held-newer")
            .observe(left)
            .on(
                |value: &u16| *value >= 200,
                Flaky {
                    remaining: Rc::new(Cell::new(1)),
                    log: Rc::clone(&logs),
                    kind: FlakyKind::Indeterminate,
                },
            )
            .observe(mid)
            .on(|_: &u16| true, Record(Rc::new(RefCell::new(Vec::new()))))
            .with_effects(test_effects()?)
            .build(&net_grants())?;

        let error = refused(bot.tick(), |fired| {
            format!("an indeterminate effect was reported as {fired} fired")
        })?;
        assert!(
            matches!(error, BotError::EffectIndeterminate { .. }),
            "expected the action's own error, got {error:?}"
        );
        assert_eq!(identities(&bot), vec![(0, 0)], "the held entry is named");
        assert!(
            matches!(
                first_hold(&bot),
                Some(TransitionHold::OutcomeUnknown { attempts: 1, .. })
            ),
            "the first tick holds the attempt: {:?}",
            first_hold(&bot)
        );
        assert!(logs.borrow().is_empty(), "nothing was recorded yet");

        // A sibling failure aborts the fold before any newer candidate can be
        // admitted. The held entry is untouched: same identity, same hold.
        mid_fail.set(true);
        let error = refused(bot.tick(), |fired| {
            format!("a failing sibling was reported as {fired} fired")
        })?;
        assert!(
            matches!(error, BotError::DomainError { .. }),
            "expected the sibling's own error, got {error:?}"
        );
        assert_eq!(
            identities(&bot),
            vec![(0, 0)],
            "the held entry survives an aborted fold"
        );
        assert!(
            matches!(
                first_hold(&bot),
                Some(TransitionHold::OutcomeUnknown { attempts: 1, .. })
            ),
            "and is still held on the same attempt: {:?}",
            first_hold(&bot)
        );

        // Recovery. The held entry is still not re-attempted without evidence,
        // and the sibling's own work is what the tick is able to report.
        mid_fail.set(false);
        match bot.tick() {
            Ok(_) => {}
            Err(error) => assert!(
                matches!(error, BotError::PendingTransition { .. }),
                "the held entry is still outstanding, got {error:?}"
            ),
        }
        assert!(
            logs.borrow().is_empty(),
            "a held effect is not attempted across a recovery without evidence"
        );

        // Evidence says it did not happen. The entry runs against the input it
        // was bound to — `Holds` never moved, so the immutable input is 200 and
        // there is no newer candidate that could have replaced it.
        let held = bot
            .pending()
            .into_iter()
            .find(|work| identity(work) == (0, 0))
            .ok_or("the held entry disappeared from the report")?;
        bot.resolve_effect(&held_key(&held)?, EffectEvidence::NotApplied)?;
        assert_eq!(bot.tick()?, 1, "the entry runs once evidence authorises it");
        assert_eq!(
            *logs.borrow(),
            vec![200],
            "the retained transition's immutable input is the one it was opened under"
        );
        Ok(())
    }

    #[test]
    fn a_failure_mid_chain_leaves_the_untouched_entries_pending() -> TestResult {
        // The counterexample to "a tick is all-or-nothing", and the regression
        // for the repair. Three entries: the first records an effect, the
        // second is refused once, the third is never reached on the failing
        // tick.
        //
        // Before the repair this test asserted the *loss*: the revision was
        // committed before any action ran, so the unchanged second tick fired
        // nothing, the refused entry was never retried, and the third entry's
        // effect was absent forever with no record of it. That assertion
        // encoded the defect as correct and has been replaced.
        //
        // The script holds still at 200 so the second tick has an unchanged
        // source, which is what makes both halves falsifiable: a moving source
        // would fire again for reasons unrelated to the failure.
        let first = Rc::new(RefCell::new(Vec::new()));
        let second = Rc::new(RefCell::new(Vec::new()));
        let third = Rc::new(RefCell::new(Vec::new()));
        let mut bot = EcsBot::builder("partial")
            .observe(Script::new(vec![200, 200]))
            .on(|value: &u16| *value >= 200, Record(Rc::clone(&first)))
            .on(
                |value: &u16| *value >= 200,
                Flaky {
                    remaining: Rc::new(Cell::new(1)),
                    log: Rc::clone(&second),
                    kind: FlakyKind::Refused,
                },
            )
            .on(|value: &u16| *value >= 200, Record(Rc::clone(&third)))
            .with_effects(test_effects()?)
            .build(&net_grants())?;

        let error = refused(bot.tick(), |fired| {
            format!("a refused action was reported as {fired} fired")
        })?;
        assert!(
            matches!(error, BotError::DomainError { .. }),
            "expected the action's own error, got {error:?}"
        );
        assert_eq!(
            *first.borrow(),
            vec![200],
            "the action before the failure ran and its effect is not rolled back"
        );
        assert!(
            second.borrow().is_empty(),
            "the refused action recorded nothing"
        );
        assert!(
            third.borrow().is_empty(),
            "the entry after the failure was not attempted on the failing tick"
        );
        assert_eq!(
            identities(&bot),
            vec![(0, 1), (0, 2)],
            "the refused entry and the entry behind it are both still outstanding"
        );
        assert!(
            matches!(
                first_hold(&bot),
                Some(TransitionHold::Failed {
                    attempts: 1,
                    budget: 3,
                    ..
                })
            ),
            "the refused entry is held as a definite failure with the attempt counted: {:?}",
            first_hold(&bot)
        );

        // The source has not moved. The retry and the untouched third entry run
        // anyway, because eligible work is retained rather than re-derived from
        // the change filter.
        assert_eq!(
            bot.tick()?,
            2,
            "the refused entry is retried and the entry behind it runs, on a still source"
        );
        assert_eq!(
            *first.borrow(),
            vec![200],
            "the acknowledged first effect is not replayed to reach the third entry"
        );
        assert_eq!(
            *second.borrow(),
            vec![200],
            "the retried action ran exactly once, on the second tick"
        );
        assert_eq!(
            *third.borrow(),
            vec![200],
            "the effect the old code lost ran once the entry ahead of it settled"
        );
        assert!(
            bot.pending().is_empty(),
            "a clean tick means nothing is left holding the transition: {:?}",
            bot.pending()
        );
        Ok(())
    }

    #[test]
    fn a_failure_before_the_first_effect_still_runs_it_once() -> TestResult {
        // The narrowest version of the defect: nothing has happened yet, the
        // first entry never stops failing, and the entry behind it must still
        // run — after the attempt budget is spent and the entry is abandoned,
        // which is reported rather than silent.
        let attempts = Rc::new(Cell::new(0));
        let log = Rc::new(RefCell::new(Vec::new()));
        // Seven polls: four at the threshold, then three below it, so the ticks
        // after the abandonment open no new entry and the ledger it leaves is
        // the one asserted on.
        let mut bot = EcsBot::builder("refusing")
            .observe(Script::new(vec![200, 200, 200, 200, 0, 0, 0]))
            .on(
                |value: &u16| *value >= 200,
                Refuses::undelivered(Rc::clone(&attempts)),
            )
            .on(|value: &u16| *value >= 200, Record(Rc::clone(&log)))
            .with_effects(test_effects()?)
            .build(&net_grants())?;

        for round in 1..=2 {
            let error = refused(bot.tick(), |fired| {
                format!("round {round} reported {fired} fired")
            })?;
            assert!(
                matches!(error, BotError::DomainError { .. }),
                "round {round}: expected the action's own error, got {error:?}"
            );
        }
        assert_eq!(attempts.get(), 2, "two ticks, two attempts");
        assert!(
            log.borrow().is_empty(),
            "the second entry is not run ahead of the entry holding it back"
        );
        assert_eq!(
            identities(&bot),
            vec![(0, 0), (0, 1)],
            "both entries are outstanding while the first keeps failing"
        );

        // Third attempt: the budget is spent and the entry is given up on
        // rather than retried forever. The tick reports the action's own typed
        // error, not a summary of it: a caller classifies a retry by matching
        // the variant, and rendering it into a string would throw that away.
        let error = refused(bot.tick(), |fired| {
            format!("a spent budget was reported as {fired} fired")
        })?;
        assert!(
            matches!(error, BotError::DomainError { .. }),
            "the abandonment does not replace the error that caused it: {error:?}"
        );
        assert_eq!(attempts.get(), 3, "exactly the declared budget was spent");

        // Giving up is reported, never silent: the entry is named with the
        // reason and the cause, and stays named.
        assert_eq!(
            first_hold(&bot),
            Some(TransitionHold::Abandoned {
                reason: AbandonReason::AttemptsExhausted { attempts: 3 },
                cause: "test::refuses: refused".into(),
            }),
            "the given-up-on entry is named after the tick that gave up on it"
        );

        // And the work it was holding back is not lost with it — but it is not
        // run either. The walk stops at the attempt that spent the budget, and
        // the abandonment it leaves is a barrier: the successor stays
        // `NotStarted` behind it and stays reported.
        //
        // These two assertions used to read `assert_eq!(bot.tick()?, 1, "the
        // unattempted work runs as soon as the entry ahead of it is decided")`
        // followed by `assert_eq!(*log.borrow(), vec![200])`, and later
        // `assert_eq!(bot.tick()?, 0, "the resolved transition fires nothing")`
        // while `pending()` was non-empty. Both are the F02 defect written down
        // as the intent — a successor executed past an abandoned prerequisite,
        // and a clean tick reported over work the ledger still names. They are
        // corrected rather than loosened: the tick is now expected to refuse
        // where it was expected to succeed.
        assert!(
            log.borrow().is_empty(),
            "the successor is not run ahead of the entry that was just decided"
        );
        let error = refused(bot.tick(), |fired| {
            format!(
                "a tick with an abandoned prerequisite reported {fired} fired and ran {:?}",
                log.borrow()
            )
        })?;
        assert!(
            matches!(error, BotError::PendingTransition { .. }),
            "expected the unresolved chain to be reported, got {error:?}"
        );
        assert!(
            log.borrow().is_empty(),
            "the unattempted work does not run past the entry that was given up on"
        );

        // Terminal, and the rest of the chain is blocked behind it, so the
        // transition stays reported: the abandonment first, because it is the
        // entry that explains the one behind it.
        let error = refused(bot.tick(), |fired| {
            format!(
                "an abandoned entry was reported as {fired} fired while pending() still \
                     names it: {:?}",
                bot.pending()
            )
        })?;
        assert!(
            matches!(error, BotError::PendingTransition { .. }),
            "expected the unresolved chain to be reported, got {error:?}"
        );
        assert!(
            identities(&bot) == vec![(0, 0), (0, 1)],
            "the abandoned entry and the entry it blocks are what is left to report: {:?}",
            bot.pending()
        );
        Ok(())
    }

    #[test]
    fn one_attempt_is_a_policy_a_caller_can_declare() -> TestResult {
        // The budget is a policy, not a constant: with one attempt the same
        // chain abandons on the first refusal instead of the third.
        let attempts = Rc::new(Cell::new(0));
        let log = Rc::new(RefCell::new(Vec::new()));
        let mut bot = EcsBot::builder("impatient")
            .with_retry_policy(RetryPolicy::ONE_ATTEMPT)
            .observe(Script::new(vec![200, 200, 200]))
            .on(
                |value: &u16| *value >= 200,
                Refuses::undelivered(Rc::clone(&attempts)),
            )
            .on(|value: &u16| *value >= 200, Record(Rc::clone(&log)))
            .with_effects(test_effects()?)
            .build(&net_grants())?;

        let error = refused(bot.tick(), |fired| {
            format!("a refusal was reported as {fired} fired")
        })?;
        assert!(
            matches!(error, BotError::DomainError { .. }),
            "expected the action's own error, got {error:?}"
        );
        assert_eq!(attempts.get(), 1, "the declared budget is one attempt");
        assert!(
            log.borrow().is_empty(),
            "the entry behind the abandoned one is not run in the tick that abandoned it"
        );

        // The next tick does not run what the abandoned entry was holding back,
        // and does not report a clean tick either. This assertion used to read
        // `assert_eq!(bot.tick()?, 1, "the next tick runs the work the abandoned
        // entry was holding back")`, which is the defect written down as the
        // intent: an abandonment is a prerequisite that is *not* satisfied, so
        // the send behind an unreserved draft must not run. It is corrected
        // rather than loosened — the tick is now expected to refuse, which is
        // strictly more than it was expected to do before.
        let error = refused(bot.tick(), |fired| {
            format!(
                "a tick with an abandoned prerequisite reported {fired} fired and ran {:?}",
                log.borrow()
            )
        })?;
        assert!(
            matches!(error, BotError::PendingTransition { .. }),
            "expected the unresolved chain to be reported, got {error:?}"
        );
        assert_eq!(attempts.get(), 1, "the abandoned entry is not retried");
        assert!(
            log.borrow().is_empty(),
            "the successor of an abandoned entry is not attempted while it stands abandoned"
        );
        assert_eq!(
            identities(&bot),
            vec![(0, 0), (0, 1)],
            "the abandonment and the entry it blocks are both still reported: {:?}",
            bot.pending()
        );

        // Evidence that the effect did not happen is the way past the barrier:
        // the entry becomes eligible again and its successor with it. The
        // action refuses once more, so this tick abandons it again — which is
        // the point of asserting it: evidence reopens the chain, it does not
        // promise the retry will succeed.
        let blocked = bot.pending().into_iter().next().ok_or("held")?;
        bot.resolve_effect(&held_key(&blocked)?, EffectEvidence::NotApplied)?;
        let error = refused(bot.tick(), |fired| {
            format!("a refusal was reported as {fired} fired")
        })?;
        assert!(
            matches!(error, BotError::DomainError { .. }),
            "expected the retry's own error, got {error:?}"
        );
        assert_eq!(attempts.get(), 2, "the revived entry attempted again");
        assert!(
            log.borrow().is_empty(),
            "and the successor is behind the barrier again, because the retry failed too"
        );
        Ok(())
    }

    #[test]
    fn a_failure_does_not_stop_a_later_chain() -> TestResult {
        // The second half of the defect: the old loop broke out of *every*
        // chain on the first error, so an independent chain behind a broken one
        // never ran, and never would.
        let attempts = Rc::new(Cell::new(0));
        let log = Rc::new(RefCell::new(Vec::new()));
        let mut bot = EcsBot::builder("two-chains")
            .observe(Script::new(vec![200, 200]))
            .on(
                |value: &u16| *value >= 200,
                Refuses::undelivered(Rc::clone(&attempts)),
            )
            .observe(Script::new(vec![200, 200]))
            .on(|value: &u16| *value >= 200, Record(Rc::clone(&log)))
            .with_effects(test_effects()?)
            .build(&net_grants())?;

        let error = refused(bot.tick(), |fired| {
            format!("a refused action was reported as {fired} fired")
        })?;
        assert!(
            matches!(error, BotError::DomainError { .. }),
            "expected the action's own error, got {error:?}"
        );
        assert_eq!(
            *log.borrow(),
            vec![200],
            "the chain after the failure ran: a failure is contained to its own chain"
        );
        assert_eq!(
            identities(&bot),
            vec![(0, 0)],
            "only the refusing chain has work outstanding: {:?}",
            bot.pending()
        );
        Ok(())
    }

    #[test]
    fn an_indeterminate_effect_is_held_until_evidence_says_what_happened() -> TestResult {
        // The effect may have happened, so a retry is a possible duplicate. The
        // substrate refuses to guess: it holds the entry, reports it every
        // tick, and waits for evidence.
        let log = Rc::new(RefCell::new(Vec::new()));
        let mut bot = indeterminate_once_bot("indeterminate", &log)?;

        let error = refused(bot.tick(), |fired| {
            format!("an indeterminate effect was reported as {fired} fired")
        })?;
        assert!(
            matches!(error, BotError::EffectIndeterminate { .. }),
            "expected the action's own error, got {error:?}"
        );
        assert!(
            log.borrow().is_empty(),
            "an indeterminate effect is not an effect: nothing was recorded"
        );

        // The source has not moved, and the entry is not re-attempted: a blind
        // retry is exactly the duplicate this state exists to prevent.
        let error = refused(bot.tick(), |fired| {
            format!("a held effect was reported as {fired} fired")
        })?;
        let BotError::PendingTransition { work, outstanding } = error else {
            return Err(format!("expected PendingTransition, got {error:?}").into());
        };
        assert_eq!(identity(&work), (0, 0), "the held entry is named");
        assert!(
            matches!(
                work.hold(),
                TransitionHold::OutcomeUnknown { attempts: 1, .. }
            ),
            "the hold carries the attempt that could not be settled: {:?}",
            work.hold()
        );
        assert_eq!(outstanding, 1, "one entry is still open");
        assert!(
            bot.pending()
                .iter()
                .all(|work| !matches!(work.hold(), TransitionHold::Abandoned { .. })),
            "nothing was given up on: {:?}",
            bot.pending()
        );
        assert!(
            log.borrow().is_empty(),
            "a held effect is not attempted again without evidence"
        );

        // Evidence that it did not happen: the entry becomes eligible again and
        // the attempt finally lands. The revision the report carries is passed
        // back with the identity, which is what makes this delivery sound: the
        // evidence is about the generation the caller was shown.
        let held = bot
            .pending()
            .into_iter()
            .next()
            .ok_or("the held entry disappeared from the report")?;
        bot.resolve_effect(&held_key(&held)?, EffectEvidence::NotApplied)?;
        assert_eq!(bot.tick()?, 1, "the entry runs once evidence authorises it");
        assert_eq!(*log.borrow(), vec![200], "the effect happened, once");
        assert!(
            bot.pending().is_empty(),
            "and nothing is left holding the transition: {:?}",
            bot.pending()
        );
        Ok(())
    }

    #[test]
    fn evidence_that_the_effect_happened_records_it_without_replaying_it() -> TestResult {
        // The other half of the evidence question, and the one that saves the
        // duplicate: the caller knows the effect is live, so it is acknowledged
        // and never attempted again.
        let log = Rc::new(RefCell::new(Vec::new()));
        let mut bot = indeterminate_once_bot("acknowledged", &log)?;

        let error = refused(bot.tick(), |fired| {
            format!("an indeterminate effect was reported as {fired} fired")
        })?;
        assert!(
            matches!(error, BotError::EffectIndeterminate { .. }),
            "expected the action's own error, got {error:?}"
        );

        let held = bot
            .pending()
            .into_iter()
            .next()
            .ok_or("the held entry is not reported")?;
        bot.resolve_effect(&held_key(&held)?, EffectEvidence::Applied)?;
        assert_eq!(
            bot.tick()?,
            0,
            "an acknowledged effect is never attempted again"
        );
        assert!(
            log.borrow().is_empty(),
            "the action that may already have run was not run a second time"
        );
        assert_eq!(bot.revisions(), vec![1], "and the transition is resolved");
        assert!(
            bot.pending().is_empty(),
            "nothing is left pending: {:?}",
            bot.pending()
        );

        // A repeat of the same evidence after the slot is gone is accepted
        // idempotently. It used to be refused as `NoSuchWork`, and that is how
        // the same acknowledgement stopped being a safe retry across a restart:
        // a reconstructed bot has no live slot to consult, and the journal's
        // record is the fact that answers (issue #106). Nothing moves a second
        // time — the durable record is already there.
        bot.resolve_effect(&held_key(&held)?, EffectEvidence::Applied)?;
        // The other evidence is still a contradiction, and it is refused
        // rather than silently replacing what was recorded. `NoSuchWork` is
        // reserved for a key the journal never recorded; this one was, and the
        // distinction is the whole reason the refusals are typed apart.
        match bot.resolve_effect(&held_key(&held)?, EffectEvidence::NotApplied) {
            Ok(()) => Err("contradicting evidence was accepted".into()),
            Err(error) => {
                assert!(
                    matches!(
                        error,
                        BotError::EvidenceContradicted {
                            settled: EffectEvidence::Applied,
                            submitted: EffectEvidence::NotApplied,
                            ..
                        }
                    ),
                    "expected EvidenceContradicted, got {error:?}"
                );
                Ok(())
            }
        }
    }

    #[test]
    fn a_source_that_moves_while_work_is_outstanding_neither_loses_nor_duplicates_it() -> TestResult
    {
        // Two movements while work is outstanding, and then a movement after it
        // resolves. An entry the transition is *holding* reads the payload the
        // transition was opened under — not the newest one — while an entry in a
        // new transition reads the newest; the effect that already happened is
        // not replayed; and the chain is not wedged afterwards.
        let first = Rc::new(RefCell::new(Vec::new()));
        let second = Rc::new(RefCell::new(Vec::new()));
        let mut bot = EcsBot::builder("moving")
            .observe(Script::new(vec![200, 503, 200, 200]))
            .on(|value: &u16| *value >= 200, Record(Rc::clone(&first)))
            .on(
                |value: &u16| *value >= 200,
                Flaky {
                    remaining: Rc::new(Cell::new(1)),
                    log: Rc::clone(&second),
                    kind: FlakyKind::Refused,
                },
            )
            .with_effects(test_effects()?)
            .build(&net_grants())?;

        let error = refused(bot.tick(), |fired| {
            format!("a refusal was reported as {fired} fired")
        })?;
        assert!(
            matches!(error, BotError::DomainError { .. }),
            "expected the action's own error, got {error:?}"
        );
        assert_eq!(*first.borrow(), vec![200], "the first entry ran once");
        assert!(second.borrow().is_empty(), "the second entry refused");

        // 503 arrives while the second entry is still outstanding. The
        // acknowledged first entry is not replayed to reach it, and the retry
        // runs against the value the transition is *bound to*: 200, the value
        // the first entry already succeeded on.
        //
        // This is the invariant, and it used to read the other way — the retry
        // took the value as it stood, and this test asserted `vec![503]` under
        // the words "the outstanding entry reads the newest value, not the one
        // it failed on". That is F04 stated as intent: entry zero had produced
        // an effect of 200, entry one would then produce an effect of 503, and
        // the transition would have acted on two command inputs while reporting
        // itself as one unit of work. A transition is one input.
        assert_eq!(bot.tick()?, 1, "only the outstanding entry runs");
        assert_eq!(
            *first.borrow(),
            vec![200],
            "an effect the transition already acknowledged is not replayed for a later movement"
        );
        assert_eq!(
            *second.borrow(),
            vec![200],
            "the outstanding entry reads the payload its transition was opened under, \
             not the one that arrived since"
        );
        assert!(
            bot.pending().is_empty(),
            "the transition is fully resolved: {:?}",
            bot.pending()
        );

        // The source is back at 200 by the next tick, which is the value the
        // transition was opened under and acknowledged against. Nothing is
        // admitted, so nothing fires: the 503 the source passed through on the
        // way is superseded, and re-running both entries here would replay an
        // effect that is already acknowledged — the duplicate half of this
        // test's name.
        //
        // This assertion used to read `assert_eq!(bot.tick()?, 2, "a new
        // movement re-evaluates both entries")` with `vec![503, 200]` logged for
        // the second entry, and it was only true because the retry above had
        // already jumped to 503. Under the binding it is 200 that is current,
        // 200 that the chain has already handled, and 503 that nothing ever
        // acted on — and nothing claims it did.
        //
        // What a source that *stays* moved does is the other half of the
        // invariant, and `an_open_transition_is_bound_to_the_payload_it_was_opened_under`
        // is where it is pinned: the new value is admitted as soon as the
        // transition has nothing open, over every entry, against itself.
        assert_eq!(
            bot.tick()?,
            0,
            "a source that has returned to the value the transition was acknowledged \
             for is not new work"
        );
        assert_eq!(
            *first.borrow(),
            vec![200],
            "and the acknowledged effect is not replayed to make it look like one"
        );
        assert_eq!(*second.borrow(), vec![200], "nor is the second entry");
        // A movement that did not move is still nothing at all.
        assert_eq!(
            bot.tick()?,
            0,
            "a still source with no outstanding work fires nothing"
        );
        assert_eq!(
            bot.revisions(),
            vec![3],
            "three polls moved the value: 200, 503, 200"
        );
        Ok(())
    }

    #[test]
    fn an_attempt_whose_outcome_was_never_recorded_is_held_not_replayed() -> TestResult {
        // The state a tick leaves behind when an attempt was begun and no
        // outcome was recorded. The effect may be live, so the next tick holds
        // it — replaying it is the duplicate this state exists to prevent.
        //
        // The journal is kept honest while the ledger is put into the state:
        // the write-ahead (`IntentAdmitted`, `DispatchPrepared`) is committed
        // by a real dispatch and the outcome append is refused underneath it,
        // which is exactly the crash window this hold names. Fabricating
        // `Unrecorded` over a key whose outcome the journal already holds
        // would make the later `NotApplied` a contradiction rather than a
        // settlement, and the journal is the fact that wins (issue #106).
        let log = Rc::new(RefCell::new(Vec::new()));
        let journal = FaultJournal::new();
        let refuse_outcome = journal.refuse_outcome();
        refuse_outcome.set(true);
        let mut bot = EcsBot::builder("interrupted")
            .observe(Script::new(vec![200, 200, 200]))
            .on(|value: &u16| *value >= 200, Record(Rc::clone(&log)))
            .with_effects(test_effects_with(Box::new(journal))?)
            .build(&net_grants())?;

        let error = refused(bot.tick(), |fired| {
            format!("a refused outcome append reported {fired} fired")
        })?;
        assert!(
            matches!(error, BotError::EffectUnrecorded { .. }),
            "expected the outcome append's own failure, got {error:?}"
        );
        assert_eq!(*log.borrow(), vec![200], "the action ran once");
        refuse_outcome.set(false);
        {
            let revision = *bot.revisions().first().ok_or("the source has a revision")?;
            // The payload is part of the record: a transition is bound to the
            // observation it was opened under, and the value here is the one the
            // script has been answering with. `None` would be a transition
            // opened with nothing observed, which holds its entries rather than
            // evaluating them against a value nobody read — a real state, but
            // not this one.
            // The same admitted input the first tick bound: a fabricated
            // stamp would mint a key the journal never recorded, and the
            // later settlement would be about a different attempt entirely.
            let input = bot
                .world
                .non_send::<Ledger>()
                .transitions
                .first()
                .and_then(Option::as_ref)
                .map_or_else(
                    || AdmittedInput {
                        identity: derive_input_stamp(1),
                        event: false,
                    },
                    |held| AdmittedInput {
                        identity: held.input,
                        event: held.event,
                    },
                );
            let mut transition = Transition::opened(input, revision, 1, Some(Erased::new(200_u16)));
            *transition
                .entries
                .first_mut()
                .ok_or("the chain declares no entries")? = EntryState::Unrecorded;
            // The attempt the unrecorded entry is on. `Unrecorded` is the state
            // a prepared dispatch leaves, so there is always an attempt to name
            // it by — and the record has to carry one, because the key a caller
            // settles against is derived from the attempt and an entry with no
            // attempt has no key for evidence to be about.
            *transition
                .attempts
                .first_mut()
                .ok_or("the chain declares no entries")? = AttemptRecord {
                begun: Some(AttemptId::FIRST),
                settled: None,
            };
            bot.world.non_send_mut::<Ledger>().put(0, Some(transition));
        }

        assert!(
            matches!(first_hold(&bot), Some(TransitionHold::Unrecorded)),
            "the interrupted attempt is reported as unrecorded: {:?}",
            first_hold(&bot)
        );
        let error = refused(bot.tick(), |fired| {
            format!("an unrecorded attempt fired {fired}")
        })?;
        let BotError::PendingTransition { work, .. } = error else {
            return Err(format!("expected PendingTransition, got {error:?}").into());
        };
        assert!(
            matches!(work.hold(), TransitionHold::Unrecorded),
            "the tick reports it as held, not as handled: {:?}",
            work.hold()
        );
        assert_eq!(
            *log.borrow(),
            vec![200],
            "the action was not run a second time: the first attempt may have taken effect"
        );

        // Evidence that it did not take effect is what unlocks the retry, and
        // it is evidence about the generation the caller was shown.
        let held = bot
            .pending()
            .into_iter()
            .next()
            .ok_or("the held entry is not reported")?;
        bot.resolve_effect(&held_key(&held)?, EffectEvidence::NotApplied)?;
        assert_eq!(bot.tick()?, 1, "and then it runs");
        assert_eq!(*log.borrow(), vec![200, 200], "exactly once more");
        Ok(())
    }

    #[test]
    fn an_action_identity_is_framed_and_portable() -> TestResult {
        // Two different parses that an unframed concatenation collapses:
        // "ab"+"c" and "a"+"bc" are the same byte string with no lengths, and
        // the same ActionId for two different declarations (issue #101).
        let ab_c = derive_action_id("ab", 0, 0, "c");
        let a_bc = derive_action_id("a", 0, 0, "bc");
        assert_ne!(
            ab_c, a_bc,
            "length framing keeps \"ab\"+\"c\" apart from \"a\"+\"bc\""
        );
        // The index is u64 either way, so this is the 32-/64-bit vector in
        // one target's clothes: the same declaration always derives the same
        // identity, and a different position never does.
        assert_eq!(
            derive_action_id("bot", 2, 3, "dom"),
            derive_action_id("bot", 2, 3, "dom")
        );
        assert_ne!(
            derive_action_id("bot", 2, 3, "dom"),
            derive_action_id("bot", 2, 3, "dom2"),
            "a different domain is a different action"
        );
        assert_ne!(
            derive_action_id("bot", 2, 3, "dom"),
            derive_action_id("bot", 3, 2, "dom"),
            "chain and entry do not commute"
        );
        // A variable-length name cannot slide into the next field: the old
        // unframed hash gave these two the same digest.
        assert_ne!(
            derive_action_id("bot", 0, 0, "dom"),
            derive_action_id("bo", 0, 0, "tdom"),
            "length framing keeps \"bot\"+\"dom\" apart from \"bo\"+\"tdom\""
        );
        Ok(())
    }

    #[test]
    fn an_unattempted_false_condition_still_skips_and_lets_its_successor_run() -> TestResult {
        // The control for issue #104's barrier: a false condition on an entry
        // that was never attempted is still a legitimate `Skip`, and the
        // successor still runs. The barrier exists for a *recovered unknown*,
        // not for every false condition — without this test the repair could
        // stop the chain at every skip and read as correct.
        let log = Rc::new(RefCell::new(Vec::new()));
        let mut bot = EcsBot::builder("legitimate-skip")
            .observe(Script::new(vec![200]))
            .on(|value: &u16| *value < 200, Record(Rc::clone(&log)))
            .on(|value: &u16| *value >= 200, Record(Rc::clone(&log)))
            .with_effects(test_effects()?)
            .build(&net_grants())?;

        assert_eq!(bot.tick()?, 1, "the successor ran behind a skipped entry");
        assert_eq!(
            *log.borrow(),
            vec![200],
            "exactly one action, the successor's: {:?}",
            *log.borrow()
        );
        assert_eq!(bot.revisions(), vec![1], "the transition resolved");
        assert!(
            bot.pending().is_empty(),
            "a skipped entry owes nothing: {:?}",
            bot.pending()
        );
        Ok(())
    }

    #[test]
    fn a_condition_that_cannot_be_evaluated_holds_the_chain_without_claiming_anything() -> TestResult
    {
        // A condition failure decides nothing about the effect. The entry has
        // not been attempted, nothing about it is claimed, and the entry behind
        // it is not run ahead of a question that has no answer — the failure
        // the old substrate turned into "this chain is done".
        //
        // The mismatched condition is built *behind* the builder now, because
        // the typed `on` refuses it: a `u16` source cannot carry a condition
        // that reads a `String`. That refusal is the front half of this fix, and
        // the back half is still needed, because erasure is not the only way to
        // reach a mis-paired chain — anything holding this world can insert an
        // entry. `typed_entry` is the erasure helper and keeps its free `T`, so
        // it can still express the defect; this test is the one place that does,
        // on purpose, to pin what happens when it is reached.
        let log = Rc::new(RefCell::new(Vec::new()));
        let mut bot = EcsBot::builder("mismatched")
            .observe(Script::new(vec![200, 200]))
            .on(|value: &u16| *value >= 200, Record(Rc::clone(&log)))
            .with_effects(test_effects()?)
            .build(&net_grants())?;
        bot.world.non_send_mut::<Chains>().0[0].entries.insert(
            0,
            typed_entry::<_, _, String>(|value: &String| value.len() >= 3, Record(Rc::clone(&log))),
        );

        let error = refused(bot.tick(), |fired| {
            format!("an evaluate error was reported as {fired} fired")
        })?;
        assert!(
            matches!(error, BotError::EvaluateError { .. }),
            "expected the condition's own error, got {error:?}"
        );
        assert!(log.borrow().is_empty(), "nothing was attempted");
        assert_eq!(
            identities(&bot),
            vec![(0, 0), (0, 1)],
            "the entry whose condition failed is still outstanding, and so is the entry \
             behind it: {:?}",
            bot.pending()
        );
        assert_eq!(
            first_hold(&bot),
            Some(TransitionHold::NotStarted),
            "a condition that cannot be evaluated is not an attempt, so nothing is abandoned"
        );

        // And it stays that way rather than decaying into an abandonment: the
        // report is the truth, not a stage on the way to losing the work.
        let error = refused(bot.tick(), |fired| {
            format!("the second tick reported {fired} fired")
        })?;
        assert!(
            matches!(error, BotError::EvaluateError { .. }),
            "the condition is evaluated again, not silently given up on: {error:?}"
        );
        assert!(log.borrow().is_empty(), "and still nothing was attempted");
        Ok(())
    }

    #[test]
    fn a_condition_failure_stops_the_walk_after_the_effects_it_cleared() -> TestResult {
        // The other half of "partial run", on the condition side, and a
        // characterisation rather than a new guarantee: this passes before and
        // after the decision phase was split out of the effect phase, and it is
        // here because that split is only sound if it does.
        //
        // Conditions are pure over the observed value, so the whole effect
        // program can be recorded before any of it runs. The equivalence to the
        // interleaved loop it replaced rests on exactly three things: the
        // entries before a failing condition still run, the entries after it
        // are not attempted, and the tick reports the condition's own error.
        let log = Rc::new(RefCell::new(Vec::new()));
        let after = Rc::new(Cell::new(0));
        let mut bot = EcsBot::builder("condition-failure")
            .observe(Script::new(vec![200, 200]))
            .on(|value: &u16| *value >= 200, Record(Rc::clone(&log)))
            .on(RefusesToEvaluate, Count(Rc::clone(&after)))
            .on(|value: &u16| *value >= 200, Count(Rc::clone(&after)))
            .with_effects(test_effects()?)
            .build(&net_grants())?;

        let error = refused(bot.tick(), |fired| {
            format!("a refused condition was reported as {fired} fired")
        })?;
        assert!(
            matches!(error, BotError::EvaluateError { .. }),
            "expected the condition's own error, got {error:?}"
        );
        assert_eq!(
            *log.borrow(),
            vec![200],
            "the effect the walk cleared before the failing condition ran"
        );
        assert_eq!(
            after.get(),
            0,
            "the entries after the failing condition were not attempted"
        );
        Ok(())
    }

    #[test]
    fn an_ambiguous_schedule_is_refused_at_build() -> TestResult {
        let mut world = World::new();

        // Two exclusive systems conflict with everything, including each other,
        // so their relative order is indeterminate.
        let mut ambiguous = Schedule::default();
        ambiguous.set_build_settings(ScheduleBuildSettings {
            ambiguity_detection: LogLevel::Error,
            ..Default::default()
        });
        ambiguous.add_systems((observe_fold, fire_plan));

        match validate(&mut ambiguous, &mut world) {
            Ok(()) => return Err("an ambiguous schedule was accepted at build".into()),
            Err(error) => assert!(
                matches!(error, BotError::DomainError { .. }),
                "a schedule-build failure must surface as a typed BotError, got {error:?}"
            ),
        }

        // Control: the same two systems, ordered, must validate. Without this
        // the refusal above could be any failure at all.
        let mut ordered = Schedule::default();
        ordered.set_build_settings(ScheduleBuildSettings {
            ambiguity_detection: LogLevel::Error,
            ..Default::default()
        });
        ordered.add_systems((observe_fold, fire_plan).chain());
        validate(&mut ordered, &mut world)?;
        Ok(())
    }

    /// An action that declares `Input = u32` while counting its attempts.
    ///
    /// Paired below with a `u16` source: the pairing is the fault, and the
    /// count is how the test tells "one attempt" from "the whole budget".
    struct CountsU32(Rc<Cell<usize>>);

    impl Execute for CountsU32 {
        type Input = u32;
        type Output = ();

        fn required_caps(&self) -> &[Cap] {
            &[]
        }

        fn effect_lifetime(&self) -> EffectLifetime {
            EffectLifetime::Local
        }

        async fn execute_action(&self, call: (Auth, &u32)) -> Result<(), BotError> {
            call.0.check(&[])?;
            self.0.set(self.0.get().saturating_add(1));
            Ok(())
        }

        fn domain_id(&self) -> &str {
            "test::counts_u32"
        }
    }

    #[test]
    fn a_mispairing_behind_the_erasure_is_a_witness_miss() -> TestResult {
        // The pairing from `Chains` to `Observed` is by index, and a vector
        // position carries no type. This is that pairing gone wrong: the chain
        // declares a `u16` source, and the staged value is a `u32`.
        //
        // Written into the staging resource directly, because the shipped path
        // cannot produce this state: `poll_sources` boxes the output of the very
        // source it took the witness from, so a disagreement means the world
        // moved behind the schedule's back. That is precisely the state the
        // witness exists to refuse rather than to downcast, and it is why the
        // test has to construct it rather than trigger it.
        //
        // The assertions are the three things the witness is for. It fires
        // *before* the value is used, so nothing is committed and no condition
        // is asked. It names both types and the site. And it is a mismatch, not
        // a domain failure, so the disposition is terminal and no retry budget
        // is touched.
        let ran = Rc::new(Cell::new(0));
        let mut bot = EcsBot::builder("mispairing")
            .observe(Script::new(vec![200]))
            .on(
                |value: &u16| *value >= 200,
                Refuses::undelivered(Rc::clone(&ran)),
            )
            .with_effects(test_effects()?)
            .build(&net_grants())?;

        // `Ok(Some(_))`: a value that *moved*, which is the only shape that
        // carries a witness to check. A source answering `Ok(None)` has proven
        // its pairing by downcasting the baseline to its own output type, and
        // there is nothing left for the rendezvous to inspect.
        bot.world.non_send_mut::<Polled>().0 = vec![Ok(Some(Erased::new(300u32)))];
        bot.schedule.run(&mut bot.world);

        match bot.world.resource::<TickError>().0 {
            Some(BotError::TypeMismatch {
                site,
                chain,
                expected,
                observed,
            }) => {
                assert_eq!(site, "observe_fold rendezvous", "the site is greppable");
                assert_eq!(chain, Some(0), "the report names which chain disagreed");
                assert_eq!(expected, "u16", "the chain's claim");
                assert_eq!(observed, "u32", "what actually arrived");
            }
            ref other => {
                return Err(format!("expected a witness miss, got {other:?}").into());
            }
        }

        assert!(
            bot.world
                .non_send::<Observed>()
                .0
                .iter()
                .all(Option::is_none),
            "the fold commits nothing on a mismatch, so the previous tick's state survives"
        );
        assert_eq!(ran.get(), 0, "the action was never reached");
        Ok(())
    }

    #[test]
    fn a_mismatched_pairing_costs_one_attempt_not_the_retry_budget() -> TestResult {
        // The chain is wired for `u16` while the action declares `u32`. That is
        // a wiring defect behind the erasure, not a domain failure: no number
        // of retries reaches a different answer, so it costs one attempt and
        // lands as terminal rather than spending the whole budget and being
        // reported as "we ran out of budget" — which names the budget as the
        // reason when the reason is that the two halves disagree.
        //
        // The report names both types, which is what makes it a diagnosis
        // rather than a report that something is wrong somewhere. It names no
        // domain, because no domain was reached.
        //
        // The attempt count is read from the ledger rather than counted by the
        // action, because the action must never be reached: the downcast is
        // checked before the proof is issued, so a mismatch costs no side
        // effect. `ran` is that second half.
        // Built behind the builder for the same reason as the condition
        // mismatch above: `on` no longer admits `CountsU32` on a `u16` source,
        // which is the fix, and the downcast arm is still what reports the
        // mis-pairing that reaches the erasure boundary anyway.
        let ran = Rc::new(Cell::new(0));
        let log = Rc::new(RefCell::new(Vec::new()));
        let mut bot = EcsBot::builder("mismatched")
            .observe(Script::new(vec![200, 200, 200, 200]))
            .on(|value: &u16| *value >= 200, Record(Rc::clone(&log)))
            .with_effects(test_effects()?)
            .build(&net_grants())?;
        bot.world.non_send_mut::<Chains>().0[0].entries[0] =
            typed_entry::<_, _, u16>(|value: &u16| *value >= 200, CountsU32(Rc::clone(&ran)));

        let error = refused(bot.tick(), |fired| {
            format!("a wiring mismatch was reported as {fired} fired")
        })?;
        assert!(
            matches!(
                error,
                BotError::TypeMismatch {
                    site: "spec::typed_entry",
                    expected: "u32",
                    observed: "u16",
                    ..
                }
            ),
            "a wiring defect is a type mismatch naming both types, not a domain failure: {error:?}"
        );
        assert_eq!(
            ran.get(),
            0,
            "the downcast is checked before the action runs, so the mismatch was not a side effect"
        );
        assert!(
            matches!(
                first_hold(&bot),
                Some(TransitionHold::Abandoned {
                    reason: AbandonReason::Terminal,
                    ..
                })
            ),
            "one attempt, and the disposition is terminal rather than `AttemptsExhausted`: {:?}",
            first_hold(&bot)
        );

        // The second tick must not spend a second attempt on the same answer.
        // That is the observable difference the budget makes: `AttemptsExhausted`
        // is a fact about how many times the substrate was willing to ask, and
        // asking twice here buys nothing.
        let error = refused(bot.tick(), |fired| {
            format!("a retried wiring mismatch reported {fired} fired")
        })?;
        assert!(
            matches!(error, BotError::PendingTransition { .. }),
            "the abandoned entry is the barrier the next tick reports, got {error:?}"
        );
        Ok(())
    }

    #[test]
    fn a_permanent_refusal_does_not_burn_the_retry_budget() -> TestResult {
        // A refusal that happens before dispatch and cannot be changed by
        // repeating it. Retrying spends attempts to learn the same answer, and
        // the report then blames the budget for a failure the budget was never
        // the reason for.
        let attempts = Rc::new(Cell::new(0));
        let mut bot = EcsBot::builder("permanent")
            .observe(Script::new(vec![200, 200, 200, 200]))
            .on(
                |value: &u16| *value >= 200,
                Refuses::permanently(Rc::clone(&attempts)),
            )
            .with_effects(test_effects()?)
            .build(&net_grants())?;

        let error = refused(bot.tick(), |fired| {
            format!("a permanent refusal was reported as {fired} fired")
        })?;
        assert!(
            matches!(error, BotError::DomainError { .. }),
            "expected the action's own error, got {error:?}"
        );
        assert_eq!(attempts.get(), 1, "a permanent refusal is attempted once");
        assert!(
            matches!(
                first_hold(&bot),
                Some(TransitionHold::Abandoned {
                    reason: AbandonReason::Terminal,
                    ..
                })
            ),
            "the disposition is terminal, not `AttemptsExhausted`: {:?}",
            first_hold(&bot)
        );
        Ok(())
    }

    // ── admitted-input identity framing ─────────────────────────────────────

    /// Two output types whose `type_name`s share a prefix, the pair the
    /// identity scheme must keep apart (issue #118).
    ///
    /// `PrefixProbeTail`'s type name is `PrefixProbe`'s name plus `b"Tail"`,
    /// and `PrefixProbe` writes that same suffix at the head of its identity
    /// bytes, so an unframed `name || bytes` stream would collide byte for
    /// byte. Under the declared-schema scheme they are distinct because their
    /// authors declared distinct schema ids — the name games cannot reach the
    /// digest any more.
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    struct PrefixProbe;

    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    struct PrefixProbeTail;

    /// The byte difference between the two type names above.
    const PREFIX_PROBE_SUFFIX: &[u8] = b"Tail";

    impl InputIdentity for PrefixProbe {
        const SCHEMA_ID: &'static [u8] = b"lgwks.bot.schema.v1.test-prefix-probe";

        fn write_identity(&self, hasher: &mut Hasher) {
            hasher.update(PREFIX_PROBE_SUFFIX);
            hasher.update(b"payload");
        }
    }

    impl InputIdentity for PrefixProbeTail {
        const SCHEMA_ID: &'static [u8] = b"lgwks.bot.schema.v1.test-prefix-probe-tail";

        fn write_identity(&self, hasher: &mut Hasher) {
            hasher.update(b"payload");
        }
    }

    /// A second schema of a type whose identity bytes are byte-for-byte
    /// identical to [`PrefixProbe`]'s — the control that proves the schema
    /// id, not the bytes, separates the two.
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    struct PrefixProbeNextSchema;

    impl InputIdentity for PrefixProbeNextSchema {
        const SCHEMA_ID: &'static [u8] = b"lgwks.bot.schema.v2.test-prefix-probe";

        fn write_identity(&self, hasher: &mut Hasher) {
            hasher.update(PREFIX_PROBE_SUFFIX);
            hasher.update(b"payload");
        }
    }

    /// The source type for the identity known-answer vectors.
    ///
    /// [`identify_output`] reads only a source's output type, so these tests name
    /// a source without building or ticking a bot over it. One generic type
    /// stands for every output they derive an identity for, and a poll — which
    /// none of them makes — is refused rather than answered.
    struct Unpolled<T>(PhantomData<fn() -> T>);

    impl<T> Observe for Unpolled<T> {
        type Output = T;

        fn required_caps(&self) -> &[Cap] {
            &[]
        }

        async fn poll(&self, _call: (Auth, ())) -> Result<T, BotError> {
            domain_refusal("test::unpolled", "identity fixtures are never polled")
        }

        fn domain_id(&self) -> &str {
            "test::unpolled"
        }
    }

    /// A payload whose identity bytes are identical to `u64`'s — the control
    /// that proves the inner schema id, not the bytes, keeps two wrapper
    /// types apart.
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    struct AltTick(u64);

    impl InputIdentity for AltTick {
        const SCHEMA_ID: &'static [u8] = b"lgwks.bot.schema.v1.test-alt-tick";

        fn write_identity(&self, hasher: &mut Hasher) {
            hasher.update(&self.0.to_le_bytes());
        }
    }

    #[test]
    fn two_output_types_sharing_a_name_prefix_hash_two_identities() {
        let plain = identify_output::<Unpolled<PrefixProbe>>(&PrefixProbe);
        let tail = identify_output::<Unpolled<PrefixProbeTail>>(&PrefixProbeTail);
        assert_ne!(
            plain.identity, tail.identity,
            "the declared schema ids must separate the pair their name and \
             byte streams would collide"
        );
    }

    #[test]
    fn a_schema_bump_moves_the_identity_of_identical_bytes() {
        // The declared migration boundary: same identity bytes under a
        // different schema id are different admitted inputs. A recovered
        // journal from the old schema therefore derives a different dispatch
        // digest and is refused as superseded rather than folded.
        let current = identify_output::<Unpolled<PrefixProbe>>(&PrefixProbe);
        let next = identify_output::<Unpolled<PrefixProbeNextSchema>>(&PrefixProbeNextSchema);
        assert_ne!(current.identity, next.identity);
    }

    #[test]
    fn the_same_output_hashes_one_identity_every_time() {
        let first = identify_output::<Script>(&7_u16);
        let second = identify_output::<Script>(&7_u16);
        assert_eq!(first.identity, second.identity);
        assert_eq!(first.event, second.event);
    }

    #[test]
    fn a_downcast_miss_still_names_the_binding_it_refused() {
        let hit = identify_output::<Script>(&7_u16);
        let miss = identify_output::<Script>(&1_000_u32);
        assert_ne!(
            hit.identity, miss.identity,
            "a missed downcast must not read as an admission of the value"
        );
    }

    #[test]
    fn the_same_event_twice_and_two_events_hash_as_documented() {
        let redelivery = identify_output::<Unpolled<EventId<u64>>>(&EventId::new(5_u64, 7_u64));
        let again = identify_output::<Unpolled<EventId<u64>>>(&EventId::new(5_u64, 7_u64));
        assert_eq!(
            redelivery.identity, again.identity,
            "the same event id over the same payload is one event"
        );
        assert!(redelivery.event, "EventId names an event");

        let other_id = identify_output::<Unpolled<EventId<u64>>>(&EventId::new(6_u64, 7_u64));
        assert_ne!(redelivery.identity, other_id.identity);

        // The payload's schema rides inside the wrapper's stream, so equal
        // ids over identical written bytes from different payload types stay
        // distinct.
        let other_payload =
            identify_output::<Unpolled<EventId<AltTick>>>(&EventId::new(5_u64, AltTick(7_u64)));
        assert_ne!(redelivery.identity, other_payload.identity);
    }

    /// Known-answer vectors for the `v2` identity scheme (issue #118).
    ///
    /// Each vector pins the exact 16-byte identity a stream must produce from
    /// its declared parts: domain, schema id, identity bytes. A toolchain,
    /// module path or crate rename cannot move these values — the stream
    /// contains none of them — so any change here is a deliberate scheme
    /// change, and the vector is what refuses it.
    #[test]
    fn identity_known_answer_vectors_hold() {
        let hex = |identity: [u8; 16]| {
            identity
                .iter()
                .map(|byte| format!("{byte:02x}"))
                .collect::<String>()
        };

        let u16_seven = hex(identify_output::<Script>(&7_u16).identity);
        assert_eq!(
            u16_seven, "878e8add50e816abdbb0901de9ed7788",
            "the u16 vector moved: the v2 identity scheme changed"
        );

        let str_value = identify_output::<Unpolled<String>>(&String::from("settle")).identity;
        assert_eq!(
            hex(str_value),
            "174d75182e8e31c49374da2f22e0b353",
            "the string vector moved: the v2 identity scheme changed"
        );

        let event = identify_output::<Unpolled<EventId<u64>>>(&EventId::new(9_u64, true)).identity;
        assert_eq!(
            hex(event),
            "f4d5d8a77b9fed69dd1474cf0620348a",
            "the event-id vector moved: the v2 identity scheme changed"
        );

        // A refused binding has its own vector: the miss names the schema it
        // refused, and the value it refused is deliberately absent.
        let miss = identify_output::<Script>(&1_000_u32).identity;
        assert_eq!(
            hex(miss),
            "f2e18c137ba6e62e78f672c22c02bc66",
            "the refused-binding vector moved: the v2 identity scheme changed"
        );
    }

    /// The applied-key index answers the same questions the vector did, at a
    /// history size where scanning before every push was quadratic.
    ///
    /// This drives the shipped path: [`Effects::note_applied`] is what the live
    /// settle and the recovered seeding both call, and [`Effects::applied_in`]
    /// is what the walk asks before it dispatches. Each key's digest is the one
    /// `applied_in` recomputes for its coordinates, which is the discriminating
    /// part — a wrong index answers false for a key it holds. The old
    /// `Vec<EffectKey>` would need Θ(n²) comparisons to build this set; the
    /// indexed form builds and queries it in one pass.
    #[test]
    fn applied_membership_answers_at_scale_where_a_scan_would_be_quadratic() -> TestResult {
        /// Distinct actions, one per obligation. Large enough that the removed
        /// scan-before-push is visibly quadratic, small enough for a suite.
        const COUNT: u64 = 50_000;

        /// A distinct 16-byte action id for `index`.
        fn action_for(index: u64) -> Result<ActionId, Box<dyn std::error::Error>> {
            Ok(ActionId::from_hex(&format!(
                "{:032x}",
                index.wrapping_add(1)
            ))?)
        }
        /// The coordinates `applied_in` would ask about for `index`.
        fn coordinates(index: u64) -> Result<(usize, usize), Box<dyn std::error::Error>> {
            let chain = index.checked_rem(16).ok_or("sixteen chains is not zero")?;
            let entry = index.checked_div(16).ok_or("sixteen chains is not zero")?;
            Ok((usize::try_from(chain)?, usize::try_from(entry)?))
        }

        let scope = test_effects()?;
        let mut effects = Effects::new(scope, JournalPosition::genesis());
        let identity = effects.identity();
        let flow = identity.flow();
        let run = identity.run();
        let environment = identity.environment();
        let epoch = EnvironmentEpoch::from_decimal("1")?;
        let attempt = AttemptId::from_decimal("1")?;
        let input = [0u8; 16];

        for index in 0..COUNT {
            let (chain, entry) = coordinates(index)?;
            let key = crate::effect::EffectIdentity::new(run, environment, flow).key(
                action_for(index)?,
                attempt,
                derive_action_digest(flow, chain, entry, &input),
                epoch,
            );
            effects.note_applied(key);
        }

        // A duplicate settlement must not grow either index.
        let (chain, entry) = coordinates(0)?;
        effects.note_applied(
            crate::effect::EffectIdentity::new(run, environment, flow).key(
                action_for(0)?,
                attempt,
                derive_action_digest(flow, chain, entry, &input),
                epoch,
            ),
        );
        assert_eq!(
            effects.applied_events.len(),
            usize::try_from(COUNT)?,
            "a duplicate settlement changed the event-identity index"
        );
        assert_eq!(
            effects.applied_latest.len(),
            usize::try_from(COUNT)?,
            "a duplicate settlement changed the latest-key index"
        );

        for index in 0..COUNT {
            let (chain, entry) = coordinates(index)?;
            let action = action_for(index)?;
            assert!(
                effects.applied_in(action, chain, entry, input, true),
                "the event identity for obligation {index} is absent from the index"
            );
            assert!(
                effects.applied_in(action, chain, entry, input, false),
                "the contract identity for obligation {index} is absent from the index"
            );
        }

        // An action the run never applied is not held, in either identity.
        let absent = action_for(COUNT)?;
        assert!(
            !effects.applied_in(absent, 0, 0, input, true)
                && !effects.applied_in(absent, 0, 0, input, false),
            "an unapplied obligation must not resolve as done"
        );
        Ok(())
    }

    /// A durable journal that grades itself `ProcessCrash` but refuses to
    /// reserve settlement capacity, counting the appends it was asked for.
    ///
    /// The shipped [`FileJournal`] reserves room
    /// against its own event ceiling; this stands in for the moment that
    /// ceiling is reached, which a test cannot reach without a hundred thousand
    /// real flushes.
    struct NoSettlementRoom {
        /// The record the appends would have gone to.
        inner: MemoryJournal,
        /// How many appends were asked for, whether or not one happened.
        appends: Rc<Cell<usize>>,
    }

    impl EffectJournal for NoSettlementRoom {
        fn durability(&self) -> DurabilityPromise {
            DurabilityPromise::ProcessCrash
        }

        fn tail(&self) -> JournalPosition {
            self.inner.tail()
        }

        fn committed(&self) -> Result<Vec<EffectEvent>, JournalError> {
            EffectJournal::committed(&self.inner)
        }

        fn compare_and_append(
            &mut self,
            expected_tail: JournalPosition,
            event: &EffectEvent,
        ) -> Result<DurableAck, JournalError> {
            self.appends.set(self.appends.get().saturating_add(1));
            self.inner.compare_and_append(expected_tail, event)
        }

        fn reserve_handoff_capacity(&self, rungs: u64) -> Result<(), JournalError> {
            Err(JournalError::CapacityExceeded {
                resource: crate::journal::JournalLimitKind::Events,
                limit: 0,
                requested: rungs,
            })
        }
    }

    /// An external handoff is refused before any rung when the settlement
    /// record does not fit, so no attempt is ever left admitted and unable to
    /// settle.
    ///
    /// Acceptance for #122 item 2 / #156: the reservation happens before the
    /// first write, so a journal that cannot hold the settlement refuses the
    /// handoff and the store stays untouched — rather than admitting the intent
    /// and the preparation and then being unable to persist the outcome.
    #[test]
    fn an_external_handoff_reserves_settlement_capacity_before_any_rung() -> TestResult {
        let appends = Rc::new(Cell::new(0));
        let journal = NoSettlementRoom {
            inner: MemoryJournal::new(),
            appends: Rc::clone(&appends),
        };
        let scope = test_effects_with(Box::new(journal))?;
        let mut effects = Effects::new(scope, JournalPosition::genesis());
        let key = crate::effect::EffectIdentity::new(
            RunId::from_hex(TEST_RUN)?,
            EnvironmentId::from_hex(TEST_ENV)?,
            FlowRevision::from_tagged("blake3_256", TEST_FLOW)?,
        )
        .key(
            ActionId::from_hex("1112131415161718191a1b1c1d1e1f20")?,
            AttemptId::from_decimal("1")?,
            ActionDigest::from_tagged(
                "blake3_256",
                "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeffe0e1e2e3e4e5e6e7e8e9eaebecedeeef",
            )?,
            EnvironmentEpoch::from_decimal("1")?,
        );

        match lgwks_std::task::block_on(effects.prepare(key, EffectLifetime::External)) {
            Err(DispatchError::Journal(JournalError::CapacityExceeded { .. })) => {}
            Err(other) => {
                return Err(format!("expected a capacity refusal, got {other:?}").into());
            }
            Ok(_) => {
                return Err("a handoff with no settlement room must be refused".into());
            }
        }
        assert_eq!(
            appends.get(),
            0,
            "the handoff must be refused before the first rung is written"
        );
        Ok(())
    }
}