capsule-runtime 0.8.0

The runtime that executes Murmur capsules. Runs packaged AI agents in isolation, enforcing WASI capability grants on a Wasmtime component sandbox.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
//! What the runtime does with the typed events a process driver reads out of its harness.
//!
//! The driver turns harness output into [`Event`]s; this module is the other half — it turns
//! those events into everything a turn records: the `inference` and `tool_call` trace events, the
//! `Inference` and `ToolCall` hooks, the OTel spans, the result text, the harness's own
//! diagnostics, and, through [`A2aStream`], the task's A2A frames. The runtime never reads the
//! harness's output itself, so nothing here interprets text; it only counts turns and writes
//! records.
//!
//! # Turns
//!
//! One logical turn is one model action, counted as the `transport: http` path counts it. A turn
//! opens at the first `text` or `tool-call` since the run started or since the last `tool-result`,
//! and closes at the next `tool-result` or terminal event. Thinking, the streaming deltas and a
//! tool call still being written (`tool-call-started`, `tool-call-progress`) never open one: a
//! harness that streams its reasoning as its own events would otherwise burn a turn per thought,
//! and `max_turns` would mean something different on each transport. The call's turn opens when
//! its complete `tool-call` arrives, which is also the event a spent budget stops the run at.
//!
//! An A2A **segment** is a separate notion, held by [`A2aStream`]: it reads the turn counter to
//! number itself and never advances it, and a streamed fragment or a started call opens one where
//! it opens no turn.

use std::{collections::HashMap, sync::Arc, time::Instant};

use murmur_artifact::{security_warning_link, W_SEC_031};
use serde_json::Value;

use crate::{
    agent::DriverUsage,
    credential_gateway::GatewayTable,
    errors::RuntimeError,
    hooks::{HookArtifact, HookEvent, HookRuntime},
    otel::OtelEmitter,
    process_driver::{Event, FailureKind, Usage},
    spend::{SpendMeter, SpendRefusal},
    streaming::StreamArtifact,
    trace::{
        FailedInference, TraceWriter, INFERENCE_ERROR_HARNESS_AUTH, INFERENCE_ERROR_HARNESS_ERROR,
        INFERENCE_ERROR_HARNESS_OTHER, INFERENCE_ERROR_HARNESS_QUOTA,
    },
};

use super::process::RunSession;
use super::process_a2a::A2aStream;
use crate::workdir_fs::WorkdirRoot;

/// The billing mode the process transport exists for. Compared as a plain string: what any other
/// value means is the harness's business, and the runtime only reports that it is not this one.
const SUBSCRIPTION_AUTH: &str = "subscription";

/// What a batch of events did to the run.
pub(super) enum SinkOutcome {
    /// Nothing terminal; keep reading.
    Continue,
    /// The harness finished the turn. Carries the result text, already recorded.
    Ended,
    /// The harness reported the turn as failed.
    Failed(RuntimeError),
    /// A turn opened past the attempt's remaining budget. The harness is killed at once rather
    /// than given the exit grace: it is mid-turn and would otherwise keep spending.
    TurnBudgetExceeded(RuntimeError),
    /// A turn closed on or past a spend ceiling. Killed at once for the same reason a turn
    /// budget is: every further turn is spend the operator said must not happen.
    SpendCeilingReached(SpendRefusal),
}

/// One set of token counts, each member independently optional.
///
/// Used twice by [`ProcessEventSink`]: as the latest cumulative report the driver made for the
/// harness run, and as the totals already attributed to turns that have closed. `None` means the
/// harness does not report that count at all — never that it reported zero, which is `Some(0)`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct UsageCounts {
    input: Option<u64>,
    output: Option<u64>,
    cache_read: Option<u64>,
    cache_creation: Option<u64>,
    thinking: Option<u64>,
}

impl UsageCounts {
    /// The members in a fixed order, so growth and replacement walk the same list.
    fn members(&self) -> [Option<u64>; 5] {
        [
            self.input,
            self.output,
            self.cache_read,
            self.cache_creation,
            self.thinking,
        ]
    }

    fn from_members(members: [Option<u64>; 5]) -> Self {
        let [input, output, cache_read, cache_creation, thinking] = members;
        Self {
            input,
            output,
            cache_read,
            cache_creation,
            thinking,
        }
    }

    /// Replace each member `report` names, leaving the rest standing.
    ///
    /// A harness that reports output on one line and a full set on the next must not lose the
    /// earlier members, and a member missing from a later report is the harness declining to
    /// repeat itself rather than retracting what it said.
    fn overlay(&mut self, report: &Usage) {
        let incoming = [
            report.input,
            report.output,
            report.cache_read,
            report.cache_creation,
            report.thinking,
        ];
        let held = self.members();
        *self = Self::from_members(std::array::from_fn(|i| incoming[i].or(held[i])));
    }

    /// What has been reported since `attributed` was last taken, member by member, advancing
    /// `attributed` by exactly that.
    ///
    /// Every reported member is the total for the harness run so far, so only its growth belongs
    /// to the turn closing now: reporting the same total twice adds nothing, and a member that
    /// shrank contributes zero and leaves the larger total attributed, so a later report back at
    /// the earlier figure cannot be counted a second time.
    fn take_growth(&self, attributed: &mut Self) -> Self {
        let latest = self.members();
        let mut counted = attributed.members();
        let growth = std::array::from_fn(|i| {
            let latest = latest[i]?;
            let already = counted[i].unwrap_or(0);
            let grown = latest.saturating_sub(already);
            counted[i] = Some(already.saturating_add(grown));
            Some(grown)
        });
        *attributed = Self::from_members(counted);
        Self::from_members(growth)
    }
}

/// A tool call the harness reported, waiting for its result so the pair can be recorded with a
/// duration the runtime measured itself.
struct PendingToolCall {
    name: String,
    input: Value,
    input_bytes: u64,
    turn: u32,
    started: Instant,
}

/// The turn currently open: which index it will be recorded under, the text it produced, and
/// whether it called anything.
struct OpenTurn {
    index: u32,
    /// The last complete `text` event of the turn. A `text` replaces what came before it.
    text: Option<String>,
    /// The first tool this turn called, which names the turn's `tool_call` decision.
    first_tool: Option<String>,
}

/// Turns the driver's events into the records of one harness run.
///
/// Holds no harness knowledge: names arrive bare and are recorded as given, and the only text it
/// ever reads is the result it writes out.
pub(super) struct ProcessEventSink<'a> {
    /// The session's records directory, where `out/result.txt` is written and every hook fault
    /// this run raises is logged.
    records_root: WorkdirRoot,
    /// This attempt's remaining turn budget, already net of the turns earlier attempts spent.
    /// `None` refuses no turn.
    max_turns: Option<u32>,
    /// The task-wide ceiling, `inference.max_turns` as declared, which a run that opens one turn
    /// too many names.
    task_max_turns: Option<u32>,
    /// How many turns have opened in this run.
    turns: u32,
    /// The task-wide number this run's first turn takes: the agent-loop turns earlier attempts of
    /// the task recorded. Every turn this run records is numbered from it.
    first_turn: u32,
    open: Option<OpenTurn>,
    pending: HashMap<String, PendingToolCall>,
    /// Set by the first terminal event, so the rest of its batch is ignored.
    finished: bool,
    /// The conversation this run belongs to, and where its session id is remembered.
    session: RunSession,
    /// The id the harness reported for this run, if it reported one at all. What it says wins
    /// over what the runtime asked for, and its absence is half of the session-gone predicate.
    /// Held rather than stored on arrival: a harness names its session before the model has
    /// produced anything, and a turn interrupted in that window leaves the harness holding no
    /// conversation to answer to.
    reported_session: Option<String>,
    /// The latest cumulative counts the driver has reported for this run, member by member.
    usage: UsageCounts,
    /// The part of [`Self::usage`] already attributed to turns that have closed. The difference
    /// between the two is what the next turn to close records.
    attributed: UsageCounts,
    /// This session's spend account, charged with each closed turn's growth and then asked
    /// whether a ceiling has been reached.
    spend: Arc<SpendMeter>,
    /// Whether this run produced observable work — see [`produces_observable_work`]. The one
    /// condition on committing the session: a run that produced nothing established no
    /// conversation, whatever it was told its session was called.
    produced: bool,
    /// Whether the run ended because the harness could not find the session it was handed. That
    /// entry is left exactly as it was, so nothing is written over it here.
    session_gone: bool,
    /// The A2A half of the same events. Borrowed rather than owned, because the attempt reads its
    /// ending from it after this sink is done with the run.
    a2a: &'a mut A2aStream,
    /// The session's gateways, whose credentials are redacted out of a failed call's `error`.
    gateways: GatewayTable,
}

/// The `harness_failed` `max-turns` message: the turn the harness opened, by the task-wide number
/// `mur trace show` prints, and the ceiling it is past — with the turns earlier attempts of the
/// task already used, when there were any.
fn turn_budget_exceeded_message(turn: u32, ceiling: u32, used_before: u32) -> String {
    let earlier = match used_before {
        0 => String::new(),
        1 => "; earlier attempts of this task used 1 of them".to_string(),
        n => format!("; earlier attempts of this task used {n} of them"),
    };
    format!(
        "the harness opened turn {turn}, past the {ceiling} turns inference.max_turns allows \
         this task{earlier}"
    )
}

impl<'a> ProcessEventSink<'a> {
    #[allow(clippy::too_many_arguments)]
    pub(super) fn new(
        records_root: &WorkdirRoot,
        max_turns: Option<u32>,
        task_max_turns: Option<u32>,
        first_turn: u32,
        session: RunSession,
        spend: Arc<SpendMeter>,
        a2a: &'a mut A2aStream,
        gateways: GatewayTable,
    ) -> Self {
        Self {
            records_root: records_root.clone(),
            max_turns,
            task_max_turns,
            turns: 0,
            first_turn,
            open: None,
            pending: HashMap::new(),
            finished: false,
            session,
            reported_session: None,
            usage: UsageCounts::default(),
            attributed: UsageCounts::default(),
            spend,
            produced: false,
            session_gone: false,
            a2a,
            gateways,
        }
    }

    /// The session's records directory, which this run writes `out/result.txt` into.
    pub(super) fn records_root(&self) -> &WorkdirRoot {
        &self.records_root
    }

    /// The runtime is about to interrupt the harness. Everything the harness says from here on is
    /// still recorded — a partial answer is worth keeping — but the attempt ends `canceled`.
    pub(super) fn mark_interrupted(&mut self) {
        self.a2a.mark_interrupted();
    }

    /// The interrupted harness had to be killed rather than ending when it was asked.
    pub(super) fn mark_harness_killed(&mut self) {
        self.a2a.mark_harness_killed();
    }

    /// The turn a record written now belongs to: the open turn, or the last one that closed —
    /// `first_turn` before any has opened.
    pub(super) fn current_turn(&self) -> u32 {
        match self.open.as_ref() {
            Some(open) => open.index,
            None => self.first_turn + self.turns.saturating_sub(1),
        }
    }

    /// Feed one `parse` batch through. Events after a terminal one, in the same batch, are
    /// ignored: the run is over and the harness is already being shut down.
    pub(super) async fn consume(
        &mut self,
        events: Vec<Event>,
        hooks: &mut HookRuntime,
        trace: &mut TraceWriter,
        otel: &mut OtelEmitter,
    ) -> SinkOutcome {
        for event in events {
            if self.finished {
                break;
            }
            match self.handle(event, hooks, trace, otel).await {
                SinkOutcome::Continue => {}
                terminal => {
                    self.finished = true;
                    return terminal;
                }
            }
        }
        SinkOutcome::Continue
    }

    /// Close the run out: commit its session, and record every tool call the harness never
    /// answered.
    ///
    /// The one place a run writes the harness session map, and the reason it is here rather than
    /// in an event arm: a session is worth remembering once the run it belongs to has produced
    /// something, and that is only known when the run is over. A run that produced nothing
    /// commits nothing, so the next turn in that context starts a conversation the harness will
    /// answer to instead of resuming one it never opened.
    ///
    /// A call with no result is not a `tool_call` record: nothing is known about how it went, and
    /// inventing a status would put a tool call in the trace that no tool ever finished.
    ///
    /// Returns the id the harness will answer to, on exactly the condition the session is
    /// committed, and `None` otherwise: that is the session a reopened attempt of the same task
    /// resumes, whether or not the context remembers it.
    pub(super) async fn finish(&mut self, trace: &mut TraceWriter) -> Option<String> {
        let continuable = (self.produced && !self.session_gone).then(|| {
            self.session.commit(self.reported_session.as_deref());
            self.session
                .effective_id(self.reported_session.as_deref())
                .to_string()
        });
        let mut unanswered: Vec<(String, String)> = self
            .pending
            .drain()
            .map(|(id, call)| (id, call.name))
            .collect();
        unanswered.sort();
        for (id, name) in unanswered {
            let _ = trace
                .write_harness_note(&format!(
                    "the harness called tool '{name}' (id {id}) and the run ended with no result \
                     for it"
                ))
                .await;
        }
        continuable
    }

