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
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
//! Capability-scoped hooks and immutable registration.
//!
//! The inventory is fixed data rather than prose: `HOOK_INVENTORY` names every
//! callback with its family, scope and decision. The gate pins that inventory and
//! the lifecycle-name mapping; production dispatch remains typed code, tracked by
//! the dispatcher references beside the inventory rather than inferred by the gate.
//! ADR-003 fixes the inventory. Waiters, producer authority, session leases, and
//! tool-execution internals are intentionally absent from every hook scope.
//!
//! # Synchronous cooperative callbacks
//!
//! Every hook method is synchronous. Within one boundary, registrations run in
//! deterministic order, and that boundary does not advance until each applicable
//! callback returns. Cancellation is checked around callbacks but cannot preempt one
//! that is currently executing, so
//! a callback must not block forever or wait for work that needs the same runtime
//! thread to advance. [`ToolHooks::after_tool_commit`] runs on the blocking pool, but
//! the Run still joins it before completing; moving it off a runtime worker does not
//! turn it into a detached callback.
//!
//! Work whose answer controls the current boundary must remain synchronous here or
//! use the asynchronous rail that owns that work, such as a
//! [`tool::Executor`](crate::runtime::tool::Executor),
//! [`tool::Provider`](crate::runtime::tool::Provider), or
//! [`model::Client`] wrapper. Passive observation may
//! instead be made asynchronous in the composition layer: an [`ObserverHooks`]
//! implementation copies the facts it needs into an owned message, submits that
//! message to a non-blocking queue, and returns. Queue capacity, overflow, ordering,
//! error reporting, shutdown draining, and process isolation are policies of that
//! adapter, not `agent::Config`. A borrowed hook scope must never escape the callback.

use std::cell::RefCell;
use std::error::Error;
use std::fmt;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;

use crate::cancel::Token;

use crate::audit;
use crate::redact::Presence;
use crate::runtime::event::StopCode;
use crate::runtime::model::{self, CompletionReason, Info, Request, RequestPlan};
use crate::runtime::session::InputTarget;
use crate::runtime::tool::{CallDisposition, StepToolSnapshot};
use crate::state::run_state::{self};
use crate::state::session_state::{self, CallbackWritePermit};
use crate::transcript::item::{Assistant, Item};
use crate::transcript::store::{
    self, Appender, Replacer, Snapshot, SnapshotReader, Store, Version,
};
use crate::value::content::Part;
use crate::value::lifecycle::{Coord, Outcome};
use crate::value::tool_call::{ToolCall, ToolResult};

/// A callback family implemented by one narrow trait.
#[cfg(test)]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub(crate) enum HookFamily {
    /// Run preparation, continuation, and natural finalization.
    Run,
    /// Injected-input admission.
    Input,
    /// Turn and Step boundaries.
    TurnStep,
    /// Model request/output boundaries.
    Model,
    /// Tool-call and tool-result boundaries.
    Tool,
    /// Passive observations.
    Observer,
    /// Transcript pre-commit reservation.
    Transcript,
    /// Agent teardown, separate from runtime hooks.
    AgentTeardown,
}

/// The fourteen capability-scoped context shapes in the immutable baseline.
#[cfg(test)]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub(crate) enum ScopeKind {
    /// Run preparation.
    Prepare,
    /// Natural Run finalization.
    Finalize,
    /// Prospective-Turn stop decision.
    Continue,
    /// Injected-input admission.
    InputAdmit,
    /// Turn boundary.
    Turn,
    /// Writable Step preparation.
    BeforeStep,
    /// Read-only completed Step.
    AfterStep,
    /// Before model invocation.
    BeforeModel,
    /// After model output assembly.
    AfterModel,
    /// Before tool admission.
    ToolCall,
    /// Before tool-result commit.
    ToolResult,
    /// After durable tool execution.
    AfterToolCommit,
    /// Passive observation with audit-only emission.
    Observer,
    /// Fully read-only, non-emitting callback.
    Read,
}

/// The closed decision families, one per callback whose return steers the runtime.
///
/// Two of the nine are additions this implementation makes over the shape it
/// inherited: [`DecisionKind::Prepare`] and [`DecisionKind::Finalize`] exist for
/// one reason stated twice. Composing initial input and composing continuation
/// input through a bare part list cannot tell "I have no opinion" apart from
/// "replace what everyone before me composed with nothing".
#[cfg(test)]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub(crate) enum DecisionKind {
    /// Model request control.
    BeforeModel,
    /// Model output rewrite.
    AfterModel,
    /// Tool-call control.
    ToolCall,
    /// Tool-result rewrite.
    ToolResult,
    /// Injected-input admission.
    InputAdmit,
    /// Run continuation or the sole hook stop request.
    Continue,
    /// Step completion and optional Turn close.
    AfterStep,
    /// Initial input composition.
    Prepare,
    /// Natural-completion continuation composition.
    Finalize,
}

/// One mechanically reviewable callback-to-capability mapping.
#[cfg(test)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub(crate) struct HookSpec {
    /// Stable callback spelling; crate-private dispatch key, not a public
    /// contract. The `On*` strings are internal inventory IDs.
    pub(crate) name: &'static str,
    /// Narrow trait family which owns the callback.
    pub(crate) family: HookFamily,
    /// Scope, or `None` when the callback has no runtime scope.
    pub(crate) scope: Option<ScopeKind>,
    /// Closed decision, or `None` when the return is observation/items/reservation.
    pub(crate) decision: Option<DecisionKind>,
}

#[cfg(test)]
pub(crate) const fn hook(
    name: &'static str,
    family: HookFamily,
    scope: Option<ScopeKind>,
    decision: Option<DecisionKind>,
) -> HookSpec {
    HookSpec {
        name,
        family,
        scope,
        decision,
    }
}

/// The complete callback inventory: every runtime callback plus Agent teardown.
///
/// The `On*` strings are crate-private dispatch keys (internal IDs), not a
/// public contract. Consumers implement the family traits; they never name
/// these spellings.
///
/// This is a slice rather than a fixed-size array on purpose. The number of
/// callbacks is data, not type: baking it into the signature would make every
/// added or removed hook a breaking change for callers that never counted them.
///
/// Dispatcher trace for review:
///
/// - `OnPrepareRun` / `OnFinalizeRun` / `OnContinueRun`:
///   `invoke_prepare` / `invoke_compose_continuation` / `invoke_decide_stop`;
/// - input, Turn, Step, and model entries: their corresponding
///   `RegistrationAdapter::invoke_*` methods;
/// - `OnBeforeToolCall` / `OnBeforeToolResult` / `OnAfterToolExecute`:
///   `invoke_before_tool_call` / `invoke_before_tool_result` / `invoke_after_tool_commit`;
/// - lifecycle entries: `lifecycle_hook_name` plus `invoke_lifecycle`;
/// - other observers: `invoke_run_admitted`, `invoke_model_event`, `invoke_audit_event`;
/// - transcript and Agent-owned teardown: `invoke_reserve` and [`RuntimeRegistry::close`].
///
/// The inventory gate intentionally verifies this data and the lifecycle mapping,
/// not reachability of those production call sites. Removing or adding a callback
/// therefore requires updating this trace and reviewing its caller as well.
#[cfg(test)]
pub(crate) const HOOK_INVENTORY: &[HookSpec] = &[
    hook(
        "OnPrepareRun",
        HookFamily::Run,
        Some(ScopeKind::Prepare),
        Some(DecisionKind::Prepare),
    ),
    hook(
        "OnFinalizeRun",
        HookFamily::Run,
        Some(ScopeKind::Finalize),
        Some(DecisionKind::Finalize),
    ),
    hook(
        "OnRunAdmitted",
        HookFamily::Observer,
        Some(ScopeKind::Read),
        None,
    ),
    hook(
        "OnBeforeToolCall",
        HookFamily::Tool,
        Some(ScopeKind::ToolCall),
        Some(DecisionKind::ToolCall),
    ),
    hook(
        "OnBeforeToolResult",
        HookFamily::Tool,
        Some(ScopeKind::ToolResult),
        Some(DecisionKind::ToolResult),
    ),
    hook(
        "OnAfterToolExecute",
        HookFamily::Tool,
        Some(ScopeKind::AfterToolCommit),
        None,
    ),
    hook(
        "OnBeforeModel",
        HookFamily::Model,
        Some(ScopeKind::BeforeModel),
        Some(DecisionKind::BeforeModel),
    ),
    hook(
        "OnAfterModel",
        HookFamily::Model,
        Some(ScopeKind::AfterModel),
        Some(DecisionKind::AfterModel),
    ),
    hook(
        "OnBeforeInputAdmit",
        HookFamily::Input,
        Some(ScopeKind::InputAdmit),
        Some(DecisionKind::InputAdmit),
    ),
    hook(
        "OnBeforeTurn",
        HookFamily::TurnStep,
        Some(ScopeKind::Turn),
        None,
    ),
    hook(
        "OnAfterTurn",
        HookFamily::TurnStep,
        Some(ScopeKind::Turn),
        None,
    ),
    hook(
        "OnBeforeStep",
        HookFamily::TurnStep,
        Some(ScopeKind::BeforeStep),
        None,
    ),
    hook(
        "OnAfterStep",
        HookFamily::TurnStep,
        Some(ScopeKind::AfterStep),
        Some(DecisionKind::AfterStep),
    ),
    hook("OnClose", HookFamily::AgentTeardown, None, None),
    hook(
        "OnContinueRun",
        HookFamily::Run,
        Some(ScopeKind::Continue),
        Some(DecisionKind::Continue),
    ),
    hook(
        "OnRunStart",
        HookFamily::Observer,
        Some(ScopeKind::Observer),
        None,
    ),
    hook(
        "OnRunEnd",
        HookFamily::Observer,
        Some(ScopeKind::Observer),
        None,
    ),
    hook(
        "OnTurnStart",
        HookFamily::Observer,
        Some(ScopeKind::Observer),
        None,
    ),
    hook(
        "OnTurnEnd",
        HookFamily::Observer,
        Some(ScopeKind::Observer),
        None,
    ),
    hook(
        "OnStepStart",
        HookFamily::Observer,
        Some(ScopeKind::Observer),
        None,
    ),
    hook(
        "OnStepEnd",
        HookFamily::Observer,
        Some(ScopeKind::Observer),
        None,
    ),
    hook(
        "OnGenerationStart",
        HookFamily::Observer,
        Some(ScopeKind::Observer),
        None,
    ),
    hook(
        "OnGenerationEnd",
        HookFamily::Observer,
        Some(ScopeKind::Observer),
        None,
    ),
    hook(
        "OnToolCallStart",
        HookFamily::Observer,
        Some(ScopeKind::Observer),
        None,
    ),
    hook(
        "OnToolCallEnd",
        HookFamily::Observer,
        Some(ScopeKind::Observer),
        None,
    ),
    hook(
        "OnModelEvent",
        HookFamily::Observer,
        Some(ScopeKind::Observer),
        None,
    ),
    hook(
        "OnAuditEvent",
        HookFamily::Observer,
        Some(ScopeKind::Read),
        None,
    ),
    hook(
        "OnTranscriptMutation",
        HookFamily::Transcript,
        Some(ScopeKind::Read),
        None,
    ),
];

/// Boxed hook callback error which preserves the concrete source for downcast.
///
/// # Effect on the Run
///
/// Returning one of these is a decision that the Run should not continue, not a
/// hint that something went wrong. Reef never retries a callback, substitutes a
/// default decision, or carries on with the remaining registrations: the failing
/// boundary short-circuits, and whatever it had composed, staged, or planned is
/// discarded rather than half-applied. Peers registered after the failure are not
/// called, and peers that already ran do not have their contributions kept.
///
/// The failure always reaches the caller with the failing registration's name
/// attached, as an [`AttributedError`]. Where it surfaces depends only on which
/// boundary was running:
///
/// - At Run admission, as
///   [`StartError::Prepare`](crate::runtime::agent::StartError::Prepare). The
///   Session lease and Agent attachment are rolled back, so admission having
///   failed means nothing was committed and no Run exists.
/// - At every other boundary, by ending the Run: its
///   [`Terminal`](crate::runtime::run::Terminal) reports
///   [`Outcome::Failed`] with the
///   [`FailureKind`](crate::runtime::run::FailureKind) of the boundary that was
///   running — [`Hook`](crate::runtime::run::FailureKind::Hook) for most,
///   [`Transcript`](crate::runtime::run::FailureKind::Transcript) or
///   [`ToolCommit`](crate::runtime::run::FailureKind::ToolCommit) for a failed
///   reservation, according to which mutation it was reserving. The retained
///   failure is reachable from the terminal, and the registration name survives
///   the whole chain.
///
/// A cancellation observed at the same boundary ends the Run as
/// [`Cancelled`](crate::value::lifecycle::Outcome::Cancelled) instead; a real
/// callback error is never downgraded to a cancellation.
///
/// This is why a degradation the Run can survive should not be reported this way.
/// A mutating scope's `emit_error` method publishes a non-fatal fact and leaves
/// the Run running, which is the right shape for a hook whose optional work
/// failed. `HookError` is for the case where continuing would be wrong.
#[derive(Clone)]
#[expect(
    clippy::module_name_repetitions,
    reason = "HookError distinguishes callback failures from the hook module's other errors"
)]
pub struct HookError(Arc<dyn Error + Send + Sync>);

impl HookError {
    /// Retains a concrete callback error without string flattening.
    #[must_use]
    pub fn new(error: impl Error + Send + Sync + 'static) -> Self {
        Self(Arc::new(error))
    }

    /// Returns the retained concrete source.
    #[must_use]
    pub fn source_ref(&self) -> &(dyn Error + Send + Sync + 'static) {
        self.0.as_ref()
    }
}

impl fmt::Debug for HookError {
    /// Renders every link of the retained chain, each one through `Display`.
    ///
    /// Printing only the outermost link would discard the chain that
    /// [`source_ref`] retains: a callback error that wraps its own cause reads
    /// as a single sentence, and the reason underneath it — the one a reader is
    /// usually after — never appears. Walking `source` states the whole chain.
    ///
    /// `Display` rather than the link's own `Debug`, because the cause is
    /// whatever a hook handed back: arbitrary text this crate neither writes
    /// nor reviews. `Display` is the rendering those types are contracted to
    /// produce, and it is what every other boxed failure in reef prints.
    ///
    /// [`source_ref`]: Self::source_ref
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut tuple = formatter.debug_tuple("HookError");
        let mut link: Option<&(dyn Error + 'static)> = Some(self.0.as_ref());
        while let Some(error) = link {
            tuple.field(&error.to_string());
            link = error.source();
        }
        tuple.finish()
    }
}

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

impl Error for HookError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(self.0.as_ref())
    }
}

/// Result returned by a mutating or reserving callback.
#[expect(
    clippy::module_name_repetitions,
    reason = "HookResult names the shared callback result contract rather than a generic module result"
)]
pub type HookResult<T> = Result<T, HookError>;

/// Stable Session identity without transcript, inbox, state-write, or lease authority.
#[derive(Clone, Copy, Debug)]
pub struct SessionIdentity<'a>(&'a Coord);

impl SessionIdentity<'_> {
    /// Returns the Session identifier carried by the callback coordinate.
    #[must_use]
    pub fn id(&self) -> &str {
        self.0.session_id()
    }
}

/// A callback-local transcript capability.
///
/// The controller creates this from an isolated [`Store`]. It exposes only
/// append and replacement authority; phase-aligned reads come from the enclosing
/// scope's `transcript` method. Nothing staged here is visible until the
/// controller commits.
#[derive(Debug)]
pub struct StagedTranscript {
    reader: SnapshotReader,
    appender: Appender,
    replacer: Replacer,
}

impl StagedTranscript {
    pub(crate) fn from_store(store: &Store) -> Self {
        Self {
            reader: store.snapshot_reader(),
            appender: store.appender(),
            replacer: store.replacer(),
        }
    }

    /// Appends an ordered owned batch to this callback's staging area.
    ///
    /// # Errors
    ///
    /// [`store::Error::VersionOverflow`] if the staged version would pass
    /// [`Version::MAX`], or [`store::Error::Poisoned`] if a writer panicked
    /// inside this staging area. There is no version conflict to report, because
    /// this append names no expected version: composing into a
    /// staging area is not a race against the live transcript, and what the
    /// boundary later commits is compare-and-set against the live version for the
    /// registrations as a whole.
    pub fn append_batch(&self, items: Vec<Item>) -> Result<Version, store::Error> {
        self.appender.append_batch(items)
    }

    /// Replaces this callback's complete staged history.
    ///
    /// # Errors
    ///
    /// [`store::Error::VersionOverflow`] or [`store::Error::Poisoned`], for the
    /// same reasons as [`append_batch`](Self::append_batch). Replacing the staged
    /// history does not replace the live one; what reaches the session is the
    /// resolved staged result, committed by the boundary that created this
    /// capability.
    pub fn replace(&self, items: Vec<Item>) -> Result<Version, store::Error> {
        self.replacer.replace(items)
    }
}

/// The internal outward capability behind mutating hook scopes.
pub(crate) trait Emitter: Send + Sync {
    /// Emits a validated, non-model-visible audit fact.
    fn emit_audit(&self, event: audit::Event);

    /// Emits a non-fatal error fact without granting event producer authority.
    fn emit_error(&self, error: Arc<dyn Error + Send + Sync>);
}

