reef-core 0.4.0

Provider-neutral primitives for building LLM agents: run lifecycle, transcript, tools, hooks
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
//! Crate-private Run → Turn → Step → Generation orchestration.
//!
//! The persistent [`Driver`] is the only phase owner. When a generation contains
//! tool calls, its tool phase emits every model-produced call in source order and
//! awaits acceptance before entering the prepare/route/commit pipeline. Only a
//! complete atomic commit is then published as source-ordered tool results. After
//! every result is accepted, the post-execution phase runs routed-slot post hooks in source/registration
//! order, strongly delivers only their real Audit/Error facts, then commits each
//! callback's staged replacement before its atomic returned-item batch. The
//! crate-private owner continuously drives the Driver and closes exactly one
//! Completed/Stopped/Cancelled/Failed terminal fact without releasing the Lease.

use std::any::Any;
use std::error;
use std::fmt;
use std::future::{Future, poll_fn};
use std::num::NonZeroU64;
use std::panic::{AssertUnwindSafe, catch_unwind, panic_any, resume_unwind};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, mpsc};

use crate::cancel::Token;
use futures_core::Stream;

use super::event::{
    Event, EventSource, InputOrigin, Kind, Producer, StopCode, StrongDecision, TerminalIntent,
    ToolEmitterGate, ValidationError, tool_emitter,
};
use super::hook::{
    self, AfterModelDecision, AfterStepDecision, BeforeModelDecision, BufferedFact,
    CallbackResources, ContinuationDecision, DispatchError, Emitter, FactBuffer,
    InputAdmitDecision, LifecycleEnd, LifecycleKind, LifecycleObservation, OwnedCallbackResources,
    OwnedToolRegistrationAdapter, StagedTranscript, StepSnapshot, StopDecision,
    ToolCallEndObservation, ToolCallProgress, TranscriptSource,
};
use super::model::{
    self, Client, CompletionReason, ContentKind, Info, Request, RequestError, RequestPlan,
    StreamError, StreamGrammar,
};
use super::run::FailureKind;
use super::session::{Claim, InputBatch, InputMailbox, InputTarget, Lease};
use super::tool::{self, CallDisposition, ExecutionError, ProviderError, StepResolutionError};
use super::tool_batch_commit::{ToolBatchCommit, ToolBatchCommitError, commit_tool_batch};
use super::tool_batch_prepare::{ToolBatchPreparePlan, prepare_tool_calls};
use super::tool_batch_route::{
    RoutedToolBatch, ToolBatchRouteError, ToolRouteBinder, ToolRouteBinding, route_and_execute,
};
use crate::audit;
use crate::state::session_state::CallbackWritePermit;
use crate::transcript::controller::{ControllerError, TranscriptController};
use crate::transcript::item::{Assistant, Item, ModelVisibility, User};
use crate::transcript::store::{self, Snapshot, Store, Version};
use crate::value::content::{Part, Segment};
use crate::value::lifecycle::{Coord, CoordError, Outcome, StepIndex};
use crate::value::tool_call::{ToolCall, ToolResult};

/// One boundary reached by a single loop advance.
///
/// The driver's own callers only need to know that an advance happened; both
/// payloads are read by the crate's tests, which assert *which* boundary it was.
#[cfg_attr(
    not(test),
    expect(dead_code, reason = "both payloads are read only by the crate's tests")
)]
pub(crate) enum Advance {
    /// A frozen inbox batch was claimed after its target phase completed.
    Input(InputBatch),
    /// One normalized model generation completed.
    Generation(Generation),
}

/// The outcome of admitting one claimed inbox batch.
pub(crate) enum InputAdmitOutcome {
    /// The (possibly rewritten) batch was atomically appended; the boundary
    /// continues into a new generation that reads the appended content.
    Admitted(InputBatch),
    /// A registration rejected the batch permanently; the boundary proceeds as
    /// if no input had been claimed, so no extra generation is produced.
    ///
    /// The reason the registration gave travels with the refusal, because it is
    /// the only thing the refusal leaves behind: a refusal is one of the two
    /// terminal states of a claim, so nothing will retry the batch.
    Rejected(String),
}

/// A completed generation plus the exact Step snapshot used to create it.
pub(crate) struct Generation {
    snapshot: Arc<StepSnapshot>,
    assistant: Assistant,
    finish_reason: String,
    completion: CompletionReason,
}

impl Generation {
    pub(crate) const fn snapshot(&self) -> &Arc<StepSnapshot> {
        &self.snapshot
    }

    pub(crate) const fn assistant(&self) -> &Assistant {
        &self.assistant
    }

    pub(crate) fn finish_reason(&self) -> &str {
        &self.finish_reason
    }

    pub(crate) const fn completion(&self) -> CompletionReason {
        self.completion
    }

    pub(crate) fn has_tool_calls(&self) -> bool {
        self.assistant
            .content()
            .iter()
            .any(|segment| matches!(segment, Segment::ToolCall { .. }))
    }

    fn tool_calls(&self) -> Vec<ToolCall> {
        self.assistant
            .content()
            .iter()
            .filter_map(|segment| match segment {
                Segment::ToolCall { call, .. } => Some(call.clone()),
                Segment::Text { .. } | Segment::Thinking { .. } => None,
            })
            .collect()
    }
}

/// The loop's outward lane: the event producer and the queue feeding it.
///
/// The two travel together because publishing is both of them. A synchronous
/// callback cannot await the producer, so it queues its facts here and the loop
/// publishes them on its behalf; [`ToolPhase::drain_hook_facts`] runs at each of
/// the loop's own publication points, which is what keeps a fact a callback
/// emitted from being overtaken by the events around it. An owner holding one
/// half without the other could either publish events that overtake queued facts
/// or queue facts nothing ever publishes, so neither is reachable alone.
#[derive(Clone, Copy)]
pub(crate) struct Outward<'a> {
    producer: &'a Arc<Producer>,
    facts: &'a FactBuffer,
}

impl<'a> Outward<'a> {
    pub(crate) const fn new(producer: &'a Arc<Producer>, facts: &'a FactBuffer) -> Self {
        Self { producer, facts }
    }
}

/// Borrowed resources for one driver's tool generations.
///
/// This bundle is crate-private and deliberately exposes no public Run API. The
/// loop owns coordinate stamping plus the real invocation-scoped emitter and
/// its close gate.
pub(super) fn lifecycle_transcript_source<'a>(
    kind: LifecycleKind,
    snapshot: Option<&'a Arc<StepSnapshot>>,
    live: &'a store::SnapshotReader,
) -> TranscriptSource<'a> {
    match kind {
        LifecycleKind::StepStart
        | LifecycleKind::GenerationStart
        | LifecycleKind::ToolCallStart => TranscriptSource::Snapshot(
            snapshot
                .expect("a Step-bound start observation carries its snapshot")
                .tools()
                .transcript(),
        ),
        LifecycleKind::RunStart
        | LifecycleKind::RunEnd
        | LifecycleKind::TurnStart
        | LifecycleKind::TurnEnd
        | LifecycleKind::StepEnd
        | LifecycleKind::GenerationEnd
        | LifecycleKind::ToolCallEnd => TranscriptSource::Reader(live),
    }
}

pub(crate) struct ToolPhase<'a> {
    outward: Outward<'a>,
    hooks: &'a hook::RuntimeRegistry,
    callback_resources: &'a [CallbackResources<'a>],
    controller: &'a TranscriptController<'a>,
    session_coord_id: String,
    run_id: String,
    session_id: Option<String>,
    /// Every lifecycle boundary this phase opened and has not yet ended.
    ///
    /// This outlives one `Driver::advance` future on purpose. An interruption
    /// drops that future at whichever await it was parked on, so the state that
    /// says "a Turn is open" cannot live inside it: the owner has to be able to
    /// close the boundary after the future is gone.
    open: Mutex<OpenBoundaries>,
    #[cfg(test)]
    test_emitter_gates: Vec<ToolEmitterGate>,
    #[cfg(test)]
    test_callback_abort_order: Option<Arc<Mutex<Vec<CallbackAbortStep>>>>,
    #[cfg(test)]
    test_callback_ack_probe: Option<tokio::sync::watch::Sender<usize>>,
}

/// The lifecycle boundaries one Run has entered and not yet left.
///
/// Only the observation plane is tracked. The outward event lane fails closed the
/// moment an interruption is latched (C18/C20), so an interrupted Run cannot
/// publish a closing `TurnEnd`/`StepEnd`/`GenerationEnd` event however much a
/// consumer would like one; a consumer learns the interruption from its event
/// stream closing and from `run::Terminal`. An observer is not a delivery, so it
/// can still be told — and it has to be, because a registration that allocated
/// something at `OnTurnStart` has nowhere else to release it.
#[derive(Debug, Default)]
struct OpenBoundaries {
    turn: Option<OpenTurn>,
    step: Option<OpenScope>,
    generation: Option<OpenScope>,
    calls: Vec<OpenToolCall>,
}

/// One entered Turn and the number of Steps entered inside it.
#[derive(Debug)]
struct OpenTurn {
    coord: Coord,
    steps: usize,
}

/// One entered Step or Generation and the frozen facts its end observation needs.
#[derive(Debug)]
struct OpenScope {
    coord: Coord,
    snapshot: Arc<StepSnapshot>,
}

/// One announced tool call whose terminal observation has not been published.
#[derive(Debug)]
struct OpenToolCall {
    coord: Coord,
    snapshot: Arc<StepSnapshot>,
    original: ToolCall,
    effective: ToolCall,
    progress: CallProgress,
}

impl OpenToolCall {
    /// Records a call the model produced, before its outward delivery is decided.
    ///
    /// The announcement deliberately precedes the `ToolCall` strong seam. The
    /// observation is the fact that the model asked for this call, which is true
    /// whatever the consumer then decides, and announcing first is what keeps
    /// every `OnToolCallStart` paired with exactly one `OnToolCallEnd`: a call
    /// whose delivery is rejected has still started, and still ends.
    fn announced(coord: Coord, snapshot: Arc<StepSnapshot>, call: ToolCall) -> Self {
        Self {
            coord,
            snapshot,
            original: call.clone(),
            effective: call,
            // No closed result exists yet, which is exactly what `NotExecuted`
            // means, so `CallProgress::settle` maps it to the resultless stage
            // and the placeholder result is never read.
            progress: CallProgress::settle(
                CallDisposition::NotExecuted,
                ToolResult::no_output(),
                ResultStage::Routed,
            ),
        }
    }

    /// Builds this call's validated terminal observation.
    fn end(self, interrupted: &LifecycleEnd) -> ToolCallEndObservation {
        let (end, milestone) = self.progress.terminal(interrupted);
        ToolCallEndObservation::try_new(self.coord, end, self.original, self.effective, milestone)
            .expect("the loop reports each call at a milestone its disposition reaches")
    }
}

/// How durable one call's closed result is.
#[derive(Clone, Copy, Debug)]
pub(super) enum ResultStage {
    /// A closed result exists but its atomic batch has not committed.
    Routed,
    /// The atomic batch committed; the post-execution hook phase is still open.
    Committed,
    /// The post-execution hook phase closed.
    Closed,
}

/// The furthest stage the tool phase reached for one announced call.
///
/// The four stages are the four `hook::ToolCallProgressKind` values, and the
/// disposition travels with the result rather than beside it, because
/// [`ToolCallEndObservation::try_new`] refuses every pair where the two disagree.
#[derive(Debug)]
pub(super) enum CallProgress {
    /// No closed result exists for this call anywhere in the loop.
    NoResult(CallDisposition),
    /// A closed result exists but its atomic batch has not committed.
    Routed(CallDisposition, ToolResult),
    /// The atomic batch committed; the post-execution hook phase is still open.
    Committed(CallDisposition, ToolResult),
    /// The post-execution hook phase closed.
    Closed(CallDisposition, ToolResult),
}

impl CallProgress {
    /// Places one closed result at the durability stage it has reached.
    ///
    /// The disposition decides whether a result milestone is legal at all, and
    /// this is the one place that decision is made. [`ToolCallEndObservation`]
    /// accepts `Truncated` and `NotExecuted` only at the `Observed` milestone and
    /// the other four only at a result milestone, so a resultless disposition
    /// stays at `NoResult` however far the batch around it got. The match is
    /// exhaustive by design: a new [`CallDisposition`] cannot be added without
    /// deciding which of the two milestone families it reaches.
    pub(super) fn settle(
        disposition: CallDisposition,
        result: ToolResult,
        stage: ResultStage,
    ) -> Self {
        match disposition {
            CallDisposition::Truncated | CallDisposition::NotExecuted => {
                Self::NoResult(disposition)
            }
            CallDisposition::Executed
            | CallDisposition::ShortCircuited
            | CallDisposition::Blocked
            | CallDisposition::Rejected => match stage {
                ResultStage::Routed => Self::Routed(disposition, result),
                ResultStage::Committed => Self::Committed(disposition, result),
                ResultStage::Closed => Self::Closed(disposition, result),
            },
        }
    }

    /// Pairs the terminal state with the milestone that state licenses.
    ///
    /// Only a closed post-execution hook phase is `Completed`; every earlier
    /// stage means the tool phase stopped somewhere, and carries the Run's own
    /// interruption end. That is also the rule `try_new` enforces, so the pairing
    /// is not a second, independent judgement.
    pub(super) fn terminal(self, interrupted: &LifecycleEnd) -> (LifecycleEnd, ToolCallProgress) {
        match self {
            Self::NoResult(disposition) => {
                (interrupted.clone(), ToolCallProgress::observed(disposition))
            }
            Self::Routed(disposition, result) => (
                interrupted.clone(),
                ToolCallProgress::result_available(disposition, result),
            ),
            Self::Committed(disposition, result) => (
                interrupted.clone(),
                ToolCallProgress::result_committed(disposition, result),
            ),
            Self::Closed(disposition, result) => (
                LifecycleEnd::Completed,
                ToolCallProgress::completed_post_hooks(disposition, result),
            ),
        }
    }
}

enum AfterToolFact {
    Audit(audit::Event),
    Error(Arc<dyn error::Error + Send + Sync>),
}

impl AfterToolFact {
    fn into_event(self) -> Result<Event, ValidationError> {
        match self {
            Self::Audit(event) => Event::from_audit(event),
            Self::Error(error) => Ok(Event::from_error(error)),
        }
    }
}

#[derive(Clone, Copy, Eq, PartialEq)]
enum CallbackAck {
    Accepted,
    Abort,
}

#[cfg(test)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum CallbackAbortStep {
    Revoked,
    AbortAckSent,
}

#[cfg(test)]
macro_rules! record_callback_abort_step {
    ($owner:expr, $step:expr) => {
        if let Some(order) = &$owner.callback_abort_order {
            order
                .lock()
                .expect("callback abort order lock remains available")
                .push($step);
        }
    };
}

