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
//! Owned outward events and the three strong-acceptance delivery seams.
//!
//! Ownership of the outward plane is settled by ADR-007: the loop produces
//! events, the consumer decides the three strong seams, and a successful channel
//! send is never treated as acceptance.
//!
//! This plane is an observable projection, not transcript serialization. Content
//! is published before the corresponding transcript append linearizes and exposes
//! renderable text plus provider item identity, not the complete
//! [`SegmentExtensions`](crate::value::content::SegmentExtensions) or record-level
//! provider data. Ordinary publication also fails closed after interruption, so a
//! committed input may have no `InputAdmitted` projection. Current history comes
//! from the Transcript; a composition layer that needs a byte-faithful resumable
//! journal uses [`TranscriptHooks`](super::hook::TranscriptHooks) and restores a
//! [`Snapshot`](crate::transcript::store::Snapshot).

use std::error::Error;
use std::fmt;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use std::sync::{Arc, Mutex as SyncMutex};
use std::task::{Context, Poll};

use crate::cancel::Token;
#[cfg(test)]
use tokio::sync::Semaphore;
use tokio::sync::{Mutex, Notify, mpsc};

use crate::audit;
use crate::redact;
use crate::transcript::item;
use crate::value::lifecycle::{Coord, Outcome};
use crate::value::tool_call::ToolCall;

/// The observable category of one outward event.
///
/// The set answers one question: what must a consumer be able to *distinguish*
/// in order to render an agent or host a Run? A fact that can be read from an
/// existing category plus its payload is deliberately not a category of its own,
/// and a fact that belongs to a policy rather than to the runtime is not one
/// either — see ADR-021 for the per-candidate reasoning.
///
/// Two absences are decisions rather than gaps:
///
/// - **There is no `GenerationStart`.** Hooks observe one
///   ([`hook::LifecycleObservation::GenerationStart`]) because its payload is
///   the frozen [`model::Request`] their own [`ModelHooks::before_model`] just
///   finished editing. A consumer must not receive that value: it is the whole projected
///   history plus the system instruction, which the consumer can already read
///   from the transcript and which no event should copy onto a stream that may be
///   logged. What a consumer needs — that a generation opened, and under which
///   coordinate — is [`Kind::StepStart`], which the phase machine publishes
///   exactly once per generation, and the [`Coord`] every later event carries.
/// - **There is no interrupted category.** An interruption closes the outward
///   lane before anything else can be published (C18/C20), so such a category
///   could not have a production emitter — which is exactly the state this set
///   was re-derived to leave. A consumer learns an interruption from its event
///   stream closing and from [`run::Terminal`], which is observable only after
///   cleanup has completed (C25).
///
/// One presence is worth naming for the same reason:
///
/// - **Input admission is a category, because nothing else could carry it.**
///   An admitted input batch is the one kind of transcript record reef commits
///   that the model did not produce, so it needs its own outward representation.
///   That representation is best-effort under the fail-closed interruption rule,
///   not an authoritative recovery record. A start or `NextTurn` batch opens a
///   Turn; a `NextStep` batch
///   is admitted at a Step boundary and does not. Deriving admission from
///   [`Kind::TurnStart`] therefore fails in both directions — a Turn also opens
///   without any admission at all, and a `NextStep` batch opens no Turn — and
///   the record itself appears in no other category. See
///   [`Kind::InputAdmitted`] and ADR-025.
///
/// [`hook::LifecycleObservation::GenerationStart`]: super::hook::LifecycleObservation::GenerationStart
/// [`ModelHooks::before_model`]: super::hook::ModelHooks::before_model
/// [`model::Request`]: super::model::Request
/// [`run::Terminal`]: super::run::Terminal
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Kind {
    /// Incremental answer text.
    TextDelta,
    /// Consolidated answer text.
    Text,
    /// Incremental model reasoning.
    ThinkingDelta,
    /// Consolidated model reasoning.
    Thinking,
    /// A turn began.
    TurnStart,
    /// A turn ended.
    TurnEnd,
    /// A step began.
    StepStart,
    /// A step ended.
    StepEnd,
    /// A real model generation ended.
    GenerationEnd,
    /// The model produced a complete tool call.
    ToolCall,
    /// A tool result was finalized.
    ToolResult,
    /// A recoverable extension degradation.
    Error,
    /// A non-model-visible audit fact.
    Audit,
    /// A policy requested a graceful run stop.
    Stop,
    /// An input batch was accepted and atomically recorded.
    ///
    /// Attempted once per batch, after the transcript append has committed and
    /// before the Turn or Step that batch opens. So it is a statement of fact,
    /// not a request: by the time a consumer sees it the record exists and
    /// nothing can take it back. The converse is not promised: C18/C20 suppress
    /// this ordinary event if interruption latches after commit. The Transcript
    /// remains authoritative. [`Event::admitted_input`] carries the projected
    /// items and which of the three routes they arrived by.
    ///
    /// A registration that wants a say runs at
    /// [`InputHooks::before_input_admit`], which is the boundary *before* the
    /// commit and the only place a batch can still be rewritten or refused.
    ///
    /// [`InputHooks::before_input_admit`]: super::hook::InputHooks::before_input_admit
    InputAdmitted,
    /// A claimed input batch was permanently refused.
    ///
    /// Only a mailbox batch can reach this. A refusal is one of the two terminal
    /// states of a claimed batch — the other is a commit — so it is not
    /// restored to the [`InputMailbox`], nothing will retry it, and the sender
    /// would otherwise wait forever for an answer that is never coming.
    /// [`Event::rejection_reason`] carries the reason the refusing registration
    /// gave.
    ///
    /// [`InputMailbox`]: super::session::InputMailbox
    InputRejected,
}

/// Which of reef's three input routes produced an admitted batch.
///
/// The routes are indistinguishable in the transcript — every one of them
/// records an [`item::User`] and nothing in the record says which — so this is
/// stated here or nowhere. A consumer that renders a conversation needs it: a
/// continuation is the agent asking itself to keep going, and drawing it as
/// something the human said would be wrong.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum InputOrigin {
    /// The input [`Agent::start`] admitted, recorded before the loop began.
    ///
    /// This is the only route that can be rewritten before it is recorded, by a
    /// [`RunHooks::prepare`](super::hook::RunHooks::prepare) registration, which
    /// is why the batch is reported rather than assumed to be what the caller
    /// passed.
    ///
    /// [`Agent::start`]: super::agent::Agent::start
    Start,
    /// A batch claimed from the Session's [`InputMailbox`].
    ///
    /// [`InputMailbox`]: super::session::InputMailbox
    Mailbox,
    /// Items a [`RunHooks::compose_continuation`](super::hook::RunHooks::compose_continuation)
    /// registration composed to open another Turn.
    Continuation,
}

/// One input batch exactly as it was recorded.
///
/// The items are the committed records and not the parts a caller submitted:
/// [`RunHooks::prepare`](super::hook::RunHooks::prepare) and
/// [`InputHooks::before_input_admit`](super::hook::InputHooks::before_input_admit)
/// both rewrite input before it is recorded, so what the transcript holds is the
/// only version worth reporting.
#[derive(Clone, Debug)]
pub struct AdmittedInput {
    origin: InputOrigin,
    items: Vec<item::Item>,
}

impl AdmittedInput {
    /// Returns which route this batch arrived by.
    #[must_use]
    pub const fn origin(&self) -> InputOrigin {
        self.origin
    }

    /// Returns the recorded items in transcript order.
    #[must_use]
    pub fn items(&self) -> &[item::Item] {
        &self.items
    }
}

/// One of the only three boundaries requiring an explicit consumer decision.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum DecisionPoint {
    /// Before tool-hook policy and executor processing.
    ToolCall,
    /// Before later result or lifecycle publication.
    ToolResult,
    /// Before work following [`ToolHooks::after_tool_commit`](super::hook::ToolHooks::after_tool_commit).
    AfterToolCommit,
}

/// A validated, nonempty opaque stop classification.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StopCode(String);

impl StopCode {
    /// Validates an opaque stop code.
    ///
    /// # Errors
    ///
    /// [`ValidationError::EmptyStopCode`] if `code` has no characters. Core never
    /// interprets the code, so an empty one would tell a consumer only that
    /// something stopped the Run and refuse to say what — which is the one thing
    /// this value exists to carry.
    pub fn new(code: String) -> Result<Self, ValidationError> {
        if code.is_empty() {
            return Err(ValidationError::EmptyStopCode);
        }
        Ok(Self(code))
    }

    /// Returns the opaque code.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// A stable outward-event validation failure.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ValidationError {
    /// An audit kind was empty.
    EmptyAuditKind,
    /// A tool-call identity was empty.
    EmptyToolCallId,
    /// A tool name was empty.
    EmptyToolName,
    /// A stop code was empty.
    EmptyStopCode,
    /// The event category and its private payload disagreed.
    PayloadMismatch,
    /// A private producer selected a decision point inconsistent with the event.
    InvalidDecisionPoint,
}

impl fmt::Display for ValidationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::EmptyAuditKind => "event audit kind must be non-empty",
            Self::EmptyToolCallId => "event tool-call identity must be non-empty",
            Self::EmptyToolName => "event tool name must be non-empty",
            Self::EmptyStopCode => "event stop code must be non-empty",
            Self::PayloadMismatch => "event category and payload do not match",
            Self::InvalidDecisionPoint => "event used an invalid decision point",
        })
    }
}

impl Error for ValidationError {}