    async fn handle(
        &mut self,
        event: Event,
        hooks: &mut HookRuntime,
        trace: &mut TraceWriter,
        otel: &mut OtelEmitter,
    ) -> SinkOutcome {
        self.produced |= produces_observable_work(&event);
        match event {
            Event::SessionStarted(info) => {
                let _ = trace
                    .write_harness_session(&info.id, &info.auth, info.model.as_deref())
                    .await;
                if !info.id.is_empty() {
                    self.reported_session = Some(info.id.clone());
                }
                if info.auth != SUBSCRIPTION_AUTH {
                    let message = format!(
                        "the harness session reports auth '{}', not '{SUBSCRIPTION_AUTH}' — this \
                         run's spend may be billed to an API key rather than to the subscription \
                         this transport exists for",
                        info.auth
                    );
                    crate::runtime_err!(
                        "[capsule-runtime] warning[{W_SEC_031}]: {message} ({})",
                        security_warning_link(W_SEC_031)
                    );
                    let _ = trace.write_harness_warning(W_SEC_031, &message).await;
                }
                SinkOutcome::Continue
            }
            Event::Text(text) => {
                if let Some(exceeded) = self.open_turn(trace).await {
                    return exceeded;
                }
                self.a2a.open_segment(self.segment_turn()).await;
                self.a2a.complete_text();
                if let Some(open) = self.open.as_mut() {
                    open.text = Some(text);
                }
                SinkOutcome::Continue
            }
            Event::ToolCall(call) => {
                if let Some(exceeded) = self.open_turn(trace).await {
                    return exceeded;
                }
                // The call's own frame is the `artifact` its result writes. What this event writes
                // is the size a started call was still holding, so the client's last
                // `tool-call-progress` is the complete input's.
                self.a2a.open_segment(self.segment_turn()).await;
                let started = self.a2a.tool_call_complete(&call.id, Instant::now()).await;
                if let Some(started) = started.filter(|started| *started != call.name) {
                    let _ = trace
                        .write_harness_note(&format!(
                            "the harness started tool call id {} as '{started}' and completed it \
                             as '{}'",
                            call.id, call.name
                        ))
                        .await;
                }
                let Some(open) = self.open.as_mut() else {
                    return SinkOutcome::Continue;
                };
                if open.first_tool.is_none() {
                    open.first_tool = Some(call.name.clone());
                }
                let input: Value = serde_json::from_str(&call.input).unwrap_or(Value::Null);
                self.pending.insert(
                    call.id,
                    PendingToolCall {
                        name: call.name,
                        input,
                        input_bytes: call.input.len() as u64,
                        turn: open.index,
                        started: Instant::now(),
                    },
                );
                SinkOutcome::Continue
            }
            Event::ToolResult(result) => {
                // The turn that issued the call closes here, before the call is recorded, so the
                // trace reads in the order the work happened: the model decided, then the tool ran.
                // A ceiling reached by that turn stops the run before the tool call is recorded:
                // the tool has already run, and its record belongs to a run that is continuing.
                // A turn that asked for a tool is not the attempt's last inference turn, and its
                // `on-inference` artifacts are dropped, as the http path drops that turn's.
                if let Err(reached) = self.close_turn(hooks, trace, otel).await {
                    return reached;
                }
                let Some(call) = self.pending.remove(&result.id) else {
                    let _ = trace
                        .write_harness_note(&format!(
                            "the harness reported a result for tool call id {} with no matching \
                             call",
                            result.id
                        ))
                        .await;
                    return SinkOutcome::Continue;
                };
                let status = if result.is_error { "error" } else { "ok" };
                let output_bytes = result.output.len() as u64;
                let result_id = result.id.clone();
                let output = result.output.clone();
                // Measured by the runtime rather than taken from the harness: the bridge executes
                // the tool, and this is the only clock that saw both ends of the call.
                let duration_ms = call
                    .started
                    .elapsed()
                    .as_millis()
                    .try_into()
                    .unwrap_or(u64::MAX);
                let _ = trace
                    .write_tool_call(
                        call.turn,
                        call.name.clone(),
                        Some(result.id),
                        call.input.clone(),
                        call.input_bytes,
                        &result.output,
                        output_bytes,
                        duration_ms,
                        status.to_string(),
                        None,
                        None,
                        None,
                    )
                    .await;
                hooks
                    .emit(
                        &self.records_root,
                        HookEvent::ToolCall {
                            turn: call.turn,
                            tool_name: call.name.clone(),
                            input_bytes: call.input_bytes,
                            input: call.input.to_string(),
                            output_bytes,
                            duration_ms,
                            status: status.to_string(),
                        },
                    )
                    .await;
                // Built from the generic events alone: the call's bare name, the result's own
                // output, id and failure flag, and the runtime's own measurement — the same
                // number the `tool_call` trace record above carries. The bridge hands tool output
                // back to the harness unfenced, it ran no subprocess this runtime saw the exit of,
                // and the event carries no truncation flag, so those three keys say so.
                self.a2a
                    .tool_result(StreamArtifact::tool_call(
                        call.name,
                        output,
                        None,
                        &result_id,
                        result.is_error,
                        duration_ms,
                        None,
                        false,
                    ))
                    .await;
                SinkOutcome::Continue
            }
            // Streaming fragments and reasoning. Each is evidence the harness is alive — which
            // the runner already took from the line arriving — and none is a model action, so none
            // opens a turn. Each does open an A2A segment: the http path writes its `working`
            // status before the driver call, and therefore before any chunk.
            Event::TextDelta(text) => {
                self.a2a.open_segment(self.segment_turn()).await;
                self.a2a.text_delta(&text);
                SinkOutcome::Continue
            }
            Event::ThinkingDelta(text) => {
                self.a2a.open_segment(self.segment_turn()).await;
                self.a2a.thinking_delta(&text);
                SinkOutcome::Continue
            }
            Event::Thinking(text) => {
                self.a2a.open_segment(self.segment_turn()).await;
                self.a2a.complete_thinking(&text);
                SinkOutcome::Continue
            }
            // A tool call the model is still writing. Like a fragment it opens no turn: the call's
            // turn opens, and is counted against the budget, when the complete `tool-call`
            // arrives. Nothing is traced: the `tool_call` record at its result is the record of
            // the call.
            Event::ToolCallStarted(start) => {
                self.a2a
                    .tool_call_started(self.segment_turn(), &start.id, &start.name)
                    .await;
                SinkOutcome::Continue
            }
            Event::ToolCallProgress(progress) => {
                self.a2a
                    .tool_call_progress(&progress.id, progress.input_bytes, Instant::now())
                    .await;
                SinkOutcome::Continue
            }
            Event::Retry(retry) => {
                let _ = trace
                    .write_harness_retry(retry.attempt, &retry.reason)
                    .await;
                SinkOutcome::Continue
            }
            // Cumulative for the whole harness run, so it is held rather than added up: what a
            // turn records is the growth `close_turn` takes off it. Held member by member, so a
            // report naming only what changed leaves the rest of the last one standing.
            Event::Usage(report) => {
                self.usage.overlay(&report);
                SinkOutcome::Continue
            }
            Event::Note(text) => {
                let _ = trace.write_harness_note(&text).await;
                SinkOutcome::Continue
            }
            Event::TurnEnd(result) => {
                // A ceiling the last turn reached outranks the answer: the run stopped at the
                // operator's limit, and `out/result.txt` says so rather than holding an answer
                // the next turn would have gone past the ceiling to improve on.
                let hook_artifacts = match self.close_turn(hooks, trace, otel).await {
                    Ok(hook_artifacts) => hook_artifacts,
                    Err(reached) => return reached,
                };
                match super::record_result(hooks, &self.records_root, &result) {
                    Ok(()) => {
                        self.a2a.turn_end(&result, hook_artifacts).await;
                        SinkOutcome::Ended
                    }
                    Err(message) => SinkOutcome::Failed(RuntimeError::AgentLoopFailed(message)),
                }
            }
            Event::TurnFailed(failure) => {
                // The failure is the run's own account of itself and outranks a ceiling the same
                // turn reached: the harness said why it stopped, and that is what is reported. A
                // failed attempt forwards no hook artifact. A budget or a cancel is no failed
                // model call, so its open turn closes as an ordinary one.
                let _ = match failed_call_code(failure.kind) {
                    Some(code) => {
                        self.record_failed_call(hooks, trace, otel, code, &failure.message)
                            .await
                    }
                    None => self.close_turn(hooks, trace, otel).await,
                };
                self.a2a.turn_failed();
                let kind = failure_kind_name(failure.kind);
                let _ = trace
                    .write_harness_failed(kind, &failure.message, "harness")
                    .await;
                // A turn launched `mode: resume` that failed without the harness ever reporting
                // the session it was handed is the harness saying it does not hold the
                // conversation this context names, which is its own failure — and leaves the
                // entry naming it exactly where it was.
                if let Some(gone) = self.session.session_gone(
                    failure.kind,
                    self.reported_session.is_some(),
                    &failure.message,
                ) {
                    self.session_gone = true;
                    return SinkOutcome::Failed(gone);
                }
                SinkOutcome::Failed(RuntimeError::HarnessTurnFailed {
                    kind: kind.to_string(),
                    message: failure.message,
                    origin: "harness".to_string(),
                })
            }
        }
    }

    /// The number, 1-based, that the turn counter would record a turn opening now under — which
    /// is the number the A2A segment opening with it carries. Reads the counter and never
    /// advances it: a segment is not a turn, and must not spend `max_turns` budget.
    fn segment_turn(&self) -> u32 {
        match self.open.as_ref() {
            Some(open) => open.index + 1,
            None => self.first_turn + self.turns + 1,
        }
    }

    /// Open a turn if none is open. Returns `Some` when doing so would exceed the attempt's
    /// budget, in which case no turn is opened and the run is over.
    async fn open_turn(&mut self, trace: &mut TraceWriter) -> Option<SinkOutcome> {
        if self.open.is_some() {
            return None;
        }
        self.turns += 1;
        if let Some(max_turns) = self.max_turns.filter(|max_turns| self.turns > *max_turns) {
            let ceiling = self.task_max_turns.unwrap_or(max_turns);
            let message = turn_budget_exceeded_message(
                self.first_turn + self.turns - 1,
                ceiling,
                ceiling.saturating_sub(max_turns),
            );
            let _ = trace
                .write_harness_failed("max-turns", &message, "runtime")
                .await;
            return Some(SinkOutcome::TurnBudgetExceeded(
                RuntimeError::HarnessTurnFailed {
                    kind: "max-turns".to_string(),
                    message,
                    origin: "runtime".to_string(),
                },
            ));
        }
        self.open = Some(OpenTurn {
            index: self.first_turn + self.turns - 1,
            text: None,
            first_tool: None,
        });
        None
    }

    /// Write the open turn's `inference` record, if one is open, charge what it cost, and hand
    /// back the artifacts its `on-inference` hooks returned — none when no turn was open — or the
    /// run's end when that took the session to a spend ceiling.
    ///
    /// The counts are the harness's own, as its driver reported them, and this transport has no
    /// second measurement: the growth of the cumulative `usage` report goes into the record's
    /// `input_tokens`/`output_tokens` — which is what the task and session totals accumulate —
    /// and `input_tokens_actual`/`output_tokens_actual` stay absent. Cache read, cache creation
    /// and thinking ride along in a [`DriverUsage`] carrying nothing else. A driver that reported
    /// no usage leaves each count absent, which the trace keeps distinct from a count of zero.
    ///
    /// The hook is handed `0` where the trace holds absent: `murmur:hook`'s `inference-event`
    /// declares both counts as plain `u64` with no optional form, and widening them would break
    /// every published hook artifact. The absent/zero distinction lives in the trace.
    async fn close_turn(
        &mut self,
        hooks: &mut HookRuntime,
        trace: &mut TraceWriter,
        otel: &mut OtelEmitter,
    ) -> Result<Vec<HookArtifact>, SinkOutcome> {
        self.close_turn_as(hooks, trace, otel, None).await
    }