#[cfg(not(test))]
macro_rules! record_callback_abort_step {
    ($owner:expr, $step:expr) => {};
}

struct AfterToolRequest {
    fact: AfterToolFact,
    ack: mpsc::Sender<CallbackAck>,
}

/// Private unwind payload used only to stop a synchronous callback after the
/// async owner rejects its current strong delivery.
struct CallbackAbort;

/// Attribution wrapper for a real hook panic. The private abort sentinel is
/// consumed separately and can never be reported as a hook panic.
///
/// The payload travels to the Run task's unwind boundary, which re-raises it
/// rather than reading it; the accessors below are the crate's tests.
#[cfg_attr(
    not(test),
    expect(dead_code, reason = "both fields are read only by the crate's tests")
)]
pub(super) struct AfterToolHookPanic {
    hook: String,
    payload: Box<dyn Any + Send>,
}

#[cfg(test)]
impl AfterToolHookPanic {
    pub(super) fn hook(&self) -> &str {
        &self.hook
    }

    pub(super) fn payload_is<T: Any>(&self) -> bool {
        self.payload.is::<T>()
    }
}

struct AfterToolCallbackOutput {
    staged: Option<(Version, Snapshot)>,
    returned: Vec<crate::transcript::item::Item>,
}

enum AfterToolCallbackExit {
    Completed(Result<AfterToolCallbackOutput, store::Error>),
    Panicked(Box<dyn Any + Send>),
}

/// Owns the request lane and blocking task as one cooperative unit.
///
/// Normal paths call `join`. If the enclosing loop future is dropped at any
/// await, `Drop` first revokes callback-local state writes, aborts a pending
/// synchronous emit, closes the request lane, then waits for cooperative blocking
/// completion before releasing the handle. Rust cannot forcibly terminate a
/// malicious or permanently blocked synchronous callback.
struct ManagedCallbackOwner {
    requests: Option<tokio::sync::mpsc::Receiver<AfterToolRequest>>,
    pending_ack: Option<mpsc::Sender<CallbackAck>>,
    callback_write_permit: Option<CallbackWritePermit>,
    handle: Option<tokio::task::JoinHandle<AfterToolCallbackExit>>,
    completed: Option<mpsc::Receiver<()>>,
    #[cfg(test)]
    callback_abort_order: Option<Arc<Mutex<Vec<CallbackAbortStep>>>>,
    #[cfg(test)]
    callback_ack_probe: Option<tokio::sync::watch::Sender<usize>>,
    #[cfg(test)]
    join_drop_handle_probe: Option<Arc<AtomicUsize>>,
}

impl ManagedCallbackOwner {
    async fn recv(&mut self) -> Option<AfterToolRequest> {
        self.requests
            .as_mut()
            .expect("callback request lane remains owned before join")
            .recv()
            .await
    }

    fn arm_ack(&mut self, ack: &mpsc::Sender<CallbackAck>) {
        self.pending_ack = Some(ack.clone());
    }

    fn acknowledge_accept(&mut self, ack: mpsc::Sender<CallbackAck>) {
        let _callback_is_waiting = ack.send(CallbackAck::Accepted);
        self.pending_ack = None;
        #[cfg(test)]
        if let Some(probe) = &self.callback_ack_probe {
            probe.send_modify(|count| *count += 1);
        }
    }

    /// Revokes callback-local writes before releasing the pending callback abort wait.
    fn revoke_callback_writes_and_abort_pending_ack(&mut self) {
        if let Some(permit) = self.callback_write_permit.take() {
            permit.revoke();
            record_callback_abort_step!(self, CallbackAbortStep::Revoked);
        }
        if let Some(ack) = self.pending_ack.take() {
            let _callback_is_waiting = ack.send(CallbackAck::Abort);
            record_callback_abort_step!(self, CallbackAbortStep::AbortAckSent);
        }
    }

    async fn join(mut self) -> AfterToolCallbackExit {
        self.requests.take();
        self.pending_ack = None;
        let exit = self
            .handle
            .as_mut()
            .expect("managed callback handle is joined once")
            .await
            .expect("managed after-tool callback owner joins");
        self.handle.take();
        let _completed = self.completed.take();
        exit
    }
}

impl Drop for ManagedCallbackOwner {
    fn drop(&mut self) {
        // Future Drop is also an abort boundary: revoke first, then unblock any
        // synchronous emit, then close and synchronously join the cooperative
        // callback owner.
        self.revoke_callback_writes_and_abort_pending_ack();
        self.requests.take();
        #[cfg(test)]
        if let Some(probe) = &self.join_drop_handle_probe {
            probe.store(usize::from(self.handle.is_some()), Ordering::SeqCst);
        }
        if self.handle.is_some() {
            self.completed
                .take()
                .expect("live callback owner retains completion receiver")
                .recv()
                .expect_err("managed blocking callback closes completion lane");
            self.handle.take();
        }
    }
}

#[cfg(test)]
pub(super) async fn managed_callback_join_retains_drop_authority() -> bool {
    let (_requests, request_receiver) = tokio::sync::mpsc::channel(1);
    let (completed, completion) = mpsc::channel();
    let (entered, entered_receiver) = mpsc::channel();
    let release = Arc::new(std::sync::Barrier::new(2));
    let worker_release = Arc::clone(&release);
    let handle = tokio::task::spawn_blocking(move || {
        let _completion = completed;
        entered.send(()).expect("join test remains live");
        worker_release.wait();
        AfterToolCallbackExit::Completed(Ok(AfterToolCallbackOutput {
            staged: None,
            returned: Vec::new(),
        }))
    });
    entered_receiver
        .recv()
        .expect("managed callback join test worker starts");
    let observed = Arc::new(AtomicUsize::new(0));
    let owner = ManagedCallbackOwner {
        requests: Some(request_receiver),
        pending_ack: None,
        callback_write_permit: None,
        handle: Some(handle),
        completed: Some(completion),
        callback_abort_order: None,
        callback_ack_probe: None,
        join_drop_handle_probe: Some(Arc::clone(&observed)),
    };
    let mut joining = Box::pin(owner.join());
    poll_fn(|context| {
        assert!(
            joining.as_mut().poll(context).is_pending(),
            "blocked callback join completed early"
        );
        std::task::Poll::Ready(())
    })
    .await;
    release.wait();
    drop(joining);
    observed.load(Ordering::SeqCst) == 1
}

/// Synchronous hook emitter backed by a per-event request/ack rendezvous.
///
/// The callback runs on Tokio's managed blocking pool. Every emit blocks here
/// until the async loop has awaited `Producer::emit_after_tool_commit` and sent
/// the matching acknowledgement. This matches the strong producer contract in
/// the event runtime; no callback code after an emit can run early.
struct RendezvousHookEmitter {
    requests: tokio::sync::mpsc::Sender<AfterToolRequest>,
}

impl RendezvousHookEmitter {
    fn emit(&self, fact: AfterToolFact) {
        let (ack, accepted) = mpsc::channel();
        let _request_sent = self.requests.blocking_send(AfterToolRequest { fact, ack });
        if accepted.recv() != Ok(CallbackAck::Accepted) {
            panic_any(CallbackAbort);
        }
    }
}

impl Emitter for RendezvousHookEmitter {
    fn emit_audit(&self, event: audit::Event) {
        self.emit(AfterToolFact::Audit(event));
    }

    fn emit_error(&self, error: Arc<dyn error::Error + Send + Sync>) {
        self.emit(AfterToolFact::Error(error));
    }
}

fn propagate_after_tool_panic(hook: String, payload: Box<dyn Any + Send>) -> ! {
    resume_unwind(Box::new(AfterToolHookPanic { hook, payload }));
}

impl<'a> ToolPhase<'a> {
    pub(crate) fn new(
        outward: Outward<'a>,
        hooks: &'a hook::RuntimeRegistry,
        callback_resources: &'a [CallbackResources<'a>],
        controller: &'a TranscriptController<'a>,
        coord_identity: &Coord,
        session_id: Option<String>,
    ) -> Self {
        Self {
            outward,
            hooks,
            callback_resources,
            controller,
            session_coord_id: coord_identity.session_id().to_owned(),
            run_id: coord_identity.run_id().to_owned(),
            session_id,
            open: Mutex::new(OpenBoundaries::default()),
            #[cfg(test)]
            test_emitter_gates: Vec::new(),
            #[cfg(test)]
            test_callback_abort_order: None,
            #[cfg(test)]
            test_callback_ack_probe: None,
        }
    }

    /// Adds a test-owned emission window to the same close/drain set as real
    /// invocation windows. This lets caller-level tests keep emission active after
    /// an executor returned without weakening the production binder contract.
    #[cfg(test)]
    pub(super) fn with_test_emitter_gate(mut self, gate: ToolEmitterGate) -> Self {
        self.test_emitter_gates.push(gate);
        self
    }

    #[cfg(test)]
    pub(super) fn with_test_callback_abort_order(
        mut self,
        order: Arc<Mutex<Vec<CallbackAbortStep>>>,
    ) -> Self {
        self.test_callback_abort_order = Some(order);
        self
    }

    #[cfg(test)]
    pub(super) fn with_test_callback_ack_probe(
        mut self,
        probe: tokio::sync::watch::Sender<usize>,
    ) -> Self {
        self.test_callback_ack_probe = Some(probe);
        self
    }
}

/// Failure surfaces owned by the loop caller.
pub(crate) enum Error {
    Cancelled,
    Transcript(store::Error),
    Tools(StepResolutionError),
    Request(RequestError),
    Model(Arc<dyn error::Error + Send + Sync>),
    Stream(StreamError),
    MissingToolPhase,
    /// A tool-call lifecycle coordinate could not represent an externally supplied value.
    Coordinate(CoordError),
    Event(ValidationError),
    ToolCallRejected,
    Prepare(DispatchError),
    Route(ToolBatchRouteError),
    Commit(ToolBatchCommitError),
    ToolResultRejected,
    AfterToolExecuteRejected,
    AfterToolExecuteTranscript(ControllerError),
    /// A claimed input batch produced an invalid `OnBeforeInputAdmit` decision.
    Input(InputAdmitError),
    /// The atomic transcript append of an admitted input batch failed.
    InputAdmitTranscript(ControllerError),
    /// The atomic transcript append of a tool-free generation failed.
    GenerationTranscript(ControllerError),
    /// A Turn, Step, model or Run boundary callback failed.
    Hook(DispatchError),
    /// The atomic transcript mutation of a boundary callback's items failed.
    BoundaryTranscript(ControllerError),
    /// An `OnBeforeModel` registration aborted the generation.
    ModelAborted(String),
}

/// An invalid `OnBeforeInputAdmit` decision produced by a registration.
///
/// `OnBeforeInputAdmit` is infallible by trait shape, so these are the only
/// fail-closed decision outcomes the loop recognizes: a rewrite must stay
/// non-empty and a rejection must carry a reason, otherwise the claimed batch
/// would silently vanish.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum InputAdmitError {
    /// A registration returned `Modify` with an empty replacement.
    EmptyModify,
    /// A registration returned `Reject` with an empty reason.
    EmptyRejectReason,
}

impl fmt::Display for InputAdmitError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(describe_input(self))
    }
}

impl error::Error for InputAdmitError {}

impl Error {
    /// Classifies this failure into the portable public taxonomy.
    ///
    /// Cancellation and the three consumer rejections never reach a failed
    /// terminal — [`TerminalLatch::record_error`] routes them to Cancelled and
    /// Stopped — so they classify as `Internal`: seeing one through
    /// [`run::Terminal::failure_kind`] would mean the runtime latched the wrong
    /// outcome, not that the consumer did something wrong.
    pub(crate) const fn classify(&self) -> FailureKind {
        match self {
            Self::Transcript(_)
            | Self::AfterToolExecuteTranscript(_)
            | Self::InputAdmitTranscript(_)
            | Self::GenerationTranscript(_)
            | Self::BoundaryTranscript(_) => FailureKind::Transcript,
            Self::Tools(_) => FailureKind::ToolResolution,
            Self::Request(_) => FailureKind::Request,
            Self::Model(_) => FailureKind::Model,
            Self::Stream(_) => FailureKind::Stream,
            Self::Event(_) => FailureKind::Event,
            Self::Prepare(_) | Self::Hook(_) | Self::ModelAborted(_) => FailureKind::Hook,
            Self::Route(_) => FailureKind::ToolExecution,
            Self::Commit(_) => FailureKind::ToolCommit,
            Self::Input(_) => FailureKind::Input,
            Self::Cancelled
            | Self::MissingToolPhase
            | Self::Coordinate(_)
            | Self::ToolCallRejected
            | Self::ToolResultRejected
            | Self::AfterToolExecuteRejected => FailureKind::Internal,
        }
    }

    /// Returns the concrete stage failure this error retains.
    ///
    /// [`fmt::Display`] renders the whole chain as text, which is what a log
    /// wants; a caller that means to *inspect* the failure instead — retry only
    /// on a provider outage, downcast to its own provider error type — needs the
    /// value. This is what [`run::Terminal::failure`] exposes through
    /// [`std::error::Error::source`].
    ///
    /// `None` is returned for the two families that genuinely have nothing
    /// underneath: cancellation and the three consumer rejections are the loop's
    /// own account of something the caller did, and the version-shape rejection
    /// is a leaf of the loop's own making.
    ///
    /// [`run::Terminal::failure`]: super::run::Terminal::failure
    pub(crate) fn cause(&self) -> Option<Arc<dyn error::Error + Send + Sync>> {
        match self {
            Self::Transcript(error) => Some(Arc::new(*error)),
            Self::Tools(error) => Some(Arc::new(error.clone())),
            Self::Request(error) => Some(Arc::new(error.clone())),
            Self::Model(error) => Some(Arc::clone(error)),
            Self::Stream(error) => Some(Arc::new(error.clone())),
            Self::Coordinate(error) => Some(Arc::new(*error)),
            Self::Event(error) => Some(Arc::new(*error)),
            Self::Prepare(error) => Some(Arc::new(error.clone())),
            Self::Route(error) => Some(Arc::new(error.execution().clone())),
            Self::Commit(ToolBatchCommitError::Rewrite { error, .. }) => {
                Some(Arc::new(error.clone()))
            }
            Self::Commit(ToolBatchCommitError::Controller(error))
            | Self::AfterToolExecuteTranscript(error)
            | Self::InputAdmitTranscript(error)
            | Self::GenerationTranscript(error) => controller_cause(error),
            Self::Input(error) => Some(Arc::new(*error)),
            Self::Hook(error) => Some(Arc::new(error.clone())),
            Self::BoundaryTranscript(error) => controller_cause(error),
            Self::Cancelled
            | Self::MissingToolPhase
            | Self::ToolCallRejected
            | Self::ToolResultRejected
            | Self::AfterToolExecuteRejected
            | Self::ModelAborted(_)
            | Self::Commit(ToolBatchCommitError::Cancelled) => None,
        }
    }