/// One fact a synchronous callback handed to the loop for publication.
#[derive(Debug)]
pub(crate) enum BufferedFact {
    Audit(audit::Event),
    Error(Arc<dyn Error + Send + Sync>),
}

/// The [`Emitter`] every synchronous callback on the loop's own thread writes to.
///
/// A callback is synchronous and the outward stream is not, so no callback can
/// publish anything itself: it records the fact here and the loop hands the queue
/// to the `Producer` at its next await point. The queue is FIFO and every drain is
/// total, so the only latitude the loop has is *when* it drains — and it drains
/// before its own next publication. That is what makes
/// [`ObserverScope::emit_audit`] mean "now" instead of "some time before this Run
/// ends": a fact queued while the model stream is still arriving reaches the
/// consumer ahead of the content event that follows it.
///
/// The one exception is a callback running on the managed blocking pool, which
/// cannot use a buffer at all: it has already returned control to no one, so it
/// emits through a request/ack rendezvous with the loop instead.
#[derive(Debug, Default)]
pub(crate) struct FactBuffer {
    facts: std::sync::Mutex<Vec<BufferedFact>>,
}

impl FactBuffer {
    /// Removes and returns every queued fact, preserving producer order.
    pub(crate) fn take_facts(&self) -> Vec<BufferedFact> {
        std::mem::take(&mut *self.facts.lock().expect("hook fact lock poisoned"))
    }

    #[cfg(test)]
    pub(crate) fn audit_kinds(&self) -> Vec<String> {
        self.facts
            .lock()
            .expect("hook fact lock poisoned")
            .iter()
            .filter_map(|fact| match fact {
                BufferedFact::Audit(event) => Some(event.kind().to_owned()),
                BufferedFact::Error(_) => None,
            })
            .collect()
    }

    #[cfg(test)]
    pub(crate) fn error_messages(&self) -> Vec<String> {
        self.facts
            .lock()
            .expect("hook fact lock poisoned")
            .iter()
            .filter_map(|fact| match fact {
                BufferedFact::Audit(_) => None,
                BufferedFact::Error(error) => Some(error.to_string()),
            })
            .collect()
    }
}

impl Emitter for FactBuffer {
    fn emit_audit(&self, event: audit::Event) {
        self.facts
            .lock()
            .expect("hook fact lock poisoned")
            .push(BufferedFact::Audit(event));
    }

    fn emit_error(&self, error: Arc<dyn Error + Send + Sync>) {
        self.facts
            .lock()
            .expect("hook fact lock poisoned")
            .push(BufferedFact::Error(error));
    }
}

#[derive(Clone, Copy, Debug)]
pub(crate) enum TranscriptSource<'a> {
    Reader(&'a SnapshotReader),
    Snapshot(&'a Snapshot),
}

impl TranscriptSource<'_> {
    pub(crate) fn snapshot(self) -> Result<Snapshot, store::Error> {
        match self {
            Self::Reader(reader) => reader.snapshot(),
            Self::Snapshot(snapshot) => Ok(snapshot.clone()),
        }
    }
}

#[derive(Clone, Copy, Debug)]
struct ReadBase<'a> {
    session: SessionIdentity<'a>,
    coord: &'a Coord,
    run_state: &'a run_state::Store,
    session_state: &'a session_state::Reader,
    transcript: TranscriptSource<'a>,
}

#[derive(Clone, Copy, Debug)]
struct WriteBase<'a> {
    read: ReadBase<'a>,
    session_state: Option<&'a session_state::Writer>,
}

#[derive(Clone, Copy, Debug)]
struct PrepareBase<'a> {
    read: ReadBase<'a>,
    session_state: Option<&'a session_state::StagedWriter>,
}

#[derive(Clone, Copy)]
struct ControlBase<'a> {
    write: WriteBase<'a>,
    emitter: &'a dyn Emitter,
}

impl fmt::Debug for ControlBase<'_> {
    /// Shows the read/write position and elides the emitter behind it.
    ///
    /// The crate-private emitter has no `Debug` supertrait, so its implementation
    /// identity is not useful to print. The trailing `..` records that something
    /// is there rather than implying nothing is.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ControlBase")
            .field("write", &self.write)
            .finish_non_exhaustive()
    }
}

#[derive(Clone, Copy, Debug)]
struct StagedBase<'a> {
    control: ControlBase<'a>,
    staged: &'a StagedTranscript,
}

macro_rules! read_capabilities {
    ($this:ident, $base:expr) => {
        /// Returns stable Session identity without broader Session authority.
        #[must_use]
        pub const fn session(&$this) -> SessionIdentity<'_> {
            $base.read.session
        }

        /// Returns the immutable callback coordinate.
        #[must_use]
        pub const fn coord(&$this) -> &Coord {
            $base.read.coord
        }

        /// Returns this hook's private per-Run scratch store.
        #[must_use]
        pub const fn run_state(&$this) -> &run_state::Store {
            $base.read.run_state
        }

        /// Returns owned-snapshot Session-state read authority.
        #[must_use]
        pub const fn session_state(&$this) -> &session_state::Reader {
            $base.read.session_state
        }

        /// Captures the complete transcript at this callback's phase position.
        ///
        /// # Errors
        ///
        /// Returns [`store::Error::Poisoned`] if the underlying transcript lock
        /// was poisoned.
        pub fn transcript(&$this) -> Result<Snapshot, store::Error> {
            $base.read.transcript.snapshot()
        }
    };
}

macro_rules! direct_read_capabilities {
    ($this:ident, $base:expr) => {
        /// Returns stable Session identity without broader Session authority.
        #[must_use]
        pub const fn session(&$this) -> SessionIdentity<'_> {
            $base.session
        }

        /// Returns the immutable callback coordinate.
        #[must_use]
        pub const fn coord(&$this) -> &Coord {
            $base.coord
        }

        /// Returns this hook's private per-Run scratch store.
        #[must_use]
        pub const fn run_state(&$this) -> &run_state::Store {
            $base.run_state
        }

        /// Returns owned-snapshot Session-state read authority.
        #[must_use]
        pub const fn session_state(&$this) -> &session_state::Reader {
            $base.session_state
        }

        /// Captures the complete transcript at this callback's phase position.
        ///
        /// # Errors
        ///
        /// Returns [`store::Error::Poisoned`] if the underlying transcript lock
        /// was poisoned.
        pub fn transcript(&$this) -> Result<Snapshot, store::Error> {
            $base.transcript.snapshot()
        }
    };
}

macro_rules! write_capabilities {
    ($this:ident, $base:expr) => {
        read_capabilities!($this, $base);

        /// Returns lease-bound write authority only for a hook which declared
        /// `requires_session_state(true)`.
        #[must_use]
        pub const fn session_state_writer(&$this) -> Option<&session_state::Writer> {
            $base.session_state
        }
    };
}

macro_rules! control_capabilities {
    ($this:ident, $base:expr) => {
        write_capabilities!($this, $base.write);

        /// Emits an audit fact through the capability-narrowed boundary.
        pub fn emit_audit(&$this, event: audit::Event) {
            $base.emitter.emit_audit(event);
        }

        /// Emits a non-fatal error through the capability-narrowed boundary.
        pub fn emit_error(&$this, error: Arc<dyn Error + Send + Sync>) {
            $base.emitter.emit_error(error);
        }
    };
}

macro_rules! staged_capabilities {
    ($this:ident, $base:expr) => {
        control_capabilities!($this, $base.control);

        /// Returns this callback's isolated transcript staging area.
        #[must_use]
        pub const fn staged(&$this) -> &StagedTranscript {
            $base.staged
        }
    };
}

/// [`RunHooks::prepare`] scope; no outward stream exists at this boundary.
///
/// Both writable capabilities are callback-local overlays. The controller owns
/// their resolution and this scope cannot mutate the live Session directly.
#[derive(Debug)]
pub struct PrepareScope<'a> {
    base: PrepareBase<'a>,
    staged: &'a StagedTranscript,
    base_snapshot: &'a Snapshot,
    input: &'a [Part],
}

impl PrepareScope<'_> {
    direct_read_capabilities!(self, self.base.read);

    /// Returns the callback-local Session-state overlay when this registration
    /// declared `requires_session_state(true)`.
    #[must_use]
    pub const fn staged_session_state_writer(&self) -> Option<&session_state::StagedWriter> {
        self.base.session_state
    }

    /// Returns this callback's isolated transcript staging area.
    #[must_use]
    pub const fn staged(&self) -> &StagedTranscript {
        self.staged
    }

    /// Returns the pre-prepare atomic transcript snapshot.
    #[must_use]
    pub const fn base_snapshot(&self) -> &Snapshot {
        self.base_snapshot
    }

    /// Returns the current composed input proposal.
    #[must_use]
    pub const fn input(&self) -> &[Part] {
        self.input
    }
}

/// [`RunHooks::compose_continuation`] scope on the natural completion path.
#[derive(Debug)]
pub struct ContinuationScope<'a> {
    base: StagedBase<'a>,
    continuation: &'a [Part],
    continuations: usize,
    turns: usize,
}

impl ContinuationScope<'_> {
    staged_capabilities!(self, self.base);

    /// Returns the preceding hook's continuation proposal.
    #[must_use]
    pub const fn continuation(&self) -> &[Part] {
        self.continuation
    }

    /// Returns the number of prior continuation Turns.
    #[must_use]
    pub const fn continuations(&self) -> usize {
        self.continuations
    }

    /// Returns the number of completed Turns.
    #[must_use]
    pub const fn turns(&self) -> usize {
        self.turns
    }
}

/// [`RunHooks::decide_stop`] scope before a prospective Turn exists.
#[derive(Debug)]
pub struct StopDecisionScope<'a> {
    base: ControlBase<'a>,
}

impl StopDecisionScope<'_> {
    control_capabilities!(self, self.base);
}

/// [`InputHooks::before_input_admit`] scope around one claimed owned batch.
#[derive(Debug)]
pub struct InputAdmitScope<'a> {
    base: ControlBase<'a>,
    target: InputTarget,
    items: &'a [Item],
}

impl InputAdmitScope<'_> {
    control_capabilities!(self, self.base);

    /// Returns the frozen mailbox target.
    #[must_use]
    pub const fn target(&self) -> InputTarget {
        self.target
    }

    /// Returns the claimed batch as a read-only slice.
    #[must_use]
    pub const fn items(&self) -> &[Item] {
        self.items
    }
}

/// Shared scope for true Turn boundary hooks.
#[derive(Debug)]
pub struct TurnScope<'a> {
    base: StagedBase<'a>,
    trigger: &'a [Item],
}

impl TurnScope<'_> {
    staged_capabilities!(self, self.base);

    /// Returns the input batch which opened this Turn.
    #[must_use]
    pub const fn trigger(&self) -> &[Item] {
        self.trigger
    }
}

/// One owned, immutable Step fact frozen after the sole writable plan window.
///
/// The runtime creates this once per Step and reuses the same [`Arc`] at every
/// later hook and lifecycle boundary. The owned plan retains all five lanes:
/// system instruction, client tools, sampling parameters, hosted extensions,
/// and ephemeral content. The tool snapshot preserves the exact routing handles
/// from which the model-visible tool lanes were materialized.
#[derive(Debug)]
pub struct StepSnapshot {
    model: Info,
    plan: RequestPlan,
    tools: StepToolSnapshot,
    shared_tools: Arc<StepToolSnapshot>,
}

impl StepSnapshot {
    pub(crate) fn freeze(model: Info, plan: RequestPlan, tools: StepToolSnapshot) -> Arc<Self> {
        // `StepToolSnapshot::shallow_clone` preserves the same executor/mapper
        // handles and transcript Arc. The public value getter can remain const,
        // while batch routing receives one shared owner without resolving providers
        // a second time through `StepToolSnapshot::shallow_clone`.
        let shared_tools = Arc::new(tools.shallow_clone());
        Arc::new(Self {
            model,
            plan,
            tools,
            shared_tools,
        })
    }

    /// Returns the complete frozen model identity and capability facts.
    #[must_use]
    pub const fn model(&self) -> &Info {
        &self.model
    }

    /// Returns the complete frozen plan, including every model-input lane.
    #[must_use]
    pub const fn plan(&self) -> &RequestPlan {
        &self.plan
    }

    /// Returns the exact immutable exposure/router snapshot for this Step.
    #[must_use]
    pub const fn tools(&self) -> &StepToolSnapshot {
        &self.tools
    }

    /// Returns the shared shallow twin used by invocation routing.
    pub(crate) const fn shared_tools(&self) -> &Arc<StepToolSnapshot> {
        &self.shared_tools
    }
}

/// `OnBeforeStep` scope and the sole writable [`RequestPlan`] window.
#[derive(Debug)]
pub struct BeforeStepScope<'a> {
    base: StagedBase<'a>,
    model: &'a Info,
    plan: &'a mut RequestPlan,
}

impl BeforeStepScope<'_> {
    staged_capabilities!(self, self.base);

    /// Returns immutable model identity and capabilities.
    #[must_use]
    pub const fn model(&self) -> &Info {
        self.model
    }

    /// Returns the unique plan which runtime re-reads after this fan-out.
    pub const fn plan(&mut self) -> &mut RequestPlan {
        self.plan
    }
}

/// `OnAfterStep` scope with the shared immutable Step snapshot.
#[derive(Debug)]
pub struct AfterStepScope<'a> {
    base: StagedBase<'a>,
    snapshot: &'a Arc<StepSnapshot>,
}

impl AfterStepScope<'_> {
    staged_capabilities!(self, self.base);

    /// Returns the exact frozen Step snapshot reused by later boundaries.
    #[must_use]
    pub fn snapshot(&self) -> &StepSnapshot {
        self.snapshot
    }
}

/// [`ModelHooks::before_model`] scope over one immutable request and Step snapshot.
#[derive(Debug)]
pub struct BeforeModelScope<'a> {
    base: ControlBase<'a>,
    snapshot: &'a Arc<StepSnapshot>,
    request: &'a Request,
}

impl BeforeModelScope<'_> {
    control_capabilities!(self, self.base);

    /// Returns the exact frozen Step snapshot.
    #[must_use]
    pub fn snapshot(&self) -> &StepSnapshot {
        self.snapshot
    }

    /// Returns the current frozen request; rewrites use the returned decision.
    #[must_use]
    pub const fn request(&self) -> &Request {
        self.request
    }
}

/// [`ModelHooks::after_model`] scope over assembled but uncommitted assistant output.
#[derive(Debug)]
pub struct AfterModelScope<'a> {
    base: ControlBase<'a>,
    snapshot: &'a Arc<StepSnapshot>,
    output: &'a Assistant,
    generated: bool,
    finish_reason: &'a str,
    completion: CompletionReason,
}

impl AfterModelScope<'_> {
    control_capabilities!(self, self.base);

    /// Returns the exact frozen Step snapshot used for this generation.
    #[must_use]
    pub fn snapshot(&self) -> &StepSnapshot {
        self.snapshot
    }

    /// Returns the current read-only assistant output.
    #[must_use]
    pub const fn output(&self) -> &Assistant {
        self.output
    }

    /// Reports whether a real model generation produced this output.
    #[must_use]
    pub const fn generated(&self) -> bool {
        self.generated
    }

    /// Returns the provider's verbatim finish label.
    ///
    /// This is empty when no provider supplied a label, including when
    /// [`BeforeModelDecision::ShortCircuit`] bypassed provider invocation.
    #[must_use]
    pub const fn finish_reason(&self) -> &str {
        self.finish_reason
    }

    /// Returns the portable completion classification.
    #[must_use]
    pub const fn completion(&self) -> CompletionReason {
        self.completion
    }
}

/// `OnBeforeToolCall` scope over one effective call and frozen Step facts.
#[derive(Debug)]
pub struct ToolCallScope<'a> {
    base: ControlBase<'a>,
    snapshot: &'a Arc<StepSnapshot>,
    call: &'a ToolCall,
}

impl ToolCallScope<'_> {
    control_capabilities!(self, self.base);

    /// Returns the exact frozen Step snapshot used by this tool batch.
    #[must_use]
    pub fn snapshot(&self) -> &StepSnapshot {
        self.snapshot
    }

    /// Returns the current call; rewrites use the returned decision.
    #[must_use]
    pub const fn call(&self) -> &ToolCall {
        self.call
    }
}

/// `OnBeforeToolResult` scope over an uncommitted closed result.
#[derive(Debug)]
pub struct ToolResultScope<'a> {
    base: ControlBase<'a>,
    snapshot: &'a Arc<StepSnapshot>,
    call: &'a ToolCall,
    disposition: CallDisposition,
    result: &'a ToolResult,
}

impl ToolResultScope<'_> {
    control_capabilities!(self, self.base);

    /// Returns the exact frozen Step snapshot used by this tool batch.
    #[must_use]
    pub fn snapshot(&self) -> &StepSnapshot {
        self.snapshot
    }

    /// Returns the final effective call.
    #[must_use]
    pub const fn call(&self) -> &ToolCall {
        self.call
    }

    /// Returns the call's stable pre-result disposition.
    #[must_use]
    pub const fn disposition(&self) -> CallDisposition {
        self.disposition
    }

    /// Returns the current closed result; rewrites use the decision.
    #[must_use]
    pub const fn result(&self) -> &ToolResult {
        self.result
    }
}