    /// Record a model call the harness failed, with `error_code` from the `INFERENCE_ERROR_*`
    /// vocabulary and `message` with the session's credentials redacted.
    ///
    /// A turn that is open closes exactly as [`Self::close_turn`] closes it — counted, with the
    /// harness's own counts, its OTel span, its `on-inference` hook and its spend charge — except
    /// that its record and its `decision` say it failed. With no turn open the record is written
    /// at the turn that would open next and counts nothing.
    pub(super) async fn record_failed_call(
        &mut self,
        hooks: &mut HookRuntime,
        trace: &mut TraceWriter,
        otel: &mut OtelEmitter,
        error_code: &'static str,
        message: &str,
    ) -> Result<Vec<HookArtifact>, SinkOutcome> {
        let error = self.gateways.redact(message);
        if self.open.is_none() {
            let _ = trace
                .write_failed_inference(FailedInference {
                    turn: self.first_turn + self.turns,
                    error_code,
                    error: &error,
                    provider_status: None,
                    usage: None,
                    origin: None,
                    choice: None,
                    message_ids: Vec::new(),
                    tool_name: None,
                    spent: None,
                    settings: None,
                    retry: crate::inference_retry::RetryNote::default(),
                })
                .await;
            return Ok(Vec::new());
        }
        self.close_turn_as(hooks, trace, otel, Some((error_code, &error)))
            .await
    }

    /// [`Self::close_turn`], recording the turn as a failed call when `failure` names one as
    /// `(error_code, error)`.
    async fn close_turn_as(
        &mut self,
        hooks: &mut HookRuntime,
        trace: &mut TraceWriter,
        otel: &mut OtelEmitter,
        failure: Option<(&'static str, &str)>,
    ) -> Result<Vec<HookArtifact>, SinkOutcome> {
        let Some(open) = self.open.take() else {
            return Ok(Vec::new());
        };
        let decision = if failure.is_some() {
            "error"
        } else if open.first_tool.is_some() {
            "tool_call"
        } else {
            "end_turn"
        };
        let spent = self.usage.take_growth(&mut self.attributed);
        // `None` throughout rather than a record of absences, so an unreporting driver's turn
        // carries no provider keys at all.
        let reported = (spent != UsageCounts::default()).then_some(DriverUsage {
            input_tokens: None,
            output_tokens: None,
            cached_tokens: spent.cache_read,
            cache_write_tokens: spent.cache_creation,
            thinking_tokens: spent.thinking,
        });
        let _ = match failure {
            Some((error_code, error)) => {
                trace
                    .write_failed_inference(FailedInference {
                        turn: open.index,
                        error_code,
                        error,
                        // A harness reports no HTTP status.
                        provider_status: None,
                        usage: reported.as_ref(),
                        origin: None,
                        choice: None,
                        message_ids: Vec::new(),
                        tool_name: open.first_tool.clone(),
                        spent: Some((spent.input, spent.output)),
                        settings: None,
                        retry: crate::inference_retry::RetryNote::default(),
                    })
                    .await
            }
            None => {
                trace
                    .write_inference(
                        open.index,
                        spent.input,
                        spent.output,
                        decision.to_string(),
                        // The runtime reads no driver response of its own on this transport, so
                        // there is no provider stop reason and no request payload to hash.
                        None,
                        open.first_tool.clone(),
                        None,
                        reported.as_ref(),
                        Vec::new(),
                        None,
                        None,
                    )
                    .await
            }
        };
        otel.emit_inference(
            open.index,
            spent.input,
            spent.output,
            decision,
            None,
            open.first_tool.as_deref(),
            0,
            None,
            reported.as_ref(),
        )
        .await;
        // No hook inference flush after this emit or the `on-tool-call` one: a hook's
        // `run-inference` is answered with `InferenceUnavailable::ProcessTransport` on this
        // transport, so it buffers no `HookInferenceRecord` or spend refusal. A change that lets
        // the call through must flush at both, ahead of the turn's own record, as http does.
        let hook_artifacts = hooks
            .emit(
                &self.records_root,
                HookEvent::Inference {
                    turn: open.index,
                    input_tokens: spent.input.unwrap_or(0),
                    output_tokens: spent.output.unwrap_or(0),
                    decision: decision.to_string(),
                    // The same value the trace records, so a hook bound to `on-inference` reads
                    // the same turn on either transport.
                    tool_name: open.first_tool.clone(),
                    prompt: None,
                    output: open.text,
                    tools: None,
                },
            )
            .await;
        // Charged after the record is written, so what the meter holds is always a sum of lines
        // already in the trace. Cache and thinking are not charged: the meter's definition is
        // `input + output` on both transports.
        self.spend
            .charge_spent(spent.input.unwrap_or(0), spent.output.unwrap_or(0));
        let Some(refusal) = self.spend.ceiling_crossed() else {
            return Ok(hook_artifacts);
        };
        let _ = trace
            .write_spend_ceiling_reached(open.index, &refusal, None)
            .await;
        self.a2a.mark_spend_refused(&refusal);
        Err(SinkOutcome::SpendCeilingReached(refusal))
    }
}

/// Whether an event is work the harness actually produced, which is the whole of what makes a
/// run's session id worth keeping.
///
/// Eight events say yes: a complete or streamed piece of text, a complete or streamed thought, a
/// tool call complete or still being written, and a turn that ended. `turn-end` counts whatever
/// its result text says — a turn that ran to completion is a conversation the harness holds,
/// however little it had to say.
///
/// The rest say no, and `session-started` is why this predicate exists: a harness prints the name
/// of its session before the model has produced anything and before it has written a transcript,
/// so a run that got no further leaves the harness with nothing to answer to under that name. A
/// retry, a note, a tool result and a failed turn each report on work rather than being it.
fn produces_observable_work(event: &Event) -> bool {
    matches!(
        event,
        Event::Text(_)
            | Event::TextDelta(_)
            | Event::Thinking(_)
            | Event::ThinkingDelta(_)
            | Event::ToolCall(_)
            | Event::ToolCallStarted(_)
            | Event::ToolCallProgress(_)
            | Event::TurnEnd(_)
    )
}

/// The `inference.error_code` a harness failure of `kind` records, or `None` for a kind that is
/// a budget or a cancel rather than a failed model call.
fn failed_call_code(kind: FailureKind) -> Option<&'static str> {
    match kind {
        FailureKind::Auth => Some(INFERENCE_ERROR_HARNESS_AUTH),
        FailureKind::Quota => Some(INFERENCE_ERROR_HARNESS_QUOTA),
        FailureKind::HarnessError => Some(INFERENCE_ERROR_HARNESS_ERROR),
        FailureKind::Other => Some(INFERENCE_ERROR_HARNESS_OTHER),
        FailureKind::MaxTurns | FailureKind::Canceled => None,
    }
}

/// The WIT spelling of a `failure-kind`, which is what the error and the trace both name.
pub(super) fn failure_kind_name(kind: FailureKind) -> &'static str {
    match kind {
        FailureKind::Auth => "auth",
        FailureKind::Quota => "quota",
        FailureKind::MaxTurns => "max-turns",
        FailureKind::Canceled => "canceled",
        FailureKind::HarnessError => "harness-error",
        FailureKind::Other => "other",
    }
}

#[cfg(test)]
mod tests {
    use std::path::{Path, PathBuf};
    use std::sync::{atomic::AtomicBool, Arc, Mutex};

    use super::*;
    use crate::agent::process::{plan_session, HarnessSessionPolicy, SessionPlan};
    use crate::harness_session::HarnessSessionMap;
    use crate::process_driver::{
        RetryInfo, SessionInfo, ToolCallInfo, ToolCallProgress, ToolCallStart, ToolResultInfo,
        TurnFailure,
    };
    use crate::streaming::{buffered, event_kind, frame_of, SseEventBuffer};
    use serde_json::Value as Json;

    /// The context every sink below runs a task under.
    const CONTEXT: &str = "ctx_test";

    /// The harness name every sink below records with the session it remembers.
    const HARNESS: &str = "fixture-harness";

    /// The label an event reads as: its kind, and for the two kinds whose shape depends on a
    /// key, the key. The same labelling the process/http parity tests compare sequences with.
    fn frame_kind(event: &Json) -> String {
        match event_kind(event).as_str() {
            "status-update" => {
                let status = &event["statusUpdate"]["status"];
                let state = status["state"].as_str().unwrap_or_default();
                let state = crate::a2a::murmur_state_name(state).unwrap_or(state);
                match state {
                    "working" => format!(
                        "status:working:{}",
                        status["message"]["parts"][0]["text"]
                            .as_str()
                            .unwrap_or_default()
                    ),
                    state => format!("status:{state}"),
                }
            }
            "text" => match frame_of(event)["final"] == Json::Bool(true) {
                true => "text:final".to_string(),
                false => "text:chunk".to_string(),
            },
            other => other.to_string(),
        }
    }

    /// What every event of `kind` says, in order: a murmur frame's payload, or a
    /// `statusUpdate`'s body for `"status"`.
    fn data_of(events: &[Json], kind: &str) -> Vec<Json> {
        events
            .iter()
            .filter_map(|event| match (kind, event_kind(event).as_str()) {
                ("status", "status-update") => Some(event["statusUpdate"].clone()),
                (wanted, found) if wanted == found => Some(frame_of(event)),
                _ => None,
            })
            .collect()
    }

    /// A sink's sinks and the workdir they write into. Held together so a test can drop the
    /// tempdir only after reading `trace.jsonl` back, and so one A2A stream spans every batch a
    /// test feeds.
    struct Harness {
        _dir: tempfile::TempDir,
        workdir: PathBuf,
        max_turns: Option<u32>,
        /// The task-wide ceiling the sink names; [`Self::max_turns`] unless a test continues a
        /// task.
        task_max_turns: Option<u32>,
        /// The task-wide number the sink's first turn takes; 0 unless a test continues a task.
        first_turn: u32,
        /// The session policy and plan this harness runs under. Held rather than the `RunSession`
        /// itself because [`ProcessEventSink::new`] takes one by value, and the sink is rebuilt
        /// per batch; planning once keeps `planned_id` the id every batch is handed.
        policy: HarnessSessionPolicy,
        plan: SessionPlan,
        /// The spend account every batch's sink shares, so a ceiling test can hold one across
        /// several batches the way one run does.
        spend: Arc<SpendMeter>,
        a2a: A2aStream,
        /// Every frame the A2A stream wrote, in order, as the session buffer recorded them.
        frames: Arc<Mutex<SseEventBuffer>>,
        hooks: HookRuntime,
        trace: TraceWriter,
        otel: OtelEmitter,
        /// The map the sink writes back into, so a test can read what the run remembered.
        map: Arc<HarnessSessionMap>,
        /// The id the runtime handed the harness for this run.
        planned_id: String,
        /// What the last batch's `finish` handed back for a reopened attempt to resume.
        carried: Option<String>,
        /// The sink's `current_turn` at the end of the last batch.
        turn: u32,
    }

    impl Harness {
        async fn new(max_turns: u32) -> Self {
            Self::threading(
                max_turns,
                Arc::new(HarnessSessionMap::new(
                    None,
                    &crate::workdir_fs::WorkdirRoot::open(Path::new("/tmp")).unwrap(),
                )),
            )
            .await
        }

        /// The same harness, running a continued attempt of a task that already recorded
        /// `first_turn` turns.
        fn continuing_from(mut self, first_turn: u32) -> Self {
            self.first_turn = first_turn;
            self
        }

        /// The same harness, under a task-wide `inference.max_turns` of `ceiling`.
        fn under_ceiling(mut self, ceiling: u32) -> Self {
            self.task_max_turns = Some(ceiling);
            self
        }

        /// The same harness, with no `inference.max_turns`.
        fn uncapped(mut self) -> Self {
            self.max_turns = None;
            self.task_max_turns = None;
            self
        }

        /// The same harness, metered by `spend` rather than by an unlimited meter.
        fn metered(mut self, spend: SpendMeter) -> Self {
            self.spend = Arc::new(spend);
            self
        }