    const fn is_rejection(&self) -> bool {
        matches!(
            self,
            Self::ToolCallRejected | Self::ToolResultRejected | Self::AfterToolExecuteRejected
        )
    }

    fn is_cancellation(&self) -> bool {
        match self {
            Self::Cancelled | Self::Prepare(DispatchError::Cancelled) => true,
            Self::Route(error) => error.execution().execution() == &ExecutionError::Cancelled,
            Self::Commit(ToolBatchCommitError::Cancelled)
            | Self::Commit(ToolBatchCommitError::Rewrite {
                error: DispatchError::Cancelled,
                ..
            })
            | Self::Commit(ToolBatchCommitError::Controller(ControllerError::Dispatch(
                DispatchError::Cancelled,
            )))
            | Self::AfterToolExecuteTranscript(ControllerError::Dispatch(
                DispatchError::Cancelled,
            ))
            | Self::InputAdmitTranscript(ControllerError::Dispatch(DispatchError::Cancelled)) => {
                true
            }
            Self::Transcript(_)
            | Self::Tools(_)
            | Self::Request(_)
            | Self::Model(_)
            | Self::Stream(_)
            | Self::MissingToolPhase
            | Self::Coordinate(_)
            | Self::Event(_)
            | Self::ToolCallRejected
            | Self::Prepare(DispatchError::Callback(_))
            | Self::Commit(_)
            | Self::ToolResultRejected
            | Self::AfterToolExecuteRejected
            | Self::AfterToolExecuteTranscript(_)
            | Self::Input(_)
            | Self::InputAdmitTranscript(_)
            | Self::GenerationTranscript(_)
            | Self::Hook(_)
            | Self::BoundaryTranscript(_)
            | Self::ModelAborted(_) => false,
        }
    }
}

/// Maps a boundary callback failure, whose cancellation is plain cancellation.
fn boundary_hook(error: DispatchError) -> Error {
    match error {
        DispatchError::Cancelled => Error::Cancelled,
        other => Error::Hook(other),
    }
}

/// Maps a boundary transcript mutation failure the same way.
fn boundary_transcript(error: ControllerError) -> Error {
    match error {
        ControllerError::Dispatch(DispatchError::Cancelled) => Error::Cancelled,
        other => Error::BoundaryTranscript(other),
    }
}

fn describe_route(error: &ToolBatchRouteError) -> String {
    format!(
        "executing the batch failed: {}",
        error.execution().execution()
    )
}

fn describe_commit(error: &ToolBatchCommitError) -> String {
    match error {
        ToolBatchCommitError::Cancelled => "cancelled before any rewrite ran".to_owned(),
        ToolBatchCommitError::Rewrite {
            source_index,
            error,
        } => format!("the rewrite at source index {source_index} failed: {error}"),
        ToolBatchCommitError::Controller(error) => {
            format!("the atomic append failed: {error}")
        }
    }
}

/// Returns the concrete failure one live transcript mutation retains.
///
/// A dispatch failure carries the hook's own error and a lease rejection
/// carries the [`LeaseError`] itself — including the leaf variants whose whole
/// content is their discriminant. Handing back only the transcript variant would
/// make `Released` and `AlreadyAdmitted` survive as rendered text and nothing
/// else, so a caller could no longer distinguish lifecycle failures without
/// matching on a string. The version-shape rejection is genuinely a leaf of this
/// loop's own making.
///
/// This mirrors what [`ControllerError::source`] already returns, so inspecting
/// the failure through the terminal and through the error chain agree.
///
/// [`ControllerError::source`]: std::error::Error::source
fn controller_cause(error: &ControllerError) -> Option<Arc<dyn error::Error + Send + Sync>> {
    match error {
        ControllerError::Dispatch(error) => Some(Arc::new(error.clone())),
        ControllerError::Lease(error) => Some(Arc::new(error.clone())),
        ControllerError::InvalidTransition { .. } => None,
    }
}

const fn describe_input(error: &InputAdmitError) -> &'static str {
    match error {
        InputAdmitError::EmptyModify => "a registration rewrote the batch to nothing",
        InputAdmitError::EmptyRejectReason => "a registration rejected without a reason",
    }
}

/// Renders the exact reason a Run failed.
///
/// Every arm names both the stage that failed and the payload that stage
/// produced. This is the text a consumer reads through
/// [`run::Terminal::failure`], so a variant that rendered only its stage would
/// leave the caller exactly as uninformed as a fixed string.
impl fmt::Display for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Cancelled => formatter.write_str("the run was cancelled"),
            Self::Transcript(error) => write!(formatter, "the transcript failed: {error}"),
            Self::Tools(error) => write!(formatter, "step tool resolution failed: {error}"),
            Self::Request(error) => write!(formatter, "the model request was rejected: {error}"),
            Self::Model(error) => write!(formatter, "the model provider failed: {error}"),
            Self::Stream(error) => write!(formatter, "the model stream was invalid: {error}"),
            Self::MissingToolPhase => {
                formatter.write_str("a generation produced tool calls with no tool phase attached")
            }
            Self::Coordinate(error) => {
                write!(formatter, "a tool-call coordinate was invalid: {error}")
            }
            Self::Event(error) => write!(formatter, "an outward event was invalid: {error}"),
            Self::ToolCallRejected => {
                formatter.write_str("the consumer rejected a tool call delivery")
            }
            Self::Prepare(error) => write!(formatter, "tool-call preparation failed: {error}"),
            Self::Route(error) => write!(
                formatter,
                "tool batch routing failed: {}",
                describe_route(error)
            ),
            Self::Commit(error) => write!(
                formatter,
                "the tool batch commit failed: {}",
                describe_commit(error)
            ),
            Self::ToolResultRejected => {
                formatter.write_str("the consumer rejected a tool result delivery")
            }
            Self::AfterToolExecuteRejected => {
                formatter.write_str("the consumer rejected an after-tool-execute delivery")
            }
            Self::AfterToolExecuteTranscript(error) => write!(
                formatter,
                "an after-tool-execute transcript mutation failed: {error}"
            ),
            Self::Input(error) => {
                write!(
                    formatter,
                    "an input admission decision was invalid: {error}"
                )
            }
            Self::InputAdmitTranscript(error) => {
                write!(formatter, "admitting an input batch failed: {error}")
            }
            Self::GenerationTranscript(error) => {
                write!(formatter, "committing the generation failed: {error}")
            }
            Self::Hook(error) => write!(formatter, "a boundary callback failed: {error}"),
            Self::BoundaryTranscript(error) => {
                write!(formatter, "committing a boundary batch failed: {error}")
            }
            Self::ModelAborted(reason) => {
                write!(formatter, "a hook aborted the model call: {reason}")
            }
        }
    }
}

/// The closed terminal fact produced by the crate-private Driver owner.
pub(crate) enum Terminal {
    Completed,
    Stopped,
    Cancelled,
    Failed(Error),
}

impl Terminal {
    #[cfg(test)]
    pub(crate) const fn outcome(&self) -> crate::value::lifecycle::Outcome {
        match self {
            Self::Completed => crate::value::lifecycle::Outcome::Completed,
            Self::Stopped => crate::value::lifecycle::Outcome::Stopped,
            Self::Cancelled => crate::value::lifecycle::Outcome::Cancelled,
            Self::Failed(_) => crate::value::lifecycle::Outcome::Failed,
        }
    }

    #[cfg(test)]
    pub(crate) const fn failure(&self) -> Option<&Error> {
        match self {
            Self::Failed(error) => Some(error),
            Self::Completed | Self::Stopped | Self::Cancelled => None,
        }
    }

    const fn priority(&self) -> u8 {
        match self {
            Self::Completed => 0,
            Self::Cancelled | Self::Stopped => 1,
            Self::Failed(_) => 2,
        }
    }
}

/// The terminal fact an open lifecycle boundary is closed with.
///
/// A boundary that is still open when the Run ends did not complete, so its end
/// is the Run's own, mapped through the same three nonfatal/fatal causes
/// [`TerminalLatch`] already resolved. Only a [`super::hook::RunHooks::decide_stop`] stop names itself,
/// which is why the code is read from the Driver's report rather than invented
/// here.
fn boundary_end(terminal: &Terminal, stop_code: Option<StopCode>) -> LifecycleEnd {
    match terminal {
        Terminal::Completed => LifecycleEnd::Completed,
        Terminal::Stopped => LifecycleEnd::Stopped { code: stop_code },
        Terminal::Cancelled => LifecycleEnd::Cancelled {
            error: Arc::new(BoundaryInterruption::canceled()),
        },
        Terminal::Failed(error) => LifecycleEnd::Failed {
            error: Arc::new(BoundaryInterruption::failed(error)),
        },
    }
}

/// Why one open lifecycle boundary was closed without completing.
///
/// [`LifecycleEnd`] wants an owned `Arc<dyn Error>`, and the crate-private stage
/// failure is neither `Clone` nor able to outlive the Driver, so the message is
/// rendered where it is still complete. The concrete failure is retained beside
/// it and returned from [`Error::source`], for the same reason
/// [`run::DriverError`] does: reading a reason is enough to diagnose a Run,
/// deciding what to do about one is not.
///
/// [`Error::source`]: std::error::Error::source
/// [`run::DriverError`]: super::run::Terminal::failure
struct BoundaryInterruption {
    message: String,
    cause: Option<Arc<dyn error::Error + Send + Sync>>,
}

impl fmt::Debug for BoundaryInterruption {
    /// Renders the retained cause through `Display`, like the message above it.
    ///
    /// A derived implementation would print the cause's own `Debug`, and the
    /// cause is whatever a provider adapter or a hook handed back — arbitrary
    /// text this crate neither writes nor reviews, in a format nobody promised.
    /// `Display` is the diagnostic those error types are contracted to produce,
    /// and it is what every other boxed failure in reef prints.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("BoundaryInterruption")
            .field("message", &self.message)
            .field("cause", &self.cause.as_ref().map(|cause| cause.to_string()))
            .finish()
    }
}

impl BoundaryInterruption {
    fn canceled() -> Self {
        Self {
            message: Error::Cancelled.to_string(),
            cause: None,
        }
    }

    fn failed(error: &Error) -> Self {
        Self {
            message: error.to_string(),
            cause: error.cause(),
        }
    }
}

/// Builds the interruption a closing boundary would report for `error`.
///
/// Boundary closure is reached only from inside a live unwind, so this is how a
/// test observes the value a hook receives without racing one.
#[cfg(test)]
pub(super) fn boundary_interruption(error: &Error) -> Arc<dyn error::Error + Send + Sync> {
    Arc::new(BoundaryInterruption::failed(error))
}

impl fmt::Display for BoundaryInterruption {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl error::Error for BoundaryInterruption {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        self.cause
            .as_ref()
            .map(|cause| cause.as_ref() as &(dyn error::Error + 'static))
    }
}

#[derive(Default)]
pub(super) struct TerminalLatch {
    candidate: Option<Terminal>,
}

impl TerminalLatch {
    pub(super) fn record(&mut self, candidate: Terminal) {
        let replace = self
            .candidate
            .as_ref()
            .is_none_or(|current| candidate.priority() > current.priority());
        if replace {
            self.candidate = Some(candidate);
        }
    }

    fn observe_control(&mut self, source: &EventSource) {
        match source.terminal_intent() {
            TerminalIntent::Running => {}
            TerminalIntent::Stopped => self.record(Terminal::Stopped),
            TerminalIntent::Cancelled => self.record(Terminal::Cancelled),
            TerminalIntent::Failed => {
                if let Some(error) = source.latch_failure() {
                    self.record(Terminal::Failed(Error::Event(error)));
                }
            }
        }
    }

    pub(super) fn record_error(&mut self, source: &EventSource, error: Error) {
        if error.is_rejection() {
            source.request_stop();
            self.observe_control(source);
        } else if error.is_cancellation() {
            self.observe_control(source);
            if self.candidate.is_none() {
                self.record(Terminal::Cancelled);
            }
        } else {
            let error = source.latch_failure().map_or(error, Error::Event);
            self.record(Terminal::Failed(error));
        }
    }

    const fn is_terminal(&self) -> bool {
        self.candidate.is_some()
    }

    pub(super) fn finish(mut self, source: &EventSource) -> Terminal {
        self.observe_control(source);
        self.candidate.unwrap_or(Terminal::Completed)
    }
}

struct Context<'a, M> {
    model: &'a M,
    lease: &'a Lease,
    #[cfg(test)]
    transcript: Option<crate::transcript::store::SnapshotReader>,
    inbox: &'a InputMailbox,
    tools: &'a tool::Registry,
    cancellation: &'a Token,
}

impl<M> Context<'_, M> {
    fn transcript_snapshot(&self) -> Result<crate::transcript::store::Snapshot, store::Error> {
        #[cfg(test)]
        if let Some(transcript) = &self.transcript {
            return transcript.snapshot();
        }
        self.lease.transcript_snapshot()
    }
}

#[derive(Clone, Copy)]
enum Phase {
    Generation,
    StepBoundary { generated_tool_calls: bool },
    TurnBoundary,
    Done,
}

/// Persistent one-based position of the next real model generation.
struct GenerationPosition {
    turn: u64,
    step: u64,
    step_in_run: u64,
    generation: u64,
}

impl GenerationPosition {
    const fn first() -> Self {
        Self {
            turn: 1,
            step: 1,
            step_in_run: 1,
            generation: 1,
        }
    }

    fn step_index(&self) -> StepIndex {
        let turn = NonZeroU64::new(self.turn).expect("runtime turns are one-based");
        let step = NonZeroU64::new(self.step).expect("runtime steps are one-based");
        let step_in_run =
            NonZeroU64::new(self.step_in_run).expect("runtime run-wide steps are one-based");
        StepIndex::new(turn, step, step_in_run)
            .expect("the driver maintains a valid step hierarchy")
    }

    fn turn_coord(&self, session_id: &str, run_id: &str) -> Coord {
        let turn = NonZeroU64::new(self.turn).expect("runtime turns are one-based");
        Coord::at_turn(session_id.to_owned(), run_id.to_owned(), turn)
            .expect("the attached tool phase carries non-empty run identities")
    }

    fn step_coord(&self, session_id: &str, run_id: &str) -> Coord {
        Coord::at_step(session_id.to_owned(), run_id.to_owned(), self.step_index())
            .expect("the attached tool phase carries non-empty run identities")
    }

    fn coord(&self, session_id: &str, run_id: &str) -> Coord {
        let generation =
            NonZeroU64::new(self.generation).expect("runtime generations are one-based");
        Coord::at_generation(
            session_id.to_owned(),
            run_id.to_owned(),
            self.step_index(),
            generation,
        )
        .expect("the attached tool phase carries non-empty run identities")
    }