/// [`ToolHooks::after_tool_commit`] scope after the complete result batch is durable.
#[derive(Debug)]
pub struct AfterToolCommitScope<'a> {
    base: StagedBase<'a>,
    snapshot: &'a Arc<StepSnapshot>,
    result: &'a ToolResult,
}

impl AfterToolCommitScope<'_> {
    staged_capabilities!(self, self.base);

    /// Returns the exact frozen Step snapshot used by this tool batch.
    #[must_use]
    pub fn snapshot(&self) -> &StepSnapshot {
        self.snapshot
    }

    /// Returns the already-durable closed result.
    #[must_use]
    pub const fn result(&self) -> &ToolResult {
        self.result
    }
}

/// Passive observer scope with audit-only emission.
pub struct ObserverScope<'a> {
    base: ReadBase<'a>,
    snapshot: Option<&'a Arc<StepSnapshot>>,
    audit_sink: &'a dyn ObserverAuditSink,
}

impl fmt::Debug for ObserverScope<'_> {
    /// Shows where the observation is anchored and elides the audit sink.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ObserverScope")
            .field("base", &self.base)
            .field("snapshot", &Presence(self.snapshot.is_some()))
            .finish_non_exhaustive()
    }
}

impl ObserverScope<'_> {
    direct_read_capabilities!(self, self.base);

    /// Returns the exact frozen Step snapshot when the boundary belongs to a Step.
    #[must_use]
    pub fn snapshot(&self) -> Option<&StepSnapshot> {
        self.snapshot.map(Arc::as_ref)
    }

    /// Emits only an audit fact; no generic Error or event authority is present.
    pub fn emit_audit(&self, event: audit::Event) {
        self.audit_sink.push(event);
    }

    fn with_audit_sink<'a>(&'a self, audit_sink: &'a dyn ObserverAuditSink) -> ObserverScope<'a> {
        ObserverScope {
            base: self.base,
            snapshot: self.snapshot,
            audit_sink,
        }
    }
}

trait ObserverAuditSink {
    fn push(&self, event: audit::Event);
}

struct CallbackAuditBuffer {
    pending: RefCell<Vec<audit::Event>>,
}

impl CallbackAuditBuffer {
    const fn new() -> Self {
        Self {
            pending: RefCell::new(Vec::new()),
        }
    }

    /// Hands FIFO facts to `emitter` after either a normal return or a panic.
    ///
    /// This is the inner of two stages, and it is not publication: it exists so
    /// that emission happens outside the callback catch boundary, and what it
    /// flushes into is normally a [`FactBuffer`], which queues again. When the
    /// fact reaches the consumer is decided there — see [`FactBuffer`] — not
    /// here.
    fn flush_to(&self, emitter: &dyn Emitter) {
        for event in self.pending.borrow_mut().drain(..) {
            emitter.emit_audit(event);
        }
    }
}

impl ObserverAuditSink for CallbackAuditBuffer {
    fn push(&self, event: audit::Event) {
        self.pending.borrow_mut().push(event);
    }
}

struct DirectAuditSink<'a>(&'a dyn Emitter);

impl ObserverAuditSink for DirectAuditSink<'_> {
    fn push(&self, event: audit::Event) {
        self.0.emit_audit(event);
    }
}

/// Fully read-only, non-emitting scope used inside serialized critical sections.
#[derive(Debug)]
pub struct ReadScope<'a> {
    base: ReadBase<'a>,
}

impl ReadScope<'_> {
    direct_read_capabilities!(self, self.base);
}

/// [`RunHooks::prepare`] decision.
///
/// Registrations run in registration order and each observes the previous one's
/// result, so a bare part list would make "I do not compose input" and "replace
/// everything composed so far with nothing" the same value — and the last
/// registration would win outright. A registration that has no opinion about the
/// input returns [`PrepareDecision::Continue`]; only [`PrepareDecision::Modify`]
/// rewrites it, and it may not rewrite it to nothing.
#[derive(Debug)]
pub enum PrepareDecision {
    /// Keep the composed input unchanged.
    Continue,
    /// Replace the composed input before admission.
    Modify(Vec<Part>),
}

/// An invalid [`RunHooks::prepare`] decision produced by a registration.
///
/// This mirrors the `Modify` rule of [`InputAdmitDecision`]: a rewrite that
/// would discard everything is invalid, not a silent no-op. Refusing it here is
/// what makes "model-visible implies recorded" hold for the admitted input — a
/// registration that blanked the caller's parts would otherwise leave the Run
/// with a first request the transcript has no record of.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum PrepareError {
    /// A registration returned `Modify` with an empty replacement.
    EmptyModify,
}

impl fmt::Display for PrepareError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyModify => {
                formatter.write_str("a registration rewrote the initial input to nothing")
            }
        }
    }
}

impl Error for PrepareError {}

/// [`RunHooks::compose_continuation`] decision.
///
/// This is [`PrepareDecision`]'s sibling and exists for the same reason:
/// registrations run in registration order and each observes the previous one's
/// result, so a bare part list would make "I have no opinion about continuing"
/// and "replace the continuation everyone before me asked for with nothing" the
/// same value, and the last registration would win outright. A registration with
/// no opinion returns [`ContinuationDecision::Keep`]; only
/// [`ContinuationDecision::Replace`] rewrites the request.
///
/// The one place it differs from `PrepareDecision` is that an **empty `Replace`
/// is legitimate here**, so there is no `FinalizeError`. A continuation is a
/// request for another Turn, not user content: replacing it with nothing is a
/// governance hook vetoing a peer's request and ending the Run, which is a
/// meaningful answer rather than data loss. `PrepareDecision` refuses an empty
/// `Modify` because there the parts *are* the caller's submission, and blanking
/// them would leave the Run with a first request the transcript never recorded.
#[derive(Debug)]
pub enum ContinuationDecision {
    /// Keep the accumulated continuation request unchanged.
    Keep,
    /// Replace the accumulated continuation request; empty ends the Run.
    Replace(Vec<Part>),
}

/// [`ModelHooks::before_model`] decision.
///
/// [`Self::Modify`] is where a composition layer normalises history for the
/// provider it is about to call. Core applies visibility and the tool-exchange
/// grammar and stops there: it never rewrites a
/// [`Segment`](crate::value::content::Segment) because a different provider
/// produced it, because deciding that one vendor's thinking segment is unusable
/// by another requires knowing both vendors' rules — a `compat` matrix core does
/// not and must not learn. A registration that changes model mid-session reads
/// [`BeforeModelScope::request`], rewrites the segments its next provider cannot
/// accept, and re-freezes through
/// [`RequestPlan::try_into_request`](crate::runtime::model::RequestPlan::try_into_request), which
/// is the only way to construct a [`Request`] and therefore cannot be bypassed.
#[derive(Debug)]
pub enum BeforeModelDecision {
    /// Continue with the current request.
    Continue,
    /// Replace the request after runtime validation.
    Modify(Request),
    /// Supply assistant output without invoking the model.
    ///
    /// [`AfterModelScope::generated`] is false, its
    /// [`AfterModelScope::finish_reason`] is empty because no provider supplied a
    /// label, and its completion classification is
    /// [`CompletionReason::Unknown`].
    ///
    /// Tool-call identities and names must be nonempty. Model-visible identities
    /// may not repeat either within this record or anywhere in the frozen request
    /// history. The runtime rejects an invalid value as a typed,
    /// registration-attributed hook failure before anything is committed.
    ShortCircuit(Assistant),
    /// Deliberately abort model invocation.
    Abort(String),
}

/// [`ModelHooks::after_model`] decision.
#[derive(Debug)]
pub enum AfterModelDecision {
    /// Keep assembled output.
    Continue,
    /// Replace assembled output before commit.
    ///
    /// Tool-call identities and names must be nonempty. Model-visible identities
    /// may not repeat either within this record or anywhere in the frozen request
    /// history. The runtime rejects an invalid value as a typed,
    /// registration-attributed hook failure before anything is committed.
    Modify(Assistant),
}

/// [`ToolHooks::before_tool_call`] decision.
#[derive(Debug)]
pub enum ToolCallDecision {
    /// Continue with the current call.
    Continue,
    /// Replace the call before execution.
    ///
    /// The runtime preserves the model-assigned id, accepts the replacement name
    /// and arguments, and attributes an empty replacement name to this hook as a
    /// typed [`model::RequestError::EmptyToolCallName`] failure.
    Modify(ToolCall),
    /// Block execution with a nonempty hook reason.
    Block(String),
    /// Supply a closed result without execution.
    ShortCircuit(ToolResult),
}

/// [`ToolHooks::before_tool_result`] decision.
#[derive(Debug)]
pub enum ToolResultDecision {
    /// Keep the current closed result.
    Continue,
    /// Replace the result before commit and publication.
    Modify(ToolResult),
}

/// [`InputHooks::before_input_admit`] decision.
#[derive(Debug)]
pub enum InputAdmitDecision {
    /// Admit the claimed batch unchanged.
    Admit,
    /// Replace the claimed batch before append.
    Modify(Vec<Item>),
    /// Permanently discard the claimed batch with a reason.
    Reject(String),
}

/// [`RunHooks::decide_stop`] decision and the sole hook-initiated stop surface.
#[derive(Debug)]
pub enum StopDecision {
    /// Continue toward the prospective Turn.
    Continue,
    /// Ask runtime to emit its unique validated `EventStop`.
    Stop(StopCode),
}

/// [`TurnStepHooks::after_step`] decision.
#[derive(Debug)]
pub enum AfterStepDecision {
    /// Keep the Turn open and append the ordered items.
    Continue(Vec<Item>),
    /// Close the current Turn after appending the ordered items.
    ///
    /// This boundary decision takes precedence over queued work: a queued
    /// [`InputTarget::NextStep`] batch is not claimed and remains in the
    /// Session-owned mailbox for a later eligible boundary or successor Run.
    EndTurn(Vec<Item>),
}

/// The ten lifecycle observation variants, mechanically paired with callbacks.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum LifecycleKind {
    /// `OnRunStart`.
    RunStart,
    /// `OnRunEnd`.
    RunEnd,
    /// `OnTurnStart`.
    TurnStart,
    /// `OnTurnEnd`.
    TurnEnd,
    /// `OnStepStart`.
    StepStart,
    /// `OnStepEnd`.
    StepEnd,
    /// `OnGenerationStart`.
    GenerationStart,
    /// `OnGenerationEnd`.
    GenerationEnd,
    /// `OnToolCallStart`.
    ToolCallStart,
    /// `OnToolCallEnd`.
    ToolCallEnd,
}

/// A closed, internally consistent lifecycle terminal fact.
#[derive(Clone)]
#[non_exhaustive]
pub enum LifecycleEnd {
    /// Normal success.
    Completed,
    /// Consumer or explicit Run stop.
    #[non_exhaustive]
    Stopped {
        /// Optional opaque hook stop code; ordinary consumer stops have none.
        code: Option<StopCode>,
    },
    /// Parent cancellation or deadline.
    #[non_exhaustive]
    Cancelled {
        /// Authoritative cancellation detail.
        error: Arc<dyn Error + Send + Sync>,
    },
    /// Execution or contract failure.
    #[non_exhaustive]
    Failed {
        /// Authoritative failure detail.
        error: Arc<dyn Error + Send + Sync>,
    },
}

impl fmt::Debug for LifecycleEnd {
    /// Names the ending and renders its cause through `Display`.
    ///
    /// The error is an arbitrary boxed failure supplied from outside this
    /// crate, so its `Debug` is neither written nor reviewed here; `Display` is
    /// the diagnostic the error type is contracted to produce, and it is what
    /// `HookError` already prints for the same reason.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Completed => formatter.write_str("Completed"),
            Self::Stopped { code } => formatter
                .debug_struct("Stopped")
                .field("code", code)
                .finish(),
            Self::Cancelled { error } => formatter
                .debug_struct("Cancelled")
                .field("error", &error.to_string())
                .finish(),
            Self::Failed { error } => formatter
                .debug_struct("Failed")
                .field("error", &error.to_string())
                .finish(),
        }
    }
}

impl LifecycleEnd {
    /// Returns the authoritative portable outcome.
    #[must_use]
    pub const fn outcome(&self) -> Outcome {
        match self {
            Self::Completed => Outcome::Completed,
            Self::Stopped { .. } => Outcome::Stopped,
            Self::Cancelled { .. } => Outcome::Cancelled,
            Self::Failed { .. } => Outcome::Failed,
        }
    }

    /// Returns the optional explicit stop code.
    #[must_use]
    pub const fn stop_code(&self) -> Option<&StopCode> {
        match self {
            Self::Stopped { code } => code.as_ref(),
            Self::Completed | Self::Cancelled { .. } | Self::Failed { .. } => None,
        }
    }

    /// Returns cancellation/failure detail when the outcome requires it.
    #[must_use]
    pub fn error(&self) -> Option<&(dyn Error + Send + Sync)> {
        match self {
            Self::Cancelled { error } | Self::Failed { error } => Some(error.as_ref()),
            Self::Completed | Self::Stopped { .. } => None,
        }
    }
}

/// Closed progress reached by a `ToolCall` before its end observation.
///
/// The private representation makes a committed result without a value and completed
/// post-hooks without finalization unrepresentable.
///
/// ```compile_fail
/// use reef_core::runtime::{hook, tool};
/// let _ = hook::ToolCallProgress {
///     disposition: tool::CallDisposition::Executed,
/// };
/// ```
#[derive(Clone, Debug)]
pub struct ToolCallProgress {
    disposition: CallDisposition,
    state: ToolCallProgressState,
}

#[derive(Clone, Debug)]
enum ToolCallProgressState {
    Observed,
    ResultAvailable(ToolResult),
    ResultCommitted(ToolResult),
    PostHooksCompleted(ToolResult),
}

/// Public classification of the closed `ToolCall` progress.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ToolCallProgressKind {
    /// The call ended before a closed result became available.
    Observed,
    /// A closed result exists but its enclosing batch is not yet durable.
    ResultAvailable,
    /// The enclosing result batch committed.
    ResultCommitted,
    /// Finalization and the post-execution hook phase both completed.
    PostHooksCompleted,
}

impl ToolCallProgress {
    pub(crate) const fn observed(disposition: CallDisposition) -> Self {
        Self {
            disposition,
            state: ToolCallProgressState::Observed,
        }
    }

    pub(crate) const fn result_available(disposition: CallDisposition, result: ToolResult) -> Self {
        Self {
            disposition,
            state: ToolCallProgressState::ResultAvailable(result),
        }
    }

    pub(crate) const fn result_committed(disposition: CallDisposition, result: ToolResult) -> Self {
        Self {
            disposition,
            state: ToolCallProgressState::ResultCommitted(result),
        }
    }

    pub(crate) const fn completed_post_hooks(
        disposition: CallDisposition,
        result: ToolResult,
    ) -> Self {
        Self {
            disposition,
            state: ToolCallProgressState::PostHooksCompleted(result),
        }
    }

    /// Returns the furthest stable call disposition.
    #[must_use]
    pub const fn disposition(&self) -> CallDisposition {
        self.disposition
    }

    /// Returns the closed progress classification.
    #[must_use]
    pub const fn kind(&self) -> ToolCallProgressKind {
        match self.state {
            ToolCallProgressState::Observed => ToolCallProgressKind::Observed,
            ToolCallProgressState::ResultAvailable(_) => ToolCallProgressKind::ResultAvailable,
            ToolCallProgressState::ResultCommitted(_) => ToolCallProgressKind::ResultCommitted,
            ToolCallProgressState::PostHooksCompleted(_) => {
                ToolCallProgressKind::PostHooksCompleted
            }
        }
    }

    /// Returns the effective result once one became available.
    #[must_use]
    pub const fn result(&self) -> Option<&ToolResult> {
        match &self.state {
            ToolCallProgressState::Observed => None,
            ToolCallProgressState::ResultAvailable(result)
            | ToolCallProgressState::ResultCommitted(result)
            | ToolCallProgressState::PostHooksCompleted(result) => Some(result),
        }
    }

    /// Reports whether the enclosing result batch is durable.
    #[must_use]
    pub const fn is_result_committed(&self) -> bool {
        matches!(
            self.state,
            ToolCallProgressState::ResultCommitted(_)
                | ToolCallProgressState::PostHooksCompleted(_)
        )
    }

    /// Reports whether the post-execution hook phase completed after finalization.
    #[must_use]
    pub const fn post_hooks_completed(&self) -> bool {
        matches!(self.state, ToolCallProgressState::PostHooksCompleted(_))
    }
}

/// Why a crate-internal `ToolCall` terminal fact was rejected.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum ToolCallEndError {
    /// This disposition cannot reach the supplied result progress.
    InvalidDisposition {
        disposition: CallDisposition,
        progress: ToolCallProgressKind,
    },
    /// Normal completion requires the closed result and post-hook phase.
    CompletedBeforePostHooks(ToolCallProgressKind),
    /// A post-hook-complete call cannot carry a non-completed terminal state.
    PostHooksWithoutCompletion(Outcome),
}