#[derive(Clone)]
enum Payload {
    Text(String),
    Lifecycle(Option<Outcome>),
    ToolCall(ToolCall),
    ToolResult(item::ToolResult),
    Audit(audit::Event),
    Error(Arc<dyn Error + Send + Sync>),
    Stop(StopCode),
    Input(AdmittedInput),
    Rejection(String),
}

impl fmt::Debug for Payload {
    /// Sizes the one variant that carries model text and flattens the error.
    ///
    /// `Text` is answer or reasoning content on its way to a consumer. `Error`
    /// holds an arbitrary third-party failure whose own `Debug` this crate does
    /// not control, so it is rendered through `Display`, which is the operator
    /// diagnostic the type is for. Every other variant already redacts itself.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Text(text) => formatter
                .debug_tuple("Text")
                .field(&redact::Bytes(text.len()))
                .finish(),
            Self::Lifecycle(outcome) => formatter.debug_tuple("Lifecycle").field(outcome).finish(),
            Self::ToolCall(call) => formatter.debug_tuple("ToolCall").field(call).finish(),
            Self::ToolResult(result) => formatter.debug_tuple("ToolResult").field(result).finish(),
            Self::Audit(audit) => formatter.debug_tuple("Audit").field(audit).finish(),
            Self::Error(error) => formatter
                .debug_tuple("Error")
                .field(&error.to_string())
                .finish(),
            Self::Stop(code) => formatter.debug_tuple("Stop").field(code).finish(),
            // `Item` redacts itself, so the batch prints its own way; the reason
            // is a diagnostic a registration wrote for an operator to read.
            Self::Input(input) => formatter.debug_tuple("Input").field(input).finish(),
            Self::Rejection(reason) => formatter.debug_tuple("Rejection").field(reason).finish(),
        }
    }
}

/// An immutable outward event; loop-owned variants have no public constructors.
#[derive(Clone, Debug)]
pub struct Event {
    kind: Kind,
    coord: Option<Coord>,
    item_id: Option<String>,
    payload: Payload,
}

impl Event {
    /// Constructs a validated extension-produced audit event.
    ///
    /// # Errors
    ///
    /// [`ValidationError::EmptyAuditKind`] if the audit fact does not name a
    /// kind. An audit fact is classified by its kind, and an unclassifiable one
    /// cannot be filtered, routed, or counted by whoever consumes the stream.
    ///
    /// This is the only construction check on the two event kinds an extension
    /// may build. The remaining [`ValidationError`] variants describe private
    /// producer mistakes and cannot be reached from here.
    pub fn from_audit(audit: audit::Event) -> Result<Self, ValidationError> {
        if audit.kind().is_empty() {
            return Err(ValidationError::EmptyAuditKind);
        }
        Ok(Self {
            kind: Kind::Audit,
            coord: None,
            item_id: None,
            payload: Payload::Audit(audit),
        })
    }

    /// Constructs a validated extension-produced non-fatal error event.
    #[must_use]
    pub fn from_error(error: Arc<dyn Error + Send + Sync>) -> Self {
        Self {
            kind: Kind::Error,
            coord: None,
            item_id: None,
            payload: Payload::Error(error),
        }
    }

    /// Returns the event category.
    #[must_use]
    pub const fn kind(&self) -> Kind {
        self.kind
    }

    /// Returns the runtime-stamped coordinate, when applicable.
    #[must_use]
    pub const fn coord(&self) -> Option<&Coord> {
        self.coord.as_ref()
    }

    /// Returns the provider's identity for the content item this event is part of.
    ///
    /// [`coord`](Self::coord) says where the event sits in reef's own
    /// Run/Turn/Step structure; this says which of the provider's items it
    /// belongs to. A single generation can produce several — an answer alongside
    /// reasoning, or several separate answer items — and they interleave, so a
    /// consumer rendering incrementally needs this to put each fragment under
    /// the right heading rather than concatenating everything a Step emitted.
    ///
    /// Present on all four content kinds, and the same string on both sides: a
    /// delta reports the identity of the
    /// [`model::Event::ContentDelta`](crate::runtime::model::Event::ContentDelta)
    /// it projects, the consolidated event reports the one the committed
    /// [`Segment`](crate::value::content::Segment) kept, and
    /// [`model::StreamGrammar`](crate::runtime::model::StreamGrammar) refuses a
    /// stream whose final does not close the identity its deltas opened. So
    /// grouping deltas by this value and then matching the consolidated event to
    /// the same group is sound, and it stays sound for a provider that streams
    /// no deltas at all.
    ///
    /// `None` on every other kind, and on a content event whose segment no
    /// provider produced — one an
    /// [`OnAfterModel`](crate::runtime::hook::ModelHooks::after_model)
    /// registration composed, for instance. A registration that replaces
    /// assistant content decides its identity too, including deciding it has
    /// none, and what reaches a consumer here is always the identity of the
    /// content it is attached to rather than of the content the provider
    /// originally sent.
    #[must_use]
    pub fn item_id(&self) -> Option<&str> {
        self.item_id.as_deref()
    }

    /// Returns text carried by a text or thinking event.
    #[must_use]
    pub fn text(&self) -> Option<&str> {
        match &self.payload {
            Payload::Text(text) => Some(text),
            _ => None,
        }
    }

    /// Returns a tool-call payload.
    #[must_use]
    pub const fn tool_call(&self) -> Option<&ToolCall> {
        match &self.payload {
            Payload::ToolCall(call) => Some(call),
            _ => None,
        }
    }

    /// Returns a tool-result payload.
    #[must_use]
    pub const fn tool_result(&self) -> Option<&item::ToolResult> {
        match &self.payload {
            Payload::ToolResult(result) => Some(result),
            _ => None,
        }
    }

    /// Returns the committed batch an [`InputAdmitted`](Kind::InputAdmitted) event projects.
    ///
    /// Never empty: an empty batch is refused before it can be recorded, because
    /// recording one would assert that somebody said nothing.
    #[must_use]
    pub const fn admitted_input(&self) -> Option<&AdmittedInput> {
        match &self.payload {
            Payload::Input(input) => Some(input),
            _ => None,
        }
    }

    /// Returns why an [`InputRejected`](Kind::InputRejected) event refused a batch.
    ///
    /// Never empty: a rejection with no reason is a hook defect that fails the
    /// Run, because the reason is the only thing the refusal leaves behind.
    #[must_use]
    pub fn rejection_reason(&self) -> Option<&str> {
        match &self.payload {
            Payload::Rejection(reason) => Some(reason),
            _ => None,
        }
    }

    /// Returns a lifecycle end outcome.
    #[must_use]
    pub const fn outcome(&self) -> Option<Outcome> {
        match self.payload {
            Payload::Lifecycle(outcome) => outcome,
            _ => None,
        }
    }

    /// Returns an audit payload.
    #[must_use]
    pub const fn as_audit(&self) -> Option<&audit::Event> {
        match &self.payload {
            Payload::Audit(audit) => Some(audit),
            _ => None,
        }
    }

    /// Returns a recoverable error payload.
    #[must_use]
    pub fn as_error(&self) -> Option<&(dyn Error + Send + Sync)> {
        match &self.payload {
            Payload::Error(error) => Some(error.as_ref()),
            _ => None,
        }
    }

    /// Returns the opaque stop classification.
    #[must_use]
    pub const fn stop_code(&self) -> Option<&StopCode> {
        match &self.payload {
            Payload::Stop(code) => Some(code),
            _ => None,
        }
    }

    const fn driver_text(kind: Kind, text: String, coord: Coord, item_id: Option<String>) -> Self {
        Self {
            kind,
            coord: Some(coord),
            item_id,
            payload: Payload::Text(text),
        }
    }

    const fn driver_lifecycle(kind: Kind, outcome: Option<Outcome>, coord: Coord) -> Self {
        Self {
            kind,
            coord: Some(coord),
            item_id: None,
            payload: Payload::Lifecycle(outcome),
        }
    }

    const fn driver_tool_call(call: ToolCall, coord: Coord) -> Self {
        Self {
            kind: Kind::ToolCall,
            coord: Some(coord),
            item_id: None,
            payload: Payload::ToolCall(call),
        }
    }

    const fn driver_tool_result(result: item::ToolResult, coord: Coord) -> Self {
        Self {
            kind: Kind::ToolResult,
            coord: Some(coord),
            item_id: None,
            payload: Payload::ToolResult(result),
        }
    }

    const fn driver_stop(code: StopCode, coord: Coord) -> Self {
        Self {
            kind: Kind::Stop,
            coord: Some(coord),
            item_id: None,
            payload: Payload::Stop(code),
        }
    }

    const fn driver_input_admitted(
        origin: InputOrigin,
        items: Vec<item::Item>,
        coord: Coord,
    ) -> Self {
        Self {
            kind: Kind::InputAdmitted,
            coord: Some(coord),
            item_id: None,
            payload: Payload::Input(AdmittedInput { origin, items }),
        }
    }

    const fn driver_input_rejected(reason: String, coord: Coord) -> Self {
        Self {
            kind: Kind::InputRejected,
            coord: Some(coord),
            item_id: None,
            payload: Payload::Rejection(reason),
        }
    }