    fn coords(&self, session_id: &str, run_id: &str) -> GenerationCoords {
        GenerationCoords {
            turn: self.turn_coord(session_id, run_id),
            step: self.step_coord(session_id, run_id),
            generation: self.coord(session_id, run_id),
        }
    }

    const fn next_step(&mut self) {
        self.step += 1;
        self.step_in_run += 1;
        self.generation += 1;
    }

    const fn next_turn(&mut self) {
        self.turn += 1;
        self.step = 1;
        self.step_in_run += 1;
        self.generation += 1;
    }
}

/// The three coordinates one generation is published under.
///
/// They are minted together so a Turn, its Step and its Generation observation
/// can never disagree about where in the hierarchy they happened.
struct GenerationCoords {
    turn: Coord,
    step: Coord,
    generation: Coord,
}

/// Facts only the Driver observes that the Run owner needs after the barrier.
///
/// [`Driver::run`] consumes the Driver at its own join barrier, so a count or a
/// code the owner reads *after* that barrier cannot be returned through it. The
/// owner therefore lends one report and reads it once the barrier has returned.
#[derive(Default)]
pub(crate) struct Report {
    turns: AtomicUsize,
    stop_code: Mutex<Option<StopCode>>,
}

impl Report {
    /// Returns how many Turns this Run opened.
    pub(crate) fn turns(&self) -> usize {
        self.turns.load(Ordering::Relaxed)
    }

    /// Returns the code a [`super::hook::RunHooks::decide_stop`] registration stopped the Run with.
    pub(crate) fn stop_code(&self) -> Option<StopCode> {
        self.stop_code
            .lock()
            .expect("driver report lock poisoned")
            .clone()
    }
}

/// Persistent caller-owned cursor through the internal Run hierarchy.
///
/// A fresh driver always enters `Generation`. The cursor reaches an inbox target
/// only after the corresponding Step or Turn has completed, which prevents a
/// pre-enqueued batch from displacing the first generation.
pub(crate) struct Driver<'a, M> {
    context: Context<'a, M>,
    tool_phase: Option<ToolPhase<'a>>,
    phase: Phase,
    generation_position: GenerationPosition,
    /// Whether a `TurnStart` has been published without its matching `TurnEnd`.
    ///
    /// The cursor alone cannot answer this: a turn opens at its first generation
    /// but closes at a boundary that may be reached several generations later,
    /// and a claimed `NextStep` batch re-enters `Generation` inside the same
    /// turn. Latching the open turn is what keeps the pair exactly balanced.
    turn_open: bool,
    /// The items that opened the current turn.
    ///
    /// This is what `OnBeforeTurn`/`OnAfterTurn` and the Turn lifecycle
    /// observation call the turn's trigger: the admitted Run input for the first
    /// turn, a claimed `NextTurn` batch or a [`super::hook::RunHooks::compose_continuation`] continuation after
    /// that.
    turn_trigger: Vec<Item>,
    /// The frozen Step facts of the step the cursor is on.
    ///
    /// `OnAfterStep` and the `StepEnd` observation both describe a step that has
    /// already been frozen, and the cursor has moved past the value by then.
    step_snapshot: Option<Arc<StepSnapshot>>,
    /// Turns opened so far, and continuations [`super::hook::RunHooks::compose_continuation`] already asked for.
    turns: usize,
    continuations: usize,
    report: Option<&'a Report>,
}

impl<'a, M: Client> Driver<'a, M> {
    pub(crate) const fn new(
        model: &'a M,
        lease: &'a Lease,
        inbox: &'a InputMailbox,
        tools: &'a tool::Registry,
        cancellation: &'a Token,
    ) -> Self {
        Self {
            context: Context {
                model,
                lease,
                #[cfg(test)]
                transcript: None,
                inbox,
                tools,
                cancellation,
            },
            tool_phase: None,
            phase: Phase::Generation,
            generation_position: GenerationPosition::first(),
            turn_open: false,
            turn_trigger: Vec::new(),
            step_snapshot: None,
            turns: 0,
            continuations: 0,
            report: None,
        }
    }

    pub(crate) fn with_tool_phase(mut self, tool_phase: ToolPhase<'a>) -> Self {
        self.tool_phase = Some(tool_phase);
        self
    }

    /// Records what opened this Run's first Turn.
    ///
    /// The admitted input is already a transcript record by the time the Driver
    /// runs, so the trigger is carried separately rather than recovered from
    /// history, where nothing distinguishes it from an earlier turn's input.
    pub(crate) fn with_turn_trigger(mut self, trigger: Vec<Item>) -> Self {
        self.turn_trigger = trigger;
        self
    }

    /// Lends the Driver the report the Run owner reads after the join barrier.
    pub(crate) const fn with_report(mut self, report: &'a Report) -> Self {
        self.report = Some(report);
        self
    }

    #[cfg(test)]
    pub(super) fn with_transcript_reader(
        model: &'a M,
        lease: &'a Lease,
        transcript: crate::transcript::store::SnapshotReader,
        inbox: &'a InputMailbox,
        tools: &'a tool::Registry,
        cancellation: &'a Token,
    ) -> Self {
        let mut driver = Self::new(model, lease, inbox, tools, cancellation);
        driver.context.transcript = Some(transcript);
        driver
    }

    /// Owns this Driver until one closed terminal fact is stable.
    ///
    /// The owner repeatedly drives every generation and claimed-input boundary;
    /// callers never need to externally loop over [`Self::advance`]. It records
    /// strong-seam rejection as a normal stop, direct cancellation as canceled,
    /// and every real loop or event-validation error in the single fatal latch.
    /// Stop publication remains exclusively owned by [`Producer::emit_stop`].
    ///
    /// Returning a [`Terminal`] is the internal join barrier: the current model
    /// future/stream has completed or been dropped, every started tool slot and
    /// invocation emitter has settled, every cooperative blocking callback has
    /// been joined, and no strong delivery remains registered with the Producer.
    /// This method deliberately does not release the borrowed [`Lease`]; the Run
    /// owner must release it only after this barrier and may then synchronously
    /// acquire a successor that observes the complete atomic transcript truth.
    pub(crate) async fn run(mut self, plan: RequestPlan, source: &EventSource) -> Terminal {
        let mut terminal = TerminalLatch::default();
        loop {
            terminal.observe_control(source);
            if terminal.is_terminal() {
                return self.close_boundaries(terminal.finish(source));
            }

            enum Drive<T> {
                Advanced(T),
                Interrupted,
            }

            // Poll advance first so a real error produced by this same poll keeps
            // priority over a concurrent stop/cancel notification. The inner
            // scope is intentional: on interruption it drops the entire advance
            // future (and therefore model/tool/emitter/callback owners) before we
            // inspect Control and publish the terminal fact.
            let driven = {
                let advance = self.advance(plan.clone());
                tokio::pin!(advance);
                tokio::select! {
                    biased;
                    result = &mut advance => Drive::Advanced(result),
                    () = source.interruption() => Drive::Interrupted,
                }
            };
            match driven {
                Drive::Advanced(Ok(Some(_))) => {}
                Drive::Advanced(Ok(None)) => {
                    return self.close_boundaries(terminal.finish(source));
                }
                Drive::Advanced(Err(error)) => {
                    terminal.record_error(source, error);
                    return self.close_boundaries(terminal.finish(source));
                }
                Drive::Interrupted => {
                    terminal.observe_control(source);
                    return self.close_boundaries(terminal.finish(source));
                }
            }
        }
    }

    /// Ends every lifecycle boundary this Run entered and never left.
    ///
    /// Called on all four exits rather than only the interrupted ones. A Run that
    /// reached its natural end has already closed every boundary in order, so
    /// this is a no-op there — and asserting that by construction is better than
    /// maintaining a second list of which exits can leave a boundary open.
    fn close_boundaries(&self, terminal: Terminal) -> Terminal {
        if let Some(tool_phase) = &self.tool_phase {
            let end = boundary_end(&terminal, self.report.and_then(Report::stop_code));
            tool_phase.close_open_observations(&end);
        }
        terminal
    }

    /// Advances to the next observable generation or claimed input.
    ///
    /// `None` is the stable natural end after a completed Turn finds no
    /// `NextTurn` input. Inbox claims are returned immediately; the owner decides
    /// whether to continue or close the terminal fact.
    pub(crate) async fn advance(&mut self, plan: RequestPlan) -> Result<Option<Advance>, Error> {
        if self.context.cancellation.is_cancelled() {
            return Err(Error::Cancelled);
        }

        loop {
            match self.phase {
                Phase::Generation => {
                    let coords = self.tool_phase.as_ref().map(|tool_phase| {
                        self.generation_position
                            .coords(&tool_phase.session_coord_id, &tool_phase.run_id)
                    });
                    self.open_turn(coords.as_ref()).await?;
                    self.emit_step_boundary(Kind::StepStart, None).await?;
                    let generation = {
                        // The model phase borrows the attached phase and this
                        // generation's coordinates; the borrow ends here so
                        // publication below can take the phase mutably.
                        let phase = self.tool_phase.as_ref();
                        Step {
                            context: &self.context,
                            phase,
                            coords: coords.as_ref(),
                        }
                        .advance(plan)
                        .await?
                    };
                    self.step_snapshot = Some(Arc::clone(generation.snapshot()));
                    let generated_tool_calls = generation.has_tool_calls();
                    if let Err(error) = self
                        .publish_generation(&generation, coords.as_ref(), generated_tool_calls)
                        .await
                    {
                        self.phase = Phase::Done;
                        return Err(error);
                    }
                    self.phase = Phase::StepBoundary {
                        generated_tool_calls,
                    };
                    return Ok(Some(Advance::Generation(generation)));
                }
                Phase::StepBoundary {
                    generated_tool_calls,
                } => {
                    let end_turn = self.close_step().await?;
                    // `EndTurn` owns this primitive boundary. A queued `NextStep`
                    // cannot reopen it and remains available to a later boundary
                    // or successor Run instead.
                    if !end_turn {
                        if let Some(mut claim) =
                            self.context.inbox.claim_conserved(InputTarget::NextStep)
                        {
                            // The claim is settled or restored before any await,
                            // so no interruption can observe it unresolved.
                            let outcome = self.admit_input(&mut claim);
                            drop(claim);
                            match outcome? {
                                InputAdmitOutcome::Admitted(input) => {
                                    self.publish_input_admitted(
                                        InputOrigin::Mailbox,
                                        input.items().to_vec(),
                                    )
                                    .await?;
                                    self.generation_position.next_step();
                                    self.phase = Phase::Generation;
                                    return Ok(Some(Advance::Input(input)));
                                }
                                InputAdmitOutcome::Rejected(reason) => {
                                    // A refusal is produced only by an attached
                                    // phase: without one `admit_input` admits
                                    // unconditionally and consults no registration.
                                    self.tool_phase
                                        .as_ref()
                                        .expect("only an attached tool phase refuses a batch")
                                        .publish_input_rejected(reason)
                                        .await?;
                                }
                            }
                        }
                    }
                    self.phase = if generated_tool_calls && !end_turn {
                        self.generation_position.next_step();
                        Phase::Generation
                    } else {
                        Phase::TurnBoundary
                    };
                }
                Phase::TurnBoundary => {
                    self.close_turn().await?;
                    // A stop decision is made before either source of a
                    // prospective Turn, so pre-enqueued input cannot defer it.
                    if self.publish_requested_stop().await? {
                        self.phase = Phase::Done;
                        continue;
                    }
                    if let Some(mut claim) =
                        self.context.inbox.claim_conserved(InputTarget::NextTurn)
                    {
                        let outcome = self.admit_input(&mut claim);
                        drop(claim);
                        match outcome? {
                            InputAdmitOutcome::Admitted(input) => {
                                self.turn_trigger = input.items().to_vec();
                                self.publish_input_admitted(
                                    InputOrigin::Mailbox,
                                    self.turn_trigger.clone(),
                                )
                                .await?;
                                self.generation_position.next_turn();
                                self.phase = Phase::Generation;
                                return Ok(Some(Advance::Input(input)));
                            }
                            InputAdmitOutcome::Rejected(reason) => {
                                // A refusal is produced only by an attached
                                // phase: without one `admit_input` admits
                                // unconditionally and consults no registration.
                                self.tool_phase
                                    .as_ref()
                                    .expect("only an attached tool phase refuses a batch")
                                    .publish_input_rejected(reason)
                                    .await?;
                            }
                        }
                    }
                    if let Some(continuation) = self.compose_continuation()? {
                        self.turn_trigger = continuation.items().to_vec();
                        self.publish_input_admitted(
                            InputOrigin::Continuation,
                            self.turn_trigger.clone(),
                        )
                        .await?;
                        self.generation_position.next_turn();
                        self.phase = Phase::Generation;
                        return Ok(Some(Advance::Input(continuation)));
                    } else {
                        self.phase = Phase::Done;
                    }
                }
                Phase::Done => return Ok(None),
            }
        }
    }

    /// Publishes one completed generation: its content, its transcript record,
    /// and its closing lifecycle event.
    ///
    /// Content is emitted before the record is committed so a consumer observes
    /// what the model said before what the model wants to do about it. A
    /// tool-calling generation commits through the batch pipeline, which owns
    /// the assistant item and every result as one transaction; a tool-free
    /// generation commits the assistant item on its own.
    async fn publish_generation(
        &mut self,
        generation: &Generation,
        coords: Option<&GenerationCoords>,
        generated_tool_calls: bool,
    ) -> Result<(), Error> {
        let cancellation = self.context.cancellation;
        let Some(tool_phase) = &mut self.tool_phase else {
            // Focused unit drivers keep the legacy advance-only contract, but a
            // tool call with no phase able to run it is still a broken contract.
            return if generated_tool_calls {
                Err(Error::MissingToolPhase)
            } else {
                Ok(())
            };
        };
        let coord = &coords
            .expect("an attached tool phase mints generation coordinates")
            .generation;
        tool_phase
            .emit_generation_content(generation, coord)
            .await?;
        if generated_tool_calls {
            tool_phase.process(generation, coord, cancellation).await?;
        } else {
            tool_phase.commit_assistant(generation, coord, cancellation)?;
        }
        tool_phase
            .emit_lifecycle_event(Kind::GenerationEnd, Some(Outcome::Completed), coord.clone())
            .await?;
        tool_phase.observe_lifecycle(
            coord,
            Some(generation.snapshot()),
            &LifecycleObservation::GenerationEnd {
                coord: coord.clone(),
                end: LifecycleEnd::Completed,
                finish_reason: generation.finish_reason().to_owned(),
                completion: generation.completion(),
            },
        );
        tool_phase.closed_generation();
        Ok(())
    }