/// A validated, externally non-constructible `ToolCall` terminal observation.
///
/// ```compile_fail
/// use reef_core::runtime::hook;
/// let _ = hook::ToolCallEndObservation {};
/// ```
///
/// Crate-internal validation is deliberately not a public escape hatch:
///
/// ```compile_fail
/// use reef_core::runtime::hook;
/// let _ = hook::ToolCallEndObservation::try_new;
/// ```
#[derive(Clone, Debug)]
pub struct ToolCallEndObservation {
    coord: Coord,
    end: LifecycleEnd,
    original_call: ToolCall,
    effective_call: ToolCall,
    progress: ToolCallProgress,
}

impl ToolCallEndObservation {
    pub(crate) fn try_new(
        coord: Coord,
        end: LifecycleEnd,
        original_call: ToolCall,
        effective_call: ToolCall,
        progress: ToolCallProgress,
    ) -> Result<Self, ToolCallEndError> {
        let progress_kind = progress.kind();
        let disposition = progress.disposition();
        let disposition_matches_progress = match progress_kind {
            ToolCallProgressKind::Observed => matches!(
                disposition,
                CallDisposition::Truncated | CallDisposition::NotExecuted
            ),
            ToolCallProgressKind::ResultAvailable
            | ToolCallProgressKind::ResultCommitted
            | ToolCallProgressKind::PostHooksCompleted => !matches!(
                disposition,
                CallDisposition::Truncated | CallDisposition::NotExecuted
            ),
        };
        if !disposition_matches_progress {
            return Err(ToolCallEndError::InvalidDisposition {
                disposition,
                progress: progress_kind,
            });
        }

        match (&end, progress_kind) {
            (LifecycleEnd::Completed, ToolCallProgressKind::PostHooksCompleted) => {}
            (LifecycleEnd::Completed, incomplete) => {
                return Err(ToolCallEndError::CompletedBeforePostHooks(incomplete));
            }
            (
                LifecycleEnd::Stopped { .. }
                | LifecycleEnd::Cancelled { .. }
                | LifecycleEnd::Failed { .. },
                ToolCallProgressKind::PostHooksCompleted,
            ) => {
                return Err(ToolCallEndError::PostHooksWithoutCompletion(end.outcome()));
            }
            (
                LifecycleEnd::Stopped { .. }
                | LifecycleEnd::Cancelled { .. }
                | LifecycleEnd::Failed { .. },
                ToolCallProgressKind::Observed
                | ToolCallProgressKind::ResultAvailable
                | ToolCallProgressKind::ResultCommitted,
            ) => {}
        }

        Ok(Self {
            coord,
            end,
            original_call,
            effective_call,
            progress,
        })
    }

    /// Returns the exact ended `ToolCall` coordinate.
    #[must_use]
    pub const fn coord(&self) -> &Coord {
        &self.coord
    }

    /// Returns the authoritative terminal state.
    #[must_use]
    pub const fn end(&self) -> &LifecycleEnd {
        &self.end
    }

    /// Returns the original model-emitted call.
    #[must_use]
    pub const fn original_call(&self) -> &ToolCall {
        &self.original_call
    }

    /// Returns the final effective call after successful rewrites.
    #[must_use]
    pub const fn effective_call(&self) -> &ToolCall {
        &self.effective_call
    }

    /// Returns the closed result/finalization progress.
    #[must_use]
    pub const fn progress(&self) -> &ToolCallProgress {
        &self.progress
    }
}

/// Complete immutable facts for exactly one lifecycle callback.
///
/// Every field is an owned value rather than a view, so an observer cannot see a
/// fact mutate under it and the producer needs no defensive copy.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum LifecycleObservation {
    /// Prepared Run input at execution start.
    #[non_exhaustive]
    RunStart {
        /// Started Run coordinate.
        coord: Coord,
        /// Prepared input after all rewrites.
        input: Vec<Part>,
    },
    /// Authoritative Run terminal fact and entered Turn count.
    #[non_exhaustive]
    RunEnd {
        /// Ended Run coordinate.
        coord: Coord,
        /// Authoritative terminal state.
        end: LifecycleEnd,
        /// Number of Turns entered.
        turns: usize,
    },
    /// Input which opened a Turn.
    #[non_exhaustive]
    TurnStart {
        /// Started Turn coordinate.
        coord: Coord,
        /// Owned trigger batch.
        trigger: Vec<Item>,
    },
    /// Authoritative Turn terminal fact and entered Step count.
    #[non_exhaustive]
    TurnEnd {
        /// Ended Turn coordinate.
        coord: Coord,
        /// Authoritative terminal state.
        end: LifecycleEnd,
        /// Number of Steps entered.
        steps: usize,
    },
    /// Frozen snapshot used by a started Step.
    #[non_exhaustive]
    StepStart {
        /// Started Step coordinate.
        coord: Coord,
        /// Exact shared Step snapshot.
        snapshot: Arc<StepSnapshot>,
    },
    /// Authoritative Step terminal fact and the same frozen snapshot.
    #[non_exhaustive]
    StepEnd {
        /// Ended Step coordinate.
        coord: Coord,
        /// Authoritative terminal state.
        end: LifecycleEnd,
        /// Exact shared Step snapshot.
        snapshot: Arc<StepSnapshot>,
    },
    /// Exact frozen provider request.
    ///
    /// This observation has no [`event::Kind`] counterpart, and that is a
    /// decision rather than an omission: its payload is the whole frozen
    /// [`Request`], so publishing it outward would copy the projected history and
    /// the system instruction onto a stream a host may log, to tell a consumer
    /// something [`event::Kind::StepStart`] already tells it. See ADR-021.
    ///
    /// [`event::Kind`]: crate::runtime::event::Kind
    /// [`event::Kind::StepStart`]: crate::runtime::event::Kind::StepStart
    #[non_exhaustive]
    GenerationStart {
        /// Started Generation coordinate.
        coord: Coord,
        /// Exact request passed to the provider.
        request: Request,
    },
    /// Authoritative generation outcome plus provider completion facts.
    #[non_exhaustive]
    GenerationEnd {
        /// Ended Generation coordinate.
        coord: Coord,
        /// Authoritative terminal state.
        end: LifecycleEnd,
        /// Verbatim provider finish label, empty when no provider supplied one.
        finish_reason: String,
        /// Normalized provider-neutral completion reason.
        completion: CompletionReason,
    },
    /// Original model-emitted `ToolCall`.
    #[non_exhaustive]
    ToolCallStart {
        /// Started `ToolCall` coordinate.
        coord: Coord,
        /// Original frozen call.
        call: ToolCall,
    },
    /// Authoritative closed `ToolCall` outcome, rewrites, result, and progress.
    ToolCallEnd(ToolCallEndObservation),
}

impl LifecycleObservation {
    /// Returns the callback variant without inspecting its payload.
    #[must_use]
    pub const fn kind(&self) -> LifecycleKind {
        match self {
            Self::RunStart { .. } => LifecycleKind::RunStart,
            Self::RunEnd { .. } => LifecycleKind::RunEnd,
            Self::TurnStart { .. } => LifecycleKind::TurnStart,
            Self::TurnEnd { .. } => LifecycleKind::TurnEnd,
            Self::StepStart { .. } => LifecycleKind::StepStart,
            Self::StepEnd { .. } => LifecycleKind::StepEnd,
            Self::GenerationStart { .. } => LifecycleKind::GenerationStart,
            Self::GenerationEnd { .. } => LifecycleKind::GenerationEnd,
            Self::ToolCallStart { .. } => LifecycleKind::ToolCallStart,
            Self::ToolCallEnd(_) => LifecycleKind::ToolCallEnd,
        }
    }

    /// Returns the exact coordinate carried by the producer.
    #[must_use]
    pub const fn coord(&self) -> &Coord {
        match self {
            Self::RunStart { coord, .. }
            | Self::RunEnd { coord, .. }
            | Self::TurnStart { coord, .. }
            | Self::TurnEnd { coord, .. }
            | Self::StepStart { coord, .. }
            | Self::StepEnd { coord, .. }
            | Self::GenerationStart { coord, .. }
            | Self::GenerationEnd { coord, .. }
            | Self::ToolCallStart { coord, .. } => coord,
            Self::ToolCallEnd(observation) => observation.coord(),
        }
    }
}

/// Immutable transcript mutation fact passed before the live commit.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum TranscriptMutation {
    /// One ordered append batch and its proposed committed version.
    #[non_exhaustive]
    Append {
        /// Version observed before the mutation.
        previous: Version,
        /// Version proposed after the mutation.
        version: Version,
        /// Complete owned append batch.
        items: Vec<Item>,
    },
    /// One complete replacement and its proposed committed snapshot.
    #[non_exhaustive]
    Replace {
        /// Version observed before the mutation.
        previous: Version,
        /// Complete immutable replacement snapshot.
        snapshot: Snapshot,
    },
}

impl TranscriptMutation {
    /// Returns the version observed before reservation.
    #[must_use]
    pub const fn previous_version(&self) -> Version {
        match self {
            Self::Append { previous, .. } | Self::Replace { previous, .. } => *previous,
        }
    }

    /// Returns the proposed post-commit version.
    #[must_use]
    pub const fn version(&self) -> Version {
        match self {
            Self::Append { version, .. } => *version,
            Self::Replace { snapshot, .. } => snapshot.version(),
        }
    }

    /// Returns the immutable mutation payload.
    #[must_use]
    pub fn items(&self) -> &[Item] {
        match self {
            Self::Append { items, .. } => items,
            Self::Replace { snapshot, .. } => snapshot.items(),
        }
    }

    /// Returns the complete proposed snapshot for a replacement.
    #[must_use]
    pub const fn replacement(&self) -> Option<&Snapshot> {
        match self {
            Self::Append { .. } => None,
            Self::Replace { snapshot, .. } => Some(snapshot),
        }
    }
}

/// A successful pre-commit reservation whose publication cannot fail.
///
/// A reservation is resolved exactly once, and both resolutions consume the box
/// so no code path can publish an aborted reservation or abort a published one.
/// The controller decides which resolution applies: any pre-commit failure
/// aborts every held reservation in reverse acquisition order, and a successful
/// commit publishes every held reservation in acquisition order and never
/// aborts. Publication is contractually infallible, which is what makes a held
/// reservation safe to publish after the commit has already succeeded.
pub trait TranscriptReservation: Send {
    /// Publishes the already-committed fact; consuming `self` forbids abort after publish.
    ///
    /// The live transcript mutation has already linearized when this runs, so an
    /// implementation must not fail. A panic is isolated by the controller, which
    /// still publishes every remaining reservation.
    fn publish(self: Box<Self>);

    /// Releases a reservation that will never be committed.
    ///
    /// The controller calls this only before the live commit, so an
    /// implementation must not assume the mutation became visible. Releasing
    /// nothing is the default, because a reservation that holds no external
    /// resource has nothing to undo.
    fn abort(self: Box<Self>) {}
}