    fn validate(&self, decision_point: Option<DecisionPoint>) -> Result<(), ValidationError> {
        if !payload_matches(self.kind, &self.payload) {
            return Err(ValidationError::PayloadMismatch);
        }
        match &self.payload {
            Payload::ToolCall(call) if call.id().as_str().is_empty() => {
                Err(ValidationError::EmptyToolCallId)
            }
            Payload::ToolCall(call) if call.name().as_str().is_empty() => {
                Err(ValidationError::EmptyToolName)
            }
            Payload::ToolResult(result) if result.call_id().as_str().is_empty() => {
                Err(ValidationError::EmptyToolCallId)
            }
            Payload::ToolResult(result) if result.tool_name().as_str().is_empty() => {
                Err(ValidationError::EmptyToolName)
            }
            Payload::Audit(audit) if audit.kind().is_empty() => {
                Err(ValidationError::EmptyAuditKind)
            }
            Payload::Stop(code) if code.as_str().is_empty() => Err(ValidationError::EmptyStopCode),
            _ if decision_point != expected_decision_point(self.kind, decision_point) => {
                Err(ValidationError::InvalidDecisionPoint)
            }
            _ => Ok(()),
        }
    }
}

const fn payload_matches(kind: Kind, payload: &Payload) -> bool {
    matches!(
        (kind, payload),
        (
            Kind::TextDelta | Kind::Text | Kind::ThinkingDelta | Kind::Thinking,
            Payload::Text(_)
        ) | (Kind::TurnStart | Kind::StepStart, Payload::Lifecycle(None))
            | (
                Kind::TurnEnd | Kind::StepEnd | Kind::GenerationEnd,
                Payload::Lifecycle(Some(_))
            )
            | (Kind::ToolCall, Payload::ToolCall(_))
            | (Kind::ToolResult, Payload::ToolResult(_))
            | (Kind::Error, Payload::Error(_))
            | (Kind::Audit, Payload::Audit(_))
            | (Kind::Stop, Payload::Stop(_))
            | (Kind::InputAdmitted, Payload::Input(_))
            | (Kind::InputRejected, Payload::Rejection(_))
    )
}

fn expected_decision_point(kind: Kind, requested: Option<DecisionPoint>) -> Option<DecisionPoint> {
    match kind {
        Kind::ToolCall => Some(DecisionPoint::ToolCall),
        Kind::ToolResult => Some(DecisionPoint::ToolResult),
        Kind::Audit | Kind::Error if requested == Some(DecisionPoint::AfterToolCommit) => requested,
        _ => None,
    }
}

/// A delivery decision was already completed.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum DecisionError {
    /// This ordinary event has no decision barrier.
    NotRequired,
    /// Another decision or cancellation already won.
    AlreadyDecided,
}

impl fmt::Display for DecisionError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::NotRequired => "event delivery does not require acceptance",
            Self::AlreadyDecided => "event delivery was already decided",
        })
    }
}

impl Error for DecisionError {}

const PENDING: u8 = 0;
const ACCEPTED: u8 = 1;
const REJECTED: u8 = 2;
const CANCELED: u8 = 3;

struct Decision {
    value: AtomicU8,
    changed: Notify,
    /// The composite interruption token this wait must wake on.
    cancel: Token,
    /// The run's shared single linearization point for its nonfatal cause.
    ///
    /// The composite token alone cannot distinguish parent cancellation from the
    /// child cancellation caused by this run's own `request_stop`/Drop, so every
    /// interruption value is selected here instead of from the token.
    nonfatal: Arc<NonfatalCause>,
    #[cfg(test)]
    after_pending_check: SyncMutex<Option<WaitBarriers>>,
}

#[cfg(test)]
struct WaitBarriers {
    checked: Arc<std::sync::Barrier>,
    resume: Arc<std::sync::Barrier>,
}

impl Decision {
    fn decide(&self, value: u8) -> Result<(), DecisionError> {
        self.value
            .compare_exchange(PENDING, value, Ordering::AcqRel, Ordering::Acquire)
            .map(|_| self.changed.notify_waiters())
            .map_err(|_| DecisionError::AlreadyDecided)
    }

    fn decide_consumer(&self, value: u8) -> Result<(), DecisionError> {
        if self.cancel.is_cancelled() {
            let _already_decided = self.decide(self.nonfatal.interrupted_decision());
            Err(DecisionError::AlreadyDecided)
        } else {
            self.decide(value)
        }
    }

    fn abandon(&self) -> Result<(), DecisionError> {
        let value = if self.cancel.is_cancelled() {
            self.nonfatal.interrupted_decision()
        } else {
            REJECTED
        };
        self.decide(value)
    }

    async fn wait(&self) -> StrongDecision {
        loop {
            let changed = self.changed.notified();
            tokio::pin!(changed);
            let _already_ready = changed.as_mut().enable();
            match self.value.load(Ordering::Acquire) {
                ACCEPTED => return StrongDecision::Accepted,
                REJECTED => return StrongDecision::Rejected,
                CANCELED => return StrongDecision::Cancelled,
                _ => {
                    #[cfg(test)]
                    self.pause_after_pending_check();
                    tokio::select! {
                        biased;
                        () = self.cancel.cancelled() => {
                            let _already_decided =
                                self.decide(self.nonfatal.interrupted_decision());
                        }
                        () = &mut changed => {}
                    }
                }
            }
        }
    }

    #[cfg(test)]
    fn pause_after_pending_check(&self) {
        let barriers = self
            .after_pending_check
            .lock()
            .expect("event wait barrier lock poisoned")
            .take();
        if let Some(barriers) = barriers {
            barriers.checked.wait();
            barriers.resume.wait();
        }
    }
}

/// One event and, at a strong decision point, its exactly-once decision guard.
///
/// Most deliveries are ordinary transport: read the [`event`](Delivery::event)
/// and move on. Three decision points are rendezvous the Run is blocked on, and
/// it does not proceed until this delivery is [`accept`](Delivery::accept)ed or
/// [`reject`](Delivery::reject)ed. Dropping one undecided rejects it.
///
/// Do not infer this from [`Event::kind`].
/// [`AfterToolCommit`](DecisionPoint::AfterToolCommit) can accompany either an
/// [`Audit`](Kind::Audit) or [`Error`](Kind::Error) event, and either kind can
/// also be an ordinary delivery. Always call
/// [`decision_point`](Delivery::decision_point) for each delivery; that makes the
/// whole acceptance protocol one line:
///
/// ```
/// # use reef_core::runtime::event;
/// # fn handle(delivery: &event::Delivery) -> Result<(), event::DecisionError> {
/// if delivery.decision_point().is_some() {
///     delivery.accept()?;
/// }
/// # Ok(())
/// # }
/// ```
///
/// A consumer that means to refuse further work — a policy that says no, a host
/// shutting down — calls [`reject`](Delivery::reject) instead. At
/// [`ToolCall`](DecisionPoint::ToolCall), rejection prevents tool-hook and executor
/// processing. At [`ToolResult`](DecisionPoint::ToolResult) or
/// [`AfterToolCommit`](DecisionPoint::AfterToolCommit), execution and commit have
/// already happened; rejection does not undo those facts and only prevents later
/// work.
pub struct Delivery {
    event: Event,
    decision_point: Option<DecisionPoint>,
    decision: Option<Arc<Decision>>,
}

impl fmt::Debug for Delivery {
    /// Shows the event, the decision point, and whether a decision is owed.
    ///
    /// The decision guard is reported by presence rather than by state: reading
    /// its state would mean loading the very atomic whose exactly-once
    /// transition the guard exists to serialise, and a formatter has no business
    /// participating in that handshake.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Delivery")
            .field("event", &self.event)
            .field("decision_point", &self.decision_point)
            .field("decision", &redact::Presence(self.decision.is_some()))
            .finish()
    }
}

impl Delivery {
    /// Returns the immutable event.
    #[must_use]
    pub const fn event(&self) -> &Event {
        &self.event
    }

    /// Returns the strong decision point, or `None` for ordinary transport delivery.
    #[must_use]
    pub const fn decision_point(&self) -> Option<DecisionPoint> {
        self.decision_point
    }

    /// Accepts this strong boundary exactly once.
    ///
    /// # Errors
    ///
    /// - [`DecisionError::NotRequired`] if this is ordinary transport delivery
    ///   rather than one of the three strong seams. Check
    ///   [`decision_point`](Self::decision_point) to tell them apart; nothing is owed
    ///   for an ordinary delivery and nothing happens if it is dropped undecided.
    /// - [`DecisionError::AlreadyDecided`] if this delivery has already been
    ///   decided, or if cancellation resolved it first. A cancelled Run's
    ///   deliveries report this even on a first call, because acceptance would
    ///   authorize work the Run is already unwinding out of — so a consumer
    ///   cannot treat this variant as "somebody else said yes".
    ///
    /// Either way the governed work does not proceed on this call's authority,
    /// and the decision that did win is not displaced.
    pub fn accept(&self) -> Result<(), DecisionError> {
        self.decision
            .as_ref()
            .ok_or(DecisionError::NotRequired)?
            .decide_consumer(ACCEPTED)
    }

    /// Rejects this strong boundary exactly once.
    ///
    /// At [`DecisionPoint::ToolCall`], rejection prevents subsequent tool-hook and
    /// executor processing. At [`DecisionPoint::ToolResult`] or
    /// [`DecisionPoint::AfterToolCommit`], the tool has already executed and its
    /// result has already been committed. Rejection does not undo those facts; it
    /// only prevents later work.
    ///
    /// # Errors
    ///
    /// [`DecisionError::NotRequired`] if this is ordinary transport delivery, or
    /// [`DecisionError::AlreadyDecided`] if a decision or a cancellation already
    /// won — the same two conditions [`accept`](Self::accept) reports, for the
    /// same reasons.
    ///
    /// Neither is a reason to retry. `NotRequired` means no decision was owed;
    /// `AlreadyDecided` means the winning decision remains in force, and this
    /// error does not reveal whether it accepted, rejected, or cancelled the
    /// boundary.
    pub fn reject(&self) -> Result<(), DecisionError> {
        self.decision
            .as_ref()
            .ok_or(DecisionError::NotRequired)?
            .decide_consumer(REJECTED)
    }
}