    /// Opens the turn the cursor is entering, exactly once.
    ///
    /// `OnBeforeTurn` runs before the boundary is announced, so a registration
    /// that seeds the turn has already recorded its items when the first Step
    /// freezes the transcript it will send.
    async fn open_turn(&mut self, coords: Option<&GenerationCoords>) -> Result<(), Error> {
        if self.turn_open {
            return Ok(());
        }
        if let Some(tool_phase) = &self.tool_phase {
            let coord = &coords
                .expect("an attached tool phase mints turn coordinates")
                .turn;
            let trigger = &self.turn_trigger;
            tool_phase.staged_boundary(
                coord,
                self.context.cancellation,
                tool_phase.has_turn_step_hooks(),
                |staged| tool_phase.before_turn(staged, trigger, self.context.cancellation),
            )?;
            tool_phase
                .emit_lifecycle_event(Kind::TurnStart, None, coord.clone())
                .await?;
            tool_phase.observe_lifecycle(
                coord,
                None,
                &LifecycleObservation::TurnStart {
                    coord: coord.clone(),
                    trigger: trigger.clone(),
                },
            );
            tool_phase.opened_turn(coord);
        }
        self.turn_open = true;
        self.turns += 1;
        if let Some(report) = self.report {
            report.turns.store(self.turns, Ordering::Relaxed);
        }
        Ok(())
    }

    /// Closes the turn the cursor is leaving.
    ///
    /// Unlike [`Self::open_turn`] this needs no latch: the turn boundary is
    /// reached only from a completed step, and a step is reached only from a
    /// generation that opened the turn.
    async fn close_turn(&mut self) -> Result<(), Error> {
        let steps = self.generation_position.step;
        if let Some(tool_phase) = &self.tool_phase {
            let coord = self
                .generation_position
                .turn_coord(&tool_phase.session_coord_id, &tool_phase.run_id);
            let trigger = &self.turn_trigger;
            tool_phase.staged_boundary(
                &coord,
                self.context.cancellation,
                tool_phase.has_turn_step_hooks(),
                |staged| tool_phase.after_turn(staged, trigger, self.context.cancellation),
            )?;
            tool_phase
                .emit_lifecycle_event(Kind::TurnEnd, Some(Outcome::Completed), coord.clone())
                .await?;
            tool_phase.observe_lifecycle(
                &coord,
                None,
                &LifecycleObservation::TurnEnd {
                    coord: coord.clone(),
                    end: LifecycleEnd::Completed,
                    // Rust's supported targets keep every step index in `usize`.
                    steps: steps as usize,
                },
            );
            tool_phase.closed_turn();
        }
        self.turn_open = false;
        Ok(())
    }

    /// Closes the step the cursor is on, and reports whether the turn ends here.
    ///
    /// `OnAfterStep` is the only decision at this boundary: any registration
    /// answering `EndTurn` ends the turn even when the generation produced tool
    /// calls, and every registration's items are appended either way.
    async fn close_step(&mut self) -> Result<bool, Error> {
        let snapshot = self
            .step_snapshot
            .take()
            .expect("a step boundary always follows a frozen generation");
        let mut end_turn = false;
        if let Some(tool_phase) = &self.tool_phase {
            let cancellation = self.context.cancellation;
            let coord = self
                .generation_position
                .step_coord(&tool_phase.session_coord_id, &tool_phase.run_id);
            tool_phase.staged_boundary(
                &coord,
                cancellation,
                tool_phase.has_turn_step_hooks(),
                |staged| {
                    let (ends_turn, items) =
                        tool_phase.after_step(staged, &snapshot, cancellation)?;
                    end_turn = ends_turn;
                    Ok(items)
                },
            )?;
            tool_phase
                .emit_lifecycle_event(Kind::StepEnd, Some(Outcome::Completed), coord.clone())
                .await?;
            tool_phase.observe_lifecycle(
                &coord,
                Some(&snapshot),
                &LifecycleObservation::StepEnd {
                    coord: coord.clone(),
                    end: LifecycleEnd::Completed,
                    snapshot: Arc::clone(&snapshot),
                },
            );
            tool_phase.closed_step();
        }
        Ok(end_turn)
    }

    /// Publishes the single privately owned `EventStop` if a policy asked for one.
    ///
    /// [`super::hook::RunHooks::decide_stop`] is the only surface that can produce a stop code
    /// (ADR-007), and this is its only exit. Returning `true` means the Run ends
    /// here as `Stopped`.
    async fn publish_requested_stop(&mut self) -> Result<bool, Error> {
        let Some(tool_phase) = &self.tool_phase else {
            return Ok(false);
        };
        let Some(code) = tool_phase.decide_stop(self.context.cancellation)? else {
            return Ok(false);
        };
        let coord = tool_phase.run_coord();
        tool_phase.drain_hook_facts(&coord).await?;
        tool_phase
            .outward
            .producer
            .emit_stop(code.clone(), coord)
            .await
            .map_err(Error::Event)?;
        if let Some(report) = self.report {
            *report
                .stop_code
                .lock()
                .expect("driver report lock poisoned") = Some(code);
        }
        Ok(true)
    }

    /// Asks every [`super::hook::RunHooks::compose_continuation`] registration whether the Run continues.
    ///
    /// A non-empty continuation is recorded as user content and opens another
    /// Turn. Together with a claimed `NextTurn` batch these are the only two
    /// things that may open one, so nothing else here advances the cursor.
    fn compose_continuation(&mut self) -> Result<Option<InputBatch>, Error> {
        let Some(tool_phase) = &self.tool_phase else {
            return Ok(None);
        };
        let cancellation = self.context.cancellation;
        let coord = tool_phase.run_coord();
        let turns = self.turns;
        let continuations = self.continuations;
        let mut continuation = Vec::new();
        tool_phase.staged_boundary(&coord, cancellation, tool_phase.has_run_hooks(), |staged| {
            let parts =
                tool_phase.compose_continuation(staged, continuations, turns, cancellation)?;
            if parts.is_empty() {
                return Ok(Vec::new());
            }
            continuation = vec![Item::User(User::new(parts, ModelVisibility::Visible))];
            Ok(continuation.clone())
        })?;
        if continuation.is_empty() {
            return Ok(None);
        }
        self.continuations += 1;
        Ok(Some(
            InputBatch::new(InputTarget::NextTurn, continuation)
                .expect("a non-empty continuation is a valid batch"),
        ))
    }

    /// Publishes one Step boundary event for the step the cursor is on.
    ///
    /// Entering the step is also what the enclosing Turn counts, so the count the
    /// Turn's end observation reports is taken here rather than recovered later:
    /// an interrupted Turn has to report the steps it entered, and by then the
    /// cursor has moved.
    async fn emit_step_boundary(&self, kind: Kind, outcome: Option<Outcome>) -> Result<(), Error> {
        if let Some(tool_phase) = &self.tool_phase {
            let coord = self
                .generation_position
                .step_coord(&tool_phase.session_coord_id, &tool_phase.run_id);
            // Rust's supported targets keep every step index in `usize`.
            tool_phase.entered_step(self.generation_position.step as usize);
            tool_phase
                .emit_lifecycle_event(kind, outcome, coord)
                .await?;
        }
        Ok(())
    }

    /// Attempts to project one committed input batch onto the outward stream.
    ///
    /// This is the only transcript record reef commits that the model did not
    /// produce, so an uninterrupted consumer needs this category to explain the
    /// boundary the input opens. It is not the recovery record: the Transcript
    /// and its reservation hooks own that authority.
    ///
    /// Publication is attempted after commit, so it reports rather than proposes:
    /// if a consumer sees it, the record already exists and no decision can
    /// withdraw it. C18/C20 still fail closed if interruption latched in between,
    /// leaving the committed record with no `InputAdmitted` event. The coordinate
    /// is the Run, matching the coordinate the append itself was stamped with —
    /// the batch belongs to the Run, not to the Turn it is about to open.
    async fn publish_input_admitted(
        &self,
        origin: InputOrigin,
        items: Vec<Item>,
    ) -> Result<(), Error> {
        if let Some(tool_phase) = &self.tool_phase {
            let coord = tool_phase.run_coord();
            tool_phase.drain_hook_facts(&coord).await?;
            tool_phase
                .outward
                .producer
                .emit_input_admitted(origin, items, coord)
                .await
                .map_err(Error::Event)?;
        }
        Ok(())
    }

    /// Admits one claimed inbox batch, or settles it unchanged when no tool
    /// phase is attached (focused unit drivers).
    ///
    /// The production owner always attaches a tool phase, so every claimed
    /// batch runs the `OnBeforeInputAdmit` fan-out and the atomic transcript
    /// append before the boundary advances. Plain unit drivers keep the legacy
    /// claim-only contract.
    fn admit_input(&mut self, claim: &mut Claim<'_>) -> Result<InputAdmitOutcome, Error> {
        let Some(tool_phase) = &mut self.tool_phase else {
            return Ok(InputAdmitOutcome::Admitted(claim.settle()));
        };
        tool_phase.admit_input(claim, self.context.cancellation)
    }
}