/// Run-phase hooks.
///
/// The three boundaries of a Run itself: what it starts with, whether it takes
/// another Turn, and what it does when it would otherwise finish.
/// [`compose_continuation`](RunHooks::compose_continuation) is how an agent keeps
/// going — returning more input continues the Run, returning nothing ends it —
/// so a Run that should do more than one turn needs this family.
///
/// ```
/// use std::sync::Arc;
/// use std::sync::atomic::{AtomicUsize, Ordering};
///
/// use reef_core::runtime::{event, hook};
///
/// /// Stops the Run after a fixed number of completed Turns.
/// struct TurnBudget {
///     remaining: AtomicUsize,
/// }
///
/// impl TurnBudget {
///     fn completed_turn(&self) -> hook::StopDecision {
///         let remaining = self.remaining.fetch_update(
///             Ordering::SeqCst,
///             Ordering::SeqCst,
///             |remaining| remaining.checked_sub(1),
///         ).unwrap_or(0);
///         if remaining > 1 {
///             hook::StopDecision::Continue
///         } else {
///             // Stop after the configured number of completed Turns. Zero also
///             // stops here without wrapping the counter to `usize::MAX`.
///             hook::StopDecision::Stop(event::StopCode::new("turn-budget".to_owned()).unwrap())
///         }
///     }
/// }
///
/// impl hook::RunHooks for TurnBudget {
///     fn prepare(&self, _scope: &hook::PrepareScope<'_>) -> hook::HookResult<hook::PrepareDecision> {
///         // `Continue` keeps what the caller submitted. `Modify` replaces it,
///         // and may not replace it with nothing.
///         Ok(hook::PrepareDecision::Continue)
///     }
///
///     fn compose_continuation(&self, _scope: &hook::ContinuationScope<'_>) -> hook::HookResult<hook::ContinuationDecision> {
///         Ok(hook::ContinuationDecision::Keep)
///     }
///
///     fn decide_stop(&self, _scope: &hook::StopDecisionScope<'_>) -> hook::HookResult<hook::StopDecision> {
///         Ok(self.completed_turn())
///     }
/// }
///
/// let budget = TurnBudget { remaining: AtomicUsize::new(4) };
/// for _ in 0..3 {
///     assert!(matches!(budget.completed_turn(), hook::StopDecision::Continue));
/// }
/// assert!(matches!(budget.completed_turn(), hook::StopDecision::Stop(_)));
/// let exhausted = TurnBudget { remaining: AtomicUsize::new(0) };
/// assert!(matches!(exhausted.completed_turn(), hook::StopDecision::Stop(_)));
/// assert_eq!(exhausted.remaining.load(Ordering::SeqCst), 0);
///
/// let mut hooks = hook::RegistryBuilder::new();
/// hooks.register(hook::Registration::new("turn-budget".to_owned()).run(Arc::new(TurnBudget {
///     remaining: AtomicUsize::new(4),
/// })));
/// ```
pub trait RunHooks: Send + Sync {
    /// Composes initial input before admission.
    ///
    /// # Errors
    ///
    /// Return one when this registration cannot decide what the Run's initial
    /// input should be — a required piece of context it could not load, or an
    /// input it judges inadmissible. This is the one hook whose failure is
    /// reported to the caller synchronously rather than through a Run:
    /// [`Agent::start`](crate::runtime::agent::Agent::start) returns
    /// [`StartError::Prepare`](crate::runtime::agent::StartError::Prepare) and no
    /// Run comes into existence, so it is also the only place a hook can refuse
    /// a Run outright instead of ending one.
    ///
    /// Reef adds one error of its own here: returning
    /// [`PrepareDecision::Modify`] with an empty replacement is refused as
    /// [`PrepareError::EmptyModify`], attributed to this registration. Composing
    /// nothing is [`PrepareDecision::Continue`]; deleting what the caller
    /// submitted is not an option, because the admitted input is also the
    /// transcript's record of it.
    ///
    /// See [`HookError`](HookError#effect-on-the-run) for what a failure costs.
    fn prepare(&self, scope: &PrepareScope<'_>) -> HookResult<PrepareDecision>;

    /// Composes a natural-completion continuation.
    ///
    /// # Errors
    ///
    /// Return one when this registration cannot decide whether the Run should
    /// continue. Note that it does not need to fail in order to *stop* the Run:
    /// [`ContinuationDecision::Replace`] with an empty continuation ends it normally,
    /// which is a governance answer rather than a failure. An error here ends the
    /// Run as failed instead, discarding the continuation every earlier
    /// registration had composed.
    ///
    /// See [`HookError`](HookError#effect-on-the-run).
    fn compose_continuation(
        &self,
        scope: &ContinuationScope<'_>,
    ) -> HookResult<ContinuationDecision>;

    /// Decides whether a prospective Turn may exist.
    ///
    /// # Errors
    ///
    /// Return one when this registration cannot decide, rather than when it
    /// decides against another Turn: refusing a Turn is
    /// [`StopDecision::Stop`], which ends the Run normally carrying a stop
    /// code a consumer can read. An error ends it as failed and publishes no stop
    /// at all.
    ///
    /// See [`HookError`](HookError#effect-on-the-run).
    fn decide_stop(&self, scope: &StopDecisionScope<'_>) -> HookResult<StopDecision>;
}

/// Injected-input admission hook.
///
/// Mid-run input arrives through
/// [`Session::input_mailbox`](crate::runtime::session::Session::input_mailbox)
/// and is claimed at the boundary it targeted. This is the one chance to rewrite
/// or refuse a claimed batch before it becomes a transcript record.
///
/// **Expect to see one batch more than once.** A claimed batch whose admission
/// neither commits nor is refused — a cancellation, a later registration's
/// contract error, a transcript failure, a panic — is restored to the mailbox
/// unrewritten (see [`InputMailbox`'s conservation
/// guarantee](crate::runtime::session::InputMailbox#conservation)), and the
/// boundary that claims it next calls this hook again. Anything a registration
/// does here besides returning its decision, such as a Session-state write or
/// an audit fact, is not rolled back, so it must be idempotent under re-entry.
///
/// ```
/// use std::sync::Arc;
///
/// use reef_core::runtime::hook;
///
/// /// Refuses injected input once the conversation is long enough.
/// struct Doorman;
///
/// impl hook::InputHooks for Doorman {
///     fn before_input_admit(&self, scope: &hook::InputAdmitScope<'_>) -> hook::InputAdmitDecision {
///         if scope.items().is_empty() {
///             // A rejection must say why; an empty reason is refused.
///             hook::InputAdmitDecision::Reject("nothing to admit".to_owned())
///         } else {
///             hook::InputAdmitDecision::Admit
///         }
///     }
/// }
///
/// let registration = hook::Registration::new("doorman".to_owned()).input(Arc::new(Doorman));
/// # let _ = registration;
/// ```
pub trait InputHooks: Send + Sync {
    /// Rewrites, admits, or permanently rejects one claimed batch.
    fn before_input_admit(&self, scope: &InputAdmitScope<'_>) -> InputAdmitDecision;
}

/// Turn and Step boundary hooks.
///
/// Four boundaries inside a Run. [`before_step`](TurnStepHooks::before_step) is
/// the only place with a writable [`crate::runtime::model::RequestPlan`],
/// so it is where per-request material goes — a compaction policy rewrites
/// history here, and a status line goes into the plan's ephemeral lane, which
/// reaches the model without ever becoming a record.
///
/// ```
/// use std::sync::Arc;
///
/// use reef_core::runtime::hook;
/// use reef_core::transcript::item;
/// use reef_core::value::content;
///
/// /// Adds one volatile line to every request, and nothing to the transcript.
/// struct StatusLine;
///
/// impl hook::TurnStepHooks for StatusLine {
///     fn before_turn(&self, _scope: &hook::TurnScope<'_>) -> hook::HookResult<Vec<item::Item>> {
///         Ok(Vec::new())
///     }
///
///     fn after_turn(&self, _scope: &hook::TurnScope<'_>) -> hook::HookResult<Vec<item::Item>> {
///         Ok(Vec::new())
///     }
///
///     fn before_step(&self, scope: &mut hook::BeforeStepScope<'_>) -> hook::HookResult<Vec<item::Item>> {
///         scope
///             .plan()
///             .push_ephemeral(content::Part::text("[battery: 42%]".to_owned()));
///         Ok(Vec::new())
///     }
///
///     fn after_step(&self, _scope: &hook::AfterStepScope<'_>) -> hook::HookResult<hook::AfterStepDecision> {
///         Ok(hook::AfterStepDecision::Continue(Vec::new()))
///     }
/// }
///
/// let registration = hook::Registration::new("status".to_owned()).turn_step(Arc::new(StatusLine));
/// # let _ = registration;
/// ```
pub trait TurnStepHooks: Send + Sync {
    /// Runs before the Turn lifecycle starts.
    ///
    /// # Errors
    ///
    /// Return one when this registration cannot produce the items the Turn should
    /// open with. The Turn is never opened: the items every earlier registration
    /// contributed are discarded together with this one's, so the transcript
    /// records no half-composed Turn opening.
    ///
    /// See [`HookError`](HookError#effect-on-the-run).
    fn before_turn(&self, scope: &TurnScope<'_>) -> HookResult<Vec<Item>>;

    /// Runs after ordinary Turn work and before its end observer.
    ///
    /// # Errors
    ///
    /// Return one when this registration cannot produce the items that should
    /// close the Turn. Nothing this boundary composed is appended. The Turn's work
    /// is already committed by this point, so the Run fails with a complete Turn
    /// behind it and no closing items — not with a partially closed Turn.
    ///
    /// See [`HookError`](HookError#effect-on-the-run).
    fn after_turn(&self, scope: &TurnScope<'_>) -> HookResult<Vec<Item>>;

    /// Runs in registration order over the sole writable `RequestPlan`.
    ///
    /// # Errors
    ///
    /// Return one when this registration cannot prepare the Step — most often
    /// because the request material it needed to add is unavailable. The Step
    /// never freezes, so no model call is made, and the plan edits earlier
    /// registrations had already applied are dropped along with this one's. That
    /// is the reason a partial plan is not worth rescuing: the registrations after
    /// this one never saw it.
    ///
    /// See [`HookError`](HookError#effect-on-the-run).
    fn before_step(&self, scope: &mut BeforeStepScope<'_>) -> HookResult<Vec<Item>>;

    /// Runs after ordinary Step work and may close its Turn.
    ///
    /// # Errors
    ///
    /// Return one when this registration cannot decide how the Step should close.
    /// Closing the Turn is not a failure — that is
    /// [`AfterStepDecision::EndTurn`] — so an error here means the decision itself
    /// could not be made. Neither the items nor the end-of-Turn decisions
    /// collected at this boundary are applied.
    ///
    /// See [`HookError`](HookError#effect-on-the-run).
    fn after_step(&self, scope: &AfterStepScope<'_>) -> HookResult<AfterStepDecision>;
}

/// Model boundary hooks.
///
/// The two sides of one generation: the request before it is sent, and the
/// assistant record before it is committed. This is where a composition layer
/// normalises history for the provider it is about to call — core never rewrites
/// a segment because a different provider produced it.
///
/// ```
/// use std::sync::Arc;
///
/// use reef_core::runtime::hook;
///
/// /// Refuses to call the model at all after a cutoff.
/// struct Circuit {
///     open: std::sync::atomic::AtomicBool,
/// }
///
/// impl hook::ModelHooks for Circuit {
///     fn before_model(&self, _scope: &hook::BeforeModelScope<'_>) -> hook::HookResult<hook::BeforeModelDecision> {
///         use std::sync::atomic::Ordering;
///         Ok(if self.open.load(Ordering::SeqCst) {
///             // Declining to call the model is a decision, not a failure.
///             hook::BeforeModelDecision::Abort("circuit open".to_owned())
///         } else {
///             hook::BeforeModelDecision::Continue
///         })
///     }
///
///     fn after_model(&self, _scope: &hook::AfterModelScope<'_>) -> hook::AfterModelDecision {
///         hook::AfterModelDecision::Continue
///     }
/// }
///
/// let registration = hook::Registration::new("circuit".to_owned()).model(Arc::new(Circuit {
///     open: std::sync::atomic::AtomicBool::new(false),
/// }));
/// # let _ = registration;
/// ```
pub trait ModelHooks: Send + Sync {
    /// Controls one immutable model request.
    ///
    /// # Errors
    ///
    /// Return one when this registration cannot produce the request it wanted to
    /// send. Declining to call the model is not a failure — that is
    /// [`BeforeModelDecision::ShortCircuit`], which supplies the output itself, or
    /// [`BeforeModelDecision::Abort`], which states a reason — and neither is
    /// rewriting the request, which is [`BeforeModelDecision::Modify`]. An error is
    /// for the case where the rewrite itself could not be built, most commonly
    /// because
    /// re-freezing the modified history through
    /// [`RequestPlan::try_into_request`](crate::runtime::model::RequestPlan::try_into_request)
    /// returned a [`RequestError`](crate::runtime::model::RequestError) this
    /// registration cannot resolve.
    ///
    /// No model call is made and no generation is recorded; rewrites from earlier
    /// registrations are discarded with this one's.
    ///
    /// See [`HookError`](HookError#effect-on-the-run).
    fn before_model(&self, scope: &BeforeModelScope<'_>) -> HookResult<BeforeModelDecision>;

    /// Rewrites successfully assembled output before commit.
    fn after_model(&self, scope: &AfterModelScope<'_>) -> AfterModelDecision;
}

/// Tool boundary hooks.
///
/// This is the synchronous policy plane over tool calls. It sees the call before
/// execution and may rewrite, block, or answer it directly.
///
/// ```
/// use std::sync::Arc;
///
/// use reef_core::runtime::hook;
/// use reef_core::transcript::item;
///
/// /// Blocks one tool by name, without touching the rest.
/// struct Policy;
///
/// impl hook::ToolHooks for Policy {
///     fn before_tool_call(&self, scope: &hook::ToolCallScope<'_>) -> hook::HookResult<hook::ToolCallDecision> {
///         Ok(if scope.call().name().as_str() == "shell.exec" {
///             // A block is an ordinary business result the model reads, not a
///             // failure: an `Err` here would fail the whole batch.
///             hook::ToolCallDecision::Block("shell is disabled".to_owned())
///         } else {
///             hook::ToolCallDecision::Continue
///         })
///     }
///
///     fn before_tool_result(&self, _scope: &hook::ToolResultScope<'_>) -> hook::HookResult<hook::ToolResultDecision> {
///         Ok(hook::ToolResultDecision::Continue)
///     }
///
///     fn after_tool_commit(&self, _scope: &hook::AfterToolCommitScope<'_>) -> Vec<item::Item> {
///         Vec::new()
///     }
/// }
///
/// let registration = hook::Registration::new("policy".to_owned()).tool(Arc::new(Policy));
/// # let _ = registration;
/// ```
///
/// # Cooperative synchronous callback contract
///
/// These callbacks are trusted, synchronous, and cooperative. An implementation
/// must not block forever, wait for work that requires the same runtime thread to
/// advance, or catch a runtime-internal abort unwind and then continue external
/// side effects. Reef retains and joins every callback owner on normal, error, and
/// strong-delivery abort paths, but does not claim to forcibly terminate a
/// malicious or permanently blocked synchronous callback.
///
/// ## How a broken one looks from outside, and who to blame
///
/// Breaking that contract produces neither an error nor a panic, so it is worth
/// knowing the shape it does produce. A [`Self::after_tool_commit`] that never
/// returns leaves a thread blocked inside a destructor during teardown: the run
/// joins the callback it promised to join, waits for a completion that is not
/// coming, and never releases. The Run does not fail — it stops finishing.
///
/// Nothing in the process reports which registration is responsible, because a
/// diagnostic emitted from a destructor would have to be a panic during unwinding
/// or a library writing to stderr, and this crate does neither. What is available
/// instead is a backtrace: `after_tool_commit` is the only callback that runs on
/// Tokio's blocking pool, and the registrations are invoked one after another
/// rather than concurrently, so at most one is in flight and the blocking thread's
/// own stack names the implementing type. A *panic* at this boundary is attributed
/// by registration name and needs no backtrace; a hang is the case that does.
pub trait ToolHooks: Send + Sync {
    /// Rewrites, blocks, or short-circuits before execution.
    ///
    /// # Errors
    ///
    /// Return one when this registration cannot decide about the call. Refusing a
    /// call is not a failure: [`ToolCallDecision::Block`] stops it with a reason and
    /// [`ToolCallDecision::ShortCircuit`] answers it directly, and both produce an
    /// ordinary business result that enters the batch like any other. An error
    /// instead fails the **whole batch**, not just this call, because the batch
    /// commits atomically and a batch missing one call's decision cannot be
    /// committed at all.
    ///
    /// A registration that cannot fail returns `Ok` unconditionally.
    ///
    /// See [`HookError`](HookError#effect-on-the-run).
    fn before_tool_call(&self, scope: &ToolCallScope<'_>) -> HookResult<ToolCallDecision>;

    /// Rewrites every closed result before commit.
    ///
    /// # Errors
    ///
    /// Return one when this registration cannot produce the result it intended to
    /// commit. Rewriting a result, including into a business error, is
    /// [`ToolResultDecision::Modify`] rather than a failure. An error fails the batch
    /// commit, so the assistant record and every result in the batch stay
    /// uncommitted — which is what keeps a rejected rewrite from leaving a call
    /// nobody answered in the transcript.
    ///
    /// See [`HookError`](HookError#effect-on-the-run).
    fn before_tool_result(&self, scope: &ToolResultScope<'_>) -> HookResult<ToolResultDecision>;

    /// Appends after an executed batch is durable; this late hook cannot fail it.
    ///
    /// Each emitted fact is a synchronous strong-acceptance rendezvous. Rejection,
    /// consumer abandonment, invalid facts, or channel closure aborts the callback.
    /// The callback must not swallow that internal abort and continue side effects;
    /// Reef nevertheless revokes this invocation's Session-state writer before
    /// releasing the abort rendezvous, so subsequent state writes fail closed.
    fn after_tool_commit(&self, scope: &AfterToolCommitScope<'_>) -> Vec<Item>;
}

/// Passive hooks isolated at the exact callback invocation boundary.
///
/// An observer watches and decides nothing, which is what makes it the family a
/// budget, a metric or a log belongs in — and
/// [`model_event`](ObserverHooks::model_event) is the only route token usage has
/// out of the runtime at all.
///
/// ```
/// use std::sync::Arc;
/// use std::sync::atomic::{AtomicU64, Ordering};
///
/// use reef_core::runtime::{model, hook};
///
/// /// Counts tokens, and observes nothing else.
/// #[derive(Default)]
/// struct Budget {
///     spent: AtomicU64,
/// }
///
/// impl hook::ObserverHooks for Budget {
///     fn model_event(&self, _scope: &hook::ObserverScope<'_>, event: &model::Event) {
///         // Usage is incremental, so adding it up is exact.
///         if let model::Event::Usage(usage) = event {
///             self.spent.fetch_add(usage.total, Ordering::SeqCst);
///         }
///     }
/// }
///
/// let registration = hook::Registration::new("budget".to_owned())
///     .observer(Arc::new(Budget::default()));
/// # let _ = registration;
/// ```
///
/// # Every method has a default, and this is the only hook family where one does
///
/// An observation returns nothing and decides nothing: reef does exactly the
/// same thing whether a registration watched a boundary or not. Not overriding a
/// method here therefore *means* "I do not watch that", which is the honest
/// reading of an empty body, and the cost of forgetting one falls entirely on
/// the registration that forgot — it sees less than it meant to, in its own
/// output, and no other registration and no Run behaves differently.
///
/// Every other hook family stays fully required, deliberately. Those return a
/// decision reef then applies, so a default would have to *pick a policy* —
/// allow the call, keep the request, continue the Run — and a registration that
/// meant to gate a tool call but misspelled the method would compile into one
/// that permits every call. That is the failure this crate designs against
/// everywhere else, which is why its enums are exhaustive, why authorisation is
/// a compile-time ladder, and why no decision type implements `Default`. A
/// silently defaulted decision is that `Default` reached by another route.
///
/// This is not a deadline that has passed: adding a default body to a required
/// method compiles for every existing implementor, so any hook here can gain one
/// later on evidence rather than on speculation.
pub trait ObserverHooks: Send + Sync {
    /// Observes synchronous Run admission without emission.
    ///
    /// The default observes nothing.
    fn run_admitted(&self, scope: &ReadScope<'_>) {
        let _ = scope;
    }

    /// Observes one closed lifecycle fact.
    ///
    /// The default observes nothing.
    fn lifecycle(&self, observation: &LifecycleObservation, scope: &ObserverScope<'_>) {
        let _ = (observation, scope);
    }

    /// Observes provider usage/done facts.
    ///
    /// This is the only route [`model::Event::Usage`] has to a hook, so a
    /// budget or accounting policy overrides this one and leaves the rest.
    ///
    /// The default observes nothing.
    fn model_event(&self, scope: &ObserverScope<'_>, event: &model::Event) {
        let _ = (scope, event);
    }

    /// Observes an audit fact inside the serialized outward boundary.
    ///
    /// The default observes nothing.
    fn audit_event(&self, scope: &ReadScope<'_>, event: &audit::Event) {
        let _ = (scope, event);
    }
}

/// Transcript reservation hook.
///
/// The seam a durable journal is built on. Every live transcript mutation the
/// Agent runtime performs is offered here *before* it linearizes: a registration
/// that can promise to publish returns a [`TranscriptReservation`], and one that
/// cannot returns an error, which aborts the mutation with nothing written.
/// Publication afterwards cannot fail, so a hook that must not lose a record does
/// its risky work — the write-ahead, the lock, the capacity check — inside
/// `reserve`.
///
/// This is an Agent-owned Run rail, not a Session-global observer. Restoring the
/// initial seed through [`Session::new`](crate::runtime::session::Session::new)
/// does not create a live mutation, and direct composition-layer calls to
/// [`Lease::append_batch_if_version`](crate::runtime::session::Lease::append_batch_if_version)
/// or [`Lease::replace_if_version`](crate::runtime::session::Lease::replace_if_version)
/// have no Agent registry to dispatch. Those calls share the Session transaction
/// lock with this rail, so they cannot cross an unresolved reservation, but a
/// caller that uses them must include them in its own persistence protocol.
///
/// [`TranscriptMutation::items`] exposes the complete owned transcript values,
/// including segment signatures, raw payloads and provider data. This is the
/// persistence rail for a byte-faithful resumable Session; the outward event stream
/// is an earlier, lossy observation projection and is not a substitute. With the
/// `serde` feature, serializing these values also serializes credential-tier
/// provider tokens, so the composition layer must protect its destination as the
/// [crate-level `Serialization` section](crate#serialization) describes.
///
/// ```
/// use std::sync::Arc;
///
/// use reef_core::runtime::hook;
///
/// /// Writes ahead, then publishes what it wrote.
/// struct Journal;
///
/// struct Reserved {
///     version: u64,
/// }
///
/// impl hook::TranscriptReservation for Reserved {
///     fn publish(self: Box<Self>) {
///         // The mutation has linearized. This cannot fail and must not.
///         let _durable = self.version;
///     }
///
///     fn abort(self: Box<Self>) {
///         // The mutation never happened; release what `reserve` took.
///     }
/// }
///
/// impl hook::TranscriptHooks for Journal {
///     fn reserve(
///         &self,
///         _scope: &hook::ReadScope<'_>,
///         mutation: &hook::TranscriptMutation,
///     ) -> hook::HookResult<Box<dyn hook::TranscriptReservation>> {
///         Ok(Box::new(Reserved { version: mutation.version().as_u64() }))
///     }
/// }
///
/// let registration = hook::Registration::new("journal".to_owned()).transcript(Arc::new(Journal));
/// # let _ = registration;
/// ```
pub trait TranscriptHooks: Send + Sync {
    /// Reserves one immutable mutation before live commit.
    ///
    /// # Errors
    ///
    /// Return one when this registration cannot promise to publish the mutation.
    /// That is the whole question this hook asks: everything that can go wrong must
    /// go wrong *here*, because [`TranscriptReservation::publish`] runs after the
    /// commit has linearized and is contractually infallible. A registration that
    /// needs to write ahead, take a lock, or reserve capacity does it now and
    /// returns an error if it cannot.
    ///
    /// A failure aborts every reservation this transaction already held, in reverse
    /// acquisition order, and the compare-and-set never runs — so the transcript is
    /// unchanged and no peer is left holding a reservation for a mutation that never
    /// happened. Registrations after this one are not called.
    ///
    /// Because a reservation failure fails the mutation rather than a callback
    /// phase, the Run's [`FailureKind`](crate::runtime::run::FailureKind) is
    /// [`Transcript`](crate::runtime::run::FailureKind::Transcript) or
    /// [`ToolCommit`](crate::runtime::run::FailureKind::ToolCommit) rather than
    /// [`Hook`](crate::runtime::run::FailureKind::Hook), even though this
    /// registration's name is still attached to the cause. At Run admission it is
    /// [`StartError::Prepare`](crate::runtime::agent::StartError::Prepare) instead.
    ///
    /// See [`HookError`](HookError#effect-on-the-run).
    fn reserve(
        &self,
        scope: &ReadScope<'_>,
        mutation: &TranscriptMutation,
    ) -> HookResult<Box<dyn TranscriptReservation>>;
}

/// Agent teardown is deliberately separate from all 27 runtime callbacks.
///
/// It is the only hook that runs outside a Run, and the only one whose failure
/// costs nothing else: [`Agent::close`](crate::runtime::agent::Agent::close)
/// invokes every registration's `close` in registration order regardless of what
/// the others did, and reports the failures together.
///
/// ```
/// use std::sync::Arc;
/// use std::sync::atomic::{AtomicBool, Ordering};
///
/// use reef_core::runtime::hook;
///
/// /// Releases something the hook opened, exactly once.
/// #[derive(Default)]
/// struct Connection {
///     closed: AtomicBool,
/// }
///
/// impl hook::AgentTeardown for Connection {
///     fn close(&self) -> hook::HookResult<()> {
///         self.closed.store(true, Ordering::SeqCst);
///         Ok(())
///     }
/// }
///
/// let registration = hook::Registration::new("connection".to_owned())
///     .teardown(Arc::new(Connection::default()));
/// # let _ = registration;
/// ```
pub trait AgentTeardown: Send + Sync {
    /// Releases hook-owned external resources.
    ///
    /// # Errors
    ///
    /// Return one when a resource could not be released cleanly — a connection
    /// that would not drain, a flush that failed. This is the one fallible hook
    /// whose failure does **not** short-circuit anything: teardown is the last
    /// thing that happens, so every registration's `close` runs in registration
    /// order regardless, and the failures are collected rather than raced. A peer
    /// that would have released a file handle still gets to.
    ///
    /// [`Agent::close`](crate::runtime::agent::Agent::close) reports them together
    /// as [`CloseError::Hooks`](crate::runtime::agent::CloseError::Hooks), whose
    /// [`TeardownError::entries`](crate::runtime::agent::TeardownError::entries)
    /// lists every failure in registration order with its hook's name. That
    /// result is cached, so a repeated close returns the same failures rather than
    /// running teardown again — an error here is final, not a retry request. A
    /// panicking `close` is caught at this boundary and reported the same way.
    ///
    /// The Agent is closed either way. There is no Run left for a failure here to
    /// affect, which is why [`HookError`](HookError#effect-on-the-run)'s Run
    /// consequences do not apply.
    fn close(&self) -> HookResult<()>;
}

/// One named hook's family registrations and state-access metadata.
pub struct Registration {
    name: String,
    requires_session_state: bool,
    run: Option<Arc<dyn RunHooks>>,
    input: Option<Arc<dyn InputHooks>>,
    turn_step: Option<Arc<dyn TurnStepHooks>>,
    model: Option<Arc<dyn ModelHooks>>,
    tool: Option<Arc<dyn ToolHooks>>,
    observer: Option<Arc<dyn ObserverHooks>>,
    transcript: Option<Arc<dyn TranscriptHooks>>,
    teardown: Option<Arc<dyn AgentTeardown>>,
}

impl fmt::Debug for Registration {
    /// Names the hook and states which hook families it actually claimed.
    ///
    /// Every hook is a trait object with no `Debug`, and presence is the whole
    /// of what a registration decides: which of the eight families this hook
    /// will be dispatched into.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Registration")
            .field("name", &self.name)
            .field("requires_session_state", &self.requires_session_state)
            .field("run", &Presence(self.run.is_some()))
            .field("input", &Presence(self.input.is_some()))
            .field("turn_step", &Presence(self.turn_step.is_some()))
            .field("model", &Presence(self.model.is_some()))
            .field("tool", &Presence(self.tool.is_some()))
            .field("observer", &Presence(self.observer.is_some()))
            .field("transcript", &Presence(self.transcript.is_some()))
            .field("teardown", &Presence(self.teardown.is_some()))
            .finish()
    }
}

impl Registration {
    /// Begins one named registration.
    #[must_use]
    pub fn new(name: String) -> Self {
        Self {
            name,
            requires_session_state: false,
            run: None,
            input: None,
            turn_step: None,
            model: None,
            tool: None,
            observer: None,
            transcript: None,
            teardown: None,
        }
    }

    /// Declares use of optional successor-Run Session state.
    #[must_use]
    pub const fn requires_session_state(mut self, required: bool) -> Self {
        self.requires_session_state = required;
        self
    }

    /// Mounts the Run family.
    #[must_use]
    pub fn run(mut self, hooks: Arc<dyn RunHooks>) -> Self {
        self.run = Some(hooks);
        self
    }

    /// Mounts the input-admission family.
    #[must_use]
    pub fn input(mut self, hooks: Arc<dyn InputHooks>) -> Self {
        self.input = Some(hooks);
        self
    }

    /// Mounts the Turn/Step family.
    #[must_use]
    pub fn turn_step(mut self, hooks: Arc<dyn TurnStepHooks>) -> Self {
        self.turn_step = Some(hooks);
        self
    }

    /// Mounts the model family.
    #[must_use]
    pub fn model(mut self, hooks: Arc<dyn ModelHooks>) -> Self {
        self.model = Some(hooks);
        self
    }

    /// Mounts the tool family.
    #[must_use]
    pub fn tool(mut self, hooks: Arc<dyn ToolHooks>) -> Self {
        self.tool = Some(hooks);
        self
    }

    /// Mounts passive observers.
    #[must_use]
    pub fn observer(mut self, hooks: Arc<dyn ObserverHooks>) -> Self {
        self.observer = Some(hooks);
        self
    }

    /// Mounts transcript reservation.
    #[must_use]
    pub fn transcript(mut self, hooks: Arc<dyn TranscriptHooks>) -> Self {
        self.transcript = Some(hooks);
        self
    }

    /// Mounts Agent teardown separately from runtime families.
    #[must_use]
    pub fn teardown(mut self, hooks: Arc<dyn AgentTeardown>) -> Self {
        self.teardown = Some(hooks);
        self
    }
}

struct RegisteredHook {
    registration: Registration,
}

/// One family hook with its immutable registration metadata.
///
/// The index is the original registry position, not a dense family-local index,
/// so controllers can key independent per-registration Run state and callback
/// transactions without losing registrations that omitted this family.
pub(crate) struct RegistrationAdapter<'a, H: ?Sized> {
    index: usize,
    name: &'a str,
    requires_session_state: bool,
    hook: &'a H,
}

/// Owned tool adapter used only by managed blocking callback owners.
pub(crate) struct OwnedToolRegistrationAdapter {
    index: usize,
    name: String,
    requires_session_state: bool,
    hook: Arc<dyn ToolHooks>,
}

impl<'a, H: ?Sized> RegistrationAdapter<'a, H> {
    pub(crate) const fn index(&self) -> usize {
        self.index
    }

    #[cfg_attr(not(test), expect(dead_code, reason = "reached only by tests so far"))]
    pub(crate) const fn name(&self) -> &'a str {
        self.name
    }

    #[cfg_attr(not(test), expect(dead_code, reason = "reached only by tests so far"))]
    pub(crate) const fn requires_session_state(&self) -> bool {
        self.requires_session_state
    }

    #[cfg_attr(not(test), expect(dead_code, reason = "reached only by tests so far"))]
    pub(crate) const fn hook(&self) -> &'a H {
        self.hook
    }
}

impl OwnedToolRegistrationAdapter {
    pub(crate) const fn index(&self) -> usize {
        self.index
    }

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

    pub(crate) fn invoke_after_tool_commit(
        &self,
        resources: CallbackResources<'_>,
        staged: &StagedTranscript,
        snapshot: &Arc<StepSnapshot>,
        result: &ToolResult,
    ) -> Vec<Item> {
        RegistrationAdapter {
            index: self.index,
            name: &self.name,
            requires_session_state: self.requires_session_state,
            hook: &*self.hook,
        }
        .invoke_after_tool_commit(resources, staged, snapshot, result)
    }
}

/// Caller-owned resources for exactly one registration callback invocation.
///
/// A controller must create a fresh `run_state::Store` per registration and a fresh
/// `StagedTranscript` per callback. This bundle deliberately carries neither a
/// registry nor commit authority; the controller decides whether successful
/// staged work is committed and always discards failed callback stages.
#[derive(Clone, Copy)]
pub(crate) struct CallbackResources<'a> {
    coord: &'a Coord,
    run_state: &'a run_state::Store,
    session_state: &'a session_state::Reader,
    session_state_writer: Option<&'a session_state::Writer>,
    emitter: &'a dyn Emitter,
}

/// Owned aliases of one registration's state capabilities.
///
/// These handles preserve the same slots and lease authority; they do not copy
/// state and never escape the crate-managed callback owner.
pub(crate) struct OwnedCallbackResources {
    run_state: run_state::Store,
    session_state: session_state::Reader,
    session_state_writer: Option<session_state::Writer>,
    callback_write_permit: Option<CallbackWritePermit>,
}

impl OwnedCallbackResources {
    /// Clones the runtime-owned half of this callback's write permit.
    pub(crate) fn callback_write_permit(&self) -> Option<CallbackWritePermit> {
        self.callback_write_permit.clone()
    }

    pub(crate) fn bind<'a>(
        &'a self,
        coord: &'a Coord,
        emitter: &'a dyn Emitter,
    ) -> CallbackResources<'a> {
        CallbackResources::new(
            coord,
            &self.run_state,
            &self.session_state,
            self.session_state_writer.as_ref(),
            emitter,
        )
    }
}

impl<'a> CallbackResources<'a> {
    pub(crate) const fn new(
        coord: &'a Coord,
        run_state: &'a run_state::Store,
        session_state: &'a session_state::Reader,
        session_state_writer: Option<&'a session_state::Writer>,
        emitter: &'a dyn Emitter,
    ) -> Self {
        Self {
            coord,
            run_state,
            session_state,
            session_state_writer,
            emitter,
        }
    }

    /// Clones only crate-private capability handles for a managed callback owner.
    ///
    /// A writable registration receives a fresh callback-local permit. The async
    /// owner retains the matching revocation handle, so aborting one callback does
    /// not revoke the registration's ordinary lease writer or any later callback.
    pub(crate) fn owned_handles(self) -> OwnedCallbackResources {
        let (session_state_writer, callback_write_permit) = match self.session_state_writer {
            Some(writer) => {
                let (writer, permit) = writer.clone_with_callback_permit();
                (Some(writer), Some(permit))
            }
            None => (None, None),
        };
        OwnedCallbackResources {
            run_state: self.run_state.clone_handle(),
            session_state: self.session_state.clone_handle(),
            session_state_writer,
            callback_write_permit,
        }
    }

    /// Rebinds only the callback coordinate while preserving this registration's
    /// private state and capability resources.
    pub(crate) const fn with_coord<'b>(self, coord: &'b Coord) -> CallbackResources<'b>
    where
        'a: 'b,
    {
        self.rebind(coord, self.emitter)
    }

    /// Rebinds one callback to its exact coordinate and outward emitter.
    ///
    /// Synchronous adapters use this crate-private bridge when only coordinate or
    /// emitter identity changes. Managed blocking callbacks instead bind the owned
    /// aliases above. Registration-private state capabilities remain unchanged.
    pub(crate) const fn rebind<'b>(
        self,
        coord: &'b Coord,
        emitter: &'b dyn Emitter,
    ) -> CallbackResources<'b>
    where
        'a: 'b,
    {
        CallbackResources {
            coord,
            run_state: self.run_state,
            session_state: self.session_state,
            session_state_writer: self.session_state_writer,
            emitter,
        }
    }

    const fn scope_factory(
        self,
        requires_session_state: bool,
        transcript: TranscriptSource<'a>,
    ) -> ScopeFactory<'a> {
        ScopeFactory::new(
            self.coord,
            self.run_state,
            self.session_state,
            self.session_state_writer,
            requires_session_state,
            transcript,
            self.emitter,
        )
    }
}

impl RegistrationAdapter<'_, dyn RunHooks> {
    /// Invokes only this registration's [`RunHooks::prepare`] callback.
    ///
    /// The caller supplies registration-private Run state plus callback-local
    /// Session-state and transcript overlays. Neither overlay is committed or
    /// discarded here; the caller owns resolution after observing this result.
    ///
    /// A returned [`PrepareDecision::Modify`] is validated here rather than by
    /// the caller, because this is the only frame that still knows *which*
    /// registration produced it: an empty replacement becomes a
    /// [`PrepareError::EmptyModify`] attributed to that name.
    pub(crate) fn invoke_prepare(
        &self,
        resources: CallbackResources<'_>,
        staged: &StagedTranscript,
        session_state_stage: Option<&session_state::StagedWriter>,
        base_snapshot: &Snapshot,
        input: &[Part],
        cancellation: &Token,
    ) -> Result<PrepareDecision, DispatchError> {
        if cancellation.is_cancelled() {
            return Err(DispatchError::Cancelled);
        }
        let factory = resources.scope_factory(
            self.requires_session_state,
            TranscriptSource::Reader(&staged.reader),
        );
        let scope = factory.prepare(staged, session_state_stage, base_snapshot, input);
        match self.hook.prepare(&scope) {
            Err(error) => Err(DispatchError::Callback(AttributedError {
                name: self.name.to_owned(),
                error,
            })),
            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
            Ok(PrepareDecision::Modify(replacement)) if replacement.is_empty() => {
                Err(DispatchError::Callback(AttributedError {
                    name: self.name.to_owned(),
                    error: HookError::new(PrepareError::EmptyModify),
                }))
            }
            Ok(decision) => Ok(decision),
        }
    }

    /// Invokes only this registration's [`RunHooks::compose_continuation`] callback.
    ///
    /// The decision governs a continuation request: a non-empty request asks the
    /// loop for another Turn rather than ending the Run. `continuation` carries
    /// what earlier registrations already asked for, so a registration can see,
    /// extend, replace or ignore it.
    ///
    /// Unlike [`RegistrationAdapter::invoke_prepare`] this validates nothing: an
    /// empty [`ContinuationDecision::Replace`] is a deliberate veto of a peer's
    /// request, not a rewrite that discards user content.
    pub(crate) fn invoke_compose_continuation(
        &self,
        resources: CallbackResources<'_>,
        staged: &StagedTranscript,
        continuation: &[Part],
        continuations: usize,
        turns: usize,
        cancellation: &Token,
    ) -> Result<ContinuationDecision, DispatchError> {
        if cancellation.is_cancelled() {
            return Err(DispatchError::Cancelled);
        }
        let factory = resources.scope_factory(
            self.requires_session_state,
            TranscriptSource::Reader(&staged.reader),
        );
        let scope = factory.compose_continuation(staged, continuation, continuations, turns);
        match self.hook.compose_continuation(&scope) {
            Err(error) => Err(DispatchError::Callback(AttributedError {
                name: self.name.to_owned(),
                error,
            })),
            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
            Ok(decision) => Ok(decision),
        }
    }

    /// Invokes only this registration's [`RunHooks::decide_stop`] callback.
    ///
    /// This is the sole surface through which a hook may stop a Run with a
    /// code; the loop converts a stopping decision into the single privately
    /// owned `EventStop` (ADR-007).
    pub(crate) fn invoke_decide_stop(
        &self,
        resources: CallbackResources<'_>,
        transcript: &SnapshotReader,
        cancellation: &Token,
    ) -> Result<StopDecision, DispatchError> {
        if cancellation.is_cancelled() {
            return Err(DispatchError::Cancelled);
        }
        let factory = resources.scope_factory(
            self.requires_session_state,
            TranscriptSource::Reader(transcript),
        );
        let scope = factory.decide_stop();
        match self.hook.decide_stop(&scope) {
            Err(error) => Err(DispatchError::Callback(AttributedError {
                name: self.name.to_owned(),
                error,
            })),
            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
            Ok(decision) => Ok(decision),
        }
    }
}

impl RegistrationAdapter<'_, dyn TurnStepHooks> {
    /// Invokes only this registration's `OnBeforeTurn` callback.
    ///
    /// `trigger` is what opened this Turn — the admitted Run input, a claimed
    /// `NextTurn` batch, or a continuation an earlier
    /// [`RunHooks::compose_continuation`] asked for.
    /// The returned items are appended before the Turn's first Step.
    pub(crate) fn invoke_before_turn(
        &self,
        resources: CallbackResources<'_>,
        staged: &StagedTranscript,
        trigger: &[Item],
        cancellation: &Token,
    ) -> Result<Vec<Item>, DispatchError> {
        self.invoke_turn(resources, staged, trigger, cancellation, TurnHook::Before)
    }