        /// A sink threading `CONTEXT` through `map`: `mode: resume` when the map already holds an
        /// id for it, `mode: new` otherwise.
        async fn threading(max_turns: u32, map: Arc<HarnessSessionMap>) -> Self {
            let dir = tempfile::tempdir().unwrap();
            let workdir = dir.path().to_path_buf();
            std::fs::create_dir_all(workdir.join("tools")).unwrap();
            let engine = crate::runtime::build_engine().unwrap();
            let hooks = HookRuntime::new(
                &engine,
                &crate::workdir_fs::WorkdirRoot::open(&workdir).unwrap(),
                &workdir,
                Vec::new(),
                crate::hooks::SessionContextData {
                    capsule_name: "cap".to_string(),
                    capsule_version: "0.1.0".to_string(),
                    session_id: "ses_test".to_string(),
                    model: "test-model".to_string(),
                    capabilities: Vec::new(),
                },
                crate::hooks::HookEnvVars::default(),
                crate::limits::ExecutionLimits::default(),
                Err(crate::inference_import::InferenceUnavailable::NotConfigured),
                None,
            )
            .await
            .unwrap();
            let trace = TraceWriter::open(
                &crate::workdir_fs::WorkdirRoot::open(&workdir).unwrap(),
                "ses_test".to_string(),
                "cap".to_string(),
                "0.1.0".to_string(),
                "test-model".to_string(),
                Vec::new(),
                crate::containment::report_for(
                    &crate::CapabilityPolicy::default(),
                    murmur_artifact::ContainmentClass::Advisory,
                    crate::sandbox::EnforcementTier::EnvironmentOnly,
                    None,
                    None,
                    None,
                    None,
                    Vec::new(),
                    Vec::new(),
                    Vec::new(),
                    &crate::runtime_dir::RuntimeDirPlacement::outside_for_test(),
                    crate::temp_dir::tier_temp_mapping(crate::sandbox::applied_tier(
                        crate::sandbox::EnforcementTier::EnvironmentOnly,
                        murmur_artifact::ContainmentClass::Advisory,
                    )),
                    crate::cgroup::IoMaxReport::default(),
                ),
                murmur_artifact::TraceCapture::Meta,
                None,
                false,
                None,
                None,
                None,
                None,
            )
            .await
            .unwrap();
            let otel = OtelEmitter::new(
                None,
                &crate::workdir_fs::WorkdirRoot::open(&workdir).unwrap(),
                "cap".to_string(),
                "0.1.0".to_string(),
            );
            let policy = HarnessSessionPolicy {
                map: Arc::clone(&map),
                context_id: Some(CONTEXT.to_string()),
                continue_conversation: true,
                forget: None,
                reopen_session: None,
            };
            let plan = plan_session(&policy);
            let planned_id = plan.session.id.clone();
            // A real broadcast and buffer, so the frames these tests read are the bytes a client
            // would have received. The buffer records them whether or not a receiver is attached,
            // which is what these tests read back.
            let (tx, _rx) = tokio::sync::broadcast::channel(256);
            let frames = Arc::new(Mutex::new(SseEventBuffer::new(256)));
            Self {
                _dir: dir,
                workdir: workdir.clone(),
                max_turns: Some(max_turns),
                task_max_turns: Some(max_turns),
                first_turn: 0,
                policy,
                plan,
                spend: Arc::new(SpendMeter::unlimited()),
                a2a: A2aStream::new(
                    Some((tx, Arc::clone(&frames))),
                    Some("tsk_test".to_string()),
                    Some(CONTEXT.to_string()),
                    Arc::new(AtomicBool::new(false)),
                ),
                frames,
                hooks,
                trace,
                otel,
                map,
                planned_id,
                carried: None,
                turn: 0,
            }
        }

        /// The sink is built per batch because it borrows the stream; its turn state is a
        /// test-local concern and every test here feeds exactly one batch.
        async fn feed(&mut self, events: Vec<Event>) -> SinkOutcome {
            let session = RunSession::new(&self.plan, &self.policy, HARNESS, "fixture-driver");
            let mut sink = ProcessEventSink::new(
                &crate::workdir_fs::WorkdirRoot::open(&self.workdir).unwrap(),
                self.max_turns,
                self.task_max_turns,
                self.first_turn,
                session,
                Arc::clone(&self.spend),
                &mut self.a2a,
                GatewayTable::default(),
            );
            let outcome = sink
                .consume(events, &mut self.hooks, &mut self.trace, &mut self.otel)
                .await;
            self.turn = sink.current_turn();
            self.carried = sink.finish(&mut self.trace).await;
            outcome
        }

        /// [`Self::feed`], then the harness goes silent past the inactivity timeout before the
        /// run reads another line: the sink records the failed call as `process.rs`'s
        /// `RunEnd::Inactive` arm does.
        async fn feed_then_go_quiet(&mut self, events: Vec<Event>) {
            let session = RunSession::new(&self.plan, &self.policy, HARNESS, "fixture-driver");
            let mut sink = ProcessEventSink::new(
                &crate::workdir_fs::WorkdirRoot::open(&self.workdir).unwrap(),
                self.max_turns,
                self.task_max_turns,
                self.first_turn,
                session,
                Arc::clone(&self.spend),
                &mut self.a2a,
                GatewayTable::default(),
            );
            sink.consume(events, &mut self.hooks, &mut self.trace, &mut self.otel)
                .await;
            let _ = sink
                .record_failed_call(
                    &mut self.hooks,
                    &mut self.trace,
                    &mut self.otel,
                    crate::trace::INFERENCE_ERROR_HARNESS_INACTIVE,
                    "the harness went quiet",
                )
                .await;
            self.turn = sink.current_turn();
            self.carried = sink.finish(&mut self.trace).await;
        }

        /// Each frame the A2A stream wrote, labelled by kind, in order.
        fn frame_kinds(&self) -> Vec<String> {
            self.frames().iter().map(frame_kind).collect()
        }

        /// Each event's `StreamResponse`, as an activated connection reads it, in order.
        fn frames(&self) -> Vec<Json> {
            buffered(&self.frames)
        }

        /// Every event written so far, parsed.
        async fn events(&mut self) -> Vec<Json> {
            self.trace.flush().await.unwrap();
            std::fs::read_to_string(self.workdir.join("trace.jsonl"))
                .unwrap()
                .lines()
                .filter(|line| !line.is_empty())
                .map(|line| serde_json::from_str(line).unwrap())
                .collect()
        }

        async fn of_type(&mut self, event_type: &str) -> Vec<Json> {
            self.events()
                .await
                .into_iter()
                .filter(|event| event["event_type"] == event_type)
                .collect()
        }
    }

    fn text(t: &str) -> Event {
        Event::Text(t.to_string())
    }

    fn tool_call(id: &str, name: &str) -> Event {
        Event::ToolCall(ToolCallInfo {
            id: id.to_string(),
            name: name.to_string(),
            input: r#"{"msg":"hi"}"#.to_string(),
        })
    }

    fn tool_result(id: &str, is_error: bool) -> Event {
        Event::ToolResult(ToolResultInfo {
            id: id.to_string(),
            output: "done".to_string(),
            is_error,
        })
    }

    fn tool_call_started(id: &str, name: &str) -> Event {
        Event::ToolCallStarted(ToolCallStart {
            id: id.to_string(),
            name: name.to_string(),
        })
    }

    fn tool_call_progress(id: &str, input_bytes: u64) -> Event {
        Event::ToolCallProgress(ToolCallProgress {
            id: id.to_string(),
            input_bytes,
        })
    }

    /// A `usage` report naming only some members, with the rest of the last one standing.
    fn usage(members: &[(&str, u64)]) -> Event {
        let mut report = Usage {
            input: None,
            output: None,
            cache_read: None,
            cache_creation: None,
            thinking: None,
        };
        for (member, value) in members {
            let slot = match *member {
                "in" => &mut report.input,
                "out" => &mut report.output,
                "cache-read" => &mut report.cache_read,
                "cache-creation" => &mut report.cache_creation,
                "thinking" => &mut report.thinking,
                other => panic!("no such usage member: {other}"),
            };
            *slot = Some(*value);
        }
        Event::Usage(report)
    }

    /// The reported counts land in `input_tokens`/`output_tokens` — which is what the totals
    /// accumulate — and the cache and thinking counts sit beside them. `*_actual` stays absent:
    /// there is one measurement on this transport and it is recorded once.
    #[tokio::test]
    async fn usage_a_reported_turn_carries_the_harness_counts() {
        let mut h = Harness::new(10).await;
        h.feed(vec![
            usage(&[
                ("in", 120),
                ("out", 30),
                ("cache-read", 900),
                ("cache-creation", 64),
                ("thinking", 2),
            ]),
            text("answer"),
            Event::TurnEnd("answer".into()),
        ])
        .await;
        let inference = &h.of_type("inference").await[0];
        assert_eq!(inference["input_tokens"], 120);
        assert_eq!(inference["output_tokens"], 30);
        assert_eq!(inference["cached_tokens"], 900);
        assert_eq!(inference["cache_write_tokens"], 64);
        assert_eq!(inference["thinking_tokens"], 2);
        assert!(
            inference.get("input_tokens_actual").is_none(),
            "{inference}"
        );
        assert!(
            inference.get("output_tokens_actual").is_none(),
            "{inference}"
        );
    }

    /// A driver that reported nothing leaves both counts off the record entirely, which is a
    /// different fact from a harness that reported spending none.
    #[tokio::test]
    async fn usage_an_unreported_turn_carries_no_counts_at_all() {
        let mut h = Harness::new(10).await;
        h.feed(vec![text("answer"), Event::TurnEnd("answer".into())])
            .await;
        let inference = &h.of_type("inference").await[0];
        assert!(inference.get("input_tokens").is_none(), "{inference}");
        assert!(inference.get("output_tokens").is_none(), "{inference}");
        assert!(inference.get("thinking_tokens").is_none(), "{inference}");
    }

    #[tokio::test]
    async fn usage_a_reported_zero_is_written_as_zero() {
        let mut h = Harness::new(10).await;
        h.feed(vec![
            usage(&[("in", 0), ("out", 0)]),
            text("answer"),
            Event::TurnEnd("answer".into()),
        ])
        .await;
        let inference = &h.of_type("inference").await[0];
        assert_eq!(inference["input_tokens"], 0);
        assert_eq!(inference["output_tokens"], 0);
    }

    /// Every report is the total for the run, so the second turn is charged the growth alone and
    /// the two turns together add up to the last report rather than to twice it.
    #[tokio::test]
    async fn usage_is_cumulative_so_each_turn_records_only_its_growth() {
        let mut h = Harness::new(10).await;
        h.feed(vec![
            usage(&[("in", 40), ("out", 20)]),
            tool_call("c1", "t"),
            tool_result("c1", false),
            usage(&[("in", 100), ("out", 50)]),
            text("two"),
            Event::TurnEnd("two".into()),
        ])
        .await;
        let inferences = h.of_type("inference").await;
        assert_eq!(inferences.len(), 2);
        assert_eq!(inferences[0]["input_tokens"], 40);
        assert_eq!(inferences[0]["output_tokens"], 20);
        assert_eq!(inferences[1]["input_tokens"], 60);
        assert_eq!(inferences[1]["output_tokens"], 30);
    }

    /// The same total reported twice adds nothing, and a member that shrinks contributes zero
    /// rather than wrapping or subtracting.
    #[tokio::test]
    async fn usage_repeated_and_shrinking_reports_add_nothing() {
        let mut h = Harness::new(10).await;
        h.feed(vec![
            usage(&[("in", 100), ("out", 50)]),
            tool_call("c1", "t"),
            tool_result("c1", false),
            usage(&[("in", 100), ("out", 10)]),
            text("two"),
            Event::TurnEnd("two".into()),
        ])
        .await;
        let inferences = h.of_type("inference").await;
        assert_eq!(inferences[1]["input_tokens"], 0);
        assert_eq!(inferences[1]["output_tokens"], 0);
    }

    /// A member a later report omits keeps the value the earlier one gave it, rather than being
    /// retracted and counted again from zero.
    #[tokio::test]
    async fn usage_a_member_a_later_report_omits_keeps_standing() {
        let mut h = Harness::new(10).await;
        h.feed(vec![
            usage(&[("in", 100), ("cache-read", 7)]),
            tool_call("c1", "t"),
            tool_result("c1", false),
            usage(&[("out", 5)]),
            text("two"),
            Event::TurnEnd("two".into()),
        ])
        .await;
        let inferences = h.of_type("inference").await;
        assert_eq!(inferences[0]["input_tokens"], 100);
        assert_eq!(inferences[0]["cached_tokens"], 7);
        assert_eq!(inferences[1]["input_tokens"], 0);
        assert_eq!(inferences[1]["output_tokens"], 5);
        // Reported once means reported from then on: the second turn's growth over the same
        // total is zero, which is a count, not an absence.
        assert_eq!(inferences[1]["cached_tokens"], 0);
    }

    /// The meter is charged `input + output` alone, and a turn that reaches the ceiling ends
    /// the run with the refusal and its `spend_ceiling_reached` record.
    #[tokio::test]
    async fn usage_reaches_the_spend_meter_and_crosses_its_ceiling() {
        let mut h = Harness::new(10)
            .await
            .metered(SpendMeter::new(Some(100), None));
        let outcome = h
            .feed(vec![
                usage(&[("in", 80), ("out", 40), ("cache-read", 9_000)]),
                text("answer"),
                Event::TurnEnd("answer".into()),
            ])
            .await;
        let refusal = match outcome {
            SinkOutcome::SpendCeilingReached(refusal) => refusal,
            _ => panic!("a turn past the ceiling must end the run"),
        };
        // Cache reads are never folded into what the meter charges: 80 + 40 crosses 100, and the
        // 9000 cached prompt tokens are beside it rather than inside it.
        assert_eq!(refusal.used, 120);
        assert_eq!(refusal.requested, 0);
        let reached = h.of_type("spend_ceiling_reached").await;
        assert_eq!(reached.len(), 1);
        assert_eq!(reached[0]["limit"], "session");
        assert!(
            refusal
                .to_string()
                .contains("inference.max_session_tokens is 100"),
            "{refusal}"
        );
    }