impl ToolPhase<'_> {
    /// Admits one claimed inbox batch through the registered
    /// `OnBeforeInputAdmit` adapters, then atomically appends the final items.
    ///
    /// This is the production caller for the public input hooks. Adapters run
    /// in registration order and each observes the previous registration's
    /// rewrite. The append is one reserve-commit-publish transaction through
    /// the same controller used by every other transcript mutation, so a
    /// failure leaves zero partial items and the next model Request reads the
    /// appended content exactly once.
    ///
    /// The claim is settled at exactly two points: a refusal, which is
    /// permanent and must never append or open an extra generation, and the
    /// append's compare-and-set, which is reported before any reservation
    /// publishes so that a panicking publisher cannot make a committed batch
    /// look unsettled. Every other exit leaves the claim unsettled, and the
    /// caller dropping it restores the original, unrewritten batch.
    pub(crate) fn admit_input(
        &self,
        claim: &mut Claim<'_>,
        cancellation: &Token,
    ) -> Result<InputAdmitOutcome, Error> {
        let target = claim.batch().target();
        let mut items = claim.batch().items().to_vec();
        let transcript = self.controller.snapshot_reader();
        for adapter in self.hooks.input_hooks() {
            let registration_resources = self
                .callback_resources
                .get(adapter.index())
                .copied()
                .expect("input-admit resources cover every registry index");
            // `OnBeforeInputAdmit` is infallible by trait shape, so the adapter's
            // only dispatch failure is cancellation, both before and after the
            // callback. Mapping every failure to
            // `Cancelled` keeps that fact stated in one place instead of carrying
            // a callback-error arm no dispatch can reach.
            let decision = adapter
                .invoke_before_input_admit(
                    registration_resources,
                    &transcript,
                    target,
                    &items,
                    cancellation,
                )
                .map_err(|_| Error::Cancelled)?;
            match decision {
                InputAdmitDecision::Admit => {}
                InputAdmitDecision::Modify(replacement) => {
                    // A rewrite that would discard the whole batch is invalid,
                    // not a silent no-op.
                    if replacement.is_empty() {
                        return Err(Error::Input(InputAdmitError::EmptyModify));
                    }
                    items = replacement;
                }
                InputAdmitDecision::Reject(reason) => {
                    // The reason is the only artifact a rejection leaves
                    // behind, so it is mandatory.
                    if reason.is_empty() {
                        return Err(Error::Input(InputAdmitError::EmptyRejectReason));
                    }
                    let _refused = claim.settle();
                    return Ok(InputAdmitOutcome::Rejected(reason));
                }
            }
        }
        self.controller
            .append_batch_settling(items.clone(), cancellation, &mut || {
                let _committed = claim.settle();
            })
            .map_err(|error| match error {
                ControllerError::Dispatch(DispatchError::Cancelled) => Error::Cancelled,
                other => Error::InputAdmitTranscript(other),
            })?;
        let batch = InputBatch::new(target, items)
            .expect("admitted input stays non-empty after validated hooks");
        Ok(InputAdmitOutcome::Admitted(batch))
    }

    /// Commits the assistant item of a generation that produced no tool calls.
    ///
    /// A tool-calling generation reaches the transcript through
    /// [`commit_tool_batch`], which needs a routed batch to commit alongside the
    /// assistant item. A plain-text generation has no batch, so without this
    /// path the model's answer — the closing turn of any agent — would be
    /// produced, validated, and then dropped. The append is the same
    /// reserve-commit-publish transaction every other mutation uses, so a
    /// failure leaves zero partial items.
    ///
    /// A generation that carries neither segments nor record-level provider data
    /// records nothing: an empty assistant item would assert that the model said
    /// something when it did not, and every later reader — persistence, resume,
    /// compaction, replay — would carry that assertion forward.
    ///
    /// Content alone is not the test, though. An empty or refused completion can
    /// still carry provider envelopes, and C27 requires those bytes, their order
    /// and their presence to survive; skipping on empty content alone would drop
    /// them. The same holds for an `OnAfterModel` rewrite, which replaces the
    /// whole [`Assistant`] and may legitimately keep only its metadata.
    pub(crate) fn commit_assistant(
        &self,
        generation: &Generation,
        generation_coord: &Coord,
        cancellation: &Token,
    ) -> Result<(), Error> {
        let assistant = generation.assistant();
        let records_nothing =
            assistant.content().is_empty() && assistant.provider_data().is_none_or(<[_]>::is_empty);
        let items = if records_nothing {
            Vec::new()
        } else {
            vec![Item::Assistant(assistant.clone())]
        };
        self.controller
            .with_coord(generation_coord)
            .append_batch(items, cancellation)
            .map_err(|error| match error {
                ControllerError::Dispatch(DispatchError::Cancelled) => Error::Cancelled,
                other => Error::GenerationTranscript(other),
            })?;
        Ok(())
    }

    /// Publishes the model-visible content of one generation in segment order.
    ///
    /// Content is emitted before the batch is committed so that a consumer sees
    /// what the model said before it sees what the model wants to do with it.
    /// These are ordinary deliveries, not strong seams: a rejected outcome means
    /// the consumer is already gone, which the terminal latch observes on its
    /// own rather than through this loop.
    ///
    /// The item identity comes from the committed record rather than from the
    /// stream, which is the only source that can still be right here: by this
    /// point `OnAfterModel` may have replaced the content outright, and a
    /// replacement carries whatever identity the registration gave it —
    /// including none. So the identity a consumer reads always describes the
    /// content it is attached to.
    pub(crate) async fn emit_generation_content(
        &self,
        generation: &Generation,
        generation_coord: &Coord,
    ) -> Result<(), Error> {
        self.drain_hook_facts(generation_coord).await?;
        for segment in generation.assistant().content() {
            let (kind, text, extensions) = match segment {
                Segment::Text { text, extensions } => (Kind::Text, text, extensions),
                Segment::Thinking { text, extensions } => (Kind::Thinking, text, extensions),
                Segment::ToolCall { .. } => continue,
            };
            self.outward
                .producer
                .emit_text(
                    kind,
                    text.clone(),
                    generation_coord.clone(),
                    extensions.item_id().map(str::to_owned),
                )
                .await
                .map_err(Error::Event)?;
        }
        Ok(())
    }

    /// Binds one registration's borrowed resources to a boundary coordinate.
    fn resources<'scope>(
        &'scope self,
        index: usize,
        coord: &'scope Coord,
    ) -> CallbackResources<'scope> {
        self.callback_resources
            .get(index)
            .copied()
            .expect("boundary resources cover every registry index")
            .with_coord(coord)
    }

    /// Returns the Run coordinate every Run-scoped boundary is stamped with.
    fn run_coord(&self) -> Coord {
        Coord::at_run(self.session_coord_id.clone(), self.run_id.clone())
            .expect("the attached tool phase carries non-empty run identities")
    }

    /// Fans one lifecycle observation out in registration order.
    ///
    /// Observers cannot fail or decide anything, so this returns nothing: a
    /// panicking observer is isolated and audited inside the adapter and its
    /// peers still run.
    fn observe_lifecycle(
        &self,
        coord: &Coord,
        snapshot: Option<&Arc<StepSnapshot>>,
        observation: &LifecycleObservation,
    ) {
        let reader = self.controller.snapshot_reader();
        let transcript = lifecycle_transcript_source(observation.kind(), snapshot, &reader);
        for adapter in self.hooks.observer_hooks() {
            let resources = self.resources(adapter.index(), coord);
            adapter.invoke_lifecycle(resources, transcript, snapshot, observation);
        }
    }

    /// Records that a Turn was entered and has not been left.
    fn opened_turn(&self, coord: &Coord) {
        self.open().turn = Some(OpenTurn {
            coord: coord.clone(),
            steps: 0,
        });
    }

    /// Records that the enclosing Turn entered its `steps`-th Step.
    fn entered_step(&self, steps: usize) {
        self.open()
            .turn
            .as_mut()
            .expect("a Step is entered only inside a Turn this phase opened")
            .steps = steps;
    }

    /// Records that a Step was entered and has not been left.
    fn opened_step(&self, coord: &Coord, snapshot: &Arc<StepSnapshot>) {
        self.open().step = Some(OpenScope {
            coord: coord.clone(),
            snapshot: Arc::clone(snapshot),
        });
    }

    /// Records that a Generation was entered and has not been left.
    fn opened_generation(&self, coord: &Coord, snapshot: &Arc<StepSnapshot>) {
        self.open().generation = Some(OpenScope {
            coord: coord.clone(),
            snapshot: Arc::clone(snapshot),
        });
    }

    fn closed_turn(&self) {
        self.open().turn.take();
    }

    fn closed_step(&self) {
        self.open().step.take();
    }

    fn closed_generation(&self) {
        self.open().generation.take();
    }

    fn open(&self) -> std::sync::MutexGuard<'_, OpenBoundaries> {
        self.open.lock().expect("driver boundary lock poisoned")
    }

    /// Ends every boundary this phase entered and never left, innermost first.
    ///
    /// The nesting order is the same one the opening observations arrived in
    /// reversed, so a registration that keeps a stack of open boundaries unwinds
    /// it rather than being handed an outer end while an inner one is still open.
    fn close_open_observations(&self, end: &LifecycleEnd) {
        let open = std::mem::take(&mut *self.open());
        self.close_tool_calls(open.calls, end);
        if let Some(generation) = open.generation {
            self.observe_lifecycle(
                &generation.coord,
                Some(&generation.snapshot),
                &LifecycleObservation::GenerationEnd {
                    coord: generation.coord.clone(),
                    end: end.clone(),
                    // A generation the provider never finished has no finish
                    // label of its own, and inventing one would put a value in
                    // the "verbatim provider" field the provider never said.
                    finish_reason: String::new(),
                    completion: CompletionReason::Unknown,
                },
            );
        }
        if let Some(step) = open.step {
            self.observe_lifecycle(
                &step.coord,
                Some(&step.snapshot),
                &LifecycleObservation::StepEnd {
                    coord: step.coord.clone(),
                    end: end.clone(),
                    snapshot: Arc::clone(&step.snapshot),
                },
            );
        }
        if let Some(turn) = open.turn {
            self.observe_lifecycle(
                &turn.coord,
                None,
                &LifecycleObservation::TurnEnd {
                    coord: turn.coord.clone(),
                    end: end.clone(),
                    steps: turn.steps,
                },
            );
        }
    }

    /// Publishes one terminal observation per announced call, in source order.
    fn close_tool_calls(&self, calls: Vec<OpenToolCall>, end: &LifecycleEnd) {
        for call in calls {
            let coord = call.coord.clone();
            let snapshot = Arc::clone(&call.snapshot);
            let observation = LifecycleObservation::ToolCallEnd(call.end(end));
            self.observe_lifecycle(&coord, Some(&snapshot), &observation);
        }
    }

    /// Fans one normalized model event out in registration order.
    ///
    /// This is the only route by which token usage leaves the runtime, so it
    /// runs for every accepted event rather than only the ones the loop itself
    /// consumes.
    fn observe_model_event(
        &self,
        coord: &Coord,
        snapshot: &Arc<StepSnapshot>,
        event: &model::Event,
    ) {
        for adapter in self.hooks.observer_hooks() {
            let resources = self.resources(adapter.index(), coord);
            adapter.invoke_model_event(
                resources,
                snapshot.tools().transcript(),
                Some(snapshot),
                event,
            );
        }
    }

    /// Announces one permanently refused batch and the reason given for it.
    ///
    /// A refusal settles the claim instead of restoring it, so it is final and
    /// nothing will retry the batch. Whoever sent it is waiting for an answer
    /// that is never coming, and the reason exists nowhere else.
    ///
    /// This lives on the phase rather than on the Driver because only a phase
    /// can produce a refusal: without one, `Driver::admit_input` admits
    /// unconditionally and no registration is consulted.
    async fn publish_input_rejected(&self, reason: String) -> Result<(), Error> {
        let coord = self.run_coord();
        self.drain_hook_facts(&coord).await?;
        self.outward
            .producer
            .emit_input_rejected(reason, coord)
            .await
            .map_err(Error::Event)?;
        Ok(())
    }

    /// Fans one audit fact out in registration order before it is published.
    fn observe_audit(&self, coord: &Coord, event: &audit::Event) {
        let transcript = self.controller.snapshot_reader();
        for adapter in self.hooks.observer_hooks() {
            let resources = self.resources(adapter.index(), coord);
            adapter.invoke_audit_event(resources, &transcript, event);
        }
    }

    /// Publishes everything synchronous callbacks queued since the last drain.
    ///
    /// Every one of the loop's own publications calls this first, so a fact a
    /// callback emitted is already on the stream by the time the next event the
    /// loop produces is. That is the whole reason it exists: a callback runs
    /// synchronously and cannot await the Producer, so without a drain owned by
    /// the loop its facts would wait until the Run task's final one and arrive
    /// after every event they were about.
    ///
    /// `coord` is the position the loop is publishing at, which is also the
    /// position the callbacks that queued these facts were bound to. Stamping it
    /// is what lets a consumer place the fact; a fact drained by the Run owner
    /// has no narrower coordinate than the Run and carries none.
    ///
    /// An interrupted Run reaches no further publication point, so facts still
    /// queued when it is interrupted are not published — the same fail-closed
    /// rule the outward lane applies to its own closing events.
    async fn drain_hook_facts(&self, coord: &Coord) -> Result<(), Error> {
        for fact in self.outward.facts.take_facts() {
            let event = match fact {
                BufferedFact::Audit(audit) => {
                    // `OnAuditEvent` observes the fact before it is published, so
                    // an observer and the outward consumer see the same value and
                    // the observer cannot answer an event the consumer already saw.
                    self.observe_audit(coord, &audit);
                    Event::from_audit(audit).map_err(Error::Event)?
                }
                BufferedFact::Error(error) => Event::from_error(error),
            };
            self.outward
                .producer
                .emit_extension(event, coord.clone())
                .await
                .expect("a successfully constructed ordinary fact remains valid");
        }
        Ok(())
    }

    /// Reports whether any registration takes part in the Turn/Step boundaries.
    fn has_turn_step_hooks(&self) -> bool {
        self.hooks.turn_step_hooks().next().is_some()
    }

    /// Reports whether any registration takes part in the Run boundaries.
    fn has_run_hooks(&self) -> bool {
        self.hooks.run_hooks().next().is_some()
    }

    /// Runs one staged-transcript boundary and commits everything it produced.
    ///
    /// Every registration observes the same staging area, so a later one sees an
    /// earlier one's rewrite, exactly as [`super::hook::RunHooks::prepare`] does
    /// at admission. Returned items are appended to that isolated history before
    /// the controller sees it,
    /// so staged history and returned items commit as one mutation or not at all.
    ///
    /// A boundary nobody registered for is skipped entirely rather than run over
    /// an empty fan-out: it would otherwise take transcript authority to commit a
    /// batch that cannot exist, and a Run with no hooks would start failing on
    /// transcript states no hook ever asked to see.
    fn staged_boundary<F>(
        &self,
        coord: &Coord,
        cancellation: &Token,
        registered: bool,
        dispatch: F,
    ) -> Result<(), Error>
    where
        F: FnOnce(&StagedTranscript) -> Result<Vec<Item>, Error>,
    {
        if !registered {
            return Ok(());
        }
        let controller = self.controller.with_coord(coord);
        let (base_version, returned, staged_store) = {
            let store = controller.staging_store().map_err(Error::Transcript)?;
            let base_version = store.version().map_err(Error::Transcript)?;
            let staged = StagedTranscript::from_store(&store);
            let returned = dispatch(&staged)?;
            drop(staged);
            (base_version, returned, store)
        };
        if staged_store.version().map_err(Error::Transcript)? != base_version {
            let snapshot = staged_store
                .into_snapshot_with_suffix(returned)
                .map_err(Error::Transcript)?;
            controller
                .replace_snapshot(snapshot, base_version, cancellation)
                .map_err(boundary_transcript)?;
        } else {
            controller
                .append_batch(returned, cancellation)
                .map_err(boundary_transcript)?;
        }
        Ok(())
    }

    /// Runs the `OnBeforeTurn` fan-out in registration order.
    fn before_turn(
        &self,
        staged: &StagedTranscript,
        trigger: &[Item],
        cancellation: &Token,
    ) -> Result<Vec<Item>, Error> {
        let coord = self.run_coord();
        let mut returned = Vec::new();
        for adapter in self.hooks.turn_step_hooks() {
            let resources = self.resources(adapter.index(), &coord);
            returned.extend(
                adapter
                    .invoke_before_turn(resources, staged, trigger, cancellation)
                    .map_err(boundary_hook)?,
            );
        }
        Ok(returned)
    }

    /// Runs the `OnAfterTurn` fan-out in registration order.
    fn after_turn(
        &self,
        staged: &StagedTranscript,
        trigger: &[Item],
        cancellation: &Token,
    ) -> Result<Vec<Item>, Error> {
        let coord = self.run_coord();
        let mut returned = Vec::new();
        for adapter in self.hooks.turn_step_hooks() {
            let resources = self.resources(adapter.index(), &coord);
            returned.extend(
                adapter
                    .invoke_after_turn(resources, staged, trigger, cancellation)
                    .map_err(boundary_hook)?,
            );
        }
        Ok(returned)
    }

    /// Runs the `OnBeforeStep` fan-out, letting each registration edit the plan.
    fn before_step(
        &self,
        staged: &StagedTranscript,
        model: &Info,
        plan: &mut RequestPlan,
        cancellation: &Token,
    ) -> Result<Vec<Item>, Error> {
        let coord = self.run_coord();
        let mut returned = Vec::new();
        for adapter in self.hooks.turn_step_hooks() {
            let resources = self.resources(adapter.index(), &coord);
            returned.extend(
                adapter
                    .invoke_before_step(resources, staged, model, plan, cancellation)
                    .map_err(boundary_hook)?,
            );
        }
        Ok(returned)
    }

    /// Runs the `OnAfterStep` fan-out and folds its decisions.
    ///
    /// A single `EndTurn` ends the turn: a registration that decided the turn is
    /// over must not be overruled by a later one that merely had nothing to say.
    fn after_step(
        &self,
        staged: &StagedTranscript,
        snapshot: &Arc<StepSnapshot>,
        cancellation: &Token,
    ) -> Result<(bool, Vec<Item>), Error> {
        let coord = self.run_coord();
        let mut end_turn = false;
        let mut returned = Vec::new();
        for adapter in self.hooks.turn_step_hooks() {
            let resources = self.resources(adapter.index(), &coord);
            let decision = adapter
                .invoke_after_step(resources, staged, snapshot, cancellation)
                .map_err(boundary_hook)?;
            match decision {
                AfterStepDecision::Continue(items) => returned.extend(items),
                AfterStepDecision::EndTurn(items) => {
                    end_turn = true;
                    returned.extend(items);
                }
            }
        }
        Ok((end_turn, returned))
    }

    /// Runs the [`super::hook::RunHooks::compose_continuation`] fan-out, threading the continuation through it.
    ///
    /// A registration that abstains leaves the request the ones before it made,
    /// exactly as [`super::hook::RunHooks::prepare`] does at admission. An explicit empty `Modify` is
    /// the deliberate opposite: it withdraws a peer's request and ends the Run.
    fn compose_continuation(
        &self,
        staged: &StagedTranscript,
        continuations: usize,
        turns: usize,
        cancellation: &Token,
    ) -> Result<Vec<Part>, Error> {
        let coord = self.run_coord();
        let mut continuation = Vec::new();
        for adapter in self.hooks.run_hooks() {
            let resources = self.resources(adapter.index(), &coord);
            let decision = adapter
                .invoke_compose_continuation(
                    resources,
                    staged,
                    &continuation,
                    continuations,
                    turns,
                    cancellation,
                )
                .map_err(boundary_hook)?;
            match decision {
                ContinuationDecision::Keep => {}
                ContinuationDecision::Replace(replacement) => continuation = replacement,
            }
        }
        Ok(continuation)
    }

    /// Runs the [`super::hook::RunHooks::decide_stop`] fan-out, stopping at the first stop decision.
    fn decide_stop(&self, cancellation: &Token) -> Result<Option<StopCode>, Error> {
        let coord = self.run_coord();
        let transcript = self.controller.snapshot_reader();
        for adapter in self.hooks.run_hooks() {
            let resources = self.resources(adapter.index(), &coord);
            match adapter
                .invoke_decide_stop(resources, &transcript, cancellation)
                .map_err(boundary_hook)?
            {
                StopDecision::Continue => {}
                StopDecision::Stop(code) => return Ok(Some(code)),
            }
        }
        Ok(None)
    }

    /// Runs the `OnBeforeModel` fan-out over one frozen request.
    ///
    /// A `Modify` is threaded into the next registration, so the last word wins
    /// and every registration sees what the one before it decided. `ShortCircuit`
    /// and `Abort` stop the fan-out at once: both are answers about whether the
    /// call happens, which a later registration cannot un-answer.
    fn before_model(
        &self,
        coord: &Coord,
        snapshot: &Arc<StepSnapshot>,
        request: Request,
        cancellation: &Token,
    ) -> Result<ModelDecision, Error> {
        let mut request = request;
        for adapter in self.hooks.model_hooks() {
            let resources = self.resources(adapter.index(), coord);
            let decision = adapter
                .invoke_before_model(resources, snapshot, &request, cancellation)
                .map_err(boundary_hook)?;
            match decision {
                BeforeModelDecision::Continue => {}
                BeforeModelDecision::Modify(replacement) => request = replacement,
                BeforeModelDecision::ShortCircuit(output) => {
                    return Ok(ModelDecision::ShortCircuit(output));
                }
                BeforeModelDecision::Abort(reason) => {
                    return Err(Error::ModelAborted(reason));
                }
            }
        }
        Ok(ModelDecision::Generate(request))
    }

    /// Runs the `OnAfterModel` fan-out over the assembled assistant output.
    #[expect(
        clippy::too_many_arguments,
        reason = "OnAfterModel observes five independent frozen model facts, matching its scope"
    )]
    fn after_model(
        &self,
        coord: &Coord,
        snapshot: &Arc<StepSnapshot>,
        output: Assistant,
        generated: bool,
        finish_reason: &str,
        completion: CompletionReason,
        cancellation: &Token,
    ) -> Result<Assistant, Error> {
        let mut output = output;
        for adapter in self.hooks.model_hooks() {
            let resources = self.resources(adapter.index(), coord);
            let decision = adapter
                .invoke_after_model(
                    resources,
                    snapshot,
                    &output,
                    generated,
                    finish_reason,
                    completion,
                    cancellation,
                )
                .map_err(boundary_hook)?;
            match decision {
                AfterModelDecision::Continue => {}
                AfterModelDecision::Modify(replacement) => output = replacement,
            }
        }
        Ok(output)
    }

    /// Publishes one lifecycle boundary event.
    pub(crate) async fn emit_lifecycle_event(
        &self,
        kind: Kind,
        outcome: Option<Outcome>,
        coord: Coord,
    ) -> Result<(), Error> {
        self.drain_hook_facts(&coord).await?;
        self.outward
            .producer
            .emit_lifecycle(kind, outcome, coord)
            .await
            .map_err(Error::Event)?;
        Ok(())
    }

    /// Publishes one nonfatal Error for each provider that degraded this Step.
    ///
    /// ADR-009 and the core contracts make this a promise, not a choice: a
    /// provider error "emits a validated nonfatal Error, discards that
    /// provider's entire returned set, and continues with static tools and other
    /// successful providers". Resolution discards the partial entries and
    /// collects the errors (`tool::Registry::resolve_step`); this is the one
    /// place that publishes each retained [`ProviderError`] as the ordinary
    /// `Kind::Error` a consumer actually observes.
    ///
    /// The errors are fanned out in provider registration order, which is the
    /// order `resolve_step` awaited the providers and the reason that resolution
    /// is sequential rather than concurrent. Each is an *ordinary* delivery — no
    /// [`DecisionPoint`](super::event::DecisionPoint) is attached and none is
    /// added — so this changes no ack semantics: a degradation is a report about
    /// work that did not happen, and there is nothing for a consumer to accept or
    /// reject.
    ///
    /// The facts a synchronous callback queued are drained first, so the Error
    /// events do not overtake them. An interrupted Run rejects ordinary
    /// deliveries, which is the same fail-closed rule every other ordinary lane
    /// applies; the outcome is intentionally ignored here for the same reason
    /// [`drain_hook_facts`](Self::drain_hook_facts) ignores it.
    async fn publish_provider_degradations(
        &self,
        coord: &Coord,
        errors: Vec<ProviderError>,
    ) -> Result<(), Error> {
        if errors.is_empty() {
            return Ok(());
        }
        self.drain_hook_facts(coord).await?;
        for error in errors {
            // `ProviderResolution` in `runtime/tool.rs` owns this exact
            // `ProviderError`, including its typed source chain; do not flatten it.
            self.outward
                .producer
                .emit_extension(Event::from_error(Arc::new(error)), coord.clone())
                .await
                // `Event::from_error` cannot fail validation, so the only
                // remaining outcome is a rejection, which the ordinary lane
                // reports by outcome rather than by error.
                .expect("a successfully constructed ordinary fact remains valid");
        }
        Ok(())
    }

    async fn invoke_after_tool_callback(
        &self,
        adapter: OwnedToolRegistrationAdapter,
        resources: OwnedCallbackResources,
        coord: Coord,
        staged_store: Store,
        snapshot: Arc<StepSnapshot>,
        result: ToolResult,
    ) -> Result<AfterToolCallbackOutput, Error> {
        // This callback publishes through a rendezvous rather than the buffer, so
        // anything still queued has to leave first or it would arrive after facts
        // emitted later.
        self.drain_hook_facts(&coord).await?;
        let callback_hook = adapter.name().to_owned();
        let callback_coord = coord.clone();
        let callback_write_permit = resources.callback_write_permit();
        let (requests, request_receiver) = tokio::sync::mpsc::channel(1);
        let (completed, completion) = mpsc::channel();
        let handle = tokio::task::spawn_blocking(move || {
            let _completion = completed;
            match catch_unwind(AssertUnwindSafe(|| {
                let emitter = RendezvousHookEmitter { requests };
                let base_version = staged_store.version()?;
                let staged = StagedTranscript::from_store(&staged_store);
                let resources = resources.bind(&callback_coord, &emitter);
                let returned =
                    adapter.invoke_after_tool_commit(resources, &staged, &snapshot, &result);
                drop(staged);
                let staged = if staged_store.version()? == base_version {
                    None
                } else {
                    Some((base_version, staged_store.into_snapshot()?))
                };
                Ok(AfterToolCallbackOutput { staged, returned })
            })) {
                Ok(output) => AfterToolCallbackExit::Completed(output),
                Err(payload) => AfterToolCallbackExit::Panicked(payload),
            }
        });
        let mut owner = ManagedCallbackOwner {
            requests: Some(request_receiver),
            pending_ack: None,
            callback_write_permit,
            handle: Some(handle),
            completed: Some(completion),
            #[cfg(test)]
            callback_abort_order: self.test_callback_abort_order.clone(),
            #[cfg(test)]
            callback_ack_probe: self.test_callback_ack_probe.clone(),
            #[cfg(test)]
            join_drop_handle_probe: None,
        };

        let mut stopped = None;
        while let Some(request) = owner.recv().await {
            let AfterToolRequest { fact, ack } = request;
            owner.arm_ack(&ack);
            // An audit fact reaches `OnAuditEvent` before it is published, so an
            // observer and the outward consumer see the same value.
            if let AfterToolFact::Audit(audit) = &fact {
                self.observe_audit(&coord, audit);
            }
            let event = match fact.into_event() {
                Ok(event) => event,
                Err(error) => {
                    owner.revoke_callback_writes_and_abort_pending_ack();
                    stopped = Some(Error::Event(error));
                    break;
                }
            };
            // `AfterToolFact::into_event` above has already validated the only two
            // event kinds admitted by this bridge, so Producer cannot reject their
            // shape. The remaining strong outcome is consumer-owned or parent
            // cancellation.
            let outcome = self
                .outward
                .producer
                .emit_after_tool_commit(event, coord.clone())
                .await
                .expect("validated after-tool Audit/Error event");
            match outcome {
                StrongDecision::Accepted => owner.acknowledge_accept(ack),
                StrongDecision::Rejected => {
                    owner.revoke_callback_writes_and_abort_pending_ack();
                    stopped = Some(Error::AfterToolExecuteRejected);
                    break;
                }
                StrongDecision::Cancelled => {
                    owner.revoke_callback_writes_and_abort_pending_ack();
                    stopped = Some(Error::Cancelled);
                    break;
                }
            }
        }
        let exit = owner.join().await;
        if let Some(error) = stopped {
            // Rejection can only be observed while the callback is blocked in the
            // matching emitter call. Its private unwind payload is control flow,
            // not a hook panic; the owner has nevertheless been joined here.
            return Err(error);
        }

        match exit {
            AfterToolCallbackExit::Completed(output) => output.map_err(Error::Transcript),
            AfterToolCallbackExit::Panicked(payload) => {
                propagate_after_tool_panic(callback_hook, payload);
            }
        }
    }

    async fn process(
        &mut self,
        generation: &Generation,
        generation_coord: &Coord,
        cancellation: &Token,
    ) -> Result<(), Error> {
        // Tool calls are produced by GenerationDriver::run from
        // model::Event::ToolCallFinal (runtime/driver.rs). Preserve that segment order
        // and do not enter the prepare/route/commit pipeline until every strong
        // delivery was accepted.
        let calls = generation.tool_calls();
        for call in &calls {
            let coord = tool_call_coord(generation_coord, call, call.name().as_str())
                .map_err(Error::Coordinate)?;
            // `OnToolCallStart` precedes the strong seam, so a call the consumer
            // rejects has still started and will still be ended by the boundary
            // closure. See `OpenToolCall::announced`.
            self.announce_tool_call(&coord, generation.snapshot(), call);
            self.drain_hook_facts(&coord).await?;
            let outcome = self
                .outward
                .producer
                .emit_tool_call(call.clone(), coord)
                .await
                .map_err(Error::Event)?;
            match outcome {
                StrongDecision::Accepted => {}
                StrongDecision::Rejected => return Err(Error::ToolCallRejected),
                StrongDecision::Cancelled => return Err(Error::Cancelled),
            }
        }

        // `StepSnapshot::freeze` makes one shallow shared twin from the sole
        // `tool::Registry::resolve_step` value at Step entry.
        // Model exposure and batch routing therefore retain identical transcript and
        // executor/mapper handles without a second provider resolution.
        let execution_snapshot = Arc::clone(generation.snapshot().shared_tools());
        let plan = prepare_tool_calls(
            calls,
            self.hooks,
            self.callback_resources,
            Arc::clone(generation.snapshot()),
            cancellation,
        )
        .map_err(Error::Prepare)?;
        self.record_effective_calls(&plan);

        let mut emitter_gates = Vec::new();
        let routed = {
            let mut route_binder = |effective_call: &ToolCall| {
                let coord = prepared_tool_call_coord(generation_coord, effective_call);
                let (emitter, emitter_gate) = tool_emitter(self.outward.producer, coord);
                emitter_gates.push(emitter_gate);
                ToolRouteBinding::new(emitter)
            };
            route_and_execute(
                plan,
                execution_snapshot,
                self.session_id.clone(),
                &mut route_binder as &mut ToolRouteBinder<'_>,
                cancellation,
            )
            .await
        };
        #[cfg(test)]
        emitter_gates.append(&mut self.test_emitter_gates);
        close_tool_emitters(emitter_gates).await;
        let routed = routed.map_err(Error::Route)?;
        self.record_routed_results(&routed);

        // Every invocation emit window is closed and drained before the atomic
        // commit. Route failures retain priority because cleanup cannot replace
        // the already-produced error with a later cancellation observation.
        // Rebinding also gives reservation/publish callbacks this generation's
        // coordinate, matching ToolCall, audit, before-result, and ToolResult.
        let generation_controller = self.controller.with_coord(generation_coord);
        let committed = commit_tool_batch(
            routed,
            generation.assistant().clone(),
            generation_coord,
            self.hooks,
            self.callback_resources,
            Arc::clone(generation.snapshot()),
            &generation_controller,
            cancellation,
        )
        .map_err(Error::Commit)?;
        self.record_commit(&committed, ResultStage::Committed);

        // `FinalizedToolCall` is produced by `commit_tool_batch` and retains the
        // exact committed
        // item. Publish that source-ordered truth rather than rebuilding it.
        for finalized in committed.finalized() {
            let coord = tool_call_coord(
                generation_coord,
                finalized.original_call(),
                finalized.effective_call().name().as_str(),
            )
            .map_err(Error::Coordinate)?;
            self.drain_hook_facts(&coord).await?;
            let outcome = self
                .outward
                .producer
                .emit_tool_result(finalized.item().clone(), coord)
                .await
                .map_err(Error::Event)?;
            match outcome {
                StrongDecision::Accepted => {}
                StrongDecision::Rejected => return Err(Error::ToolResultRejected),
                StrongDecision::Cancelled => return Err(Error::Cancelled),
            }
        }

        // The committed records are the source-order truth;
        // only routed slots (Executed/Rejected) reached that boundary.
        // Every ToolResult has already been accepted before any callback starts.
        for finalized in committed
            .finalized()
            .iter()
            .filter(|finalized| routed_disposition(finalized.disposition()))
        {
            let coord = tool_call_coord(
                generation_coord,
                finalized.original_call(),
                finalized.effective_call().name().as_str(),
            )
            .map_err(Error::Coordinate)?;
            for adapter in self.hooks.owned_tool_hooks() {
                let registration_resources = self
                    .callback_resources
                    .get(adapter.index())
                    .copied()
                    .expect("after-tool resources cover every registry index")
                    .owned_handles();

                // Each callback stages from current live truth, including every
                // successful earlier registration/slot transaction. The owned
                // hook, resources, snapshot, and result move into one managed
                // blocking owner; the async side always joins that owner.
                let staged_store = generation_controller
                    .staging_store()
                    .map_err(Error::Transcript)?;
                let callback = self
                    .invoke_after_tool_callback(
                        adapter,
                        registration_resources,
                        coord.clone(),
                        staged_store,
                        Arc::clone(generation.snapshot()),
                        finalized.item().result().clone(),
                    )
                    .await?;

                // The main batch is already durable. A late Run cancellation must
                // not erase successfully accepted callback facts, so these two
                // independent transactions use fresh pre-commit tokens. The
                // staged replacement commits first; returned items then append as
                // one all-or-nothing registration-visible batch.
                if let Some((base_version, snapshot)) = callback.staged {
                    generation_controller
                        .replace_snapshot(snapshot, base_version, &Token::new())
                        .map_err(Error::AfterToolExecuteTranscript)?;
                }
                generation_controller
                    .append_batch(callback.returned, &Token::new())
                    .map_err(Error::AfterToolExecuteTranscript)?;
            }
        }

        // The post-execution hook phase is one phase for the whole batch, so
        // every call reaches its terminal milestone when the phase closes — a
        // settled slot the phase does not apply to at the same moment as a routed
        // one. Publishing here rather than per slot is what keeps the terminal
        // facts in source order.
        self.record_commit(&committed, ResultStage::Closed);
        let closed = std::mem::take(&mut self.open().calls);
        self.close_tool_calls(closed, &LifecycleEnd::Completed);
        Ok(())
    }

    /// Records `OnToolCallStart` and opens this call's terminal bookkeeping.
    fn announce_tool_call(&self, coord: &Coord, snapshot: &Arc<StepSnapshot>, call: &ToolCall) {
        self.observe_lifecycle(
            coord,
            Some(snapshot),
            &LifecycleObservation::ToolCallStart {
                coord: coord.clone(),
                call: call.clone(),
            },
        );
        self.open().calls.push(OpenToolCall::announced(
            coord.clone(),
            Arc::clone(snapshot),
            call.clone(),
        ));
    }

    /// Retains the final effective call of every announced source position.
    ///
    /// Taken from the prepare plan rather than from the routed batch so that a
    /// execution failure still reports the call that was going to run,
    /// which is the one a rewrite already replaced.
    fn record_effective_calls(&self, plan: &ToolBatchPreparePlan) {
        let mut open = self.open();
        for (call, prepared) in open.calls.iter_mut().zip(plan.entries()) {
            call.effective = prepared.effective().clone();
        }
    }

    /// Advances every announced call to the closed result routing produced.
    ///
    /// The result is cloned because the routed batch is consumed whole by the
    /// atomic commit. That clone is what lets an interrupted commit report the
    /// disposition the call actually reached instead of claiming it never ran.
    fn record_routed_results(&self, routed: &RoutedToolBatch) {
        let mut open = self.open();
        for (call, record) in open.calls.iter_mut().zip(routed.records()) {
            let outcome = record.outcome();
            call.progress = CallProgress::settle(
                outcome.disposition(),
                outcome.result().clone(),
                ResultStage::Routed,
            );
        }
    }

    /// Advances every announced call to its durable result at `stage`.
    ///
    /// Called twice: once with [`ResultStage::Committed`] as soon as the atomic
    /// append returns, so an interruption between there and the end of the phase
    /// reports a durable result rather than a discarded one, and once with
    /// [`ResultStage::Closed`] when the phase itself closes.
    fn record_commit(&self, committed: &ToolBatchCommit, stage: ResultStage) {
        let mut open = self.open();
        for (call, finalized) in open.calls.iter_mut().zip(committed.finalized()) {
            call.progress = CallProgress::settle(
                finalized.disposition(),
                finalized.item().result().clone(),
                stage,
            );
        }
    }
}