    /// Invokes only this registration's `OnAfterTurn` callback.
    pub(crate) fn invoke_after_turn(
        &self,
        resources: CallbackResources<'_>,
        staged: &StagedTranscript,
        trigger: &[Item],
        cancellation: &Token,
    ) -> Result<Vec<Item>, DispatchError> {
        self.invoke_turn(resources, staged, trigger, cancellation, TurnHook::After)
    }

    /// Runs one Turn-boundary callback.
    ///
    /// Both boundaries take the same scope and return the same shape, so the
    /// cancellation and attribution rules exist once and cannot drift apart.
    fn invoke_turn(
        &self,
        resources: CallbackResources<'_>,
        staged: &StagedTranscript,
        trigger: &[Item],
        cancellation: &Token,
        boundary: TurnHook,
    ) -> Result<Vec<Item>, DispatchError> {
        if cancellation.is_cancelled() {
            return Err(DispatchError::Cancelled);
        }
        let factory = resources.scope_factory(
            self.requires_session_state,
            TranscriptSource::Reader(&staged.reader),
        );
        let scope = factory.turn(staged, trigger);
        let result = match boundary {
            TurnHook::Before => self.hook.before_turn(&scope),
            TurnHook::After => self.hook.after_turn(&scope),
        };
        match result {
            Err(error) => Err(DispatchError::Callback(AttributedError {
                name: self.name.to_owned(),
                error,
            })),
            Ok(_items) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
            Ok(items) => Ok(items),
        }
    }