impl Drop for Delivery {
    fn drop(&mut self) {
        if let Some(decision) = &self.decision {
            let _already_decided = decision.abandon();
        }
    }
}

/// The unique consumer of a run's outward events.
///
/// There is exactly one of these per Run. An observable start receives it atomically
/// from [`Agent::start_observed`](crate::runtime::agent::Agent::start_observed); the
/// compatibility [`Run::take_events`](crate::runtime::run::Run::take_events) path hands
/// it over once after `Agent::start`. Draining it to `None` is how a consumer knows
/// the Run's outward lane is closed; the
/// [`Terminal`](crate::runtime::run::Terminal) is then already resolved or about
/// to be, and [`Run::wait`](crate::runtime::run::Run::wait) produces it.
///
/// Dropping this stream asks the Run to stop. That is deliberate — a consumer
/// that has stopped listening is stating it wants nothing further — so a Run you
/// mean to finish should be drained rather than abandoned.
///
/// ```
/// # use reef_core::runtime::event;
/// # async fn drain(events: &mut event::Stream) -> Vec<event::Kind> {
/// let mut seen = Vec::new();
/// while let Some(delivery) = events.recv().await {
///     seen.push(delivery.event().kind());
///     // Three decision points are rendezvous; do not infer them from Event::kind.
///     // AfterToolCommit can accompany Audit or Error. Always ask the delivery.
///     if delivery.decision_point().is_some() {
///         delivery.accept().expect("a fresh strong delivery accepts once");
///     }
/// }
/// seen
/// # }
/// ```
///
/// It also implements [`futures_core::Stream`], so a consumer already built
/// around stream combinators can use it directly.
pub struct Stream {
    receiver: mpsc::UnboundedReceiver<Delivery>,
    control: Arc<Control>,
}

impl fmt::Debug for Stream {
    /// Reports whether the run's outward lane has latched a fatal violation.
    ///
    /// The load is relaxed on purpose: this is a diagnostic read, and ordering
    /// it against the producer would let formatting influence the very
    /// termination sequence it is trying to describe.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Stream")
            .field("fatal", &self.control.fatal.load(Ordering::Relaxed))
            .finish()
    }
}

impl Stream {
    /// Receives the next delivery.
    pub async fn recv(&mut self) -> Option<Delivery> {
        self.receiver.recv().await
    }
}

impl futures_core::Stream for Stream {
    type Item = Delivery;

    fn poll_next(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.receiver.poll_recv(context)
    }
}