async fn close_tool_emitters(gates: Vec<ToolEmitterGate>) {
    for gate in gates {
        gate.close_and_wait().await;
    }
}

const fn routed_disposition(disposition: CallDisposition) -> bool {
    !matches!(
        disposition,
        CallDisposition::Blocked
            | CallDisposition::ShortCircuited
            | CallDisposition::Truncated
            | CallDisposition::NotExecuted
    )
}

pub(super) fn tool_call_coord(
    generation: &Coord,
    call: &ToolCall,
    effective_name: &str,
) -> Result<Coord, CoordError> {
    let turn = NonZeroU64::new(generation.turn()).expect("tool calls belong to a turn");
    let step = NonZeroU64::new(generation.step_in_turn()).expect("tool calls belong to a step");
    let step_in_run =
        NonZeroU64::new(generation.step_in_run()).expect("tool calls carry a run-wide step");
    let generation_index =
        NonZeroU64::new(generation.generation()).expect("tool calls belong to a generation");
    let step = StepIndex::new(turn, step, step_in_run)
        .expect("the runtime generation coordinate has a valid hierarchy");
    Coord::at_tool_call(
        generation.session_id().to_owned(),
        generation.run_id().to_owned(),
        step,
        generation_index,
        call.id().as_str().to_owned(),
        effective_name.to_owned(),
    )
}