    /// Invokes only this registration's `OnAfterStep` callback.
    ///
    /// The decision decides whether the Turn continues past this Step; the items
    /// it carries are appended either way.
    pub(crate) fn invoke_after_step(
        &self,
        resources: CallbackResources<'_>,
        staged: &StagedTranscript,
        snapshot: &Arc<StepSnapshot>,
        cancellation: &Token,
    ) -> Result<AfterStepDecision, DispatchError> {
        if cancellation.is_cancelled() {
            return Err(DispatchError::Cancelled);
        }
        let factory = resources.scope_factory(
            self.requires_session_state,
            TranscriptSource::Reader(&staged.reader),
        );
        let scope = factory.after_step(staged, snapshot);
        match self.hook.after_step(&scope) {
            Err(error) => Err(DispatchError::Callback(AttributedError {
                name: self.name.to_owned(),
                error,
            })),
            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
            Ok(decision) => Ok(decision),
        }
    }

    /// Invokes only this registration's `OnBeforeStep` callback.
    ///
    /// The caller supplies registration-private Run state, a lease-bound writer,
    /// and a callback-local staged transcript. This method has no authority to
    /// commit that staged transcript into the live Session.
    pub(crate) fn invoke_before_step(
        &self,
        resources: CallbackResources<'_>,
        staged: &StagedTranscript,
        model: &Info,
        plan: &mut RequestPlan,
        cancellation: &Token,
    ) -> Result<Vec<Item>, DispatchError> {
        if cancellation.is_cancelled() {
            return Err(DispatchError::Cancelled);
        }
        let factory = resources.scope_factory(
            self.requires_session_state,
            TranscriptSource::Reader(&staged.reader),
        );
        let mut scope = factory.before_step(staged, model, plan);
        match self.hook.before_step(&mut scope) {
            Err(error) => Err(DispatchError::Callback(AttributedError {
                name: self.name.to_owned(),
                error,
            })),
            Ok(_items) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
            Ok(items) => Ok(items),
        }
    }
}

impl RegistrationAdapter<'_, dyn ObserverHooks> {
    /// Invokes only this registration's lifecycle observer.
    ///
    /// Callback audits are buffered locally. Buffer flushes and core panic
    /// audits remain outside the catch boundary, so core panics propagate.
    pub(crate) fn invoke_lifecycle(
        &self,
        resources: CallbackResources<'_>,
        transcript: TranscriptSource<'_>,
        snapshot: Option<&Arc<StepSnapshot>>,
        observation: &LifecycleObservation,
    ) {
        let factory = resources.scope_factory(self.requires_session_state, transcript);
        let pending = CallbackAuditBuffer::new();
        let scope = factory.observer(snapshot);
        let buffered_scope = scope.with_audit_sink(&pending);
        let panicked = match catch_unwind(AssertUnwindSafe(|| {
            self.hook.lifecycle(observation, &buffered_scope);
        })) {
            Ok(()) => false,
            Err(payload) => {
                std::mem::forget(payload);
                true
            }
        };
        pending.flush_to(resources.emitter);
        if panicked {
            emit_observer_panic(
                resources.emitter,
                self.name,
                lifecycle_hook_name(observation.kind()),
            );
        }
    }

    /// Invokes only this registration's synchronous admission observer.
    pub(crate) fn invoke_run_admitted(
        &self,
        resources: CallbackResources<'_>,
        transcript: &SnapshotReader,
    ) {
        let factory = resources.scope_factory(
            self.requires_session_state,
            TranscriptSource::Reader(transcript),
        );
        let scope = factory.read();
        let panicked = match catch_unwind(AssertUnwindSafe(|| self.hook.run_admitted(&scope))) {
            Ok(()) => false,
            Err(payload) => {
                std::mem::forget(payload);
                true
            }
        };
        if panicked {
            emit_observer_panic(resources.emitter, self.name, "OnRunAdmitted");
        }
    }

    /// Invokes only this registration's model-event observer.
    pub(crate) fn invoke_model_event(
        &self,
        resources: CallbackResources<'_>,
        transcript: &Snapshot,
        snapshot: Option<&Arc<StepSnapshot>>,
        event: &model::Event,
    ) {
        let factory = resources.scope_factory(
            self.requires_session_state,
            TranscriptSource::Snapshot(transcript),
        );
        let pending = CallbackAuditBuffer::new();
        let scope = factory.observer(snapshot);
        let buffered_scope = scope.with_audit_sink(&pending);
        let panicked = match catch_unwind(AssertUnwindSafe(|| {
            self.hook.model_event(&buffered_scope, event);
        })) {
            Ok(()) => false,
            Err(payload) => {
                std::mem::forget(payload);
                true
            }
        };
        pending.flush_to(resources.emitter);
        if panicked {
            emit_observer_panic(resources.emitter, self.name, "OnModelEvent");
        }
    }

    /// Invokes only this registration's serialized audit observer.
    pub(crate) fn invoke_audit_event(
        &self,
        resources: CallbackResources<'_>,
        transcript: &SnapshotReader,
        event: &audit::Event,
    ) {
        let factory = resources.scope_factory(
            self.requires_session_state,
            TranscriptSource::Reader(transcript),
        );
        let scope = factory.read();
        let panicked = match catch_unwind(AssertUnwindSafe(|| self.hook.audit_event(&scope, event)))
        {
            Ok(()) => false,
            Err(payload) => {
                std::mem::forget(payload);
                true
            }
        };
        if panicked {
            emit_observer_panic(resources.emitter, self.name, "OnAuditEvent");
        }
    }
}

impl RegistrationAdapter<'_, dyn InputHooks> {
    /// Invokes only this registration's `OnBeforeInputAdmit` callback.
    ///
    /// `OnBeforeInputAdmit` is infallible by trait shape, so cancellation is the
    /// only dispatch failure. The pre-callback check fails the claimed batch
    /// rather than admitting new work after cancellation.
    pub(crate) fn invoke_before_input_admit(
        &self,
        resources: CallbackResources<'_>,
        transcript: &SnapshotReader,
        target: InputTarget,
        items: &[Item],
        cancellation: &Token,
    ) -> Result<InputAdmitDecision, DispatchError> {
        if cancellation.is_cancelled() {
            return Err(DispatchError::Cancelled);
        }
        let factory = resources.scope_factory(
            self.requires_session_state,
            TranscriptSource::Reader(transcript),
        );
        let scope = factory.input_admit(target, items);
        let decision = self.hook.before_input_admit(&scope);
        if cancellation.is_cancelled() {
            return Err(DispatchError::Cancelled);
        }
        Ok(decision)
    }
}

fn validate_hook_assistant(
    registration: &str,
    assistant: &Assistant,
    snapshot: &StepSnapshot,
) -> Result<(), DispatchError> {
    // `Step::advance` in runtime/driver.rs freezes this transcript immediately
    // before formal RequestPlan validation. Reusing model.rs's projection and
    // global identity walk here keeps hook output on that same request grammar
    // while retaining the producing registration's attribution frame.
    model::validate_assistant(assistant, snapshot.tools().transcript().items()).map_err(|error| {
        DispatchError::Callback(AttributedError {
            name: registration.to_owned(),
            error: HookError::new(error),
        })
    })
}

impl RegistrationAdapter<'_, dyn ModelHooks> {
    /// Invokes only this registration's `OnBeforeModel` callback.
    ///
    /// A real callback error outranks a concurrently observed cancellation, so
    /// the cancellation re-check runs only on the `Ok` path.
    pub(crate) fn invoke_before_model(
        &self,
        resources: CallbackResources<'_>,
        snapshot: &Arc<StepSnapshot>,
        request: &Request,
        cancellation: &Token,
    ) -> Result<BeforeModelDecision, DispatchError> {
        if cancellation.is_cancelled() {
            return Err(DispatchError::Cancelled);
        }
        let factory = resources.scope_factory(
            self.requires_session_state,
            TranscriptSource::Snapshot(snapshot.tools().transcript()),
        );
        let scope = factory.before_model(snapshot, request);
        match self.hook.before_model(&scope) {
            Err(error) => Err(DispatchError::Callback(AttributedError {
                name: self.name.to_owned(),
                error,
            })),
            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
            Ok(decision) => {
                if let BeforeModelDecision::ShortCircuit(assistant) = &decision {
                    validate_hook_assistant(self.name, assistant, snapshot)?;
                }
                Ok(decision)
            }
        }
    }

    /// Invokes only this registration's `OnAfterModel` callback.
    #[expect(
        clippy::too_many_arguments,
        reason = "OnAfterModel observes five independent frozen model facts plus its resources"
    )]
    pub(crate) fn invoke_after_model(
        &self,
        resources: CallbackResources<'_>,
        snapshot: &Arc<StepSnapshot>,
        output: &Assistant,
        generated: bool,
        finish_reason: &str,
        completion: CompletionReason,
        cancellation: &Token,
    ) -> Result<AfterModelDecision, DispatchError> {
        if cancellation.is_cancelled() {
            return Err(DispatchError::Cancelled);
        }
        let factory = resources.scope_factory(
            self.requires_session_state,
            TranscriptSource::Snapshot(snapshot.tools().transcript()),
        );
        let scope = factory.after_model(snapshot, output, generated, finish_reason, completion);
        let decision = self.hook.after_model(&scope);
        if cancellation.is_cancelled() {
            return Err(DispatchError::Cancelled);
        }
        if let AfterModelDecision::Modify(assistant) = &decision {
            validate_hook_assistant(self.name, assistant, snapshot)?;
        }
        Ok(decision)
    }
}

impl RegistrationAdapter<'_, dyn ToolHooks> {
    /// Invokes only this registration's `OnBeforeToolCall` callback.
    ///
    /// This rewrite plane runs strictly before execution, which therefore sees
    /// the final effective call. Validation remains
    /// in this registration frame so an empty effective name is a typed,
    /// registration-attributed failure rather than a later coordinate panic.
    pub(crate) fn invoke_before_tool_call(
        &self,
        resources: CallbackResources<'_>,
        snapshot: &Arc<StepSnapshot>,
        call: &ToolCall,
        cancellation: &Token,
    ) -> Result<ToolCallDecision, DispatchError> {
        if cancellation.is_cancelled() {
            return Err(DispatchError::Cancelled);
        }
        let factory = resources.scope_factory(
            self.requires_session_state,
            TranscriptSource::Snapshot(snapshot.tools().transcript()),
        );
        let scope = factory.tool_call(snapshot, call);
        match self.hook.before_tool_call(&scope) {
            Err(error) => Err(DispatchError::Callback(AttributedError {
                name: self.name.to_owned(),
                error,
            })),
            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
            Ok(ToolCallDecision::Modify(modified)) if modified.name().as_str().is_empty() => {
                Err(DispatchError::Callback(AttributedError {
                    name: self.name.to_owned(),
                    error: HookError::new(model::RequestError::EmptyToolCallName {
                        call_id: call.id().as_str().to_owned(),
                    }),
                }))
            }
            Ok(decision) => Ok(decision),
        }
    }

    /// Invokes only this registration's `OnBeforeToolResult` callback.
    ///
    /// Each rewrite is observed by the next registration, so the committed
    /// append, the outward result event, and the `ToolCall` end observation all
    /// report the same output.
    pub(crate) fn invoke_before_tool_result(
        &self,
        resources: CallbackResources<'_>,
        snapshot: &Arc<StepSnapshot>,
        call: &ToolCall,
        disposition: CallDisposition,
        result: &ToolResult,
        cancellation: &Token,
    ) -> Result<ToolResultDecision, DispatchError> {
        if cancellation.is_cancelled() {
            return Err(DispatchError::Cancelled);
        }
        let factory = resources.scope_factory(
            self.requires_session_state,
            TranscriptSource::Snapshot(snapshot.tools().transcript()),
        );
        let scope = factory.tool_result(snapshot, call, disposition, result);
        match self.hook.before_tool_result(&scope) {
            Err(error) => Err(DispatchError::Callback(AttributedError {
                name: self.name.to_owned(),
                error,
            })),
            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
            Ok(decision) => Ok(decision),
        }
    }

    /// Invokes only this registration's [`ToolHooks::after_tool_commit`] callback.
    ///
    /// The result batch is already durable at this boundary, so this late hook
    /// cannot fail the batch and takes no cancellation token: cancelling here
    /// would drop items that belong to an already-committed batch.
    pub(crate) fn invoke_after_tool_commit(
        &self,
        resources: CallbackResources<'_>,
        staged: &StagedTranscript,
        snapshot: &Arc<StepSnapshot>,
        result: &ToolResult,
    ) -> Vec<Item> {
        let factory = resources.scope_factory(
            self.requires_session_state,
            TranscriptSource::Reader(&staged.reader),
        );
        let scope = factory.after_tool_commit(staged, snapshot, result);
        self.hook.after_tool_commit(&scope)
    }
}

impl RegistrationAdapter<'_, dyn TranscriptHooks> {
    /// Invokes only this registration's `OnTranscriptMutation` callback.
    ///
    /// The callback runs inside the controller's single pre-commit critical
    /// section and therefore receives a [`ReadScope`], which cannot re-enter the
    /// commit path or the outward boundary. Returning the reservation to
    /// the caller keeps abort/publish authority with the controller.
    pub(crate) fn invoke_reserve(
        &self,
        resources: CallbackResources<'_>,
        transcript: &Snapshot,
        mutation: &TranscriptMutation,
    ) -> Result<Box<dyn TranscriptReservation>, DispatchError> {
        let factory = resources.scope_factory(
            self.requires_session_state,
            TranscriptSource::Snapshot(transcript),
        );
        let scope = factory.read();
        self.hook.reserve(&scope, mutation).map_err(|error| {
            DispatchError::Callback(AttributedError {
                name: self.name.to_owned(),
                error,
            })
        })
    }
}

/// Fail-closed hook-roster error reported by [`crate::runtime::agent::Agent::new`].
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum RegistryError {
    /// A hook name was empty.
    EmptyName,
    /// A hook name appeared more than once.
    DuplicateName(String),
}

impl fmt::Display for RegistryError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyName => formatter.write_str("hook name must be non-empty"),
            Self::DuplicateName(name) => write!(formatter, "duplicate hook name: {name}"),
        }
    }
}

impl Error for RegistryError {}

/// One callback failure attributed to its stable registration name.
#[derive(Clone, Debug)]
pub struct AttributedError {
    name: String,
    error: HookError,
}

impl AttributedError {
    /// Returns the hook registration name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the unflattened callback error.
    #[must_use]
    pub const fn error(&self) -> &HookError {
        &self.error
    }
}

impl fmt::Display for AttributedError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "hook {} failed: {}", self.name, self.error)
    }
}

impl Error for AttributedError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(&self.error)
    }
}

/// Which of the two Turn-boundary callbacks one dispatch runs.
#[derive(Clone, Copy)]
enum TurnHook {
    Before,
    After,
}

/// Mutating dispatch failure with callback errors distinct from cancellation.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub(crate) enum DispatchError {
    /// A real callback failed and outranks a concurrently observed cancellation.
    Callback(AttributedError),
    /// Cancellation was observed after the preceding callback returned normally.
    Cancelled,
}

impl fmt::Display for DispatchError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Callback(failure) => write!(
                formatter,
                "hook {} failed: {}",
                failure.name(),
                failure.error()
            ),
            Self::Cancelled => formatter.write_str("cancelled around a callback"),
        }
    }
}