impl Drop for Stream {
    fn drop(&mut self) {
        self.control.request_stop();
        self.receiver.close();
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum DeliveryOutcome {
    Delivered,
    Accepted,
    Rejected,
}

/// The precise decision at one of the three runtime-owned strong seams.
///
/// This stays crate-private so the outward delivery API remains unchanged.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum StrongDecision {
    Accepted,
    Rejected,
    Cancelled,
}

impl From<StrongDecision> for DeliveryOutcome {
    fn from(decision: StrongDecision) -> Self {
        match decision {
            StrongDecision::Accepted => Self::Accepted,
            StrongDecision::Rejected | StrongDecision::Cancelled => Self::Rejected,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct DeliveryResolution {
    outward: DeliveryOutcome,
    strong: Option<StrongDecision>,
}

impl DeliveryResolution {
    const fn ordinary(outward: DeliveryOutcome) -> Self {
        Self {
            outward,
            strong: None,
        }
    }

    fn strong(decision: StrongDecision) -> Self {
        Self {
            outward: decision.into(),
            strong: Some(decision),
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum TerminalIntent {
    Running,
    Stopped,
    Cancelled,
    Failed,
}

impl TerminalIntent {
    #[cfg_attr(not(test), expect(dead_code, reason = "reached only by tests so far"))]
    pub(crate) const fn outcome(self) -> Option<Outcome> {
        match self {
            Self::Running => None,
            Self::Stopped => Some(Outcome::Stopped),
            Self::Cancelled => Some(Outcome::Cancelled),
            Self::Failed => Some(Outcome::Failed),
        }
    }
}

/// No nonfatal terminal cause has been frozen yet.
const NONFATAL_NONE: u8 = 0;
/// A normal `request_stop`/`Stream` Drop won the linearization point.
const NONFATAL_STOPPED: u8 = 1;
/// Real parent cancellation won the linearization point.
const NONFATAL_CANCELED: u8 = 2;

/// The run's single linearization point for its one nonfatal terminal cause.
///
/// `Stopped` and `Cancelled` are two *causes* of the same interruption, so they
/// cannot be derived independently from the cancellation tree: the child token
/// this run cancels for its own normal stop is indistinguishable from parent
/// cancellation once observed. Only the caller-owned `parent` token — which this
/// run never cancels — separates the two, and the first observer to resolve the
/// cause freezes it here for every later observer.
///
/// The frozen cause is never rewritten. A fatal failure is a strictly higher,
/// independent latch on [`Control`], so it can still upgrade the terminal in
/// either order without this cause ever being lost or reinterpreted.
struct NonfatalCause {
    /// The caller-owned token whose cancellation is real parent cancellation.
    parent: Token,
    cause: SyncMutex<u8>,
}

impl NonfatalCause {
    /// Resolves the frozen nonfatal cause, freezing it on first resolution.
    ///
    /// `normal_stop` is `true` only for `request_stop`/`Stream` Drop, which
    /// is itself a stop request. Every other caller merely observes: it can
    /// freeze `Cancelled` from an already cancelled parent, but never invents a
    /// stop. Reading `parent` inside the critical section is what keeps a
    /// stop-induced child cancellation from ever being reported as `Cancelled`,
    /// and what makes a parent cancellation that already won outrank a later
    /// normal stop.
    fn freeze(&self, normal_stop: bool) -> u8 {
        let mut cause = self
            .cause
            .lock()
            .expect("event nonfatal cause lock poisoned");
        if *cause == NONFATAL_NONE {
            if self.parent.is_cancelled() {
                *cause = NONFATAL_CANCELED;
            } else if normal_stop {
                *cause = NONFATAL_STOPPED;
            }
        }
        *cause
    }

    /// Reads the frozen cause without resolving or freezing anything.
    #[cfg(test)]
    fn frozen(&self) -> u8 {
        *self
            .cause
            .lock()
            .expect("event nonfatal cause lock poisoned")
    }

    /// Selects the strong decision point value an interrupted delivery must linearize to.
    fn interrupted_decision(&self) -> u8 {
        if self.freeze(false) == NONFATAL_CANCELED {
            CANCELED
        } else {
            REJECTED
        }
    }
}

#[cfg(test)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum FreezePoint {
    Stop,
    Fatal,
}

#[cfg(test)]
struct TestFreezePause {
    point: FreezePoint,
    reached: Arc<std::sync::Barrier>,
    resume: Arc<std::sync::Barrier>,
}

#[cfg(test)]
struct TestFinalConfirmPause {
    reached: Semaphore,
    resume: Semaphore,
}

/// One held tool emission, announced synchronously and released asynchronously.
///
/// The waiter is a synchronous tool mapper on the loop's own runtime thread, so
/// the announcement cannot be a future: nothing would poll it.
#[cfg(test)]
struct TestEmitPause {
    reached: std::sync::mpsc::Sender<()>,
    resume: Semaphore,
}

struct Control {
    /// The one frozen nonfatal cause, shared with every strong decision.
    nonfatal: Arc<NonfatalCause>,
    fatal: AtomicBool,
    fatal_event: SyncMutex<Option<ValidationError>>,
    stop_emitted: AtomicBool,
    pending: SyncMutex<Option<Arc<Decision>>>,
    /// The composite interruption token cancelled by parent cancellation and by
    /// this run's own normal stop.
    cancel: Token,
    interruption: Token,
    #[cfg(test)]
    before_reject_pause: SyncMutex<Option<TestFreezePause>>,
    #[cfg(test)]
    after_final_confirm_pause: SyncMutex<Option<Arc<TestFinalConfirmPause>>>,
}

/// Abandons and clears the producer's strong-decision slot on completion or future Drop.
///
/// The serialized producer owns at most one decision. Keeping that registration
/// behind an RAII guard prevents a dropped `Driver::run` future from leaving a
/// stale strong decision reachable through `Control` after its delivery owner has
/// already been unwound.
struct PendingDecision<'a> {
    control: &'a Control,
    decision: Arc<Decision>,
}

impl Drop for PendingDecision<'_> {
    fn drop(&mut self) {
        // The producer future owns the live side of this handshake. If that
        // future is dropped, terminate the decision before making the slot
        // available to a successor; otherwise an already-delivered guard could
        // still accept work whose owner no longer exists.
        let _already_decided = self.decision.abandon();
        self.control.clear(&self.decision);
    }
}

impl Control {
    fn intent(&self) -> TerminalIntent {
        // Fatal is an independent, strictly higher latch, so it wins in either
        // interleaving order without ever consulting the nonfatal cause.
        if self.fatal.load(Ordering::Acquire) {
            return TerminalIntent::Failed;
        }
        // Observing only: this can freeze Cancelled from an already cancelled
        // parent, but it never invents a stop.
        match self.nonfatal.freeze(false) {
            NONFATAL_CANCELED => TerminalIntent::Cancelled,
            NONFATAL_STOPPED => TerminalIntent::Stopped,
            _ => TerminalIntent::Running,
        }
    }

    fn strong_interruption(&self) -> Option<StrongDecision> {
        if self.fatal.load(Ordering::Acquire) {
            return Some(StrongDecision::Rejected);
        }
        match self.nonfatal.freeze(false) {
            NONFATAL_CANCELED => Some(StrongDecision::Cancelled),
            NONFATAL_STOPPED => Some(StrongDecision::Rejected),
            _ => None,
        }
    }

    /// Linearizes the decision exposed to the strong decision point caller.
    ///
    /// A consumer acceptance is only an internal handshake result. Stop or fatal
    /// control may freeze after that CAS but before `reject_pending` reaches it;
    /// consulting this shared control point prevents such an internal acceptance
    /// from authorizing tool execution. Rejection and cancellation already encode
    /// a terminal consumer/control choice and are preserved.
    fn final_confirm_strong(&self, decision: StrongDecision) -> StrongDecision {
        if decision == StrongDecision::Accepted {
            self.strong_interruption().unwrap_or(decision)
        } else {
            decision
        }
    }

    #[cfg(test)]
    fn pause_before_reject(&self, point: FreezePoint) {
        let pause = {
            let mut slot = self
                .before_reject_pause
                .lock()
                .expect("event freeze pause lock poisoned");
            if slot.as_ref().is_some_and(|pause| pause.point == point) {
                slot.take()
            } else {
                None
            }
        };
        if let Some(pause) = pause {
            pause.reached.wait();
            pause.resume.wait();
        }
    }

    #[cfg(test)]
    async fn pause_after_final_confirm(&self) {
        let pause = self
            .after_final_confirm_pause
            .lock()
            .expect("event final-confirm pause lock poisoned")
            .take();
        if let Some(pause) = pause {
            pause.reached.add_permits(1);
            pause
                .resume
                .acquire()
                .await
                .expect("event final-confirm pause remains open")
                .forget();
        }
    }

    /// Reports whether an interruption is already frozen for this run.
    ///
    /// This is the shared gate for registration and ordinary emission: both must
    /// fail closed once any nonfatal cause or fatal failure has been latched.
    fn interrupted(&self) -> bool {
        self.fatal.load(Ordering::Acquire) || self.nonfatal.freeze(false) != NONFATAL_NONE
    }

    fn register(&self, decision: &Arc<Decision>) {
        let mut pending = self.pending.lock().expect("event pending lock poisoned");
        if self.interrupted() {
            let _already_decided = decision.decide(self.nonfatal.interrupted_decision());
        } else {
            *pending = Some(decision.clone());
        }
    }

    fn clear(&self, decision: &Arc<Decision>) {
        let mut pending = self.pending.lock().expect("event pending lock poisoned");
        if pending
            .as_ref()
            .is_some_and(|current| Arc::ptr_eq(current, decision))
        {
            pending.take();
        }
    }

    /// Terminates the registered strong decision with the frozen nonfatal cause.
    fn reject_pending(&self) {
        let decided = self.nonfatal.interrupted_decision();
        if let Some(decision) = self
            .pending
            .lock()
            .expect("event pending lock poisoned")
            .take()
        {
            let _already_decided = decision.decide(decided);
        }
    }

    /// Freezes a normal stop cause, unless a parent cancellation already won.
    fn latch_stop(&self) {
        let _cause = self.nonfatal.freeze(true);
        #[cfg(test)]
        self.pause_before_reject(FreezePoint::Stop);
        self.reject_pending();
        self.interruption.cancel();
    }

    fn request_stop(&self) {
        self.latch_stop();
        // The composite token is cancelled only after the cause is frozen, so no
        // observer can mistake this run's own stop for parent cancellation.
        self.cancel.cancel();
    }

    fn fail(&self, event_error: Option<ValidationError>) -> Option<ValidationError> {
        let first_event_error = {
            let mut fatal_event = self
                .fatal_event
                .lock()
                .expect("event fatal latch lock poisoned");
            if !self.fatal.load(Ordering::Acquire) {
                *fatal_event = event_error;
                self.fatal.store(true, Ordering::Release);
            }
            *fatal_event
        };
        #[cfg(test)]
        self.pause_before_reject(FreezePoint::Fatal);
        self.reject_pending();
        self.interruption.cancel();
        self.cancel.cancel();
        first_event_error
    }
}

pub(crate) struct Producer {
    sender: mpsc::UnboundedSender<Delivery>,
    control: Arc<Control>,
    serial: Mutex<()>,
}

impl Producer {
    pub(crate) async fn emit_text(
        &self,
        kind: Kind,
        text: String,
        coord: Coord,
        item_id: Option<String>,
    ) -> Result<DeliveryOutcome, ValidationError> {
        self.emit(Event::driver_text(kind, text, coord, item_id), None)
            .await
    }

    pub(crate) async fn emit_lifecycle(
        &self,
        kind: Kind,
        outcome: Option<Outcome>,
        coord: Coord,
    ) -> Result<DeliveryOutcome, ValidationError> {
        self.emit(Event::driver_lifecycle(kind, outcome, coord), None)
            .await
    }

    pub(crate) async fn emit_input_admitted(
        &self,
        origin: InputOrigin,
        items: Vec<item::Item>,
        coord: Coord,
    ) -> Result<DeliveryOutcome, ValidationError> {
        self.emit(Event::driver_input_admitted(origin, items, coord), None)
            .await
    }

    pub(crate) async fn emit_input_rejected(
        &self,
        reason: String,
        coord: Coord,
    ) -> Result<DeliveryOutcome, ValidationError> {
        self.emit(Event::driver_input_rejected(reason, coord), None)
            .await
    }

    pub(crate) async fn emit_tool_call(
        &self,
        call: ToolCall,
        coord: Coord,
    ) -> Result<StrongDecision, ValidationError> {
        self.emit_strong(
            Event::driver_tool_call(call, coord),
            DecisionPoint::ToolCall,
        )
        .await
    }

    pub(crate) async fn emit_tool_result(
        &self,
        result: item::ToolResult,
        coord: Coord,
    ) -> Result<StrongDecision, ValidationError> {
        self.emit_strong(
            Event::driver_tool_result(result, coord),
            DecisionPoint::ToolResult,
        )
        .await
    }

    pub(crate) async fn emit_extension(
        &self,
        mut event: Event,
        coord: Coord,
    ) -> Result<DeliveryOutcome, ValidationError> {
        event.coord = Some(coord);
        self.emit(event, None).await
    }

    pub(crate) async fn emit_after_tool_commit(
        &self,
        mut event: Event,
        coord: Coord,
    ) -> Result<StrongDecision, ValidationError> {
        event.coord = Some(coord);
        self.emit_strong(event, DecisionPoint::AfterToolCommit)
            .await
    }

    pub(crate) async fn emit(
        &self,
        event: Event,
        decision_point: Option<DecisionPoint>,
    ) -> Result<DeliveryOutcome, ValidationError> {
        if let Some(decision_point) = decision_point {
            return self
                .emit_strong(event, decision_point)
                .await
                .map(Into::into);
        }
        let _serial = self.serial.lock().await;
        if self.control.interrupted() {
            return Ok(DeliveryOutcome::Rejected);
        }
        self.emit_locked(event, None)
            .await
            .map(|resolution| resolution.outward)
    }

    async fn emit_strong(
        &self,
        event: Event,
        decision_point: DecisionPoint,
    ) -> Result<StrongDecision, ValidationError> {
        let _serial = self.serial.lock().await;
        if let Some(decision) = self.control.strong_interruption() {
            return Ok(decision);
        }
        Ok(self
            .emit_locked(event, Some(decision_point))
            .await?
            .strong
            .expect("a strong decision point always has a decision"))
    }

    async fn emit_locked(
        &self,
        event: Event,
        decision_point: Option<DecisionPoint>,
    ) -> Result<DeliveryResolution, ValidationError> {
        if let Err(error) = event.validate(decision_point) {
            let _first_event_error = self.control.fail(Some(error));
            return Err(error);
        }
        let decision = decision_point.map(|_| {
            Arc::new(Decision {
                value: AtomicU8::new(PENDING),
                changed: Notify::new(),
                cancel: self.control.cancel.clone(),
                nonfatal: Arc::clone(&self.control.nonfatal),
                #[cfg(test)]
                after_pending_check: SyncMutex::new(None),
            })
        });
        let _pending = decision.as_ref().map(|decision| {
            self.control.register(decision);
            PendingDecision {
                control: &self.control,
                decision: Arc::clone(decision),
            }
        });
        let delivery = Delivery {
            event,
            decision_point,
            decision: decision.clone(),
        };
        // An unbounded lane accepts the delivery immediately, so the only two
        // reasons not to hand it over are that this Run is already interrupted
        // or that the consumer has dropped its stream. Cancellation is checked
        // first to keep the pre-existing precedence: an interrupted Run does not
        // publish, even when the consumer is still listening.
        let delivered = !self.control.cancel.is_cancelled() && self.sender.send(delivery).is_ok();
        let outcome = if let Some(decision) = &decision {
            if !delivered {
                let _already_decided = decision.abandon();
            }
            let decision = self.control.final_confirm_strong(decision.wait().await);
            #[cfg(test)]
            self.control.pause_after_final_confirm().await;
            DeliveryResolution::strong(decision)
        } else {
            DeliveryResolution::ordinary(if delivered {
                DeliveryOutcome::Delivered
            } else {
                DeliveryOutcome::Rejected
            })
        };
        Ok(outcome)
    }

    pub(crate) async fn emit_stop(
        &self,
        code: StopCode,
        coord: Coord,
    ) -> Result<DeliveryOutcome, ValidationError> {
        if self.control.stop_emitted.swap(true, Ordering::AcqRel) {
            return Ok(DeliveryOutcome::Rejected);
        }
        self.control.latch_stop();
        let _serial = self.serial.lock().await;
        if self.control.cancel.is_cancelled() {
            return Ok(DeliveryOutcome::Rejected);
        }
        self.emit_locked(Event::driver_stop(code, coord), None)
            .await
            .map(|resolution| resolution.outward)
    }
}

/// A restricted per-invocation emit failure.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ToolEmitError {
    /// The invocation's emit window already closed.
    Closed,
    /// The event was not delivered to the outward consumer.
    Rejected,
    /// The supplied extension fact was invalid.
    Invalid(ValidationError),
}

impl fmt::Display for ToolEmitError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Closed => formatter.write_str("tool invocation emit window is closed"),
            Self::Rejected => formatter.write_str("tool invocation event was not delivered"),
            Self::Invalid(error) => write!(formatter, "invalid tool invocation event: {error}"),
        }
    }
}