fn prepared_tool_call_coord(generation: &Coord, effective_call: &ToolCall) -> Coord {
    // `prepare_tool_calls` retains the externally validated model ID, while the
    // registration adapter rejects every empty rewritten name. The parent is an
    // already-typed generation coordinate, so every constructor precondition is
    // a core invariant at this boundary.
    tool_call_coord(generation, effective_call, effective_call.name().as_str())
        .expect("prepared tool calls have valid coordinates")
}

/// What the `OnBeforeModel` fan-out decided about one generation.
enum ModelDecision {
    /// Call the provider with this request.
    Generate(Request),
    /// Skip the provider; this output is the generation.
    ShortCircuit(Assistant),
}

struct Step<'a, 'phase, M> {
    context: &'a Context<'a, M>,
    phase: Option<&'a ToolPhase<'phase>>,
    coords: Option<&'a GenerationCoords>,
}

impl<M: Client> Step<'_, '_, M> {
    async fn advance(self, mut plan: RequestPlan) -> Result<Generation, Error> {
        let model = self.context.model.info();

        // `OnBeforeStep` runs before the Step freezes anything, which is what
        // makes it *before* the step: the items it appends are part of the
        // history this Step sends, and the plan it edits is the plan this Step
        // freezes. The tool lane is the exception and is authoritative from
        // resolution below, because collision-freedom is not a hook's to
        // decide.
        if let Some(phase) = self.phase {
            let cancellation = self.context.cancellation;
            let coord = &self
                .coords
                .expect("an attached tool phase mints step coordinates")
                .step;
            phase.staged_boundary(coord, cancellation, phase.has_turn_step_hooks(), |staged| {
                phase.before_step(staged, &model, &mut plan, cancellation)
            })?;
        }

        // Snapshot producers are `Lease::transcript_snapshot`,
        // `tool::Registry::resolve_step`, and `StepSnapshot::freeze`.
        // All three complete before Client::generate is first polled.
        //
        // Provider resolution is the one await between the transcript freeze and
        // the request, and it is placed here rather than earlier because it must
        // see this Step's transcript. Race it with the Run's parent token through
        // the same `await_or_cancel` used for model work: cancellation drops the
        // whole resolution future with nothing to undo. The transcript snapshot
        // is a value, no request exists yet, and no executor has been reached.
        let transcript = freeze_transcript(self.context.transcript_snapshot())?;
        let resolution = await_or_cancel(
            self.context.cancellation,
            self.context
                .tools
                .resolve_step(transcript, self.context.cancellation),
        )
        .await?;
        let (tools, provider_errors) = resolution.map_err(Error::Tools)?.into_parts();
        // Each degraded provider is reported once, in registration order, between
        // the Step's opening event (published by the owner before this future
        // runs) and the model request below. These are ordinary Errors with no
        // decision point, so no consumer ack is created or changed.
        if let Some(phase) = self.phase {
            let coord = &self
                .coords
                .expect("an attached tool phase mints step coordinates")
                .step;
            phase
                .publish_provider_degradations(coord, provider_errors)
                .await?;
        }
        tools.apply_to_plan(&mut plan);

        let snapshot = StepSnapshot::freeze(model, plan.clone(), tools);
        let request = plan
            .try_into_request(snapshot.tools().transcript().items().to_vec())
            .map_err(Error::Request)?;

        if let Some(phase) = self.phase {
            let coords = self
                .coords
                .expect("an attached tool phase mints step coordinates");
            phase.observe_lifecycle(
                &coords.step,
                Some(&snapshot),
                &LifecycleObservation::StepStart {
                    coord: coords.step.clone(),
                    snapshot: Arc::clone(&snapshot),
                },
            );
            phase.opened_step(&coords.step, &snapshot);
        }

        GenerationDriver {
            model: self.context.model,
            snapshot,
            cancellation: self.context.cancellation,
            phase: self.phase,
            coords: self.coords,
        }
        .run(request)
        .await
    }
}

struct GenerationDriver<'a, 'phase, M> {
    model: &'a M,
    snapshot: Arc<StepSnapshot>,
    cancellation: &'a Token,
    phase: Option<&'a ToolPhase<'phase>>,
    coords: Option<&'a GenerationCoords>,
}

impl<M: Client> GenerationDriver<'_, '_, M> {
    /// Publishes one incremental content event.
    ///
    /// The consolidated `Text`/`Thinking` events published once the generation
    /// is complete are the record of what the model said; these deltas are the
    /// same content as it arrives, so a consumer can render an answer while it
    /// is still being produced. Both carry the same generation coordinate.
    ///
    /// The provider's item identity travels with the delta. A generation can
    /// interleave several items, so without it a consumer rendering
    /// incrementally has no way to tell which heading a fragment belongs under,
    /// and reef would be deleting an identity it was handed.
    async fn emit_content_delta(
        &self,
        id: String,
        kind: ContentKind,
        delta: String,
    ) -> Result<(), Error> {
        let Some((phase, coords)) = self.phase.zip(self.coords) else {
            return Ok(());
        };
        let kind = match kind {
            ContentKind::Text => Kind::TextDelta,
            ContentKind::Thinking => Kind::ThinkingDelta,
        };
        phase.drain_hook_facts(&coords.generation).await?;
        phase
            .outward
            .producer
            .emit_text(kind, delta, coords.generation.clone(), Some(id))
            .await
            .map_err(Error::Event)?;
        Ok(())
    }

    fn observe_model_event(&self, event: &model::Event) {
        if let Some((phase, coords)) = self.phase.zip(self.coords) {
            phase.observe_model_event(&coords.generation, &self.snapshot, event);
        }
    }

    async fn run(self, request: Request) -> Result<Generation, Error> {
        let request = match self.phase.zip(self.coords) {
            Some((phase, coords)) => {
                match phase.before_model(
                    &coords.generation,
                    &self.snapshot,
                    request,
                    self.cancellation,
                )? {
                    ModelDecision::Generate(request) => request,
                    ModelDecision::ShortCircuit(output) => {
                        return self.short_circuit(output, coords, phase);
                    }
                }
            }
            None => request,
        };
        if let Some((phase, coords)) = self.phase.zip(self.coords) {
            phase.observe_lifecycle(
                &coords.generation,
                Some(&self.snapshot),
                &LifecycleObservation::GenerationStart {
                    coord: coords.generation.clone(),
                    request: request.clone(),
                },
            );
            phase.opened_generation(&coords.generation, &self.snapshot);
        }
        self.generate(request).await
    }

    /// Closes a generation the model never ran.
    ///
    /// `OnAfterModel` still runs, with `generated` false, because a registration
    /// that rewrites assistant output must see every output — including one an
    /// earlier registration substituted for the provider's.
    fn short_circuit(
        &self,
        output: Assistant,
        coords: &GenerationCoords,
        phase: &ToolPhase<'_>,
    ) -> Result<Generation, Error> {
        let assistant = phase.after_model(
            &coords.generation,
            &self.snapshot,
            output,
            false,
            "",
            CompletionReason::Unknown,
            self.cancellation,
        )?;
        Ok(Generation {
            snapshot: Arc::clone(&self.snapshot),
            assistant,
            finish_reason: String::new(),
            completion: CompletionReason::Unknown,
        })
    }

    async fn generate(self, request: Request) -> Result<Generation, Error> {
        closing_cancel_gate(self.cancellation)?;
        let events = await_or_cancel(self.cancellation, self.model.generate(request)).await?;
        let events = events.map_err(|error| Error::Model(Arc::new(error)))?;
        closing_cancel_gate(self.cancellation)?;
        tokio::pin!(events);

        let mut grammar = StreamGrammar::new();
        let mut segments = Vec::new();
        let mut terminal = None;
        loop {
            let event = await_or_cancel(
                self.cancellation,
                poll_fn(|context| events.as_mut().poll_next(context)),
            )
            .await?;
            let Some(event) = event else {
                closing_cancel_gate(self.cancellation)?;
                break;
            };
            let event = event.map_err(|error| Error::Model(Arc::new(error)))?;
            // A provider or grammar error is evidence produced by this poll and
            // remains more specific than concurrent cancellation. Only a valid
            // item crosses the closing cancellation gate.
            grammar.accept(&event).map_err(Error::Stream)?;
            closing_cancel_gate(self.cancellation)?;
            // Every accepted event is observed, not only the ones the loop
            // consumes: token usage reaches the composition layer through here
            // and nowhere else.
            self.observe_model_event(&event);
            match event {
                model::Event::ContentFinal {
                    id,
                    kind,
                    content,
                    extensions,
                } => {
                    // The identity the provider declared on the stream is the
                    // identity the record keeps. Stamping it here rather than
                    // asking every adapter to repeat itself is what makes the
                    // delta lane and the consolidated lane agree: `StreamGrammar`
                    // has already tied this `id` to the deltas that accumulated
                    // into `content`, so there is one identity and one place it
                    // comes from.
                    let extensions = extensions.with_item_id(id);
                    segments.push(match kind {
                        ContentKind::Text => Segment::Text {
                            text: content,
                            extensions,
                        },
                        ContentKind::Thinking => Segment::Thinking {
                            text: content,
                            extensions,
                        },
                    });
                }
                model::Event::ToolCallFinal { call, extensions } => {
                    segments.push(Segment::ToolCall { call, extensions });
                }
                model::Event::Done {
                    finish_reason,
                    completion,
                    provider_data,
                } => terminal = Some((finish_reason, completion, provider_data)),
                model::Event::ContentDelta { id, kind, delta } => {
                    self.emit_content_delta(id, kind, delta).await?;
                }
                model::Event::ToolCallStart { .. }
                | model::Event::ToolCallArgumentsDelta { .. }
                | model::Event::Usage(_) => {}
            }
        }
        grammar.finish().map_err(Error::Stream)?;
        let (finish_reason, completion, provider_data) =
            terminal.expect("StreamGrammar accepted a terminal event");
        // The model spoke, so the record it produced is model-visible. A
        // registration that wants it kept out of later requests says so through
        // `AfterModelDecision::Modify` below; reef does not decide that for it.
        let assistant = Assistant::new(segments, Some(provider_data));
        let assistant = match self.phase.zip(self.coords) {
            Some((phase, coords)) => phase.after_model(
                &coords.generation,
                &self.snapshot,
                assistant,
                true,
                &finish_reason,
                completion,
                self.cancellation,
            )?,
            None => assistant,
        };
        Ok(Generation {
            snapshot: self.snapshot,
            assistant,
            finish_reason,
            completion,
        })
    }
}

pub(super) fn freeze_transcript(
    snapshot: Result<crate::transcript::store::Snapshot, store::Error>,
) -> Result<crate::transcript::store::Snapshot, Error> {
    snapshot.map_err(Error::Transcript)
}

async fn await_or_cancel<T>(
    cancellation: &Token,
    future: impl Future<Output = T>,
) -> Result<T, Error> {
    tokio::select! {
        biased;
        output = future => Ok(output),
        () = cancellation.cancelled() => Err(Error::Cancelled),
    }
}

fn closing_cancel_gate(cancellation: &Token) -> Result<(), Error> {
    if cancellation.is_cancelled() {
        Err(Error::Cancelled)
    } else {
        Ok(())
    }
}