impl Error for DispatchError {
    /// Returns the attributed callback failure, chain intact.
    ///
    /// The immediate cause is the [`AttributedError`], not the [`HookError`]
    /// inside it. Returning the inner error directly would drop the one link
    /// that carries the registration name, so a caller walking the chain could
    /// read the failure but never learn which hook produced it. The name is
    /// not recoverable from anything below, and `AttributedError` yields the
    /// callback error from its own `source`, so nothing deeper is lost.
    ///
    /// Cancellation is the runtime's own observation rather than a report of
    /// something else, so it has no cause underneath it.
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Callback(failure) => Some(failure),
            Self::Cancelled => None,
        }
    }
}

/// Mutable hook roster consumed by [`crate::runtime::agent::Agent::new`].
///
/// Pass this builder directly to
/// [`agent::Config::new`](crate::runtime::agent::Config::new).
#[derive(Default)]
pub struct RegistryBuilder {
    hooks: Vec<Registration>,
}

impl fmt::Debug for RegistryBuilder {
    /// Lists the hook names registered so far, in registration order.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        debug_hook_names("RegistryBuilder", self.hooks.iter(), formatter)
    }
}

// A registry and the builder it is frozen from are both identified by the
// ordered hook roster they carry, and registration order is dispatch order.
fn debug_hook_names<'a>(
    name: &str,
    hooks: impl Iterator<Item = &'a Registration>,
    formatter: &mut fmt::Formatter<'_>,
) -> fmt::Result {
    formatter
        .debug_struct(name)
        .field(
            "hooks",
            &hooks
                .map(|registration| registration.name.as_str())
                .collect::<Vec<_>>(),
        )
        .finish()
}

impl RegistryBuilder {
    /// Creates an empty builder.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Appends one complete hook registration in observable fan-out order.
    pub fn register(&mut self, hook: Registration) -> &mut Self {
        self.hooks.push(hook);
        self
    }

    /// Validates and freezes the one runtime registry owned by an Agent.
    pub(crate) fn build_runtime(self) -> Result<RuntimeRegistry, RegistryError> {
        self.freeze().map(RuntimeRegistry::new)
    }

    fn freeze(self) -> Result<FrozenRegistry, RegistryError> {
        let mut names = std::collections::HashSet::new();
        let mut hooks = Vec::with_capacity(self.hooks.len());
        for registration in self.hooks {
            if registration.name.is_empty() {
                return Err(RegistryError::EmptyName);
            }
            if !names.insert(registration.name.clone()) {
                return Err(RegistryError::DuplicateName(registration.name));
            }
            hooks.push(RegisteredHook { registration });
        }
        Ok(FrozenRegistry {
            hooks: hooks.into(),
        })
    }
}

/// Frozen registration storage owned by the Agent runtime registry.
#[derive(Clone)]
pub(crate) struct FrozenRegistry {
    hooks: Arc<[RegisteredHook]>,
}

/// Agent-private runtime hook registry with stable registration-order fan-out.
#[derive(Clone)]
pub(crate) struct RuntimeRegistry {
    frozen: FrozenRegistry,
}

impl RuntimeRegistry {
    const fn new(frozen: FrozenRegistry) -> Self {
        Self { frozen }
    }
}

impl std::ops::Deref for RuntimeRegistry {
    type Target = FrozenRegistry;

    fn deref(&self) -> &Self::Target {
        &self.frozen
    }
}

impl fmt::Debug for RuntimeRegistry {
    /// Lists the frozen hook roster, in registration order.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        debug_hook_names(
            "RuntimeRegistry",
            self.frozen.hooks.iter().map(|hook| &hook.registration),
            formatter,
        )
    }
}

impl FrozenRegistry {
    /// Returns the number of named registrations.
    #[must_use]
    pub(crate) fn len(&self) -> usize {
        self.hooks.len()
    }

    /// Reports whether no hook is registered.
    #[cfg(test)]
    #[must_use]
    pub(crate) fn is_empty(&self) -> bool {
        self.hooks.is_empty()
    }

    /// Iterates stable registration names.
    #[must_use]
    pub(crate) fn names(&self) -> impl ExactSizeIterator<Item = &str> {
        self.hooks
            .iter()
            .map(|hook| hook.registration.name.as_str())
    }

    /// Reports whether any hook requires optional Session state support.
    #[must_use]
    pub(crate) fn requires_session_state(&self) -> bool {
        self.hooks
            .iter()
            .any(|hook| hook.registration.requires_session_state)
    }

    pub(crate) fn run_hooks(&self) -> impl Iterator<Item = RegistrationAdapter<'_, dyn RunHooks>> {
        self.hooks
            .iter()
            .enumerate()
            .filter_map(|(index, registered)| {
                registered
                    .registration
                    .run
                    .as_deref()
                    .map(|hook| RegistrationAdapter {
                        index,
                        name: registered.registration.name.as_str(),
                        requires_session_state: registered.registration.requires_session_state,
                        hook,
                    })
            })
    }

    pub(crate) fn input_hooks(
        &self,
    ) -> impl Iterator<Item = RegistrationAdapter<'_, dyn InputHooks>> {
        self.hooks
            .iter()
            .enumerate()
            .filter_map(|(index, registered)| {
                registered
                    .registration
                    .input
                    .as_deref()
                    .map(|hook| RegistrationAdapter {
                        index,
                        name: registered.registration.name.as_str(),
                        requires_session_state: registered.registration.requires_session_state,
                        hook,
                    })
            })
    }

    pub(crate) fn turn_step_hooks(
        &self,
    ) -> impl Iterator<Item = RegistrationAdapter<'_, dyn TurnStepHooks>> {
        self.hooks
            .iter()
            .enumerate()
            .filter_map(|(index, registered)| {
                registered
                    .registration
                    .turn_step
                    .as_deref()
                    .map(|hook| RegistrationAdapter {
                        index,
                        name: registered.registration.name.as_str(),
                        requires_session_state: registered.registration.requires_session_state,
                        hook,
                    })
            })
    }

    pub(crate) fn model_hooks(
        &self,
    ) -> impl Iterator<Item = RegistrationAdapter<'_, dyn ModelHooks>> {
        self.hooks
            .iter()
            .enumerate()
            .filter_map(|(index, registered)| {
                registered
                    .registration
                    .model
                    .as_deref()
                    .map(|hook| RegistrationAdapter {
                        index,
                        name: registered.registration.name.as_str(),
                        requires_session_state: registered.registration.requires_session_state,
                        hook,
                    })
            })
    }

    pub(crate) fn tool_hooks(
        &self,
    ) -> impl Iterator<Item = RegistrationAdapter<'_, dyn ToolHooks>> {
        self.hooks
            .iter()
            .enumerate()
            .filter_map(|(index, registered)| {
                registered
                    .registration
                    .tool
                    .as_deref()
                    .map(|hook| RegistrationAdapter {
                        index,
                        name: registered.registration.name.as_str(),
                        requires_session_state: registered.registration.requires_session_state,
                        hook,
                    })
            })
    }

    pub(crate) fn owned_tool_hooks(
        &self,
    ) -> impl Iterator<Item = OwnedToolRegistrationAdapter> + '_ {
        self.hooks
            .iter()
            .enumerate()
            .filter_map(|(index, registered)| {
                registered
                    .registration
                    .tool
                    .as_ref()
                    .map(|hook| OwnedToolRegistrationAdapter {
                        index,
                        name: registered.registration.name.clone(),
                        requires_session_state: registered.registration.requires_session_state,
                        hook: Arc::clone(hook),
                    })
            })
    }

    pub(crate) fn observer_hooks(
        &self,
    ) -> impl Iterator<Item = RegistrationAdapter<'_, dyn ObserverHooks>> {
        self.hooks
            .iter()
            .enumerate()
            .filter_map(|(index, registered)| {
                registered
                    .registration
                    .observer
                    .as_deref()
                    .map(|hook| RegistrationAdapter {
                        index,
                        name: registered.registration.name.as_str(),
                        requires_session_state: registered.registration.requires_session_state,
                        hook,
                    })
            })
    }

    pub(crate) fn transcript_hooks(
        &self,
    ) -> impl Iterator<Item = RegistrationAdapter<'_, dyn TranscriptHooks>> {
        self.hooks
            .iter()
            .enumerate()
            .filter_map(|(index, registered)| {
                registered
                    .registration
                    .transcript
                    .as_deref()
                    .map(|hook| RegistrationAdapter {
                        index,
                        name: registered.registration.name.as_str(),
                        requires_session_state: registered.registration.requires_session_state,
                        hook,
                    })
            })
    }

    /// Fans out Agent teardown and collects every error without short-circuiting.
    ///
    /// This operation is crate-private and reached in production only by
    /// [`crate::runtime::agent::Agent::close`]. A callback panic is isolated as a
    /// registration-attributed [`crate::runtime::agent::ClosePanickedError`]. Later
    /// callbacks still run, so one broken teardown cannot suppress its peers.
    ///
    /// The captured panic payload is deliberately forgotten rather than dropped:
    /// [`std::panic::panic_any`] permits payloads whose destructor also panics, and
    /// dropping such a payload would escape this isolation boundary. This leaks one
    /// captured payload value per panicking callback invocation, confined to this
    /// already-pathological path, in exchange for preserving the teardown guarantee
    /// for every legal payload.
    #[must_use]
    pub(crate) fn close(&self) -> Vec<AttributedError> {
        let panic_error = HookError::new(crate::runtime::agent::ClosePanickedError);
        let mut failures = Vec::new();
        for hook in self.hooks.iter() {
            let Some(teardown) = &hook.registration.teardown else {
                continue;
            };
            let error = match catch_unwind(AssertUnwindSafe(|| teardown.close())) {
                Ok(Ok(())) => continue,
                Ok(Err(error)) => error,
                Err(payload) => {
                    // A legal `panic_any` payload may itself panic in `Drop`. There
                    // is no generally safe way to destroy an arbitrary captured
                    // payload: catching that second panic only produces another
                    // arbitrary payload to dispose of. Leak exactly this payload
                    // instead, so teardown isolation remains total and later
                    // registrations still run.
                    std::mem::forget(payload);
                    panic_error.clone()
                }
            };
            failures.push(AttributedError {
                name: hook.registration.name.clone(),
                error,
            });
        }
        failures
    }
}

pub(crate) const fn lifecycle_hook_name(kind: LifecycleKind) -> &'static str {
    match kind {
        LifecycleKind::RunStart => "OnRunStart",
        LifecycleKind::RunEnd => "OnRunEnd",
        LifecycleKind::TurnStart => "OnTurnStart",
        LifecycleKind::TurnEnd => "OnTurnEnd",
        LifecycleKind::StepStart => "OnStepStart",
        LifecycleKind::StepEnd => "OnStepEnd",
        LifecycleKind::GenerationStart => "OnGenerationStart",
        LifecycleKind::GenerationEnd => "OnGenerationEnd",
        LifecycleKind::ToolCallStart => "OnToolCallStart",
        LifecycleKind::ToolCallEnd => "OnToolCallEnd",
    }
}

fn emit_observer_panic(emitter: &dyn Emitter, registration: &str, callback: &str) {
    let payload = format!("{registration}:{callback}")
        .into_bytes()
        .into_boxed_slice();
    emitter.emit_audit(audit::Event::new(
        "hook.observer_panic".to_owned(),
        Some(payload),
    ));
}

pub(crate) struct ScopeFactory<'a> {
    coord: &'a Coord,
    run_state: &'a run_state::Store,
    session_state: &'a session_state::Reader,
    session_state_writer: Option<&'a session_state::Writer>,
    requires_session_state: bool,
    transcript: TranscriptSource<'a>,
    emitter: &'a dyn Emitter,
    direct_audit: DirectAuditSink<'a>,
}

impl<'a> ScopeFactory<'a> {
    /// Builds scopes for one hook adapter. `requires_session_state` is taken
    /// from that adapter's frozen registration metadata; a writer is never
    /// exposed when the declaration is false.
    pub(crate) const fn new(
        coord: &'a Coord,
        run_state: &'a run_state::Store,
        session_state: &'a session_state::Reader,
        session_state_writer: Option<&'a session_state::Writer>,
        requires_session_state: bool,
        transcript: TranscriptSource<'a>,
        emitter: &'a dyn Emitter,
    ) -> Self {
        Self {
            coord,
            run_state,
            session_state,
            session_state_writer,
            requires_session_state,
            transcript,
            emitter,
            direct_audit: DirectAuditSink(emitter),
        }
    }

    const fn read_base(&self) -> ReadBase<'a> {
        ReadBase {
            session: SessionIdentity(self.coord),
            coord: self.coord,
            run_state: self.run_state,
            session_state: self.session_state,
            transcript: self.transcript,
        }
    }

    const fn write_base(&self) -> WriteBase<'a> {
        WriteBase {
            read: self.read_base(),
            session_state: if self.requires_session_state {
                self.session_state_writer
            } else {
                None
            },
        }
    }

    const fn control_base(&self) -> ControlBase<'a> {
        ControlBase {
            write: self.write_base(),
            emitter: self.emitter,
        }
    }

    const fn staged_base(&self, staged: &'a StagedTranscript) -> StagedBase<'a> {
        StagedBase {
            control: self.control_base(),
            staged,
        }
    }

    pub(crate) const fn prepare(
        &self,
        staged: &'a StagedTranscript,
        session_state_stage: Option<&'a session_state::StagedWriter>,
        base_snapshot: &'a Snapshot,
        input: &'a [Part],
    ) -> PrepareScope<'a> {
        PrepareScope {
            base: PrepareBase {
                read: self.read_base(),
                session_state: if self.requires_session_state {
                    session_state_stage
                } else {
                    None
                },
            },
            staged,
            base_snapshot,
            input,
        }
    }

    pub(crate) const fn compose_continuation(
        &self,
        staged: &'a StagedTranscript,
        continuation: &'a [Part],
        continuations: usize,
        turns: usize,
    ) -> ContinuationScope<'a> {
        ContinuationScope {
            base: self.staged_base(staged),
            continuation,
            continuations,
            turns,
        }
    }

    pub(crate) const fn decide_stop(&self) -> StopDecisionScope<'a> {
        StopDecisionScope {
            base: self.control_base(),
        }
    }

    pub(crate) const fn input_admit(
        &self,
        target: InputTarget,
        items: &'a [Item],
    ) -> InputAdmitScope<'a> {
        InputAdmitScope {
            base: self.control_base(),
            target,
            items,
        }
    }

    pub(crate) const fn turn(
        &self,
        staged: &'a StagedTranscript,
        trigger: &'a [Item],
    ) -> TurnScope<'a> {
        TurnScope {
            base: self.staged_base(staged),
            trigger,
        }
    }

    pub(crate) const fn before_step<'scope>(
        &'scope self,
        staged: &'scope StagedTranscript,
        model: &'scope Info,
        plan: &'scope mut RequestPlan,
    ) -> BeforeStepScope<'scope> {
        BeforeStepScope {
            base: self.staged_base(staged),
            model,
            plan,
        }
    }

    pub(crate) const fn after_step(
        &self,
        staged: &'a StagedTranscript,
        snapshot: &'a Arc<StepSnapshot>,
    ) -> AfterStepScope<'a> {
        AfterStepScope {
            base: self.staged_base(staged),
            snapshot,
        }
    }

    pub(crate) const fn before_model(
        &self,
        snapshot: &'a Arc<StepSnapshot>,
        request: &'a Request,
    ) -> BeforeModelScope<'a> {
        BeforeModelScope {
            base: self.control_base(),
            snapshot,
            request,
        }
    }

    pub(crate) const fn after_model(
        &self,
        snapshot: &'a Arc<StepSnapshot>,
        output: &'a Assistant,
        generated: bool,
        finish_reason: &'a str,
        completion: CompletionReason,
    ) -> AfterModelScope<'a> {
        AfterModelScope {
            base: self.control_base(),
            snapshot,
            output,
            generated,
            finish_reason,
            completion,
        }
    }

    pub(crate) const fn tool_call(
        &self,
        snapshot: &'a Arc<StepSnapshot>,
        call: &'a ToolCall,
    ) -> ToolCallScope<'a> {
        ToolCallScope {
            base: self.control_base(),
            snapshot,
            call,
        }
    }

    pub(crate) const fn tool_result(
        &self,
        snapshot: &'a Arc<StepSnapshot>,
        call: &'a ToolCall,
        disposition: CallDisposition,
        result: &'a ToolResult,
    ) -> ToolResultScope<'a> {
        ToolResultScope {
            base: self.control_base(),
            snapshot,
            call,
            disposition,
            result,
        }
    }

    pub(crate) const fn after_tool_commit(
        &self,
        staged: &'a StagedTranscript,
        snapshot: &'a Arc<StepSnapshot>,
        result: &'a ToolResult,
    ) -> AfterToolCommitScope<'a> {
        AfterToolCommitScope {
            base: self.staged_base(staged),
            snapshot,
            result,
        }
    }

    pub(crate) fn observer(&self, snapshot: Option<&'a Arc<StepSnapshot>>) -> ObserverScope<'_> {
        ObserverScope {
            base: self.read_base(),
            snapshot,
            audit_sink: &self.direct_audit,
        }
    }

    pub(crate) const fn read(&self) -> ReadScope<'a> {
        ReadScope {
            base: self.read_base(),
        }
    }
}