impl Error for ToolEmitError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Invalid(error) => Some(error),
            Self::Closed | Self::Rejected => None,
        }
    }
}

struct Outward {
    producer: Arc<Producer>,
    coord: Coord,
}

enum EmitTarget {
    Closed,
    Open(Outward),
}

struct EmitterState {
    target: EmitTarget,
    active: usize,
}

struct ToolEmitterInner {
    state: SyncMutex<EmitterState>,
    idle: Notify,
    /// Holds one emission inside its open window until a test releases it.
    ///
    /// The outward lane is unbounded, so a real emission never stays in flight
    /// long enough for a test to observe the close/drain barrier it is supposed
    /// to cross. This is the same shape as the two `Control` pauses.
    #[cfg(test)]
    pause: SyncMutex<Option<Arc<TestEmitPause>>>,
}

impl ToolEmitterInner {
    #[cfg(test)]
    async fn pause(&self) {
        let pause = self
            .pause
            .lock()
            .expect("tool emitter pause lock poisoned")
            .take();
        if let Some(pause) = pause {
            let _observer_may_be_gone = pause.reached.send(());
            pause
                .resume
                .acquire()
                .await
                .expect("tool emitter pause remains open")
                .forget();
        }
    }

    fn enter(&self) -> Option<(ActiveEmit<'_>, Arc<Producer>, Coord)> {
        let mut state = self.state.lock().expect("tool emitter lock poisoned");
        match &state.target {
            EmitTarget::Closed => None,
            EmitTarget::Open(outward) => {
                let producer = Arc::clone(&outward.producer);
                let coord = outward.coord.clone();
                state.active += 1;
                Some((ActiveEmit { inner: self }, producer, coord))
            }
        }
    }

    fn leave(&self) {
        let mut state = self.state.lock().expect("tool emitter lock poisoned");
        state.active -= 1;
        if state.active == 0 {
            self.idle.notify_waiters();
        }
    }

    fn close(&self) {
        self.state
            .lock()
            .expect("tool emitter lock poisoned")
            .target = EmitTarget::Closed;
    }

    async fn drain(&self) {
        loop {
            let idle = self.idle.notified();
            tokio::pin!(idle);
            let _already_ready = idle.as_mut().enable();
            if self
                .state
                .lock()
                .expect("tool emitter lock poisoned")
                .active
                == 0
            {
                return;
            }
            idle.await;
        }
    }
}

/// Releases one in-flight emission even when the executor future is dropped.
struct ActiveEmit<'a> {
    inner: &'a ToolEmitterInner,
}

impl Drop for ActiveEmit<'_> {
    fn drop(&mut self) {
        self.inner.leave();
    }
}

/// The only emit capability handed to one tool invocation.
///
/// The typed constructors make loop-owned categories unrepresentable: an
/// executor cannot forge text, thinking, tool, lifecycle, or stop events, and it
/// cannot replay an [`Event`] observed from the outward stream. The runtime
/// stamps the call's [`Coord`], so neither producer authority nor outward event
/// state is ever reachable from an executor.
///
/// [`emit_audit`](Self::emit_audit) and [`emit_error`](Self::emit_error) are
/// async: each call is serialized with other outward emissions and returns once
/// the event is enqueued on the unbounded outward lane. Ordinary Audit/Error
/// delivery has no consumer acknowledgement; success means the stream remained
/// open for the enqueue. This differs from a hook scope's synchronous
/// `emit_audit` and `emit_error` methods, which queue locally and return
/// immediately because a synchronous callback cannot await.
/// Immediately after the paired invocation returns, the runtime closes this
/// window and every later call is a [`ToolEmitError::Closed`] no-op.
pub struct ToolEmitter {
    inner: Arc<ToolEmitterInner>,
}

impl fmt::Debug for ToolEmitter {
    /// Prints the bare type name, which is the honest answer here.
    ///
    /// This is the one type in the crate with nothing to distinguish two live
    /// values by. Its entire state is an emitter-state machine behind a mutex
    /// and a `Notify`; whether the window is open changes under the reader's
    /// feet, and reporting it would describe a moment that has already passed.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.debug_struct("ToolEmitter").finish()
    }
}

impl ToolEmitter {
    /// Creates an emitter that is already closed and carries no authority.
    ///
    /// Composition layers and tests that route a call outside a live run use
    /// this to satisfy the invocation contract; every emission is a
    /// [`ToolEmitError::Closed`] no-op.
    #[must_use]
    pub fn closed() -> Self {
        Self {
            inner: Arc::new(ToolEmitterInner {
                state: SyncMutex::new(EmitterState {
                    target: EmitTarget::Closed,
                    active: 0,
                }),
                idle: Notify::new(),
                #[cfg(test)]
                pause: SyncMutex::new(None),
            }),
        }
    }

    /// Emits one non-model-visible audit fact.
    ///
    /// # Errors
    ///
    /// Returns [`ToolEmitError::Invalid`] for an empty audit kind,
    /// [`ToolEmitError::Closed`] after the invocation window closed, and
    /// [`ToolEmitError::Rejected`] when the outward stream closed before enqueue.
    ///
    /// # Panics
    ///
    /// If the lock guarding the invocation's emit window is poisoned, per the
    /// crate-level [lock-poisoning contract](crate#lock-poisoning).
    pub async fn emit_audit(&self, audit: audit::Event) -> Result<(), ToolEmitError> {
        let event = Event::from_audit(audit).map_err(ToolEmitError::Invalid)?;
        self.emit_extension(event).await
    }

    /// Emits one recoverable, non-fatal degradation notice.
    ///
    /// # Errors
    ///
    /// Returns [`ToolEmitError::Closed`] after the invocation window closed and
    /// [`ToolEmitError::Rejected`] when the outward stream closed before enqueue.
    ///
    /// # Panics
    ///
    /// If the lock guarding the invocation's emit window is poisoned, per the
    /// crate-level [lock-poisoning contract](crate#lock-poisoning).
    pub async fn emit_error(
        &self,
        error: Arc<dyn Error + Send + Sync>,
    ) -> Result<(), ToolEmitError> {
        self.emit_extension(Event::from_error(error)).await
    }

    async fn emit_extension(&self, event: Event) -> Result<(), ToolEmitError> {
        let Some((_active, producer, coord)) = self.inner.enter() else {
            return Err(ToolEmitError::Closed);
        };
        #[cfg(test)]
        self.inner.pause().await;
        let outcome = producer.emit_extension(event, coord).await;
        // Both public constructors pre-validate, so the producer's fatal
        // validation lane is unreachable here and non-delivery is the only
        // remaining failure fact.
        if matches!(outcome, Ok(DeliveryOutcome::Delivered)) {
            Ok(())
        } else {
            Err(ToolEmitError::Rejected)
        }
    }
}

/// The runtime-owned close side of one invocation's emit window.
pub(crate) struct ToolEmitterGate {
    inner: Arc<ToolEmitterInner>,
}

impl ToolEmitterGate {
    /// Closes the window, then waits for every already-active emission.
    pub(crate) async fn close_and_wait(self) {
        self.inner.close();
        self.inner.drain().await;
    }
}

/// Mints one invocation-scoped emitter and its runtime-owned close gate.
pub(crate) fn tool_emitter(
    producer: &Arc<Producer>,
    coord: Coord,
) -> (ToolEmitter, ToolEmitterGate) {
    let inner = Arc::new(ToolEmitterInner {
        state: SyncMutex::new(EmitterState {
            target: EmitTarget::Open(Outward {
                producer: Arc::clone(producer),
                coord,
            }),
            active: 0,
        }),
        idle: Notify::new(),
        #[cfg(test)]
        pause: SyncMutex::new(None),
    });
    (
        ToolEmitter {
            inner: Arc::clone(&inner),
        },
        ToolEmitterGate { inner },
    )
}

pub(crate) struct EventSource {
    stream: Option<Stream>,
    control: Arc<Control>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct StreamTakenError;

impl EventSource {
    pub(crate) fn take_stream(&mut self) -> Result<Stream, StreamTakenError> {
        self.stream.take().ok_or(StreamTakenError)
    }

    pub(crate) fn request_stop(&self) {
        self.control.request_stop();
    }

    pub(crate) fn terminal_intent(&self) -> TerminalIntent {
        self.control.intent()
    }