    /// A run under the ceiling ends the way it would with no ceiling at all.
    #[tokio::test]
    async fn usage_a_run_under_the_ceiling_is_untouched() {
        let mut h = Harness::new(10)
            .await
            .metered(SpendMeter::new(Some(1_000), None));
        let outcome = h
            .feed(vec![
                usage(&[("in", 80), ("out", 40)]),
                text("answer"),
                Event::TurnEnd("answer".into()),
            ])
            .await;
        assert!(matches!(outcome, SinkOutcome::Ended));
        assert!(h.of_type("spend_ceiling_reached").await.is_empty());
    }

    #[tokio::test]
    async fn one_text_and_a_terminal_event_are_one_turn() {
        let mut h = Harness::new(10).await;
        assert!(matches!(
            h.feed(vec![text("hello"), Event::TurnEnd("hello".into())])
                .await,
            SinkOutcome::Ended
        ));
        let inferences = h.of_type("inference").await;
        assert_eq!(inferences.len(), 1);
        assert_eq!(inferences[0]["decision"], "end_turn");
        assert_eq!(
            std::fs::read_to_string(h.workdir.join("out/result.txt")).unwrap(),
            "hello"
        );
    }

    /// A tool result closes the turn that issued the call, and the next action opens a new one.
    #[tokio::test]
    async fn a_tool_result_closes_its_turn_and_the_next_action_opens_another() {
        let mut h = Harness::new(10).await;
        h.feed(vec![
            tool_call("c1", "echo-tool"),
            tool_result("c1", false),
            text("all done"),
            Event::TurnEnd("all done".into()),
        ])
        .await;
        let inferences = h.of_type("inference").await;
        assert_eq!(inferences.len(), 2, "{inferences:#?}");
        assert_eq!(inferences[0]["decision"], "tool_call");
        assert_eq!(inferences[0]["tool_name"], "echo-tool");
        assert_eq!(inferences[0]["turn"], 0);
        assert_eq!(inferences[1]["decision"], "end_turn");
        assert_eq!(inferences[1]["turn"], 1);

        let calls = h.of_type("tool_call").await;
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0]["tool_name"], "echo-tool");
        assert_eq!(calls[0]["tool_call_id"], "c1");
        assert_eq!(calls[0]["status"], "ok");
        assert_eq!(calls[0]["turn"], 0);
    }

    /// A continued attempt numbers its turns on from the task's earlier ones, on the trace and on
    /// the A2A stream alike, while its budget still counts only its own turns.
    #[tokio::test]
    async fn a_continued_attempt_numbers_its_turns_from_the_task_s_first_turn() {
        let mut h = Harness::new(2).await.continuing_from(3);
        h.feed(Vec::new()).await;
        assert_eq!(
            h.turn, 3,
            "before any turn opens, the current turn is the first one"
        );

        let mut h = Harness::new(2).await.continuing_from(3);
        h.feed(vec![
            tool_call("c1", "echo-tool"),
            tool_result("c1", false),
            text("all done"),
            Event::TurnEnd("all done".into()),
        ])
        .await;
        let turns: Vec<Json> = h
            .of_type("inference")
            .await
            .into_iter()
            .map(|record| record["turn"].clone())
            .collect();
        assert_eq!(turns, [3, 4]);
        assert_eq!(h.of_type("tool_call").await[0]["turn"], 3);
        assert_eq!(h.turn, 4);
        let statuses: Vec<String> = h
            .frame_kinds()
            .into_iter()
            .filter(|kind| kind.starts_with("status:working:inference turn"))
            .collect();
        assert_eq!(
            statuses,
            [
                "status:working:inference turn 4",
                "status:working:inference turn 5"
            ]
        );

        let mut h = Harness::new(2).await.continuing_from(3);
        let outcome = h
            .feed(vec![
                tool_call("c1", "t"),
                tool_result("c1", false),
                tool_call("c2", "t"),
                tool_result("c2", false),
                text("a third turn"),
            ])
            .await;
        assert!(
            matches!(outcome, SinkOutcome::TurnBudgetExceeded(_)),
            "the attempt's own budget of two turns still bounds it"
        );
        assert_eq!(h.of_type("inference").await.len(), 2);
    }

    #[tokio::test]
    async fn an_error_result_is_recorded_as_one() {
        let mut h = Harness::new(10).await;
        h.feed(vec![
            tool_call("c1", "echo-tool"),
            tool_result("c1", true),
            Event::TurnEnd(String::new()),
        ])
        .await;
        assert_eq!(h.of_type("tool_call").await[0]["status"], "error");
    }

    /// Thinking and the streaming deltas are not model actions: a run of nothing but those, then
    /// one `text`, is one turn.
    #[tokio::test]
    async fn thinking_and_deltas_never_open_a_turn() {
        let mut h = Harness::new(1).await;
        let outcome = h
            .feed(vec![
                Event::Thinking("pondering".into()),
                Event::ThinkingDelta("more".into()),
                Event::TextDelta("par".into()),
                text("answer"),
                Event::TurnEnd("answer".into()),
            ])
            .await;
        assert!(matches!(outcome, SinkOutcome::Ended));
        assert_eq!(h.of_type("inference").await.len(), 1);
    }

    #[tokio::test]
    async fn a_turn_past_the_budget_ends_the_run() {
        let mut h = Harness::new(1).await;
        let outcome = h
            .feed(vec![
                tool_call("c1", "t"),
                tool_result("c1", false),
                text("a second turn"),
            ])
            .await;
        match outcome {
            SinkOutcome::TurnBudgetExceeded(RuntimeError::HarnessTurnFailed {
                kind,
                origin,
                ..
            }) => {
                assert_eq!(kind, "max-turns");
                assert_eq!(origin, "runtime");
            }
            _ => panic!("a turn past the budget must end the run"),
        }
        assert_eq!(h.of_type("inference").await.len(), 1);
        let failed = h.of_type("harness_failed").await;
        assert_eq!(failed[0]["kind"], "max-turns");
        assert_eq!(failed[0]["source"], "runtime");
    }

    /// With no `inference.max_turns`, the sink opens every turn the harness reports.
    #[tokio::test]
    async fn no_turn_cap_refuses_no_turn() {
        let mut h = Harness::new(1).await.uncapped();
        let mut events = Vec::new();
        for call in 0..12 {
            let id = format!("c{call}");
            events.push(tool_call(&id, "t"));
            events.push(tool_result(&id, false));
        }
        events.push(text("the last turn"));
        let outcome = h.feed(events).await;
        assert!(
            !matches!(outcome, SinkOutcome::TurnBudgetExceeded(_)),
            "an uncapped run refuses no turn"
        );
        // Each turn is written when the next one opens; the thirteenth is still open.
        assert_eq!(h.of_type("inference").await.len(), 12);
        assert_eq!(h.turn, 12);
        assert!(h.of_type("harness_failed").await.is_empty());
    }

    /// A continued attempt that opens a turn past its budget names that turn as `mur trace show`
    /// numbers it across the task, the task-wide ceiling, and the turns earlier attempts used.
    #[tokio::test]
    async fn a_turn_past_the_budget_names_the_task_wide_turn_and_the_ceiling() {
        let mut h = Harness::new(2).await.continuing_from(3).under_ceiling(5);
        let outcome = h
            .feed(vec![
                tool_call("c1", "t"),
                tool_result("c1", false),
                tool_call("c2", "t"),
                tool_result("c2", false),
                text("a third turn"),
            ])
            .await;
        let expected = "the harness opened turn 5, past the 5 turns inference.max_turns allows \
                        this task; earlier attempts of this task used 3 of them";
        match outcome {
            SinkOutcome::TurnBudgetExceeded(RuntimeError::HarnessTurnFailed {
                kind,
                message,
                ..
            }) => {
                assert_eq!(kind, "max-turns");
                assert_eq!(message, expected);
            }
            _ => panic!("a turn past the budget must end the run"),
        }
        let failed = h.of_type("harness_failed").await;
        assert_eq!(failed[0]["message"], expected, "{}", failed[0]);
        let turns: Vec<Json> = h
            .of_type("inference")
            .await
            .into_iter()
            .map(|record| record["turn"].clone())
            .collect();
        assert_eq!(
            turns,
            [3, 4],
            "the turn named is the one after the last recorded"
        );
    }

    #[tokio::test]
    async fn a_failed_turn_fails_the_run_and_names_its_kind() {
        let mut h = Harness::new(10).await;
        let outcome = h
            .feed(vec![
                text("partial"),
                Event::TurnFailed(TurnFailure {
                    kind: FailureKind::Auth,
                    message: "not signed in".into(),
                }),
            ])
            .await;
        match outcome {
            SinkOutcome::Failed(RuntimeError::HarnessTurnFailed {
                kind,
                message,
                origin,
            }) => {
                assert_eq!(kind, "auth");
                assert_eq!(message, "not signed in");
                assert_eq!(origin, "harness");
            }
            _ => panic!("a turn-failed event must fail the run"),
        }
        assert_eq!(
            h.of_type("inference").await.len(),
            1,
            "the open turn is closed before the failure"
        );
        assert_eq!(h.of_type("harness_failed").await[0]["source"], "harness");
        assert!(
            !h.workdir.join("out/result.txt").exists(),
            "a failed turn produces no result"
        );
    }

    /// A harness `auth` failure with a turn open records that turn as the failed call it was,
    /// counted with the harness's own counts, ahead of the `harness_failed` line.
    #[tokio::test]
    async fn an_auth_failure_records_the_open_turn_as_a_failed_call() {
        let mut h = Harness::new(10).await;
        h.feed(vec![
            text("partial"),
            usage(&[("in", 10), ("out", 5)]),
            Event::TurnFailed(TurnFailure {
                kind: FailureKind::Auth,
                message: "not signed in".into(),
            }),
        ])
        .await;
        let events = h.events().await;
        let inference = h.of_type("inference").await;
        assert_eq!(inference.len(), 1);
        let record = &inference[0];
        assert_eq!(record["turn"], 0);
        assert_eq!(record["decision"], "error");
        assert_eq!(record["stop_reason"], "error");
        assert_eq!(record["error_code"], "harness_auth");
        assert_eq!(record["error"], "not signed in");
        assert_eq!(record["input_tokens"], 10);
        assert_eq!(record["output_tokens"], 5);
        assert!(record.get("provider_status").is_none());
        assert_eq!(h.trace.task_turns(), 1, "the open turn stays counted");
        let position = |event_type: &str| {
            events
                .iter()
                .position(|event| event["event_type"] == event_type)
                .unwrap()
        };
        assert!(position("inference") < position("harness_failed"));
        assert_eq!(h.of_type("harness_failed").await[0]["kind"], "auth");
    }

    /// A harness failure with no turn open records one failed call that counts nothing.
    #[tokio::test]
    async fn a_quota_failure_with_no_open_turn_records_an_uncounted_call() {
        let mut h = Harness::new(10).await;
        h.feed(vec![Event::TurnFailed(TurnFailure {
            kind: FailureKind::Quota,
            message: "out of credit".into(),
        })])
        .await;
        let inference = h.of_type("inference").await;
        assert_eq!(inference.len(), 1);
        assert_eq!(inference[0]["turn"], 0);
        assert_eq!(inference[0]["error_code"], "harness_quota");
        assert!(inference[0].get("input_tokens").is_none());
        assert!(inference[0].get("output_tokens").is_none());
        assert!(inference[0].get("provider_status").is_none());
        assert_eq!(h.trace.task_turns(), 0);
        assert_eq!(h.of_type("harness_failed").await.len(), 1);
    }

    /// A budget or a cancel is not a failed model call: its open turn closes as an ordinary one.
    #[tokio::test]
    async fn max_turns_and_canceled_failures_record_no_failed_call() {
        for kind in [FailureKind::MaxTurns, FailureKind::Canceled] {
            let mut h = Harness::new(10).await;
            h.feed(vec![
                text("partial"),
                Event::TurnFailed(TurnFailure {
                    kind,
                    message: "stopped".into(),
                }),
            ])
            .await;
            let inference = h.of_type("inference").await;
            assert_eq!(inference.len(), 1, "{kind:?}");
            assert_eq!(inference[0]["decision"], "end_turn", "{kind:?}");
            assert!(inference[0].get("error_code").is_none(), "{kind:?}");
            assert!(inference[0].get("provider_status").is_none(), "{kind:?}");
        }
    }

    /// A harness that goes quiet mid-turn leaves its open turn recorded as a failed call.
    #[tokio::test]
    async fn an_inactive_harness_records_its_open_turn_as_a_failed_call() {
        let mut h = Harness::new(10).await;
        h.feed_then_go_quiet(vec![text("thinking"), usage(&[("in", 4), ("out", 2)])])
            .await;
        let inference = h.of_type("inference").await;
        assert_eq!(inference.len(), 1);
        assert_eq!(inference[0]["turn"], 0);
        assert_eq!(inference[0]["decision"], "error");
        assert_eq!(inference[0]["error_code"], "harness_inactive");
        assert_eq!(inference[0]["error"], "the harness went quiet");
        assert_eq!(inference[0]["input_tokens"], 4);
        assert!(inference[0].get("provider_status").is_none());
        assert_eq!(h.trace.task_turns(), 1);
    }

    /// Nothing after the first terminal event in a batch is acted on: the run is over.
    #[tokio::test]
    async fn events_after_a_terminal_event_are_ignored() {
        let mut h = Harness::new(10).await;
        h.feed(vec![
            text("first"),
            Event::TurnEnd("first".into()),
            text("second"),
            Event::TurnEnd("second".into()),
        ])
        .await;
        assert_eq!(h.of_type("inference").await.len(), 1);
        assert_eq!(
            std::fs::read_to_string(h.workdir.join("out/result.txt")).unwrap(),
            "first"
        );
    }

    #[tokio::test]
    async fn a_non_subscription_session_is_warned_about_and_traced() {
        let mut h = Harness::new(10).await;
        h.feed(vec![Event::SessionStarted(SessionInfo {
            id: "harness-session-9".into(),
            auth: "api-key".into(),
            model: Some("a-model".into()),
        })])
        .await;
        let sessions = h.of_type("harness_session").await;
        assert_eq!(sessions[0]["harness_session_id"], "harness-session-9");
        assert_eq!(sessions[0]["auth"], "api-key");
        assert_eq!(sessions[0]["model"], "a-model");
        let warnings = h.of_type("harness_warning").await;
        assert_eq!(warnings[0]["code"], W_SEC_031);
        assert!(warnings[0]["message"].as_str().unwrap().contains("api-key"));
    }

    #[tokio::test]
    async fn a_subscription_session_raises_no_warning() {
        let mut h = Harness::new(10).await;
        h.feed(vec![Event::SessionStarted(SessionInfo {
            id: "s".into(),
            auth: SUBSCRIPTION_AUTH.into(),
            model: None,
        })])
        .await;
        assert_eq!(h.of_type("harness_session").await.len(), 1);
        assert!(h.of_type("harness_warning").await.is_empty());
    }

    #[tokio::test]
    async fn retries_and_notes_are_traced() {
        let mut h = Harness::new(10).await;
        h.feed(vec![
            Event::Retry(RetryInfo {
                attempt: 2,
                reason: "overloaded".into(),
            }),
            Event::Note("a line the driver could not read".into()),
        ])
        .await;
        let retries = h.of_type("harness_retry").await;
        assert_eq!(retries[0]["attempt"], 2);
        assert_eq!(retries[0]["reason"], "overloaded");
        assert_eq!(
            h.of_type("harness_note").await[0]["text"],
            "a line the driver could not read"
        );
    }

    // ── The A2A frames one attempt writes ─────────────────────────────────────

    /// A segment that streams fragments and then reports the complete text sends the client one
    /// cursor removal and never the words twice: on this wire a `text` replaces, and the client
    /// keeps what it was streamed.
    #[tokio::test]
    async fn a_streamed_segment_sends_one_cursor_removal() {
        let mut h = Harness::new(10).await;
        h.feed(vec![
            Event::TextDelta("one ".into()),
            Event::TextDelta("two".into()),
            text("one two"),
            Event::TurnEnd("one two".into()),
        ])
        .await;
        assert_eq!(
            h.frame_kinds(),
            vec![
                "status:working:inference turn 1",
                "text:chunk",
                "text:chunk",
                "text:final",
            ],
            "{:#?}",
            h.frames()
        );
        let texts = data_of(&h.frames(), "text");
        assert_eq!(texts[0]["text"], "one ");
        assert_eq!(texts[1]["text"], "two");
        assert_eq!(texts[2]["text"], "", "the cursor removal carries no text");
        assert_eq!(texts[2]["final"], true);
    }

    /// The cursor removal a segment owes is paid before the artifact frame that closes it, so a
    /// client's streamed item is complete before the tool result lands under it.
    #[tokio::test]
    async fn a_cursor_removal_precedes_the_artifact_that_closes_its_segment() {
        let mut h = Harness::new(10).await;
        h.feed(vec![
            Event::TextDelta("thinking about it".into()),
            tool_call("c1", "echo-tool"),
            tool_result("c1", false),
            text("done"),
            Event::TurnEnd("done".into()),
        ])
        .await;
        assert_eq!(
            h.frame_kinds(),
            vec![
                "status:working:inference turn 1",
                "text:chunk",
                "text:final",
                "artifact",
                "status:working:inference turn 2",
                "text:final",
            ],
            "{:#?}",
            h.frames()
        );
    }

    /// Every key of the artifact frame comes from the contract's own events, or from the
    /// runtime's own measurement of the call.
    #[tokio::test]
    async fn the_artifact_frame_is_built_from_the_generic_events() {
        let mut h = Harness::new(10).await;
        h.feed(vec![
            tool_call("c1", "echo-tool"),
            tool_result("c1", true),
            Event::TurnEnd(String::new()),
        ])
        .await;
        let frames = h.frames();
        let artifact = &data_of(&frames, "artifact")[0];
        assert_eq!(artifact["toolName"], "echo-tool");
        assert_eq!(artifact["content"], "done");
        assert_eq!(artifact["toolCallId"], "c1");
        assert_eq!(artifact["isError"], true);
        assert!(artifact["durationMs"].is_number(), "{artifact}");
        assert_eq!(
            artifact["fenceSource"],
            Json::Null,
            "the bridge returns tool output unfenced"
        );
        assert_eq!(artifact["exitCode"], Json::Null);
        assert_eq!(artifact["truncated"], false);
    }

    /// A tool result nothing called for writes no frame, the same way it writes no `tool_call`
    /// record.
    #[tokio::test]
    async fn an_unmatched_tool_result_writes_no_frame() {
        let mut h = Harness::new(10).await;
        h.feed(vec![tool_result("ghost", false)]).await;
        assert!(h.frame_kinds().is_empty(), "{:#?}", h.frames());
    }

    /// A segment that streamed the client its text does not send it again when the turn ends.
    #[tokio::test]
    async fn a_turn_end_after_streamed_text_sends_no_fallback() {
        let mut h = Harness::new(10).await;
        h.feed(vec![
            Event::TextDelta("all of it".into()),
            Event::TurnEnd("all of it".into()),
        ])
        .await;
        assert_eq!(
            h.frame_kinds(),
            vec![
                "status:working:inference turn 1",
                "text:chunk",
                "text:final"
            ],
            "{:#?}",
            h.frames()
        );
        assert_eq!(
            data_of(&h.frames(), "text")[1]["text"],
            "",
            "the one final text frame is the cursor removal, not the result again"
        );
    }

    /// A segment that streamed nothing sends the whole result as one final text frame — what the
    /// http path does for a driver that emits no chunks.
    #[tokio::test]
    async fn a_turn_end_after_an_unstreamed_segment_sends_the_result() {
        let mut h = Harness::new(10).await;
        h.feed(vec![
            text("the answer"),
            Event::TurnEnd("the answer".into()),
        ])
        .await;
        assert_eq!(
            h.frame_kinds(),
            vec!["status:working:inference turn 1", "text:final"],
            "{:#?}",
            h.frames()
        );
        assert_eq!(data_of(&h.frames(), "text")[0]["text"], "the answer");
    }

    /// An empty result is no answer to send.
    #[tokio::test]
    async fn a_turn_end_with_an_empty_result_sends_no_text() {
        let mut h = Harness::new(10).await;
        h.feed(vec![text(""), Event::TurnEnd(String::new())]).await;
        assert_eq!(
            h.frame_kinds(),
            vec!["status:working:inference turn 1"],
            "{:#?}",
            h.frames()
        );
    }

    /// Thinking reaches the client, and a complete `thinking` after fragments is not sent again:
    /// the client already has every word of it.
    #[tokio::test]
    async fn thinking_fragments_are_sent_once() {
        let mut h = Harness::new(10).await;
        h.feed(vec![
            Event::ThinkingDelta("step ".into()),
            Event::ThinkingDelta("one".into()),
            Event::Thinking("step one".into()),
            text("done"),
            Event::TurnEnd("done".into()),
        ])
        .await;
        let frames = h.frames();
        let thinking = data_of(&frames, "thinking");
        assert_eq!(thinking.len(), 2, "{frames:#?}");
        assert_eq!(thinking[0]["text"], "step ");
        assert_eq!(thinking[1]["text"], "one");
        for frame in &thinking {
            assert_eq!(
                frame["final"], false,
                "thinking is never final on this wire"
            );
        }
    }

    /// A complete `thinking` with no fragments before it is the client's only copy, and is sent.
    #[tokio::test]
    async fn a_whole_thinking_is_sent_when_nothing_streamed_it() {
        let mut h = Harness::new(10).await;
        h.feed(vec![
            Event::Thinking("whole thought".into()),
            text("done"),
            Event::TurnEnd("done".into()),
        ])
        .await;
        let frames = h.frames();
        let thinking = data_of(&frames, "thinking");
        assert_eq!(thinking.len(), 1, "{frames:#?}");
        assert_eq!(thinking[0]["text"], "whole thought");
        assert_eq!(thinking[0]["final"], false);
    }

    /// A provider retry, a note and the session's own start are trace records and nothing else:
    /// the http stream has no frame for any of them, and a frame here would be one the two
    /// transports do not share.
    #[tokio::test]
    async fn retries_notes_and_session_starts_write_no_frame() {
        let mut h = Harness::new(10).await;
        h.feed(vec![
            Event::SessionStarted(SessionInfo {
                id: "s".into(),
                auth: SUBSCRIPTION_AUTH.into(),
                model: None,
            }),
            Event::Retry(RetryInfo {
                attempt: 2,
                reason: "overloaded".into(),
            }),
            Event::Note("a line the driver could not read".into()),
        ])
        .await;
        assert!(h.frame_kinds().is_empty(), "{:#?}", h.frames());
    }

    /// A segment's number is the number the turn counter would give a turn opening with it, so a
    /// fragment that opens a segment before the turn it belongs to names the same turn.
    #[tokio::test]
    async fn a_segment_carries_the_number_of_the_turn_it_opens_with() {
        let mut h = Harness::new(10).await;
        h.feed(vec![
            tool_call("c1", "echo-tool"),
            tool_result("c1", false),
            Event::TextDelta("second".into()),
            text("second"),
            Event::TurnEnd("second".into()),
        ])
        .await;
        let working: Vec<String> = h
            .frame_kinds()
            .into_iter()
            .filter(|kind| kind.starts_with("status:working"))
            .collect();
        assert_eq!(
            working,
            vec![
                "status:working:inference turn 1",
                "status:working:inference turn 2"
            ],
            "{:#?}",
            h.frames()
        );
        assert_eq!(
            h.of_type("inference").await.len(),
            2,
            "a segment reads the turn counter and never advances it"
        );
    }

    // ── Hook artifacts on the turn `turn-end` closes ──────────────────────────
    //
    // The harness's `HookRuntime` has no hooks staged, so these drive the stream directly with
    // the artifacts `close_turn` would have handed it.

    fn hook_artifact(hook_name: &str, payload: &str) -> HookArtifact {
        HookArtifact {
            hook_name: hook_name.to_string(),
            payload: payload.to_string(),
        }
    }

    /// A turn that streamed nothing sends its hook artifact before the whole result.
    #[tokio::test]
    async fn hook_artifact_precedes_the_fallback_text() {
        let mut h = Harness::new(10).await;
        h.a2a.open_segment(1).await;
        h.a2a
            .turn_end("the answer", vec![hook_artifact("review", "{}")])
            .await;
        assert_eq!(
            h.frame_kinds(),
            vec!["status:working:inference turn 1", "artifact", "text:final"],
            "{:#?}",
            h.frames()
        );
        assert_eq!(data_of(&h.frames(), "text")[0]["text"], "the answer");
    }

    /// A streamed turn pays its cursor removal first, so the client's streamed item is complete
    /// before the hook artifact lands under it, and sends no second text.
    #[tokio::test]
    async fn hook_artifact_follows_the_cursor_removal() {
        let mut h = Harness::new(10).await;
        h.a2a.open_segment(1).await;
        h.a2a.text_delta("all of it");
        h.a2a
            .turn_end("all of it", vec![hook_artifact("review", "{}")])
            .await;
        assert_eq!(
            h.frame_kinds(),
            vec![
                "status:working:inference turn 1",
                "text:chunk",
                "text:final",
                "artifact",
            ],
            "{:#?}",
            h.frames()
        );
        assert_eq!(data_of(&h.frames(), "text")[1]["text"], "");
    }

    /// Several hooks' artifacts reach the client in the order they were handed over, which is
    /// hook-registration order.
    #[tokio::test]
    async fn hook_artifact_order_is_kept() {
        let mut h = Harness::new(10).await;
        h.a2a
            .turn_end(
                "",
                vec![hook_artifact("first", "1"), hook_artifact("second", "2")],
            )
            .await;
        let names: Vec<Json> = data_of(&h.frames(), "artifact")
            .iter()
            .map(|frame| frame["toolName"].clone())
            .collect();
        assert_eq!(names, vec!["first", "second"], "{:#?}", h.frames());
    }

    /// An interrupted attempt delivers no answer, and a hook's verdict on it is not one either.
    #[tokio::test]
    async fn hook_artifact_is_not_sent_by_an_interrupted_attempt() {
        let mut h = Harness::new(10).await;
        h.a2a.open_segment(1).await;
        h.a2a.mark_interrupted();
        h.a2a
            .turn_end("the answer", vec![hook_artifact("review", "{}")])
            .await;
        assert_eq!(
            h.frame_kinds(),
            vec!["status:working:inference turn 1"],
            "{:#?}",
            h.frames()
        );
    }

    /// A run with no A2A task has nowhere to send a hook artifact, and does not try, even where a
    /// broadcast exists.
    #[tokio::test]
    async fn hook_artifact_without_a_task_writes_nothing() {
        let (tx, _rx) = tokio::sync::broadcast::channel(16);
        let frames = Arc::new(Mutex::new(SseEventBuffer::new(16)));
        let mut a2a = A2aStream::new(
            Some((tx, Arc::clone(&frames))),
            None,
            None,
            Arc::new(AtomicBool::new(false)),
        );
        a2a.turn_end("the answer", vec![hook_artifact("review", "{}")])
            .await;
        let mut bare = A2aStream::new(None, None, None, Arc::new(AtomicBool::new(false)));
        bare.turn_end("the answer", vec![hook_artifact("review", "{}")])
            .await;
        assert!(matches!(
            frames.lock().unwrap().replay_from(0),
            crate::streaming::ReplayResult::Complete(frames) if frames.is_empty()
        ));
    }

    /// The frame is `StreamArtifact::hook`'s, key for key: the operator's own hook speaking,
    /// unfenced, with none of a tool call's keys.
    #[tokio::test]
    async fn hook_artifact_frame_is_the_hook_constructor() {
        let mut h = Harness::new(10).await;
        h.a2a
            .turn_end("", vec![hook_artifact("review", r#"{"reviewed":true}"#)])
            .await;
        let frames = h.frames();
        let artifact = &data_of(&frames, "artifact")[0];
        assert_eq!(
            artifact,
            &serde_json::to_value(crate::streaming::MurmurFrame::Artifact(
                StreamArtifact::hook("review".to_string(), r#"{"reviewed":true}"#.to_string())
            ))
            .unwrap()
        );
        assert_eq!(artifact["fenceSource"], Json::Null);
        assert_eq!(artifact["toolCallId"], Json::Null);
    }

    /// The attempt's ending, on the two paths out of a run the harness itself ends. The stream
    /// writes no final status of its own: the task's one final frame is the reopen loop's.
    #[tokio::test]
    async fn an_attempt_records_its_ending_and_writes_no_final_status() {
        let mut h = Harness::new(10).await;
        h.feed(vec![
            text("the answer"),
            Event::TurnEnd("the answer".into()),
        ])
        .await;
        let ending = h.a2a.ending(&Ok(crate::agent::AgentLoopExit::Ok));
        assert_eq!(ending.state, crate::a2a::TaskState::Completed);
        assert_eq!(ending.response.as_deref(), Some("the answer"));
        assert_eq!(ending.message, "task completed");
        assert!(
            data_of(&h.frames(), "status")
                .iter()
                .all(|status| status["status"]["state"] == "TASK_STATE_WORKING"),
            "{:#?}",
            h.frames()
        );

        let mut h = Harness::new(10).await;
        h.feed(vec![Event::TurnFailed(TurnFailure {
            kind: FailureKind::Auth,
            message: "not signed in".into(),
        })])
        .await;
        let ending = h.a2a.ending(&Err(RuntimeError::HarnessTurnFailed {
            kind: "auth".into(),
            message: "not signed in".into(),
            origin: "harness".into(),
        }));
        assert!(h.frame_kinds().is_empty(), "{:#?}", h.frames());
        assert_eq!(ending.state, crate::a2a::TaskState::Failed);
        assert!(ending.response.is_none());
        assert!(ending.message.contains("E-RUN-033"), "{}", ending.message);
        assert!(ending.message.contains("auth"), "{}", ending.message);
        assert!(
            ending.message.contains("not signed in"),
            "{}",
            ending.message
        );
    }

    /// Once the runtime has interrupted an attempt it ends `canceled`, whatever the harness says
    /// next: a finished turn is not a completion and a failed one — of any kind, the `canceled`
    /// kind a harness that honours an interrupt reports included — is not a failure. The answer
    /// the harness produced anyway is kept, and is not sent as the client's final text.
    #[tokio::test]
    async fn an_interrupted_attempt_ends_canceled_whatever_the_harness_said() {
        let last_words = || {
            let mut events = vec![Event::TurnEnd("the answer".into())];
            for kind in [
                FailureKind::Auth,
                FailureKind::Quota,
                FailureKind::MaxTurns,
                FailureKind::Canceled,
                FailureKind::HarnessError,
                FailureKind::Other,
            ] {
                events.push(Event::TurnFailed(TurnFailure {
                    kind,
                    message: "stopped".into(),
                }));
            }
            // And a run the harness never answered at all.
            events.push(Event::Note("nothing terminal here".into()));
            events
        };
        for last in last_words() {
            for killed in [false, true] {
                let mut h = Harness::new(10).await;
                h.a2a.mark_interrupted();
                h.feed(vec![text("the answer"), last.clone()]).await;
                if killed {
                    h.a2a.mark_harness_killed();
                }
                let ending = h.a2a.ending(&Ok(crate::agent::AgentLoopExit::Canceled));

                assert!(
                    data_of(&h.frames(), "status")
                        .iter()
                        .all(|status| status["status"]["state"] == "TASK_STATE_WORKING"),
                    "{:#?}",
                    h.frames()
                );
                assert_eq!(ending.state, crate::a2a::TaskState::Canceled);
                assert!(ending.response.is_none());
                assert_eq!(
                    ending.message.contains("the harness was killed"),
                    killed,
                    "{}",
                    ending.message
                );
                assert!(
                    !h.frame_kinds().contains(&"text:final".to_string()),
                    "a stopped task is sent no final answer: {:#?}",
                    h.frames()
                );
            }
        }
    }

    /// A run with no A2A task — `mur run`, a `task.md` launch — writes no frame at all.
    #[tokio::test]
    async fn a_run_with_no_task_writes_no_frames() {
        let mut h = Harness::new(10).await;
        let frames = Arc::clone(&h.frames);
        let (tx, _rx) = tokio::sync::broadcast::channel(16);
        h.a2a = A2aStream::new(
            Some((tx, Arc::clone(&frames))),
            None,
            None,
            Arc::new(AtomicBool::new(false)),
        );
        h.feed(vec![
            Event::TextDelta("streamed".into()),
            tool_call("c1", "echo-tool"),
            tool_result("c1", false),
            text("done"),
            Event::TurnEnd("done".into()),
        ])
        .await;
        let ending = h.a2a.ending(&Ok(crate::agent::AgentLoopExit::Ok));
        assert_eq!(
            ending.state,
            crate::a2a::TaskState::Completed,
            "a run with no task still records how it ended"
        );
        assert!(h.frame_kinds().is_empty(), "{:#?}", h.frames());
    }

    /// A result nobody called for, and a call nobody answered, are both notes — never a
    /// `tool_call` record for something that did not happen.
    #[tokio::test]
    async fn unpaired_calls_and_results_are_notes() {
        let mut h = Harness::new(10).await;
        h.feed(vec![tool_result("ghost", false), tool_call("c9", "t")])
            .await;
        let notes = h.of_type("harness_note").await;
        assert_eq!(notes.len(), 2, "{notes:#?}");
        assert!(notes[0]["text"].as_str().unwrap().contains("ghost"));
        assert!(notes[1]["text"].as_str().unwrap().contains("c9"));
        assert!(h.of_type("tool_call").await.is_empty());
    }

    // ── A tool call being written ─────────────────────────────────────────────

    /// The `input_bytes` of every `tool-call-progress` frame, in order.
    fn progress_sizes(frames: &[Json]) -> Vec<u64> {
        data_of(frames, "tool-call-progress")
            .iter()
            .map(|data| data["inputBytes"].as_u64().expect("inputBytes is a u64"))
            .collect()
    }

    /// A started call writes its start and its size after the segment's `working` status and
    /// before the `artifact` that answers it, all carrying the call's id. The size the complete
    /// call arrives with is written then, though the interval since the first has not passed.
    #[tokio::test]
    async fn a_started_tool_call_writes_its_start_and_size_before_its_artifact() {
        let mut h = Harness::new(10).await;
        h.feed(vec![
            tool_call_started("c1", "echo-tool"),
            tool_call_progress("c1", 12),
            tool_call_progress("c1", 40),
            tool_call("c1", "echo-tool"),
            tool_result("c1", false),
            Event::TurnEnd(String::new()),
        ])
        .await;
        assert_eq!(
            h.frame_kinds(),
            [
                "status:working:inference turn 1",
                "tool-call-started",
                "tool-call-progress",
                "tool-call-progress",
                "artifact",
            ]
        );
        let frames = h.frames();
        let started = data_of(&frames, "tool-call-started");
        assert_eq!(
            started[0],
            serde_json::json!({"frame": "tool-call-started", "toolCallId": "c1", "toolName": "echo-tool"})
        );
        assert_eq!(progress_sizes(&frames), [12, 40]);
        let progress = data_of(&frames, "tool-call-progress");
        assert!(progress.iter().all(|data| data["toolCallId"] == "c1"));
        assert_eq!(data_of(&frames, "artifact")[0]["toolCallId"], "c1");
    }

    /// A started call and its progress are not model actions: the same run with and without them
    /// records the same turns.
    #[tokio::test]
    async fn a_started_tool_call_opens_no_turn() {
        let run = |reported: bool| {
            let mut events = vec![text("working on it")];
            if reported {
                events.push(tool_call_started("c1", "echo-tool"));
                events.push(tool_call_progress("c1", 12));
            }
            events.extend([
                tool_call("c1", "echo-tool"),
                tool_result("c1", false),
                text("done"),
                Event::TurnEnd("done".into()),
            ]);
            events
        };
        let mut records = Vec::new();
        for reported in [false, true] {
            let mut h = Harness::new(10).await;
            h.feed(run(reported)).await;
            let inferences: Vec<Json> = h
                .of_type("inference")
                .await
                .into_iter()
                .map(|record| {
                    serde_json::json!([record["turn"], record["decision"], record["tool_name"]])
                })
                .collect();
            records.push((inferences, h.turn));
        }
        assert_eq!(records[0], records[1]);
        assert_eq!(records[0].0.len(), 2, "{:?}", records[0]);
    }

    /// With the budget spent, a started call and its progress leave the run going; the complete
    /// call is the model action, and it is what ends the run.
    #[tokio::test]
    async fn a_started_tool_call_does_not_spend_the_turn_budget() {
        let spent = || vec![tool_call("c0", "t"), tool_result("c0", false)];

        let mut h = Harness::new(1).await;
        let mut events = spent();
        events.extend([tool_call_started("c1", "t"), tool_call_progress("c1", 12)]);
        assert!(matches!(h.feed(events).await, SinkOutcome::Continue));
        assert_eq!(data_of(&h.frames(), "tool-call-started").len(), 1);

        let mut h = Harness::new(1).await;
        let mut events = spent();
        events.extend([
            tool_call_started("c1", "t"),
            tool_call_progress("c1", 12),
            tool_call("c1", "t"),
        ]);
        assert!(matches!(
            h.feed(events).await,
            SinkOutcome::TurnBudgetExceeded(_)
        ));
    }

    /// What the stream cannot believe writes nothing: progress for a call never started, a second
    /// start, a start after the call is complete or answered, a start with no id, and a size no
    /// larger than one already reported.
    #[tokio::test]
    async fn a_tool_call_report_out_of_order_writes_no_frame() {
        let mut h = Harness::new(10).await;
        h.feed(vec![tool_call_progress("c1", 12)]).await;
        assert!(h.frame_kinds().is_empty(), "{:?}", h.frame_kinds());

        let mut h = Harness::new(10).await;
        h.feed(vec![
            tool_call_started("c1", "echo-tool"),
            tool_call_started("c1", "echo-tool"),
        ])
        .await;
        assert_eq!(
            h.frame_kinds(),
            ["status:working:inference turn 1", "tool-call-started"]
        );

        let mut h = Harness::new(10).await;
        h.feed(vec![
            tool_call("c1", "echo-tool"),
            tool_call_started("c1", "echo-tool"),
            tool_call_progress("c1", 12),
        ])
        .await;
        assert_eq!(h.frame_kinds(), ["status:working:inference turn 1"]);

        let mut h = Harness::new(10).await;
        h.feed(vec![
            tool_call("c1", "echo-tool"),
            tool_result("c1", false),
            tool_call_started("c1", "echo-tool"),
            tool_call_progress("c1", 12),
        ])
        .await;
        assert_eq!(
            h.frame_kinds(),
            ["status:working:inference turn 1", "artifact"]
        );

        let mut h = Harness::new(10).await;
        h.feed(vec![
            tool_call_started("", "echo-tool"),
            tool_call_progress("", 12),
        ])
        .await;
        assert!(h.frame_kinds().is_empty(), "{:?}", h.frame_kinds());

        let mut h = Harness::new(10).await;
        h.feed(vec![
            tool_call_started("c1", "echo-tool"),
            tool_call_progress("c1", 40),
            tool_call_progress("c1", 40),
            tool_call_progress("c1", 12),
            tool_call("c1", "echo-tool"),
        ])
        .await;
        assert_eq!(progress_sizes(&h.frames()), [40]);
    }

    /// A start replaces none of the text the segment streamed, so it pays no cursor removal; the
    /// result that closes the segment does.
    #[tokio::test]
    async fn a_started_tool_call_pays_no_cursor_removal() {
        let mut h = Harness::new(10).await;
        h.feed(vec![
            Event::TextDelta("let me write that".into()),
            tool_call_started("c1", "echo-tool"),
        ])
        .await;
        assert_eq!(
            h.frame_kinds(),
            [
                "status:working:inference turn 1",
                "text:chunk",
                "tool-call-started",
            ]
        );
    }

    /// A complete call named differently from its start is recorded as the harness reported the
    /// complete call, and the difference is noted.
    #[tokio::test]
    async fn a_call_completed_under_another_name_is_noted() {
        let mut h = Harness::new(10).await;
        h.feed(vec![
            tool_call_started("c1", "write_file"),
            tool_call("c1", "echo-tool"),
            tool_result("c1", false),
        ])
        .await;
        let notes = h.of_type("harness_note").await;
        assert_eq!(notes.len(), 1, "{notes:#?}");
        let note = notes[0]["text"].as_str().unwrap();
        assert!(note.contains("c1"), "{note}");
        assert!(note.contains("'write_file'"), "{note}");
        assert!(note.contains("'echo-tool'"), "{note}");
        assert_eq!(data_of(&h.frames(), "artifact")[0]["toolName"], "echo-tool");
    }

    /// Hundreds of sizes in one batch write a handful of frames, so the task's first frames stay
    /// in the replay buffer.
    #[tokio::test]
    async fn a_burst_of_progress_writes_a_bounded_number_of_frames() {
        let mut h = Harness::new(10).await;
        let mut events = vec![tool_call_started("c1", "echo-tool")];
        events.extend((1..=350).map(|i| tool_call_progress("c1", i * 20)));
        events.push(tool_call("c1", "echo-tool"));
        h.feed(events).await;
        let sizes = progress_sizes(&h.frames());
        assert!(
            (1..=2).contains(&sizes.len()),
            "{} progress frames: {sizes:?}",
            sizes.len()
        );
        assert_eq!(sizes.last(), Some(&7000));
        let replay = h.frames.lock().unwrap().replay_from(0);
        match replay {
            crate::streaming::ReplayResult::Complete(frames) => {
                assert_eq!(frames[0].id, 1);
            }
            crate::streaming::ReplayResult::WithGap { .. } => {
                panic!("the burst evicted the task's first frames")
            }
        }
    }

    /// The event a run names its session with. Every session test below starts from one.
    fn session_started(id: &str) -> Event {
        Event::SessionStarted(SessionInfo {
            id: id.to_string(),
            auth: SUBSCRIPTION_AUTH.into(),
            model: None,
        })
    }

    /// Whatever the harness calls its session is what the context is keyed on from then on.
    #[tokio::test]
    async fn harness_session_the_reported_id_replaces_the_one_the_runtime_minted() {
        let mut h = Harness::new(10).await;
        h.feed(vec![
            session_started("harness-chose-this"),
            text("here it is"),
            Event::TurnEnd("here it is".into()),
        ])
        .await;
        assert_eq!(h.map.get(CONTEXT).as_deref(), Some("harness-chose-this"));
        assert_ne!(h.planned_id, "harness-chose-this");
    }

    /// The harness named its session and then the turn was interrupted before it produced
    /// anything. Nothing is remembered, so the next task in this context starts a conversation
    /// the harness will answer to.
    #[tokio::test]
    async fn harness_session_a_run_that_only_named_its_session_remembers_nothing() {
        let mut h = Harness::new(10).await;
        h.feed(vec![session_started("named-but-empty")]).await;
        assert_eq!(h.map.get(CONTEXT), None);
    }

    /// The four events that are not work: a retry, a note, a tool result nobody called for, and a
    /// failed turn leave the context exactly as they found it.
    #[tokio::test]
    async fn harness_session_reports_about_work_are_not_work() {
        let mut h = Harness::new(10).await;
        h.feed(vec![
            session_started("named-but-empty"),
            Event::Retry(RetryInfo {
                attempt: 2,
                reason: "overloaded".into(),
            }),
            Event::Note("a line the driver could not read".into()),
            tool_result("ghost", false),
            Event::TurnFailed(TurnFailure {
                kind: FailureKind::Canceled,
                message: "stopped".into(),
            }),
        ])
        .await;
        assert_eq!(h.map.get(CONTEXT), None);
    }

    /// Each of the seven events that is work, on its own, with no terminal event after it: the
    /// run was interrupted past the window where the harness has a name and no conversation, and
    /// the session it established is kept. A call the model has only begun writing is model
    /// output in that session, like a fragment.
    #[tokio::test]
    async fn harness_session_any_observable_work_commits_the_reported_id() {
        for work in [
            text("an answer"),
            Event::TextDelta("an ".into()),
            Event::Thinking("pondering".into()),
            Event::ThinkingDelta("pond".into()),
            tool_call("c1", "echo-tool"),
            tool_call_started("c1", "echo-tool"),
            tool_call_progress("c1", 12),
        ] {
            let mut h = Harness::new(10).await;
            h.feed(vec![session_started("worked"), work]).await;
            assert_eq!(h.map.get(CONTEXT).as_deref(), Some("worked"));
        }
    }

    /// A harness that says nothing about its session answers to the id it was handed.
    #[tokio::test]
    async fn harness_session_a_silent_run_that_ends_remembers_the_minted_id() {
        let mut h = Harness::new(10).await;
        assert_eq!(h.map.get(CONTEXT), None);
        h.feed(vec![Event::TurnEnd("done".into())]).await;
        assert_eq!(h.map.get(CONTEXT).as_deref(), Some(h.planned_id.as_str()));
    }

    /// The session a run leaves for a reopened attempt of its task is the one it commits, on the
    /// same condition: the reported id over the handed one, and nothing from a run that produced
    /// no work or lost its session.
    #[tokio::test]
    async fn harness_session_a_run_carries_to_a_reopen_exactly_what_it_commits() {
        let mut h = Harness::new(10).await;
        h.feed(vec![session_started("worked"), text("an answer")])
            .await;
        assert_eq!(h.carried.as_deref(), Some("worked"));

        let mut h = Harness::new(10).await;
        h.feed(vec![Event::TurnEnd("done".into())]).await;
        assert_eq!(h.carried.as_deref(), Some(h.planned_id.as_str()));

        let mut h = Harness::new(10).await;
        h.feed(vec![session_started("named-but-empty")]).await;
        assert_eq!(h.carried, None);

        let map = Arc::new(HarnessSessionMap::new(
            None,
            &crate::workdir_fs::WorkdirRoot::open(Path::new("/tmp")).unwrap(),
        ));
        map.put(CONTEXT, "remembered", HARNESS, "fixture-driver");
        let mut h = Harness::threading(10, map).await;
        h.feed(vec![Event::TurnFailed(TurnFailure {
            kind: FailureKind::HarnessError,
            message: "no conversation found with session id remembered".into(),
        })])
        .await;
        assert_eq!(h.carried, None);
    }

    /// Nothing was established, so nothing is remembered.
    #[tokio::test]
    async fn harness_session_a_failed_run_with_no_session_remembers_nothing() {
        let mut h = Harness::new(10).await;
        h.feed(vec![Event::TurnFailed(TurnFailure {
            kind: FailureKind::Auth,
            message: "not signed in".into(),
        })])
        .await;
        assert_eq!(h.map.get(CONTEXT), None);
    }

    /// A resumed turn the harness never acknowledged fails as a missing conversation, and leaves
    /// the entry exactly as it was so the next task fails the same way.
    #[tokio::test]
    async fn harness_session_a_resume_the_harness_never_acknowledged_fails_as_gone() {
        let map = Arc::new(HarnessSessionMap::new(
            None,
            &crate::workdir_fs::WorkdirRoot::open(Path::new("/tmp")).unwrap(),
        ));
        map.put(CONTEXT, "remembered", HARNESS, "fixture-driver");
        let mut h = Harness::threading(10, map).await;
        assert_eq!(h.planned_id, "remembered");

        let outcome = h
            .feed(vec![Event::TurnFailed(TurnFailure {
                kind: FailureKind::HarnessError,
                message: "no conversation found with session id remembered".into(),
            })])
            .await;
        let SinkOutcome::Failed(error) = outcome else {
            panic!("a resume the harness could not find fails the turn");
        };
        assert!(
            matches!(error, RuntimeError::HarnessSessionGone { .. }),
            "{error}"
        );
        assert_eq!(h.map.get(CONTEXT).as_deref(), Some("remembered"));
        // The harness still said what happened, in the trace, under its own kind.
        assert_eq!(
            h.of_type("harness_failed").await[0]["kind"],
            "harness-error"
        );
    }

    /// An expired login is not a missing conversation.
    #[tokio::test]
    async fn harness_session_an_auth_failure_on_a_resume_is_still_a_turn_failure() {
        let map = Arc::new(HarnessSessionMap::new(
            None,
            &crate::workdir_fs::WorkdirRoot::open(Path::new("/tmp")).unwrap(),
        ));
        map.put(CONTEXT, "remembered", HARNESS, "fixture-driver");
        let mut h = Harness::threading(10, map).await;

        let outcome = h
            .feed(vec![Event::TurnFailed(TurnFailure {
                kind: FailureKind::Auth,
                message: "not signed in".into(),
            })])
            .await;
        let SinkOutcome::Failed(error) = outcome else {
            panic!("a failed turn fails the run");
        };
        assert!(
            matches!(error, RuntimeError::HarnessTurnFailed { .. }),
            "{error}"
        );
    }

    #[tokio::test]
    async fn harness_session_a_resumed_turn_that_ends_keeps_its_id() {
        let map = Arc::new(HarnessSessionMap::new(
            None,
            &crate::workdir_fs::WorkdirRoot::open(Path::new("/tmp")).unwrap(),
        ));
        map.put(CONTEXT, "remembered", HARNESS, "fixture-driver");
        let mut h = Harness::threading(10, map).await;
        assert_eq!(h.planned_id, "remembered");

        h.feed(vec![
            Event::SessionStarted(SessionInfo {
                id: "remembered".into(),
                auth: SUBSCRIPTION_AUTH.into(),
                model: None,
            }),
            Event::Text("here it is".into()),
            Event::TurnEnd("here it is".into()),
        ])
        .await;
        assert_eq!(h.map.get(CONTEXT).as_deref(), Some("remembered"));
    }
}