    /// Resolves when outward control stops or fails the run.
    ///
    /// This signal is deliberately independent of the parent-derived cancellation
    /// token. Consumer drop must wake the Driver even though it cannot cancel the
    /// parent, while explicit parent cancellation stays on the Driver's normal
    /// cancellation path so already-durable facts and real fatal errors retain
    /// their established priority.
    pub(crate) async fn interruption(&self) {
        self.control.interruption.cancelled().await;
    }

    pub(crate) fn latch_failure(&self) -> Option<ValidationError> {
        self.control.fail(None)
    }

    #[cfg(test)]
    fn state(&self) -> (bool, bool, bool) {
        (
            self.control.nonfatal.frozen() == NONFATAL_STOPPED,
            self.control.fatal.load(Ordering::Acquire),
            self.control.cancel.is_cancelled(),
        )
    }
}

/// Creates the outward lane for one Run.
///
/// The lane is unbounded on purpose. Every blocking boundary Reef has is an
/// explicit acknowledgement — the three strong seams wait on their own
/// [`Decision`], not on buffer space — so letting a full buffer also stall the
/// loop would make delivery latency a second, invisible flow-control mechanism.
/// With an unbounded lane a slow or inattentive consumer can never wedge a Run:
/// the only way a send fails is that the consumer dropped its stream, which is
/// that consumer stating it wants nothing further.
pub(crate) fn channel(parent: &Token) -> (Arc<Producer>, EventSource) {
    let (sender, receiver) = mpsc::unbounded_channel();
    let nonfatal = Arc::new(NonfatalCause {
        parent: parent.clone(),
        cause: SyncMutex::new(NONFATAL_NONE),
    });
    let control = Arc::new(Control {
        nonfatal,
        fatal: AtomicBool::new(false),
        fatal_event: SyncMutex::new(None),
        stop_emitted: AtomicBool::new(false),
        pending: SyncMutex::new(None),
        cancel: parent.child_token(),
        interruption: Token::new(),
        #[cfg(test)]
        before_reject_pause: SyncMutex::new(None),
        #[cfg(test)]
        after_final_confirm_pause: SyncMutex::new(None),
    });
    let producer = Arc::new(Producer {
        sender,
        control: control.clone(),
        serial: Mutex::new(()),
    });
    let stream = Stream {
        receiver,
        control: control.clone(),
    };
    (
        producer,
        EventSource {
            stream: Some(stream),
            control,
        },
    )
}

#[cfg(test)]
pub(crate) mod testing {
    use super::*;

    /// The runtime path that publishes one event category.
    ///
    /// This exists so that "which variants can a consumer actually see" is a
    /// value rather than a comment. Nothing in the crate reads it to make a
    /// decision; it is read by
    /// `driver_tests::every_event_kind_reaches_a_consumer_from_a_real_run`.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub(crate) enum Emission {
        /// [`Producer::emit_text`], from streamed or consolidated content.
        Content,
        /// [`Producer::emit_lifecycle`], from a Turn, Step or Generation boundary.
        Lifecycle,
        /// [`Producer::emit_tool_call`], at the `ToolCall` strong decision point.
        ToolCall,
        /// [`Producer::emit_tool_result`], at the `ToolResult` strong decision point.
        ToolResult,
        /// [`ToolEmitter`], the only extension-owned emission authority.
        Extension,
        /// [`Producer::emit_stop`], the single privately owned `EventStop`.
        Stop,
        /// [`Producer::emit_input_admitted`]/[`Producer::emit_input_rejected`],
        /// the loop's two statements about a claimed or composed input batch.
        Input,
    }

    /// The runtime path that publishes `kind`.
    ///
    /// Exhaustive with no wildcard arm on purpose. Adding a variant to [`Kind`]
    /// stops the crate compiling here, and the compiler error lands on the one
    /// list a new variant has to join — [`ALL_KINDS`] is immediately below it.
    /// Once the variant is in that list,
    /// `every_event_kind_reaches_a_consumer_from_a_real_run` requires a real
    /// [`Driver`] run to publish it, so a variant cannot be declared without
    /// being wired.
    ///
    /// Rust has no stable way to enumerate an enum's variants, so the list itself
    /// is written by hand; what is mechanical is that the list cannot be reached
    /// without a compiler error first, and cannot be satisfied afterwards without
    /// a production emitter.
    ///
    /// [`Driver`]: crate::runtime::driver::Driver
    pub(crate) const fn emission(kind: Kind) -> Emission {
        match kind {
            Kind::TextDelta | Kind::Text | Kind::ThinkingDelta | Kind::Thinking => {
                Emission::Content
            }
            Kind::TurnStart
            | Kind::TurnEnd
            | Kind::StepStart
            | Kind::StepEnd
            | Kind::GenerationEnd => Emission::Lifecycle,
            Kind::ToolCall => Emission::ToolCall,
            Kind::ToolResult => Emission::ToolResult,
            Kind::Audit | Kind::Error => Emission::Extension,
            Kind::Stop => Emission::Stop,
            Kind::InputAdmitted | Kind::InputRejected => Emission::Input,
        }
    }

    /// Every event category a consumer can observe.
    pub(crate) const ALL_KINDS: &[Kind] = &[
        Kind::TextDelta,
        Kind::Text,
        Kind::ThinkingDelta,
        Kind::Thinking,
        Kind::TurnStart,
        Kind::TurnEnd,
        Kind::StepStart,
        Kind::StepEnd,
        Kind::GenerationEnd,
        Kind::ToolCall,
        Kind::ToolResult,
        Kind::Error,
        Kind::Audit,
        Kind::Stop,
        Kind::InputAdmitted,
        Kind::InputRejected,
    ];

    pub(crate) fn text(kind: Kind, text: &str, coord: Coord) -> Event {
        Event::driver_text(kind, text.into(), coord, None)
    }

    pub(crate) fn lifecycle(kind: Kind, outcome: Option<Outcome>, coord: Coord) -> Event {
        Event::driver_lifecycle(kind, outcome, coord)
    }

    pub(crate) fn tool_call(call: ToolCall, coord: Coord) -> Event {
        Event::driver_tool_call(call, coord)
    }

    pub(crate) fn tool_result(result: item::ToolResult, coord: Coord) -> Event {
        Event::driver_tool_result(result, coord)
    }

    pub(crate) fn stop(code: StopCode, coord: Coord) -> Event {
        Event::driver_stop(code, coord)
    }

    pub(crate) fn input_admitted(
        origin: InputOrigin,
        items: Vec<item::Item>,
        coord: Coord,
    ) -> Event {
        Event::driver_input_admitted(origin, items, coord)
    }

    pub(crate) fn input_rejected(reason: String, coord: Coord) -> Event {
        Event::driver_input_rejected(reason, coord)
    }

    pub(crate) fn forged(kind: Kind, event: Event) -> Event {
        Event { kind, ..event }
    }

    pub(crate) fn invalid_audit(coord: Coord) -> Event {
        Event {
            kind: Kind::Audit,
            coord: Some(coord),
            item_id: None,
            payload: Payload::Audit(audit::Event::new(String::new(), None)),
        }
    }

    pub(crate) fn invalid_stop(coord: Coord) -> Event {
        Event {
            kind: Kind::Stop,
            coord: Some(coord),
            item_id: None,
            payload: Payload::Stop(StopCode(String::new())),
        }
    }

    pub(crate) fn control(source: &EventSource) -> (bool, bool, bool) {
        source.state()
    }

    pub(crate) use super::FreezePoint;

    #[derive(Clone)]
    pub(crate) struct InterruptionProbe(Arc<Control>);

    impl InterruptionProbe {
        pub(crate) fn request_stop(&self) {
            self.0.request_stop();
        }

        pub(crate) fn fail(&self) {
            let _first_event_error = self.0.fail(Some(ValidationError::PayloadMismatch));
        }
    }

    pub(crate) fn interruption_probe(source: &EventSource) -> InterruptionProbe {
        InterruptionProbe(Arc::clone(&source.control))
    }

    pub(crate) struct FreezePauseProbe {
        reached: Arc<std::sync::Barrier>,
        resume: Arc<std::sync::Barrier>,
    }

    impl FreezePauseProbe {
        pub(crate) fn wait_until_frozen(&self) {
            self.reached.wait();
        }

        pub(crate) fn resume_rejection(&self) {
            self.resume.wait();
        }
    }

    pub(crate) fn pause_before_reject(
        source: &EventSource,
        point: FreezePoint,
    ) -> (InterruptionProbe, FreezePauseProbe) {
        let reached = Arc::new(std::sync::Barrier::new(2));
        let resume = Arc::new(std::sync::Barrier::new(2));
        *source
            .control
            .before_reject_pause
            .lock()
            .expect("event freeze pause lock poisoned") = Some(TestFreezePause {
            point,
            reached: Arc::clone(&reached),
            resume: Arc::clone(&resume),
        });
        (
            interruption_probe(source),
            FreezePauseProbe { reached, resume },
        )
    }

    pub(crate) struct FinalConfirmPauseProbe(Arc<TestFinalConfirmPause>);

    impl FinalConfirmPauseProbe {
        pub(crate) async fn wait_until_confirmed(&self) {
            self.0
                .reached
                .acquire()
                .await
                .expect("event final-confirm pause remains open")
                .forget();
        }

        pub(crate) fn resume_return(&self) {
            self.0.resume.add_permits(1);
        }
    }

    pub(crate) fn pause_after_final_confirm(source: &EventSource) -> FinalConfirmPauseProbe {
        let pause = Arc::new(TestFinalConfirmPause {
            reached: Semaphore::new(0),
            resume: Semaphore::new(0),
        });
        *source
            .control
            .after_final_confirm_pause
            .lock()
            .expect("event final-confirm pause lock poisoned") = Some(Arc::clone(&pause));
        FinalConfirmPauseProbe(pause)
    }

    pub(crate) fn intent(source: &EventSource) -> TerminalIntent {
        source.terminal_intent()
    }

    pub(crate) fn has_pending_strong_decision(source: &EventSource) -> bool {
        source
            .control
            .pending
            .lock()
            .expect("event pending lock poisoned")
            .is_some()
    }

    pub(crate) fn stale_pending_guard_preserves_successor(source: &EventSource) -> (bool, bool) {
        let decision = || {
            Arc::new(Decision {
                value: AtomicU8::new(PENDING),
                changed: Notify::new(),
                cancel: source.control.cancel.clone(),
                nonfatal: Arc::clone(&source.control.nonfatal),
                after_pending_check: SyncMutex::new(None),
            })
        };
        let stale = decision();
        source.control.register(&stale);
        let stale_guard = PendingDecision {
            control: &source.control,
            decision: Arc::clone(&stale),
        };
        let successor = decision();
        source.control.register(&successor);

        drop(stale_guard);
        let successor_preserved = source
            .control
            .pending
            .lock()
            .expect("event pending lock poisoned")
            .as_ref()
            .is_some_and(|pending| Arc::ptr_eq(pending, &successor));
        let stale_abandoned = stale.decide(ACCEPTED) == Err(DecisionError::AlreadyDecided);
        source.control.reject_pending();
        (successor_preserved, stale_abandoned)
    }

    #[derive(Clone)]
    pub(crate) struct EmitterProbe(Arc<ToolEmitterInner>);

    impl EmitterProbe {
        pub(crate) fn state(&self) -> (bool, usize) {
            let state = self.0.state.lock().expect("tool emitter lock poisoned");
            (matches!(state.target, EmitTarget::Closed), state.active)
        }
    }

    pub(crate) fn emitter_probe(emitter: &ToolEmitter) -> EmitterProbe {
        EmitterProbe(Arc::clone(&emitter.inner))
    }

    /// Holds one emission open inside its window until the test releases it.
    #[derive(Clone)]
    pub(crate) struct EmitPauseProbe(Arc<TestEmitPause>);

    impl EmitPauseProbe {
        /// Announces the held emission on `reached` once it is inside the window.
        pub(crate) fn new(reached: std::sync::mpsc::Sender<()>) -> Self {
            Self(Arc::new(TestEmitPause {
                reached,
                resume: Semaphore::new(0),
            }))
        }

        /// Arms this pause for the emitter's next emission only.
        pub(crate) fn arm(&self, emitter: &ToolEmitter) {
            *emitter
                .inner
                .pause
                .lock()
                .expect("tool emitter pause lock poisoned") = Some(Arc::clone(&self.0));
        }

        pub(crate) fn resume(&self) {
            self.0.resume.add_permits(1);
        }
    }

    /// Cancels the Run-local token without latching a nonfatal cause.
    ///
    /// Every public route into this state latches the cause first, which makes
    /// the outward hand-over's own cancellation check unobservable from outside.
    /// That check is the last thing standing between a cancelled Run and a
    /// published event, so it is worth pinning rather than assuming.
    pub(crate) fn cancel_lane(source: &EventSource) {
        source.control.cancel.cancel();
    }

    pub(crate) fn fail(source: &EventSource) {
        let _first_event_error = source.control.fail(Some(ValidationError::PayloadMismatch));
    }

    #[derive(Clone)]
    pub(crate) struct DecisionProbe(Arc<Decision>);

    impl DecisionProbe {
        pub(crate) fn plain(cancel: Token) -> Self {
            let nonfatal = Arc::new(NonfatalCause {
                parent: cancel.clone(),
                cause: SyncMutex::new(NONFATAL_NONE),
            });
            Self(Arc::new(Decision {
                value: AtomicU8::new(PENDING),
                changed: Notify::new(),
                cancel,
                nonfatal,
                after_pending_check: SyncMutex::new(None),
            }))
        }

        pub(crate) fn paused_after_pending_check(
            cancel: Token,
        ) -> (Self, Arc<std::sync::Barrier>, Arc<std::sync::Barrier>) {
            let checked = Arc::new(std::sync::Barrier::new(2));
            let resume = Arc::new(std::sync::Barrier::new(2));
            let nonfatal = Arc::new(NonfatalCause {
                parent: cancel.clone(),
                cause: SyncMutex::new(NONFATAL_NONE),
            });
            let decision = Arc::new(Decision {
                value: AtomicU8::new(PENDING),
                changed: Notify::new(),
                cancel,
                nonfatal,
                after_pending_check: SyncMutex::new(Some(WaitBarriers {
                    checked: checked.clone(),
                    resume: resume.clone(),
                })),
            });
            (Self(decision), checked, resume)
        }

        pub(crate) fn accept(&self) -> Result<(), DecisionError> {
            self.0.decide_consumer(ACCEPTED)
        }

        pub(crate) fn reject(&self) -> Result<(), DecisionError> {
            self.0.decide_consumer(REJECTED)
        }

        pub(crate) async fn wait(&self) -> StrongDecision {
            self.0.wait().await
        }
    }

    pub(crate) fn register_probe(source: &EventSource) -> bool {
        let decision = DecisionProbe::plain(source.control.cancel.clone()).0;
        source.control.register(&decision);
        decision.value.load(Ordering::Acquire) == REJECTED
    }

    /// Observes one emitter's in-flight emission count so concurrency tests can
    /// wait on real state instead of task-scheduling luck.
    pub(crate) fn tool_emitter_active(emitter: &ToolEmitter) -> usize {
        emitter
            .inner
            .state
            .lock()
            .expect("tool emitter lock poisoned")
            .active
    }
}

/// The serialized form of [`Kind`] (ADR-019 D5).
///
/// A kind travels as its own tag and nothing else. [`Event`] itself is not
/// serializable and cannot be: its private payload carries an
/// `Arc<dyn Error + Send + Sync>`, and its loop-owned variants have no public
/// constructors. So a serialized `Kind` is the tag a lifecycle record carries,
/// not a protocol, and nothing here should be read as delivering one.
///
/// `Kind` is `#[non_exhaustive]`, but its serialized form carries no schema
/// version. Compatibility is content-driven: an unknown tag on ingress is an
/// error rather than a fallback variant, while a recognized tag is not rejected
/// merely because a different reef version wrote it.
#[cfg(feature = "serde")]
mod serde_impl {
    use std::fmt::{self, Formatter};

    use serde_core::de::{
        Deserialize, Deserializer, EnumAccess, Error as DeError, VariantAccess, Visitor,
    };
    use serde_core::ser::{Serialize, Serializer};

    use super::Kind;
    use crate::wire::IdentifierSeed;

    const NAME: &str = "Kind";
    const VARIANTS: &[&str] = &[
        "text_delta",
        "text",
        "thinking_delta",
        "thinking",
        "turn_start",
        "turn_end",
        "step_start",
        "step_end",
        "generation_end",
        "tool_call",
        "tool_result",
        "error",
        "audit",
        "stop",
        "input_admitted",
        "input_rejected",
    ];

    impl Serialize for Kind {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let (index, tag) = match self {
                Self::TextDelta => (0, "text_delta"),
                Self::Text => (1, "text"),
                Self::ThinkingDelta => (2, "thinking_delta"),
                Self::Thinking => (3, "thinking"),
                Self::TurnStart => (4, "turn_start"),
                Self::TurnEnd => (5, "turn_end"),
                Self::StepStart => (6, "step_start"),
                Self::StepEnd => (7, "step_end"),
                Self::GenerationEnd => (8, "generation_end"),
                Self::ToolCall => (9, "tool_call"),
                Self::ToolResult => (10, "tool_result"),
                Self::Error => (11, "error"),
                Self::Audit => (12, "audit"),
                Self::Stop => (13, "stop"),
                Self::InputAdmitted => (14, "input_admitted"),
                Self::InputRejected => (15, "input_rejected"),
            };
            serializer.serialize_unit_variant(NAME, index, tag)
        }
    }

    impl<'de> Deserialize<'de> for Kind {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            deserializer.deserialize_enum(NAME, VARIANTS, KindVisitor)
        }
    }

    struct KindVisitor;

    impl<'de> Visitor<'de> for KindVisitor {
        type Value = Kind;

        fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
            formatter.write_str("an outward event kind")
        }

        fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
        where
            A: EnumAccess<'de>,
        {
            let (tag, variant) = data.variant_seed(IdentifierSeed(VARIANTS))?;
            variant.unit_variant()?;
            match tag.0.as_str() {
                "text_delta" => Ok(Kind::TextDelta),
                "text" => Ok(Kind::Text),
                "thinking_delta" => Ok(Kind::ThinkingDelta),
                "thinking" => Ok(Kind::Thinking),
                "turn_start" => Ok(Kind::TurnStart),
                "turn_end" => Ok(Kind::TurnEnd),
                "step_start" => Ok(Kind::StepStart),
                "step_end" => Ok(Kind::StepEnd),
                "generation_end" => Ok(Kind::GenerationEnd),
                "tool_call" => Ok(Kind::ToolCall),
                "tool_result" => Ok(Kind::ToolResult),
                "error" => Ok(Kind::Error),
                "audit" => Ok(Kind::Audit),
                "stop" => Ok(Kind::Stop),
                "input_admitted" => Ok(Kind::InputAdmitted),
                "input_rejected" => Ok(Kind::InputRejected),
                unknown => Err(A::Error::unknown_variant(unknown, VARIANTS)),
            }
        }
    }
}