agents-kit 0.0.1

Rust agent control Kit for Codex, OpenCode, and provider-backed Custom runtimes
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
mod codex_release;
mod lance_state_support;
mod native_cleanup;

use lance_state_support::LanceStateDirectory;
use native_cleanup::NativeCleanup;

use std::collections::BTreeMap;
use std::net::SocketAddr;
use std::num::NonZeroUsize;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::Duration;

use agents_kit::config::{AgentConfig, CodexConfig};
use agents_kit::conversation::NewConversation;
use agents_kit::error::{DeadlineKind, ErrorDetail, ErrorKind, ErrorPhase, Operation};
use agents_kit::notification::{
    ConversationNotificationKind, NotificationResolution, ProcessState,
};
use agents_kit::prompt::{PromptEvent, PromptRequest, StructuredOutputRequest};
use agents_kit::workspace::{
    DeleteWorkspaceRequest, NewWorkspace, UpdateWorkspaceRequest, WorkspaceContext,
    WorkspaceDefaults, WorkspaceExecutionPolicy, WorkspaceNetworkAccess, WorkspaceRoot,
    WorkspaceRootAccess, WorkspaceSandboxMode,
};
use agents_kit::{Agent, AgentBuilder, AgentStorage, Conversation, ConversationBackend, Workspace};
use agents_kit::{AgentBackend, WorkspaceBackend};
use futures_util::{FutureExt, SinkExt, StreamExt};
use serde_json::{Value, json};
use storage_kit::state::config::{LanceStateStoreConfig, StateStoreConfig};
use storage_kit::state::record::{
    StateKey, StateListRequest, StateListResponse, StateRecord, StateRecordSnapshot,
};
use storage_kit::{
    StateStore, StateStoreBackend, StateStoreError, StateTransaction, StateTransactionBackend,
};
use tokio::net::TcpListener;
use tokio::sync::{mpsc, oneshot};
use tokio::task::JoinHandle;
use tokio_tungstenite::tungstenite::Message;

// Protocol fixture only: the selected rust-v0.163.0 archive's App Server v2
// AgentMessageDeltaNotification supplies threadId, turnId, itemId and delta.
// This drives the real Kit WebSocket adapter; it is not live Codex evidence.
struct CodexPeer {
    address: SocketAddr,
    events: mpsc::Sender<Value>,
    turns: mpsc::Receiver<String>,
    responses: mpsc::Receiver<Value>,
    interrupts: Arc<AtomicUsize>,
    identity: Arc<std::sync::Mutex<Value>>,
    features: Arc<std::sync::Mutex<Value>>,
    models: Arc<std::sync::Mutex<Value>>,
    requests: Arc<std::sync::Mutex<Vec<Value>>>,
    hold_initialization: Arc<AtomicBool>,
    initializations: Arc<AtomicUsize>,
    thread_starts: Arc<AtomicUsize>,
    rejections: Arc<std::sync::Mutex<BTreeMap<String, Value>>>,
    resume_overrides: Arc<std::sync::Mutex<serde_json::Map<String, Value>>>,
    history: Arc<std::sync::Mutex<Value>>,
    history_override: Arc<std::sync::Mutex<Option<Value>>>,
    held_history: Arc<std::sync::Mutex<Option<oneshot::Receiver<()>>>>,
    history_entered: Arc<tokio::sync::Notify>,
    stop: Option<oneshot::Sender<()>>,
    task: Option<JoinHandle<()>>,
}

enum FirstStart {
    Ordinary,
    PaginatedEmpty,
    Materialization(Value),
    DeferredInterruptTerminal,
    ThreadObservation(oneshot::Receiver<()>),
    RecoveredTurn {
        status: String,
        error: Value,
        items: Vec<Value>,
    },
    Held(oneshot::Receiver<()>),
    EarlyDeltas {
        count: usize,
        release: Option<oneshot::Receiver<()>>,
        turn: Option<String>,
    },
}

impl CodexPeer {
    async fn start() -> Self {
        Self::start_with(FirstStart::Ordinary).await
    }

    async fn start_with(mut first_start: FirstStart) -> Self {
        let listener = TcpListener::bind("127.0.0.1:0")
            .await
            .expect("protocol listener");
        let address = listener.local_addr().expect("listener address");
        let (events, mut inbound) = mpsc::channel::<Value>(64);
        let (accepted, turns) = mpsc::channel(16);
        let (replied, responses) = mpsc::channel(16);
        let interrupts = Arc::new(AtomicUsize::new(0));
        let observed_interrupts = Arc::clone(&interrupts);
        let features = Arc::new(std::sync::Mutex::new(json!({"data":[
            {"name":"enable_fanout","enabled":false}, {"name":"multi_agent","enabled":false},
            {"name":"multi_agent_v2","enabled":false}],"nextCursor":null})));
        let reported_features = Arc::clone(&features);
        let models = Arc::new(std::sync::Mutex::new(
            json!({"data":[{"model":"selected-model","displayName":"Selected","hidden":false,
            "supportedReasoningEfforts":[{"reasoningEffort":"medium"}],"defaultReasoningEffort":"medium",
            "supportsPersonality":true,"isDefault":true}],"nextCursor":null}),
        ));
        let reported_models = Arc::clone(&models);
        let requests = Arc::new(std::sync::Mutex::new(Vec::new()));
        let observed_requests = Arc::clone(&requests);
        let identity = Arc::new(std::sync::Mutex::new(json!("codex/0.163.0")));
        let reported_identity = Arc::clone(&identity);
        let hold_initialization = Arc::new(AtomicBool::new(false));
        let held_initialization = Arc::clone(&hold_initialization);
        let initializations = Arc::new(AtomicUsize::new(0));
        let observed_initializations = Arc::clone(&initializations);
        let thread_starts = Arc::new(AtomicUsize::new(0));
        let observed_thread_starts = Arc::clone(&thread_starts);
        let rejections = Arc::new(std::sync::Mutex::new(BTreeMap::<String, Value>::new()));
        let request_rejections = Arc::clone(&rejections);
        let resume_overrides = Arc::new(std::sync::Mutex::new(serde_json::Map::new()));
        let reported_resume_overrides = Arc::clone(&resume_overrides);
        let history = Arc::new(std::sync::Mutex::new(Value::Null));
        let observed_history = Arc::clone(&history);
        let history_override = Arc::new(std::sync::Mutex::new(None::<Value>));
        let overridden_history = Arc::clone(&history_override);
        let held_history = Arc::new(std::sync::Mutex::new(None::<oneshot::Receiver<()>>));
        let held_history_response = Arc::clone(&held_history);
        let history_entered = Arc::new(tokio::sync::Notify::new());
        let entered_history = Arc::clone(&history_entered);
        let (stop, mut stopped) = oneshot::channel();
        let task = tokio::spawn(async move {
            let connection = tokio::select! {
                connection = listener.accept() => connection.expect("protocol connection").0,
                _ = &mut stopped => return,
            };
            let mut socket = tokio_tungstenite::accept_async(connection)
                .await
                .expect("WebSocket handshake");
            let mut thread = Value::Null;
            let mut policy = Value::Null;
            let mut next_turn = 0;
            let mut defer_interrupt_terminal = false;
            let paginated = matches!(first_start, FirstStart::PaginatedEmpty);
            let mut materialized = false;
            let mut loaded = true;
            loop {
                tokio::select! {
                    _ = &mut stopped => return,
                    event = inbound.recv() => {
                        let Some(event) = event else { break };
                        if event["method"] == "turn/completed" && !defer_interrupt_terminal {
                            thread["turns"] = json!([event["params"]["turn"].clone()]);
                        }
                        if defer_interrupt_terminal && event["method"] == "turn/completed" {
                            let terminal = &event["params"]["turn"];
                            if let Some(turn) = thread["turns"].as_array_mut().unwrap().iter_mut().find(|turn| turn["id"] == terminal["id"])
                                && turn["status"] == "inProgress" {
                                turn["status"] = terminal["status"].clone();
                                turn["error"] = terminal["error"].clone();
                            }
                        }
                        if defer_interrupt_terminal && event["method"] == "item/completed" {
                            let turn_id = &event["params"]["turnId"];
                            if let Some(turn) = thread["turns"].as_array_mut().unwrap().iter_mut().find(|turn| turn["id"] == *turn_id)
                                && turn["status"] == "inProgress" {
                                turn["items"].as_array_mut().unwrap().push(event["params"]["item"].clone());
                            }
                        }
                        *observed_history.lock().unwrap() = thread.clone();
                        if socket.send(Message::Text(event.to_string().into())).await.is_err() { break }
                    }
                    frame = socket.next() => {
                        let Some(Ok(Message::Text(frame))) = frame else { break };
                        let request: Value = serde_json::from_str(&frame).expect("JSON-RPC request");
                        let Some(method) = request["method"].as_str() else {
                            replied.send(request).await.expect("approval response observer");
                            continue;
                        };
                        if method == "initialized" { continue }
                        if method == "initialize" {
                            observed_initializations.fetch_add(1, Ordering::SeqCst);
                            if held_initialization.load(Ordering::SeqCst) { continue }
                        }
                        observed_requests.lock().unwrap().push(request.clone());
                        let rejection = request_rejections.lock().expect("fixture rejections").get(method).cloned();
                        if let Some(error) = rejection {
                            let response = json!({"id":request["id"],"error":error});
                            if socket.send(Message::Text(response.to_string().into())).await.is_err() { break }
                            continue;
                        }
                        let params = &request["params"];
                        if method == "thread/read" && params["includeTurns"] == true
                            && let FirstStart::Materialization(reply) = &first_start
                        {
                            let mut response = json!({"id":request["id"]});
                            if let Some(error) = reply.get("error") {
                                response["error"] = error.clone();
                            } else {
                                let mut read = thread.clone();
                                for (field, value) in reply.as_object().unwrap() {
                                    if value.is_null() { read.as_object_mut().unwrap().remove(field); }
                                    else { read[field] = value.clone(); }
                                }
                                response["result"] = json!({"thread":read});
                            }
                            if socket.send(Message::Text(response.to_string().into())).await.is_err() { break }
                            continue;
                        }
                        if method == "thread/resume" && paginated && !loaded && !materialized {
                            let response = json!({"id":request["id"],"error":{"code":-32600,"message":"thread rollout has not been persisted"}});
                            if socket.send(Message::Text(response.to_string().into())).await.is_err() { break }
                            continue;
                        }
                        if method == "thread/read" && params["threadId"] == "child-thread" && params["includeTurns"] == true {
                            let response = json!({"id":request["id"],"error":{"code":-32600,"message":"ephemeral child has no readable durable history"}});
                            if socket.send(Message::Text(response.to_string().into())).await.is_err() { break }
                            continue;
                        }
                        let mut result = match method {
                            "initialize" => json!({"userAgent":reported_identity.lock().unwrap().clone()}),
                            "thread/start" => {
                                observed_thread_starts.fetch_add(1, Ordering::SeqCst);
                                thread = json!({"id":"stream-thread", "cwd":params["cwd"], "parentThreadId":null,
                                    "threadSource":params["threadSource"], "turns":[]});
                                policy = json!({"cwd":params["cwd"], "runtimeWorkspaceRoots":params["runtimeWorkspaceRoots"],
                                    "sandbox":{"type":"dangerFullAccess"}, "activePermissionProfile":{"id":":danger-full-access","extends":null}});
                                if matches!(&first_start, FirstStart::ThreadObservation(_)) {
                                    let FirstStart::ThreadObservation(release) = std::mem::replace(&mut first_start, FirstStart::Ordinary) else {
                                        unreachable!("thread observation was selected");
                                    };
                                    let event = json!({"method":"thread/started","params":{"thread":thread.clone()}});
                                    socket.send(Message::Text(event.to_string().into())).await.expect("same-thread creation notification");
                                    tokio::select! {
                                        result = release => result.expect("release original thread/start response"),
                                        _ = &mut stopped => return,
                                    }
                                }
                                let mut response = policy.clone();
                                response["thread"] = thread.clone();
                                response
                            }
                            "thread/read" => {
                                if let Some(history) = overridden_history.lock().unwrap().as_ref() {
                                    json!({"thread":history})
                                } else if params["threadId"] == "child-thread" {
                                    let mut child = thread.clone();
                                    child["id"] = json!("child-thread");
                                    child["parentThreadId"] = json!("stream-thread");
                                    child["turns"] = json!([{"id":"child-turn","status":"inProgress","itemsView":"full","items":[],"error":null}]);
                                    json!({"thread":child})
                                } else if params["threadId"] == "foreign-thread" {
                                    json!({"thread":{"id":"foreign-thread","parentThreadId":null,"turns":[]}})
                                } else {
                                    json!({"thread":thread})
                                }
                            }
                            "thread/resume" => {
                                loaded = true;
                                let mut response = policy.clone();
                                response.as_object_mut().unwrap().extend(reported_resume_overrides.lock().unwrap().clone());
                                response["thread"] = thread.clone();
                                response
                            }
                            "thread/name/set" => { materialized = true; json!({}) },
                            "thread/delete" | "thread/backgroundTerminals/clean" => json!({}),
                            "thread/list" | "thread/backgroundTerminals/list" => json!({"data":[],"nextCursor":null}),
                            "thread/unsubscribe" => { loaded = false; json!({"status":"unsubscribed"}) },
                            "experimentalFeature/list" => reported_features.lock().unwrap().clone(),
                            "model/list" => reported_models.lock().unwrap().clone(),
                            "turn/start" => {
                                next_turn += 1;
                                let id = format!("turn-{next_turn}");
                                let mut turn = json!({"id":id,"status":"inProgress","items":[],"error":null});
                                if defer_interrupt_terminal || matches!(&first_start, FirstStart::DeferredInterruptTerminal) {
                                    defer_interrupt_terminal = true;
                                    turn["itemsView"] = json!("full");
                                    turn["items"] = json!([{"type":"userMessage","id":format!("user-{id}"),"clientId":params["clientUserMessageId"]}]);
                                    thread["turns"].as_array_mut().unwrap().push(turn.clone());
                                } else {
                                    thread["turns"] = json!([turn.clone()]);
                                }
                                *observed_history.lock().unwrap() = thread.clone();
                                accepted.send(id.clone()).await.expect("turn observer");
                                if next_turn == 1 {
                                    match std::mem::replace(&mut first_start, FirstStart::Ordinary) {
                                        FirstStart::Ordinary | FirstStart::PaginatedEmpty | FirstStart::Materialization(_) => {}
                                        FirstStart::DeferredInterruptTerminal => {}
                                        FirstStart::ThreadObservation(_) => panic!("thread observation must be consumed before a turn starts"),
                                        FirstStart::RecoveredTurn { status, error, mut items } => {
                                            items.insert(0, json!({"type":"userMessage","clientId":params["clientUserMessageId"]}));
                                            thread["turns"] = json!([{"id":id,"status":status,"itemsView":"full",
                                                "items":items,"error":error}]);
                                            turn = Value::Null;
                                        }
                                        FirstStart::Held(release) => {
                                            tokio::select! {
                                                result = release => result.expect("release original native start"),
                                                _ = &mut stopped => return,
                                            }
                                        }
                                        FirstStart::EarlyDeltas { count, release, turn: observed_turn } => {
                                            for index in 0..count {
                                                let event = json!({"method":"item/agentMessage/delta","params":{
                                                    "threadId":"stream-thread","turnId":observed_turn.as_deref().unwrap_or(&id),"itemId":"early-answer",
                                                    "delta":format!("early {index}")}});
                                                socket.send(Message::Text(event.to_string().into())).await.expect("early native delta");
                                            }
                                            if let Some(release) = release {
                                                tokio::select! {
                                                    result = release => result.expect("release receipt after early output"),
                                                    _ = &mut stopped => return,
                                                }
                                            }
                                        }
                                    }
                                }
                                json!({"turn":turn})
                            }
                            "turn/interrupt" => {
                                observed_interrupts.fetch_add(1, Ordering::SeqCst);
                                let turn = thread["turns"].as_array_mut().unwrap().iter_mut()
                                    .find(|turn| turn["id"] == params["turnId"]).expect("exact interrupted turn");
                                turn["status"] = json!("interrupted");
                                json!({})
                            }
                            method => panic!("unhandled fixture request {method}"),
                        };
                        *observed_history.lock().unwrap() = thread.clone();
                        if method == "thread/read" && params["includeTurns"] == true {
                            let release = held_history_response.lock().unwrap().take();
                            if let Some(release) = release {
                                entered_history.notify_one();
                                tokio::select! {
                                    result = release => { if result.is_err() { return } },
                                    _ = &mut stopped => return,
                                }
                            }
                        }
                        if method == "thread/read" {
                            result["readState"] = json!({"firstUnread":{"type":"turn","turnId":"earlier-turn"},"revision":"opaque"});
                        } else if method == "thread/list" {
                            result["readStates"] = json!({});
                        }
                        let response = json!({"id":request["id"],"result":result});
                        if socket.send(Message::Text(response.to_string().into())).await.is_err() { break }
                        if method == "turn/interrupt" && !defer_interrupt_terminal {
                            let event = json!({"method":"turn/completed","params":{"threadId":"stream-thread","turn":thread["turns"][0]}});
                            if socket.send(Message::Text(event.to_string().into())).await.is_err() { break }
                        }
                    }
                }
            }
            // Keep the fixture task alive until explicit cleanup, including
            // after Kit transport drop, so public runtime task counts cannot
            // mistake a finished peer for a remaining Kit task.
            let _ = stopped.await;
        });
        Self {
            address,
            events,
            turns,
            responses,
            interrupts,
            identity,
            features,
            models,
            requests,
            hold_initialization,
            initializations,
            thread_starts,
            rejections,
            resume_overrides,
            history,
            history_override,
            held_history,
            history_entered,
            stop: Some(stop),
            task: Some(task),
        }
    }

    async fn turn(&mut self) -> String {
        tokio::time::timeout(Duration::from_secs(3), self.turns.recv())
            .await
            .expect("native acceptance progress")
            .expect("native accepted turn")
    }

    fn reject(&self, method: &str, code: i64, message: &str) {
        self.rejections
            .lock()
            .expect("fixture rejections")
            .insert(method.to_owned(), json!({"code":code,"message":message}));
    }

    async fn request(&self, id: i64, method: &str, params: Value) {
        self.events
            .send(json!({"id":id,"method":method,"params":params}))
            .await
            .expect("fixture request source");
    }

    async fn notify(&self, method: &str, params: Value) {
        self.events
            .send(json!({"method":method,"params":params}))
            .await
            .expect("fixture event source");
    }

    async fn complete(&self, turn: &str, text: &str) {
        self.notify(
            "item/completed",
            json!({"threadId":"stream-thread","turnId":turn,"completedAtMs":1,
            "item":{"id":"answer","type":"agentMessage","text":text,"phase":"final_answer"}}),
        )
        .await;
        self.notify("turn/completed", json!({"threadId":"stream-thread", "turn":{"id":turn,"status":"completed","items":[],"error":null}})).await;
    }

    async fn fail(&self, turn: &str, info: Value) {
        self.notify(
            "turn/completed",
            json!({"threadId":"stream-thread", "turn":{
            "id":turn,"status":"failed","items":[],"error":{
                "message":"secret-token native-private-path", "codexErrorInfo":info,
                "additionalDetails":"provider-private-id"}}}),
        )
        .await;
    }

    async fn shutdown(mut self) {
        if let Some(stop) = self.stop.take() {
            let _ = stop.send(());
        }
        if let Some(mut task) = self.task.take() {
            match tokio::time::timeout(Duration::from_secs(3), &mut task).await {
                Ok(result) => result.expect("fixture task"),
                Err(_) => {
                    task.abort();
                    let _ = task.await;
                    panic!("fixture join bound");
                }
            }
        }
    }
}

impl Drop for CodexPeer {
    fn drop(&mut self) {
        if let Some(task) = &self.task {
            task.abort();
        }
    }
}

#[derive(Clone)]
struct WaiterFaultStore {
    inner: StateStore,
    fault: WaiterFault,
    armed: Arc<AtomicBool>,
    attempts: Arc<AtomicUsize>,
}

#[derive(Clone)]
enum WaiterFault {
    InteractionPublication {
        point: InteractionFaultPoint,
        source: StorageFaultSource,
        owner_task: Arc<std::sync::Mutex<Option<tokio::task::Id>>>,
        failures: usize,
        rollback_failure: bool,
        rollbacks: Arc<AtomicUsize>,
    },
    RollbackFailure,
    HeldClear {
        entered: Arc<tokio::sync::Semaphore>,
        release: Arc<tokio::sync::Semaphore>,
        observation_error: bool,
    },
    NotificationReceipt {
        observation: bool,
        cleanup_failure: bool,
        observe_next: Arc<AtomicBool>,
        restore_prefix: Arc<std::sync::Mutex<Option<Value>>>,
        sequence_gap: Arc<AtomicBool>,
        entered: Arc<tokio::sync::Semaphore>,
        release: Arc<tokio::sync::Semaphore>,
        committed: Arc<AtomicUsize>,
    },
    Storage {
        point: StorageFaultPoint,
        source: StorageFaultSource,
        scope: StorageFaultScope,
        skip_transactions: usize,
        transactions: Arc<AtomicUsize>,
    },
    Retry,
    ForeignOwner,
    TerminalRecord {
        patch: Value,
        captured: Arc<std::sync::Mutex<Option<Value>>>,
    },
    TimeoutIntent {
        failures: usize,
    },
    ThreadCreationObservation {
        case: CreationObservationCase,
        reconciled: Arc<tokio::sync::Semaphore>,
        entered: Arc<tokio::sync::Semaphore>,
        release: Arc<[tokio::sync::Semaphore; 2]>,
        committed: Arc<tokio::sync::Semaphore>,
        conflicts: Arc<AtomicUsize>,
    },
    CreationFailure {
        point: StorageFaultPoint,
        source: StorageFaultSource,
        cleanup_failure: bool,
        native_starts: Arc<AtomicUsize>,
        rollbacks: Arc<AtomicUsize>,
    },
    HeldCreation {
        entered: Arc<tokio::sync::Notify>,
        release: Arc<tokio::sync::Semaphore>,
    },
    HeldCommit {
        waiter: &'static str,
        entered: Arc<tokio::sync::Notify>,
        release: Arc<tokio::sync::Semaphore>,
        completed: Arc<AtomicUsize>,
    },
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum CreationObservationCase {
    EventWins,
    ForegroundWins,
    DifferentThread,
    ChangedObligation,
    UnchangedObligation,
    ReadbackUnavailable,
}

struct WaiterFaultTransaction {
    inner: StateTransaction,
    owner: WaiterFaultStore,
    held_waiter: bool,
    held_clear: bool,
    held_notification: bool,
    held_creation_observation: Option<usize>,
    creation_load_failed: bool,
    storage_selected: bool,
    interaction_staged: bool,
    publication_fault: bool,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum InteractionFaultPoint {
    Begin,
    PromptLoad,
    Journal,
    Continuation,
    Commit,
    HeldStaging,
    HeldCommit,
    AmbiguousCommit,
    StaleDuplicate,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum StorageFaultPoint {
    Begin,
    Load,
    Put,
    Delete,
    Commit,
}

impl StorageFaultPoint {
    fn phase(self) -> ErrorPhase {
        match self {
            Self::Begin | Self::Put | Self::Delete => ErrorPhase::StateWrite,
            Self::Load => ErrorPhase::StateRead,
            Self::Commit => ErrorPhase::StateCommit,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum StorageFaultSource {
    Unavailable,
    TimedOut,
    Conflict,
}

impl StorageFaultSource {
    fn error(self) -> StateStoreError {
        match self {
            Self::Unavailable => {
                StateStoreError::unavailable("secret-storage-operation", "secret-storage-message")
            }
            Self::TimedOut => StateStoreError::timed_out("secret-storage-operation", 37),
            Self::Conflict => StateStoreError::transaction_conflict(
                "secret-storage-operation",
                "secret-storage-message",
            ),
        }
    }
}

#[derive(Clone)]
enum StorageFaultScope {
    Any,
    Task(Option<tokio::task::Id>),
}

impl StorageFaultScope {
    fn includes_current_task(&self) -> bool {
        match self {
            Self::Any => true,
            Self::Task(expected) => *expected == tokio::task::try_id(),
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum StorageFaultOperation {
    Prompt,
    PromptStream,
    Abort,
    CloseConversation,
    UpdateWorkspace,
    DeleteWorkspace,
}

impl StorageFaultOperation {
    fn operation(self) -> Operation {
        match self {
            Self::Prompt | Self::PromptStream => Operation::Prompt,
            Self::Abort => Operation::Abort,
            Self::CloseConversation => Operation::CloseConversation,
            Self::UpdateWorkspace => Operation::UpdateWorkspace,
            Self::DeleteWorkspace => Operation::DeleteWorkspace,
        }
    }

    fn retries_conflict(self) -> bool {
        matches!(
            self,
            Self::Prompt | Self::PromptStream | Self::Abort | Self::CloseConversation
        )
    }

    async fn assert_fault(self, point: StorageFaultPoint, source: StorageFaultSource) {
        let store = WaiterFaultStore {
            inner: StateStore::connect(StateStoreConfig::Lance(LanceStateStoreConfig::memory()))
                .await
                .expect("fault store"),
            fault: WaiterFault::Storage {
                point,
                source,
                // An active prompt independently polls its state. Fault the
                // caller's abort transaction, not that competing prompt owner.
                scope: if self == Self::Abort {
                    StorageFaultScope::Task(tokio::task::try_id())
                } else {
                    StorageFaultScope::Any
                },
                // Public close first checks its idle prompt through abort. Select
                // the close mutation itself, rather than that preceding owner.
                skip_transactions: usize::from(self == Self::CloseConversation),
                transactions: Arc::new(AtomicUsize::new(0)),
            },
            armed: Arc::new(AtomicBool::new(false)),
            attempts: Arc::new(AtomicUsize::new(0)),
        };
        let CodexFixture {
            mut peer,
            agent,
            workspace,
            conversation,
            root,
        } = CodexFixture::build_with_store(CodexPeer::start().await, store.clone()).await;
        let mut conversation = Some(conversation);
        let mut active = None;
        let observed = std::panic::AssertUnwindSafe(async {
            let before = workspace.info().await.expect("workspace before fault");
            let conversation_id = conversation.as_ref().expect("conversation").id().clone();
            if self == Self::Abort {
                let stream = conversation.as_ref().expect("conversation")
                    .prompt_stream(PromptRequest::new("active cancellation target").unwrap())
                    .await.expect("active prompt");
                let turn = peer.turn().await;
                active = Some((stream, turn));
                let key = StateKey::new("agents_kit_codex_prompts_v1", conversation_id.as_str()).unwrap();
                tokio::time::timeout(Duration::from_secs(3), async {
                    loop {
                        if store.inner.load(key.clone()).await.unwrap().is_some_and(|record| {
                            record.record.value["state"]["state"] == "running"
                        }) {
                            break;
                        }
                        tokio::task::yield_now().await;
                    }
                }).await.expect("accepted prompt must settle before fault admission");
            }
            store.armed.store(true, Ordering::SeqCst);
            let succeeds = source == StorageFaultSource::Conflict && self.retries_conflict();
            let result = tokio::time::timeout(Duration::from_secs(3), async {
                match self {
                    Self::Prompt => {
                        let mut prompt = Box::pin(conversation.as_ref().unwrap()
                            .prompt(PromptRequest::new("phase probe").unwrap()));
                        if succeeds {
                            let turn = tokio::select! {
                                turn = peer.turn() => turn,
                                result = &mut prompt => panic!("conflict must retry admission: {result:?}"),
                            };
                            peer.complete(&turn, "accepted once").await;
                        }
                        prompt.await.map(|response| assert_eq!(response.output(), "accepted once"))
                    }
                    Self::PromptStream => {
                        let mut stream = conversation.as_ref().unwrap()
                            .prompt_stream(PromptRequest::new("stream phase probe").unwrap()).await?;
                        if succeeds {
                            let turn = peer.turn().await;
                            peer.complete(&turn, "accepted once").await;
                        }
                        match stream.recv().await {
                            Some(Err(error)) => Err(error),
                            Some(Ok(PromptEvent::Completed(response))) => {
                                assert_eq!(response.output(), "accepted once");
                                Ok(())
                            }
                            event => panic!("expected a terminal phase result: {event:?}"),
                        }
                    }
                    Self::Abort => conversation.as_ref().unwrap().abort().await,
                    Self::CloseConversation => conversation.take().unwrap().close().await,
                    Self::UpdateWorkspace => agent.update_workspace(UpdateWorkspaceRequest::new(
                        before.id().clone(), before.revision(), "replacement", before.context().clone(),
                        before.defaults().clone(),
                    ).unwrap()).await.map(|_| ()),
                    Self::DeleteWorkspace => agent.delete_workspace(DeleteWorkspaceRequest::new(
                        before.id().clone(), before.revision(),
                    ).unwrap()).await,
                }
            }).await.expect("public operation must settle after a definite injected failure");
            store.armed.store(false, Ordering::SeqCst);
            assert_eq!(store.attempts.load(Ordering::SeqCst), 1, "{self:?} {point:?}");
            if let Some((mut stream, turn)) = active.take() {
                if !succeeds {
                    assert_eq!(peer.interrupts.load(Ordering::SeqCst), 0,
                        "uncommitted cancellation cannot dispatch a native interrupt");
                    peer.complete(&turn, "original prompt completed").await;
                }
                let terminal = tokio::time::timeout(Duration::from_secs(3), stream.recv())
                    .await.expect("accepted prompt settlement");
                if succeeds {
                    assert!(matches!(terminal, Some(Err(error)) if error.kind() == ErrorKind::Cancelled));
                    assert_eq!(peer.interrupts.load(Ordering::SeqCst), 1);
                } else {
                    assert!(matches!(terminal, Some(Ok(PromptEvent::Completed(response)))
                        if response.output() == "original prompt completed"));
                }
            }
            let after = agent.workspace_info(before.id().clone()).await.expect("workspace remains committed");
            assert_eq!(after.revision(), before.revision(), "failed mutation cannot advance revision");
            assert_eq!(after.name(), before.name());
            let conversations = workspace.list_conversations().await.expect("durable conversation inventory");
            assert_eq!(conversations.len(), usize::from(!(self == Self::CloseConversation && succeeds)));
            if !conversations.is_empty() {
                assert_eq!(conversations[0].id(), &conversation_id);
            }
            assert!(matches!(peer.turns.try_recv(), Err(mpsc::error::TryRecvError::Empty)),
                "failed admission and conflict retries cannot duplicate native work");
            if succeeds {
                result.expect("one exact conflict must preserve the permitted retry");
            } else {
                let error = result.expect_err("injected dependency failure");
                assert_eq!(error.context().operation, self.operation(), "{self:?} {point:?}");
                assert_eq!(error.context().phase, point.phase(), "{self:?} {point:?}: {error:?}");
                match source {
                    StorageFaultSource::Unavailable => {
                        assert_eq!(error.kind(), ErrorKind::Integration);
                        assert_eq!(error.detail(), Some(&ErrorDetail::ServiceUnavailable));
                    }
                    StorageFaultSource::TimedOut => {
                        assert_eq!(error.kind(), ErrorKind::Timeout);
                        assert_eq!(error.detail(), Some(&ErrorDetail::DeadlineElapsed {
                            kind: DeadlineKind::Operation, timeout: Some(Duration::from_millis(37)),
                        }));
                    }
                    StorageFaultSource::Conflict => {
                        assert_eq!(error.kind(), ErrorKind::Conflict);
                        assert_eq!(error.detail(), Some(&ErrorDetail::TransactionConflict));
                    }
                }
                assert!(error.cause().is_none());
                assert!(error.supplementary().is_empty());
                assert!(!format!("{error} {error:?}").contains("secret-storage"));
            }
        }).catch_unwind().await;
        store.armed.store(false, Ordering::SeqCst);
        if let Some((stream, turn)) = active.take() {
            peer.complete(&turn, "cleanup terminal").await;
            drop(stream);
        }
        drop(conversation);
        drop(workspace);
        let stopped = tokio::time::timeout(Duration::from_secs(4), agent.shutdown()).await;
        peer.shutdown().await;
        let removed = std::fs::remove_dir_all(root);
        if let Err(panic) = observed {
            std::panic::resume_unwind(panic);
        }
        stopped
            .expect("Agent shutdown bound")
            .expect("Agent shutdown");
        removed.expect("fixture directory cleanup");
    }
}

impl WaiterFaultStore {
    async fn assert_interaction_publication(
        point: InteractionFaultPoint,
        source: StorageFaultSource,
        rollback_failure: bool,
        failures: usize,
    ) {
        let raw = StateStore::connect(StateStoreConfig::Lance(LanceStateStoreConfig::memory()))
            .await
            .unwrap();
        let armed = Arc::new(AtomicBool::new(false));
        let attempts = Arc::new(AtomicUsize::new(0));
        let rollbacks = Arc::new(AtomicUsize::new(0));
        let store = Self {
            inner: raw.clone(),
            armed: Arc::clone(&armed),
            attempts: Arc::clone(&attempts),
            fault: WaiterFault::InteractionPublication {
                point,
                source,
                owner_task: Arc::new(std::sync::Mutex::new(None)),
                failures,
                rollback_failure,
                rollbacks: Arc::clone(&rollbacks),
            },
        };
        let mut fixture = CodexFixture::build_with_store(CodexPeer::start().await, store).await;
        let observed = std::panic::AssertUnwindSafe(tokio::time::timeout(Duration::from_secs(4), async {
            let mut notifications = fixture.conversation.notification_stream().unwrap();
            let mut stream = fixture.conversation.prompt_stream(PromptRequest::new("approval publication").unwrap()).await.unwrap();
            let turn = fixture.peer.turn().await;
            let prompt_key = StateKey::new("agents_kit_codex_prompts_v1", fixture.conversation.id().as_str()).unwrap();
            loop {
                if raw.load(prompt_key.clone()).await.unwrap().unwrap().record.value["state"]["turn_id"] == turn { break; }
                tokio::task::yield_now().await;
            }
            armed.store(true, Ordering::SeqCst);
            let callback = json!("exact-publication-callback");
            fixture.peer.events.send(json!({"id":callback,"method":"item/commandExecution/requestApproval","params":{
                "threadId":"stream-thread","turnId":turn,"itemId":"running-command","approvalId":"distinct-approval",
                "kind":"writeStdin","startedAtMs":1,"availableDecisions":["accept","cancel"]}})).await.unwrap();
            let succeeds = source == StorageFaultSource::Conflict && !rollback_failure && failures != usize::MAX
                && point != InteractionFaultPoint::HeldStaging;
            let committed = succeeds || point == InteractionFaultPoint::AmbiguousCommit;
            let notification = if point == InteractionFaultPoint::AmbiguousCommit {
                let response = fixture.peer.responses.recv().await.unwrap();
                assert_eq!(response["id"], callback);
                assert_eq!(response["error"]["code"], -32603);
                None
            } else { tokio::select! {
                notification = notifications.recv() => {
                    assert!(succeeds, "non-conflict or failed rollback must not be retried");
                    Some(notification.unwrap().unwrap())
                }
                response = fixture.peer.responses.recv() => {
                    let response = response.unwrap();
                    assert!(!succeeds, "exact precommit conflict must reconcile, not reject: {response}");
                    assert_eq!(response["id"], callback);
                    assert_eq!(response["error"]["code"], -32603);
                    assert!(!response.to_string().contains("secret"));
                    None
                }
            } };
            armed.store(false, Ordering::SeqCst);
            let attempted = attempts.load(Ordering::SeqCst);
            if failures == usize::MAX {
                assert!((2..=121).contains(&attempted), "conflict attempts must remain bounded: {attempted}");
            } else {
                assert_eq!(attempted, if succeeds && point != InteractionFaultPoint::HeldCommit { failures + 1 } else { 1 }, "{point:?}");
            }
            let failed_attempts = if succeeds { failures } else { attempted };
            assert_eq!(rollbacks.load(Ordering::SeqCst), if matches!(point, InteractionFaultPoint::Begin | InteractionFaultPoint::Commit | InteractionFaultPoint::HeldCommit | InteractionFaultPoint::AmbiguousCommit) { 0 } else { failed_attempts },
                "failed staging must explicitly settle rollback before retry or rejection");
            let continuations = raw.list(StateListRequest::new("agents_kit_codex_continuations_v1").unwrap()).await.unwrap();
            assert_eq!(continuations.records.len(), usize::from(committed));
            let journal_key = StateKey::new("agents_kit_conversation_notifications_v1", fixture.conversation.id().as_str()).unwrap();
            let journal = raw.load(journal_key).await.unwrap().unwrap();
            let pending = journal.record.value["pending"].as_array().unwrap();
            assert_eq!(pending.iter().filter(|entry| entry["kind"]["kind"] == "interaction").count(), usize::from(committed));
            if let Some(notification) = notification {
                assert!(matches!(notification.kind(), ConversationNotificationKind::Interaction { title, .. } if title == "Terminal input approval"));
                let continuation = &continuations.records[0].record.value;
                assert_eq!(continuation["request_id"], callback);
                assert_eq!(continuation["notification_id"], json!(notification.id()));
                drop(notifications);
                notifications = fixture.conversation.notification_stream().unwrap();
                let replay = notifications.recv().await.unwrap().unwrap();
                assert_eq!(replay.id(), notification.id());
                assert_eq!(replay.kind(), notification.kind());
                let resolution = fixture.conversation.resolve_notification(notification.id().clone(), NotificationResolution::Allow).await.unwrap_err();
                assert_eq!(resolution.kind(), ErrorKind::Conflict, "enqueue ambiguity remains fenced");
                assert_eq!(fixture.peer.responses.recv().await.unwrap(), json!({"id":callback,"result":{"decision":"accept"}}));
                let repeated = fixture.conversation.resolve_notification(notification.id().clone(), NotificationResolution::Allow).await.unwrap_err();
                assert_eq!(repeated.kind(), ErrorKind::Conflict);
            } else if !committed {
                assert!(tokio::time::timeout(Duration::from_millis(30), notifications.recv()).await.is_err());
            }
            fixture.peer.complete(&turn, "exact approval terminal").await;
            assert!(matches!(stream.recv().await, Some(Ok(PromptEvent::Completed(response))) if response.output() == "exact approval terminal"));
            assert!(stream.recv().await.is_none());
            assert!(fixture.peer.responses.try_recv().is_err(), "no duplicate native reply");
        })).catch_unwind().await;
        armed.store(false, Ordering::SeqCst);
        let mut cleanup = NativeCleanup::new(Duration::from_secs(4));
        cleanup.settle(fixture.conversation.close()).await;
        cleanup.settle(fixture.workspace.close()).await;
        cleanup.settle(fixture.agent.shutdown()).await;
        cleanup
            .settle(async {
                fixture.peer.shutdown().await;
                Ok::<(), agents_kit::KitError>(())
            })
            .await;
        cleanup
            .settle(async { std::fs::remove_dir_all(fixture.root) })
            .await;
        cleanup.finish(observed);
    }

    fn publication_failure(&self, current: InteractionFaultPoint) -> Option<StateStoreError> {
        let WaiterFault::InteractionPublication {
            point,
            source,
            owner_task,
            failures,
            ..
        } = &self.fault
        else {
            return None;
        };
        if current != *point || !self.armed.load(Ordering::SeqCst) {
            return None;
        }
        if matches!(
            point,
            InteractionFaultPoint::Begin | InteractionFaultPoint::PromptLoad
        ) {
            let mut owner = owner_task.lock().unwrap();
            if owner.is_none() || *owner != tokio::task::try_id() {
                return None;
            }
            *owner = None;
        }
        if self.attempts.fetch_add(1, Ordering::SeqCst) < *failures {
            Some(source.error())
        } else {
            None
        }
    }

    fn storage_failure(
        &self,
        current: StorageFaultPoint,
        selected: bool,
    ) -> Option<StateStoreError> {
        let WaiterFault::Storage { point, source, .. } = &self.fault else {
            return None;
        };
        if selected && current == *point && self.armed.swap(false, Ordering::SeqCst) {
            self.attempts.fetch_add(1, Ordering::SeqCst);
            Some(source.error())
        } else {
            None
        }
    }
}

#[tokio::test]
async fn codex_interaction_publication_reconciles_journal_conflict() {
    WaiterFaultStore::assert_interaction_publication(
        InteractionFaultPoint::Journal,
        StorageFaultSource::Conflict,
        false,
        1,
    )
    .await;
}

#[tokio::test]
async fn codex_interaction_publication_reconciles_continuation_conflict() {
    WaiterFaultStore::assert_interaction_publication(
        InteractionFaultPoint::Continuation,
        StorageFaultSource::Conflict,
        false,
        1,
    )
    .await;
}

#[tokio::test]
async fn codex_interaction_publication_reconciles_commit_conflict() {
    WaiterFaultStore::assert_interaction_publication(
        InteractionFaultPoint::Commit,
        StorageFaultSource::Conflict,
        false,
        1,
    )
    .await;
}

#[tokio::test]
async fn codex_interaction_publication_does_not_retry_other_failures() {
    for source in [
        StorageFaultSource::Unavailable,
        StorageFaultSource::TimedOut,
    ] {
        WaiterFaultStore::assert_interaction_publication(
            InteractionFaultPoint::Journal,
            source,
            false,
            1,
        )
        .await;
        WaiterFaultStore::assert_interaction_publication(
            InteractionFaultPoint::Commit,
            source,
            false,
            1,
        )
        .await;
    }
    WaiterFaultStore::assert_interaction_publication(
        InteractionFaultPoint::Journal,
        StorageFaultSource::Conflict,
        true,
        1,
    )
    .await;
}

impl StateStoreBackend for WaiterFaultStore {
    type Transaction = WaiterFaultTransaction;

    async fn load(&self, key: StateKey) -> Result<Option<StateRecordSnapshot>, StateStoreError> {
        if key.namespace().as_str() == "agents_kit_codex_thread_creations_v2"
            && let WaiterFault::ThreadCreationObservation {
                case,
                conflicts,
                reconciled,
                ..
            } = &self.fault
            && conflicts.load(Ordering::SeqCst) > 0
        {
            let snapshot = if *case == CreationObservationCase::ReadbackUnavailable
                && self.armed.swap(false, Ordering::SeqCst)
            {
                Err(StateStoreError::unavailable(
                    "load",
                    "injected creation readback failure",
                ))
            } else {
                self.inner.load(key).await
            };
            reconciled.add_permits(1);
            return snapshot;
        }
        if key.namespace().as_str() == "agents_kit_conversation_notifications_v1"
            && let WaiterFault::NotificationReceipt {
                observe_next,
                entered,
                release,
                ..
            } = &self.fault
            && observe_next.swap(false, Ordering::SeqCst)
        {
            entered.add_permits(1);
            release.acquire().await.unwrap().forget();
        }
        let notification = key.namespace().as_str() == "agents_kit_conversation_notifications_v1";
        let mut snapshot = self.inner.load(key).await?;
        if notification
            && let WaiterFault::NotificationReceipt { restore_prefix, .. } = &self.fault
            && let Some(prefix) = restore_prefix.lock().unwrap().take()
            && let Some(snapshot) = &mut snapshot
        {
            Arc::make_mut(&mut snapshot.record.value)["pending"]
                .as_array_mut()
                .unwrap()
                .insert(0, prefix);
        }
        if notification
            && let WaiterFault::NotificationReceipt { sequence_gap, .. } = &self.fault
            && sequence_gap.swap(false, Ordering::SeqCst)
            && let Some(snapshot) = &mut snapshot
        {
            let value = Arc::make_mut(&mut snapshot.record.value);
            value["next_sequence"] = json!(value["next_sequence"].as_u64().unwrap() + 1);
        }
        Ok(snapshot)
    }

    async fn list(&self, request: StateListRequest) -> Result<StateListResponse, StateStoreError> {
        let continuation = request.namespace().as_str() == "agents_kit_codex_continuations_v1";
        let mut response = self.inner.list(request).await?;
        if continuation
            && self.armed.load(Ordering::SeqCst)
            && let WaiterFault::InteractionPublication { owner_task, .. } = &self.fault
        {
            *owner_task.lock().unwrap() = tokio::task::try_id();
        }
        if continuation
            && self.armed.load(Ordering::SeqCst)
            && matches!(
                &self.fault,
                WaiterFault::InteractionPublication {
                    point: InteractionFaultPoint::StaleDuplicate,
                    ..
                }
            )
        {
            for snapshot in &mut response.records {
                Arc::make_mut(&mut snapshot.record.value)["state"] = json!("pending");
            }
            self.attempts.fetch_add(1, Ordering::SeqCst);
        }
        Ok(response)
    }

    async fn begin_transaction(&self) -> Result<Self::Transaction, StateStoreError> {
        if let Some(error) = self.publication_failure(InteractionFaultPoint::Begin) {
            return Err(error);
        }
        let storage_selected = match &self.fault {
            WaiterFault::Storage {
                scope,
                skip_transactions,
                transactions,
                ..
            } if self.armed.load(Ordering::SeqCst) && scope.includes_current_task() => {
                transactions.fetch_add(1, Ordering::SeqCst) >= *skip_transactions
            }
            _ => false,
        };
        if let Some(error) = self.storage_failure(StorageFaultPoint::Begin, storage_selected) {
            return Err(error);
        }
        Ok(WaiterFaultTransaction {
            inner: self.inner.begin_transaction().await?,
            owner: self.clone(),
            held_waiter: false,
            held_clear: false,
            held_notification: false,
            held_creation_observation: None,
            creation_load_failed: false,
            storage_selected,
            interaction_staged: false,
            publication_fault: false,
        })
    }
}

impl StateTransactionBackend for WaiterFaultTransaction {
    async fn load(
        &mut self,
        key: StateKey,
    ) -> Result<Option<StateRecordSnapshot>, StateStoreError> {
        if let Some(error) = self
            .owner
            .storage_failure(StorageFaultPoint::Load, self.storage_selected)
        {
            return Err(error);
        }
        let creation = key.namespace().as_str() == "agents_kit_codex_thread_creations_v2";
        let prompt = key.namespace().as_str() == "agents_kit_codex_prompts_v1";
        if prompt
            && let Some(error) = self
                .owner
                .publication_failure(InteractionFaultPoint::PromptLoad)
        {
            self.publication_fault = true;
            return Err(error);
        }
        let mut snapshot = self.inner.load(key).await?;
        if creation
            && let WaiterFault::CreationFailure {
                point,
                source,
                native_starts,
                ..
            } = &self.owner.fault
            && *point == StorageFaultPoint::Load
            && native_starts.load(Ordering::SeqCst) == 1
            && self.owner.armed.swap(false, Ordering::SeqCst)
        {
            self.creation_load_failed = true;
            self.owner.attempts.fetch_add(1, Ordering::SeqCst);
            return Err(source.error());
        }
        if prompt
            && matches!(&self.owner.fault, WaiterFault::ForeignOwner)
            && self.owner.armed.load(Ordering::SeqCst)
            && let Some(snapshot) = &mut snapshot
            && snapshot.record.value["waiter"] == "delivering"
        {
            self.owner.attempts.fetch_add(1, Ordering::SeqCst);
            Arc::make_mut(&mut snapshot.record.value)["client_message_id"] =
                json!("foreign-generation");
        }
        Ok(snapshot)
    }

    async fn put(&mut self, mut record: StateRecord) -> Result<(), StateStoreError> {
        let journal_interaction = record.key.namespace().as_str()
            == "agents_kit_conversation_notifications_v1"
            && record.value["pending"].as_array().is_some_and(|pending| {
                pending
                    .iter()
                    .any(|entry| entry["kind"]["kind"] == "interaction")
            });
        let continuation = record.key.namespace().as_str() == "agents_kit_codex_continuations_v1";
        self.interaction_staged |= continuation;
        if continuation
            && self
                .owner
                .publication_failure(InteractionFaultPoint::HeldStaging)
                .is_some()
        {
            self.publication_fault = true;
            tokio::time::sleep(Duration::from_millis(3100)).await;
        }
        let point = if journal_interaction {
            Some(InteractionFaultPoint::Journal)
        } else if continuation {
            Some(InteractionFaultPoint::Continuation)
        } else {
            None
        };
        if let Some(error) = point.and_then(|point| self.owner.publication_failure(point)) {
            self.publication_fault = true;
            return Err(error);
        }
        if record.key.namespace().as_str() == "agents_kit_codex_thread_creations_v2"
            && record.value["state"]["native_thread_id"] == "stream-thread"
            && let WaiterFault::ThreadCreationObservation {
                case,
                entered,
                release,
                ..
            } = &self.owner.fault
            && self.owner.armed.load(Ordering::SeqCst)
        {
            let position = self.owner.attempts.fetch_add(1, Ordering::SeqCst);
            if position < release.len() {
                if position == 0 {
                    match case {
                        CreationObservationCase::DifferentThread => {
                            Arc::make_mut(&mut record.value)["state"]["native_thread_id"] =
                                json!("other-thread");
                        }
                        CreationObservationCase::ChangedObligation => {
                            Arc::make_mut(&mut record.value)["native_name"] =
                                json!("different-obligation");
                        }
                        CreationObservationCase::UnchangedObligation => {
                            record = StateRecord::new(
                                StateKey::new("fixture_receipts", "unrelated_commit").unwrap(),
                                json!(true),
                            );
                        }
                        CreationObservationCase::EventWins
                        | CreationObservationCase::ForegroundWins
                        | CreationObservationCase::ReadbackUnavailable => {}
                    }
                }
                self.inner.put(record).await?;
                self.held_creation_observation = Some(position);
                entered.add_permits(1);
                release[position]
                    .acquire()
                    .await
                    .expect("release staged creation observation")
                    .forget();
                return Ok(());
            }
        }
        self.held_notification |= record.key.namespace().as_str()
            == "agents_kit_conversation_notifications_v1"
            && matches!(self.owner.fault, WaiterFault::NotificationReceipt { .. })
            && self.owner.armed.load(Ordering::SeqCst);
        if self.held_notification
            && let WaiterFault::NotificationReceipt {
                cleanup_failure: true,
                ..
            } = &self.owner.fault
            && self.owner.attempts.fetch_add(1, Ordering::SeqCst) == 0
        {
            return Err(StateStoreError::transaction_conflict(
                "put",
                "injected receipt conflict before rollback failure",
            ));
        }
        if let Some(error) = self
            .owner
            .storage_failure(StorageFaultPoint::Put, self.storage_selected)
        {
            return Err(error);
        }
        if record.key.namespace().as_str() == "agents_kit_codex_prompts_v1"
            && record.value["state"]["state"] == "terminal"
            && let WaiterFault::TerminalRecord { patch, captured } = &self.owner.fault
            && self.owner.armed.swap(false, Ordering::SeqCst)
        {
            *captured.lock().unwrap() = Some(record.value.as_ref().clone());
            let value = Arc::make_mut(&mut record.value);
            for (key, replacement) in patch.as_object().unwrap() {
                if key == "version" && replacement.is_null() {
                    value.as_object_mut().unwrap().remove(key);
                } else {
                    value[key] = replacement.clone();
                }
            }
            self.owner.attempts.fetch_add(1, Ordering::SeqCst);
        }
        if record.key.namespace().as_str() == "agents_kit_codex_prompts_v1"
            && record.value["waiter"] == "timed_out"
            && let WaiterFault::TimeoutIntent { failures } = &self.owner.fault
            && self.owner.armed.load(Ordering::SeqCst)
            && self.owner.attempts.fetch_add(1, Ordering::SeqCst) < *failures
        {
            return Err(StateStoreError::transaction_conflict(
                "put",
                "injected timeout intent conflict",
            ));
        }
        if let WaiterFault::HeldCommit { waiter, .. } = &self.owner.fault {
            self.held_waiter |= record.key.namespace().as_str() == "agents_kit_codex_prompts_v1"
                && record.value["waiter"].as_str() == Some(*waiter);
        }
        if record.key.namespace().as_str() == "agents_kit_codex_prompts_v1"
            && record.value["state"]["state"] == "prepared"
            && let WaiterFault::HeldCreation { entered, release } = &self.owner.fault
            && self.owner.armed.swap(false, Ordering::SeqCst)
        {
            self.inner.put(record).await?;
            entered.notify_one();
            release
                .acquire()
                .await
                .expect("release held caller transaction")
                .forget();
            return Ok(());
        }
        if record.key.namespace().as_str() == "agents_kit_codex_prompts_v1"
            && record.value["waiter"] == "lost"
            && matches!(&self.owner.fault, WaiterFault::Retry)
            && self.owner.armed.load(Ordering::SeqCst)
        {
            self.owner.attempts.fetch_add(1, Ordering::SeqCst);
            return Err(StateStoreError::transaction_conflict(
                "put",
                "injected terminal waiter conflict",
            ));
        }
        self.inner.put(record).await
    }

    async fn delete(&mut self, key: StateKey) -> Result<(), StateStoreError> {
        if let Some(error) = self
            .owner
            .storage_failure(StorageFaultPoint::Delete, self.storage_selected)
        {
            return Err(error);
        }
        self.held_clear |= key.namespace().as_str() == "agents_kit_codex_prompts_v1"
            && matches!(self.owner.fault, WaiterFault::HeldClear { .. })
            && self.owner.armed.load(Ordering::SeqCst);
        self.inner.delete(key).await
    }

    async fn commit(self) -> Result<(), StateStoreError> {
        if self.interaction_staged
            && self
                .owner
                .publication_failure(InteractionFaultPoint::HeldCommit)
                .is_some()
        {
            tokio::time::sleep(Duration::from_millis(3100)).await;
            return self.inner.commit().await;
        }
        if self.interaction_staged
            && let Some(error) = self
                .owner
                .publication_failure(InteractionFaultPoint::AmbiguousCommit)
        {
            self.inner.commit().await?;
            return Err(error);
        }
        if self.interaction_staged
            && let Some(error) = self
                .owner
                .publication_failure(InteractionFaultPoint::Commit)
        {
            self.inner.rollback().await?;
            return Err(error);
        }
        if self.held_clear
            && let WaiterFault::HeldClear {
                entered,
                release,
                observation_error,
            } = &self.owner.fault
            && self.owner.armed.swap(false, Ordering::SeqCst)
        {
            self.inner.commit().await?;
            self.owner.attempts.fetch_add(1, Ordering::SeqCst);
            entered.add_permits(1);
            release.acquire().await.unwrap().forget();
            return if *observation_error {
                Err(StateStoreError::unavailable(
                    "commit",
                    "owned clear observation failed after publication",
                ))
            } else {
                Ok(())
            };
        }

        if let WaiterFault::CreationFailure {
            point,
            source,
            native_starts,
            ..
        } = &self.owner.fault
            && *point == StorageFaultPoint::Commit
            && native_starts.load(Ordering::SeqCst) == 1
            && self.owner.armed.swap(false, Ordering::SeqCst)
        {
            self.owner.attempts.fetch_add(1, Ordering::SeqCst);
            self.inner.rollback().await?;
            return Err(source.error());
        }
        if let Some(position) = self.held_creation_observation
            && let WaiterFault::ThreadCreationObservation {
                case,
                reconciled,
                committed,
                conflicts,
                ..
            } = &self.owner.fault
        {
            let result = self.inner.commit().await;
            if result.is_ok() {
                committed.add_permits(1);
                if position == 1 && *case == CreationObservationCase::ForegroundWins {
                    reconciled.acquire().await.unwrap().forget();
                }
            }
            if matches!(&result, Err(StateStoreError::TransactionConflict { .. })) {
                conflicts.fetch_add(1, Ordering::SeqCst);
            }
            return result;
        }
        if self.held_notification
            && let WaiterFault::NotificationReceipt {
                observation,
                cleanup_failure: false,
                observe_next,
                entered,
                release,
                committed,
                ..
            } = &self.owner.fault
            && self.owner.armed.swap(false, Ordering::SeqCst)
        {
            self.inner.commit().await?;
            committed.fetch_add(1, Ordering::SeqCst);
            if *observation {
                observe_next.store(true, Ordering::SeqCst);
            } else {
                entered.add_permits(1);
                release.acquire().await.unwrap().forget();
            }
            return Ok(());
        }

        if let Some(error) = self
            .owner
            .storage_failure(StorageFaultPoint::Commit, self.storage_selected)
        {
            self.inner.rollback().await?;
            return Err(error);
        }
        if self.held_waiter
            && let WaiterFault::HeldCommit {
                entered,
                release,
                completed,
                ..
            } = &self.owner.fault
            && self.owner.armed.swap(false, Ordering::SeqCst)
        {
            self.owner.attempts.fetch_add(1, Ordering::SeqCst);
            entered.notify_one();
            release
                .acquire()
                .await
                .expect("release admitted waiter commit")
                .forget();
            self.inner.commit().await?;
            completed.fetch_add(1, Ordering::SeqCst);
            return Ok(());
        }
        self.inner.commit().await
    }

    async fn rollback(self) -> Result<(), StateStoreError> {
        self.inner.rollback().await?;
        if matches!(self.owner.fault, WaiterFault::RollbackFailure)
            && self.owner.armed.swap(false, Ordering::SeqCst)
        {
            self.owner.attempts.fetch_add(1, Ordering::SeqCst);
            return Err(StateStoreError::unavailable(
                "rollback",
                "native observation rollback failed",
            ));
        }

        if self.publication_fault
            && let WaiterFault::InteractionPublication {
                rollback_failure,
                rollbacks,
                ..
            } = &self.owner.fault
        {
            rollbacks.fetch_add(1, Ordering::SeqCst);
            if *rollback_failure {
                return Err(StateStoreError::unavailable(
                    "secret-rollback",
                    "secret-cleanup",
                ));
            }
        }
        if self.creation_load_failed
            && let WaiterFault::CreationFailure {
                cleanup_failure,
                rollbacks,
                ..
            } = &self.owner.fault
        {
            rollbacks.fetch_add(1, Ordering::SeqCst);
            if *cleanup_failure {
                return Err(StateStoreError::unavailable(
                    "rollback",
                    "injected creation rollback failure",
                ));
            }
        }
        if self.held_notification
            && let WaiterFault::NotificationReceipt {
                cleanup_failure: true,
                ..
            } = &self.owner.fault
            && self.owner.attempts.load(Ordering::SeqCst) == 1
        {
            return Err(StateStoreError::unavailable(
                "rollback",
                "injected receipt rollback unavailable",
            ));
        }
        Ok(())
    }
}

struct CodexFixture<S: StateStoreBackend = StateStore> {
    peer: CodexPeer,
    agent: Agent<S>,
    workspace: Workspace<S>,
    conversation: Conversation<S>,
    root: PathBuf,
}

impl CodexFixture {
    async fn build() -> Self {
        let peer = CodexPeer::start().await;
        Self::build_with_peer(peer).await
    }

    async fn build_with_peer(peer: CodexPeer) -> Self {
        let store = StateStore::connect(StateStoreConfig::Lance(LanceStateStoreConfig::memory()))
            .await
            .expect("fixture store");
        Self::build_with_store(peer, store).await
    }

    async fn assert_amendment_decision(decision: Value, approvable: bool) {
        let mut fixture = Self::build().await;
        let mut notifications = fixture
            .conversation
            .notification_stream()
            .expect("approval notifications");
        let mut stream = fixture
            .conversation
            .prompt_stream(PromptRequest::new("approve command").expect("prompt"))
            .await
            .expect("prompt admission");
        let turn = fixture.peer.turn().await;
        fixture
            .peer
            .request(
                19,
                "item/commandExecution/requestApproval",
                json!({
                    "threadId":"stream-thread", "turnId":turn, "itemId":"command",
                    "startedAtMs":1, "command":"printf approved",
                    "availableDecisions":["accept", decision, "cancel"]
                }),
            )
            .await;
        let observed =
            std::panic::AssertUnwindSafe(tokio::time::timeout(Duration::from_secs(3), async {
                tokio::select! {
                    response = fixture.peer.responses.recv() => (None, None, response),
                    notification = notifications.recv() => {
                        let notification = notification
                            .expect("approval delivery remains open")
                            .expect("approval notification");
                        let resolution = fixture.conversation.resolve_notification(
                            notification.id().clone(), NotificationResolution::Allow,
                        ).await;
                        let response = fixture.peer.responses.recv().await;
                        (Some(notification), Some(resolution), response)
                    }
                }
            }))
            .catch_unwind()
            .await;
        if matches!(&observed, Ok(Ok((Some(_), _, _)))) {
            fixture
                .peer
                .notify(
                    "serverRequest/resolved",
                    json!({"threadId":"stream-thread", "requestId":19}),
                )
                .await;
        }
        fixture.peer.complete(&turn, "approved terminal").await;
        let terminal = tokio::time::timeout(Duration::from_secs(3), stream.recv()).await;
        drop(notifications);
        fixture.shutdown().await;

        let (notification, resolution, response) = match observed {
            Ok(observed) => observed.expect("approval response bound"),
            Err(panic) => std::panic::resume_unwind(panic),
        };
        if approvable {
            assert_eq!(
                response,
                Some(json!({"id":19,"result":{"decision":"accept"}})),
                "a pinned optional amendment must not reject the approval request"
            );
            assert!(matches!(
                notification
                    .as_ref()
                    .map(|notification| notification.kind()),
                Some(ConversationNotificationKind::Interaction {
                    response_schema: None,
                    ..
                })
            ));
            assert!(resolution.is_some_and(|result| {
                result
                    .as_ref()
                    .map_or_else(|error| error.kind() == ErrorKind::Conflict, |()| true)
            }));
        } else {
            let response = response.expect("malformed approval receives a native error");
            assert_eq!(response["id"], 19);
            assert_eq!(response["error"]["code"], -32602);
            assert!(response.get("result").is_none());
            assert!(
                notification.is_none(),
                "malformed approval must not publish an interaction"
            );
            assert!(resolution.is_none());
        }
        assert!(matches!(
            terminal,
            Ok(Some(Ok(PromptEvent::Completed(response)))) if response.output() == "approved terminal"
        ));
    }
}

impl<S: StateStoreBackend> CodexFixture<S> {
    async fn build_with_store(peer: CodexPeer, store: S) -> Self {
        let config = AgentConfig::new(
            CodexConfig::tcp(peer.address, Duration::from_secs(3), Duration::from_secs(3))
                .expect("Codex config")
                .into(),
            Duration::from_secs(3),
            NonZeroUsize::new(1).expect("one prompt"),
        )
        .expect("Agent config");
        let agent = AgentBuilder::create(config, AgentStorage::new(store))
            .build()
            .await
            .expect("Codex fixture Agent");
        let root =
            std::env::temp_dir().join(format!("agents-kit-codex-stream-{}", uuid::Uuid::new_v4()));
        std::fs::create_dir(&root).expect("fixture directory");
        let root = root.canonicalize().expect("canonical fixture root");
        let context = WorkspaceContext::new(
            root.clone(),
            vec![WorkspaceRoot::new(root.clone(), WorkspaceRootAccess::ReadWrite).expect("root")],
            WorkspaceExecutionPolicy::new(
                WorkspaceSandboxMode::FullAccess,
                WorkspaceNetworkAccess::Enabled,
            ),
        )
        .expect("context");
        let workspace = agent
            .new_workspace(
                NewWorkspace::new("protocol-stream", context, WorkspaceDefaults::empty())
                    .expect("workspace request"),
            )
            .await
            .expect("workspace");
        let conversation = workspace
            .new_conversation(
                NewConversation::new(None, None, Vec::new()).expect("conversation request"),
            )
            .await
            .expect("conversation");
        Self {
            peer,
            agent,
            workspace,
            conversation,
            root,
        }
    }

    async fn settle(self) -> Result<(), agents_kit::KitError> {
        let conversation = self.conversation.close().await;
        let workspace = self.workspace.close().await;
        let agent = self.agent.shutdown().await;
        self.peer.shutdown().await;
        std::fs::remove_dir_all(self.root).expect("fixture directory cleanup");
        conversation.and(workspace).and(agent)
    }

    async fn shutdown(self) {
        self.settle().await.expect("fixture cleanup");
    }

    async fn revoke(self, baseline: usize) {
        drop(self.conversation);
        drop(self.workspace);
        drop(self.agent);
        let runtime = tokio::runtime::Handle::current();
        tokio::time::timeout(Duration::from_secs(3), async {
            while runtime.metrics().num_alive_tasks() > baseline {
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("revoked native runtime must retain no owned tasks");
        self.peer.shutdown().await;
        std::fs::remove_dir_all(self.root).expect("fixture directory cleanup");
    }

    async fn finish_next_prompt(&mut self) {
        let deadline = tokio::time::Instant::now() + Duration::from_secs(3);
        loop {
            let mut prompt = Box::pin(
                self.conversation
                    .prompt(PromptRequest::new("next prompt").expect("prompt")),
            );
            let turn = tokio::select! {
                turn = self.peer.turn() => Some(turn),
                result = &mut prompt => {
                    assert!(matches!(result, Err(error) if error.kind() == ErrorKind::Busy), "only definite preadmission Busy can be retried");
                    None
                }
                _ = tokio::time::sleep_until(deadline) => panic!("retained generation did not settle"),
            };
            if let Some(turn) = turn {
                assert_eq!(turn, "turn-2", "observation loss cannot replay native work");
                self.peer.complete(&turn, "next terminal").await;
                let response = tokio::time::timeout_at(deadline, &mut prompt)
                    .await
                    .expect("next prompt deadline")
                    .expect("next terminal");
                assert_eq!(response.output(), "next terminal");
                return;
            }
            tokio::task::yield_now().await;
        }
    }
}

#[tokio::test]
async fn codex_initialization_reports_current_sdk_version() {
    let fixture = CodexFixture::build().await;
    let initializations = fixture
        .peer
        .requests
        .lock()
        .expect("observed protocol requests")
        .iter()
        .filter(|request| request["method"] == "initialize")
        .map(|request| request["params"]["clientInfo"].clone())
        .collect::<Vec<_>>();
    fixture.shutdown().await;
    assert_eq!(initializations.len(), 1);
    assert_eq!(initializations[0]["name"], "agents-kit");
    assert_eq!(initializations[0]["version"], env!("CARGO_PKG_VERSION"));
}

#[tokio::test]
async fn codex_initialization_timeout_identifies_server_verification() {
    let peer = CodexPeer::start().await;
    peer.hold_initialization.store(true, Ordering::SeqCst);
    let config = AgentConfig::new(
        CodexConfig::tcp(
            peer.address,
            Duration::from_secs(2),
            Duration::from_millis(100),
        )
        .expect("native config")
        .into(),
        Duration::from_secs(2),
        NonZeroUsize::new(1).unwrap(),
    )
    .unwrap();
    let store = StateStore::connect(StateStoreConfig::Lance(LanceStateStoreConfig::memory()))
        .await
        .unwrap();
    let result = tokio::time::timeout(
        Duration::from_secs(5),
        AgentBuilder::create(config, AgentStorage::new(store)).build(),
    )
    .await;
    let initialized = peer.initializations.load(Ordering::SeqCst);
    let error = match result {
        Ok(Err(error)) => Some(error),
        Ok(Ok(agent)) => {
            let _ = agent.shutdown().await;
            None
        }
        Err(_) => None,
    };
    peer.shutdown().await;
    assert_eq!(
        initialized, 1,
        "the request reached server verification exactly once"
    );
    let error = error.expect("stalled initialization must fail within its deadline");
    assert_eq!(error.kind(), ErrorKind::Timeout);
    assert_eq!(error.context().operation, Operation::Build);
    assert_eq!(error.context().phase, ErrorPhase::ServerVerification);
}

#[tokio::test]
async fn codex_process_delivery_reconciles_ambiguous_approval_at_prompt_terminal() {
    let mut fixture = CodexFixture::build().await;
    let observed =
        std::panic::AssertUnwindSafe(tokio::time::timeout(Duration::from_secs(3), async {
            let mut receiver = fixture
                .conversation
                .notification_stream()
                .expect("process notification receiver");
            let mut stream = fixture
                .conversation
                .prompt_stream(PromptRequest::new("one native process").expect("prompt"))
                .await
                .expect("process prompt admission");
            let turn = fixture.peer.turn().await;
            fixture
                .peer
                .notify(
                    "item/started",
                    json!({
                        "threadId":"stream-thread", "turnId":turn, "startedAtMs":1,
                        "item":{"id":"command", "type":"commandExecution", "status":"inProgress",
                            "command":"printf process; exit 7", "cwd":fixture.root,
                            "commandActions":[], "aggregatedOutput":null, "exitCode":null}
                    }),
                )
                .await;
            let running = receiver
                .recv()
                .await
                .expect("running delivery")
                .expect("running item");
            assert!(matches!(
                running.kind(),
                ConversationNotificationKind::Process {
                    state: ProcessState::Running,
                    ..
                }
            ));
            drop(receiver);
            receiver = fixture
                .conversation
                .notification_stream()
                .expect("replay receiver");
            let replay = receiver
                .recv()
                .await
                .expect("running replay")
                .expect("replayed item");
            assert_eq!(replay.id(), running.id());
            assert_eq!(replay.kind(), running.kind());

            fixture
                .peer
                .request(
                    29,
                    "item/commandExecution/requestApproval",
                    json!({
                        "threadId":"stream-thread", "turnId":turn, "itemId":"command",
                        "startedAtMs":1, "command":"printf process; exit 7",
                        "availableDecisions":["accept", "cancel"]
                    }),
                )
                .await;
            let approval = receiver
                .recv()
                .await
                .expect("approval delivery")
                .expect("approval item");
            assert!(matches!(
                approval.kind(),
                ConversationNotificationKind::Interaction {
                    response_schema: None,
                    ..
                }
            ));
            assert!(
                matches!(
                    fixture
                        .conversation
                        .resolve_notification(approval.id().clone(), NotificationResolution::Allow,)
                        .await,
                    Err(error) if error.kind() == ErrorKind::Conflict
                ),
                "native enqueue cannot prove acceptance"
            );
            assert_eq!(
                fixture.peer.responses.recv().await,
                Some(json!({"id":29,"result":{"decision":"accept"}}))
            );
            fixture
                .peer
                .notify(
                    "serverRequest/resolved",
                    json!({
                        "threadId":"stream-thread", "requestId":29
                    }),
                )
                .await;
            fixture
                .peer
                .notify(
                    "item/completed",
                    json!({
                        "threadId":"stream-thread", "turnId":turn, "completedAtMs":2,
                        "item":{"id":"command", "type":"commandExecution", "status":"failed",
                            "command":"printf process; exit 7", "cwd":fixture.root,
                            "commandActions":[], "aggregatedOutput":"process", "exitCode":7}
                    }),
                )
                .await;
            assert!(
                matches!(receiver.recv().await, Some(Err(error)) if error.kind() == ErrorKind::Conflict),
                "ambiguous approval must block later process delivery"
            );
            assert!(
                receiver.recv().await.is_none(),
                "conflicted receiver must stay fused"
            );
            assert!(
                matches!(
                    fixture.conversation.notification_stream(),
                    Err(error) if error.kind() == ErrorKind::Conflict
                ),
                "receiver acquisition cannot bypass owning reconciliation"
            );
            assert!(
                matches!(
                    fixture
                        .conversation
                        .resolve_notification(approval.id().clone(), NotificationResolution::Allow,)
                        .await,
                    Err(error) if error.kind() == ErrorKind::Conflict
                ),
                "ambiguous response must never be resent"
            );

            fixture.peer.complete(&turn, "process_DONE").await;
            assert!(matches!(stream.recv().await,
                Some(Ok(PromptEvent::Completed(response))) if response.output() == "process_DONE"));
            assert!(stream.recv().await.is_none());
            assert!(
                receiver.recv().await.is_none(),
                "reconciliation does not revive the old receiver"
            );
            receiver = fixture
                .conversation
                .notification_stream()
                .expect("reconciled receiver");
            let exited = receiver
                .recv()
                .await
                .expect("retained exit delivery")
                .expect("retained exit item");
            assert_ne!(exited.id(), running.id());
            assert_ne!(exited.id(), approval.id());
            match (running.kind(), exited.kind()) {
                (
                    ConversationNotificationKind::Process {
                        label: running_label,
                        ..
                    },
                    ConversationNotificationKind::Process {
                        label,
                        state: ProcessState::Exited { exit_code },
                    },
                ) => {
                    assert_eq!(label, running_label);
                    assert_eq!(*exit_code, Some(7));
                }
                _ => panic!("retained process exit must follow the original running item"),
            }
            drop(receiver);
            receiver = fixture
                .conversation
                .notification_stream()
                .expect("exit replay receiver");
            let replay = receiver
                .recv()
                .await
                .expect("exit replay")
                .expect("replayed exit item");
            assert_eq!(replay.id(), exited.id());
            assert_eq!(replay.kind(), exited.kind());
            drop(receiver);
            drop(stream);
            fixture.finish_next_prompt().await;
        }))
        .catch_unwind()
        .await;

    // Preserve a failed assertion until every fixture owner has been joined.
    let CodexFixture {
        conversation,
        workspace,
        agent,
        mut peer,
        root,
    } = fixture;
    let conversation_closed = conversation.close().await;
    let workspace_closed = workspace.close().await;
    let agent_stopped = agent.shutdown().await;
    if let Some(stop) = peer.stop.take() {
        let _ = stop.send(());
    }
    let peer_joined = if let Some(mut task) = peer.task.take() {
        let joined = tokio::time::timeout(Duration::from_secs(3), &mut task).await;
        if joined.is_err() {
            task.abort();
            let _ = task.await;
        }
        Some(joined)
    } else {
        None
    };
    let extra_response = peer.responses.try_recv();
    drop(peer);
    let directory_removed = std::fs::remove_dir_all(root);
    match observed {
        Ok(result) => result.expect("process ambiguity proof must remain bounded"),
        Err(panic) => std::panic::resume_unwind(panic),
    }
    conversation_closed.expect("conversation cleanup");
    workspace_closed.expect("workspace cleanup");
    agent_stopped.expect("Agent cleanup");
    peer_joined
        .expect("owned peer task")
        .expect("peer join bound")
        .expect("peer task");
    directory_removed.expect("fixture directory cleanup");
    assert!(
        matches!(
            extra_response,
            Err(mpsc::error::TryRecvError::Empty | mpsc::error::TryRecvError::Disconnected)
        ),
        "approval continuation must have exactly one native response"
    );
}

// Pinned rust-v0.163.0: app-server-protocol/schema/typescript/v2/
// CommandExecutionApprovalDecision.ts keeps enum payload field names in snake_case.
#[tokio::test]
async fn codex_command_approval_available_decision_execpolicy_amendment() {
    CodexFixture::assert_amendment_decision(
        json!({
            "acceptWithExecpolicyAmendment": { "execpolicy_amendment": ["printf"] }
        }),
        true,
    )
    .await;
}

#[tokio::test]
async fn codex_command_approval_available_decision_network_policy_amendment() {
    CodexFixture::assert_amendment_decision(
        json!({
            "applyNetworkPolicyAmendment": {
                "network_policy_amendment": { "host":"example.com", "action":"allow" }
            }
        }),
        true,
    )
    .await;
}

#[tokio::test]
async fn codex_command_approval_available_decision_rejects_malformed_amendments() {
    let mut failures = Vec::new();
    for (case, decision) in [
        (
            "execpolicy/missing",
            json!({"acceptWithExecpolicyAmendment": {}}),
        ),
        (
            "execpolicy/wrong-type",
            json!({"acceptWithExecpolicyAmendment": {"execpolicy_amendment": "printf"}}),
        ),
        (
            "execpolicy/wrong-spelling",
            json!({"acceptWithExecpolicyAmendment": {"execpolicyAmendment": ["printf"]}}),
        ),
        (
            "network/missing",
            json!({"applyNetworkPolicyAmendment": {}}),
        ),
        (
            "network/wrong-type",
            json!({"applyNetworkPolicyAmendment": {"network_policy_amendment": "example.com"}}),
        ),
        (
            "network/wrong-spelling",
            json!({"applyNetworkPolicyAmendment": {
                "networkPolicyAmendment": {"host":"example.com", "action":"allow"}
            }}),
        ),
    ] {
        eprintln!("checking malformed amendment {case}: {decision}");
        // The fixture joins its owned Agent and peer before its assertions.
        // Exercise every malformed case even when an earlier one is accepted.
        if std::panic::AssertUnwindSafe(CodexFixture::assert_amendment_decision(
            decision.clone(),
            false,
        ))
        .catch_unwind()
        .await
        .is_err()
        {
            failures.push((case, decision));
        }
    }
    assert!(
        failures.is_empty(),
        "malformed amendment cases failed: {failures:?}"
    );
}

#[tokio::test]
async fn codex_file_read_rejection_never_exposes_native_error_prose() {
    let fixture = CodexFixture::build().await;
    fixture.peer.reject(
        "fs/readFile",
        -32603,
        "secret-token native-private-path provider-private-id",
    );
    let result = tokio::time::timeout(
        Duration::from_secs(3),
        fixture.conversation.read_file(PathBuf::from("answer.txt")),
    )
    .await;
    fixture.shutdown().await;
    let error = result
        .expect("read-file deadline")
        .expect_err("native rejection");
    assert_eq!(error.kind(), ErrorKind::Integration);
    assert_eq!(error.detail(), Some(&ErrorDetail::RemoteInternal));
    assert_eq!(error.context().operation, Operation::ReadFile);
    assert_eq!(error.context().phase, ErrorPhase::ResponseRead);
    for text in [
        error.message().to_owned(),
        error.to_string(),
        format!("{error:?}"),
    ] {
        assert!(!text.contains("secret-token"));
        assert!(!text.contains("native-private-path"));
        assert!(!text.contains("provider-private-id"));
    }
}

#[tokio::test]
async fn codex_typed_terminal_failures_survive_unary_stream_and_durable_delivery() {
    let cases = [
        (json!("rateLimitExceeded"), ErrorDetail::RateLimited, None),
        (
            json!("flexUnavailable"),
            ErrorDetail::ServiceUnavailable,
            None,
        ),
        (
            json!("misalignmentPolicyViolation"),
            ErrorDetail::PolicyRejected,
            None,
        ),
        (json!("tooManyDenials"), ErrorDetail::PolicyRejected, None),
        (
            json!("future-private-error"),
            ErrorDetail::RemoteRejected,
            None,
        ),
        (
            json!({"future-private-error":{"secret-token":true}}),
            ErrorDetail::RemoteRejected,
            None,
        ),
        (
            json!("contextWindowExceeded"),
            ErrorDetail::ContextLimit,
            None,
        ),
        (
            json!("sessionBudgetExceeded"),
            ErrorDetail::SessionLimit,
            None,
        ),
        (
            json!("usageLimitExceeded"),
            ErrorDetail::ResourceExhausted,
            None,
        ),
        (
            json!("serverOverloaded"),
            ErrorDetail::ServiceUnavailable,
            None,
        ),
        (json!("cyberPolicy"), ErrorDetail::PolicyRejected, None),
        (
            json!({"httpConnectionFailed":{"httpStatusCode":503}}),
            ErrorDetail::TransportFailure,
            Some(503),
        ),
        (
            json!({"responseStreamConnectionFailed":{"httpStatusCode":502}}),
            ErrorDetail::TransportFailure,
            Some(502),
        ),
        (
            json!("internalServerError"),
            ErrorDetail::RemoteInternal,
            None,
        ),
        (
            json!("unauthorized"),
            ErrorDetail::AuthenticationRejected,
            None,
        ),
        (json!("badRequest"), ErrorDetail::InvalidRequest, None),
        (
            json!("threadRollbackFailed"),
            ErrorDetail::RemoteRejected,
            None,
        ),
        (json!("sandboxError"), ErrorDetail::RemoteRejected, None),
        (
            json!({"responseStreamDisconnected":{"httpStatusCode":500}}),
            ErrorDetail::TransportFailure,
            Some(500),
        ),
        (
            json!({"responseTooManyFailedAttempts":{"httpStatusCode":429}}),
            ErrorDetail::RemoteRejected,
            Some(429),
        ),
        (
            json!({"activeTurnNotSteerable":{"turnKind":"review"}}),
            ErrorDetail::PreconditionFailed,
            None,
        ),
        (json!("other"), ErrorDetail::RemoteRejected, None),
        (Value::Null, ErrorDetail::RemoteRejected, None),
    ];
    for (info, detail, status) in cases {
        for streaming in [false, true] {
            let mut fixture = CodexFixture::build().await;
            let observed = std::panic::AssertUnwindSafe(async {
                if streaming {
                    let mut stream = fixture.conversation.prompt_stream(PromptRequest::new("fail").unwrap()).await.unwrap();
                    let turn = fixture.peer.turn().await;
                    fixture.peer.notify("item/agentMessage/delta", json!({"threadId":"stream-thread","turnId":turn,"itemId":"answer","delta":"partial"})).await;
                    assert!(matches!(tokio::time::timeout(Duration::from_secs(3), stream.recv()).await.unwrap(), Some(Ok(PromptEvent::OutputDelta { .. }))));
                    fixture.peer.fail(&turn, info.clone()).await;
                    let result = tokio::time::timeout(Duration::from_secs(3), stream.recv()).await.unwrap();
                    let error = result.expect("terminal event").expect_err("failed turn cannot complete");
                    assert!(tokio::time::timeout(Duration::from_secs(3), stream.recv()).await.unwrap().is_none());
                    error
                } else {
                    let mut prompt = Box::pin(fixture.conversation.prompt(PromptRequest::new("fail").unwrap()));
                    let turn = tokio::select! {
                        turn = fixture.peer.turn() => turn,
                        result = &mut prompt => panic!("early completion: {result:?}"),
                    };
                    fixture.peer.fail(&turn, info.clone()).await;
                    tokio::time::timeout(Duration::from_secs(3), prompt).await.unwrap().expect_err("failed turn cannot complete")
                }
            }).catch_unwind().await;
            let cleanup = fixture.settle().await;
            let error = match observed {
                Ok(error) => error,
                Err(panic) => std::panic::resume_unwind(panic),
            };
            assert_eq!(error.kind(), ErrorKind::Integration, "{info}");
            assert_eq!(error.context().operation, Operation::Prompt);
            assert_eq!(error.context().phase, ErrorPhase::ModelGeneration);
            assert_eq!(error.detail(), Some(&detail), "{info}");
            assert_eq!(error.http_status(), status, "{info}");
            cleanup.expect("fixture cleanup");
            assert!(!format!("{error} {error:?} {}", error.message()).contains("secret-token"));
        }
    }
}

#[tokio::test]
async fn codex_recovered_terminal_failure_retains_typed_history_error() {
    let peer = CodexPeer::start_with(FirstStart::RecoveredTurn { status: "failed".to_owned(), items: vec![], error: json!({
        "message":"secret-token", "codexErrorInfo":{"httpConnectionFailed":{"httpStatusCode":503}},
        "additionalDetails":"native-private-path"
    }) })
    .await;
    let fixture = CodexFixture::build_with_peer(peer).await;
    let result = tokio::time::timeout(
        Duration::from_secs(3),
        fixture
            .conversation
            .prompt(PromptRequest::new("recover").unwrap()),
    )
    .await;
    fixture.shutdown().await;
    let error = result
        .expect("recovery bound")
        .expect_err("authoritative failed history");
    assert_eq!(error.kind(), ErrorKind::Integration);
    assert_eq!(error.detail(), Some(&ErrorDetail::TransportFailure));
    assert_eq!(error.http_status(), Some(503));
    assert_eq!(error.context().operation, Operation::Prompt);
    assert_eq!(error.context().phase, ErrorPhase::ModelGeneration);
    assert!(!format!("{error} {error:?}").contains("secret-token"));
}

#[tokio::test]
async fn codex_retry_advisory_is_not_a_terminal_or_a_replay_request() {
    let mut fixture = CodexFixture::build().await;
    let mut stream = fixture
        .conversation
        .prompt_stream(PromptRequest::new("retry advisory").unwrap())
        .await
        .unwrap();
    let turn = fixture.peer.turn().await;
    fixture.peer.notify("error", json!({"threadId":"stream-thread","turnId":turn,"willRetry":true,
        "error":{"message":"secret-token","codexErrorInfo":"serverOverloaded","additionalDetails":null}})).await;
    let premature = tokio::time::timeout(Duration::from_millis(30), stream.recv()).await;
    fixture.peer.complete(&turn, "complete once").await;
    let terminal = tokio::time::timeout(Duration::from_secs(3), stream.recv()).await;
    let eof = tokio::time::timeout(Duration::from_secs(3), stream.recv()).await;
    let replay = fixture.peer.turns.try_recv();
    fixture.shutdown().await;
    assert!(premature.is_err());
    assert!(
        matches!(terminal.unwrap(), Some(Ok(PromptEvent::Completed(response))) if response.output() == "complete once")
    );
    assert!(eof.unwrap().is_none());
    assert!(matches!(replay, Err(mpsc::error::TryRecvError::Empty)));
}

#[tokio::test]
async fn codex_abort_storage_load_failure_preserves_detector_phase() {
    StorageFaultOperation::Abort
        .assert_fault(StorageFaultPoint::Load, StorageFaultSource::Unavailable)
        .await;
}

#[tokio::test]
async fn codex_prompt_storage_failures_preserve_detector_phase() {
    for point in [
        StorageFaultPoint::Begin,
        StorageFaultPoint::Load,
        StorageFaultPoint::Put,
        StorageFaultPoint::Commit,
    ] {
        StorageFaultOperation::Prompt
            .assert_fault(point, StorageFaultSource::Unavailable)
            .await;
    }
    StorageFaultOperation::PromptStream
        .assert_fault(StorageFaultPoint::Load, StorageFaultSource::Unavailable)
        .await;
}

#[tokio::test]
async fn codex_abort_storage_failures_preserve_detector_phase() {
    for point in [
        StorageFaultPoint::Begin,
        StorageFaultPoint::Put,
        StorageFaultPoint::Commit,
    ] {
        StorageFaultOperation::Abort
            .assert_fault(point, StorageFaultSource::Unavailable)
            .await;
    }
}

#[tokio::test]
async fn codex_close_storage_failures_preserve_detector_phase() {
    for point in [
        StorageFaultPoint::Begin,
        StorageFaultPoint::Load,
        StorageFaultPoint::Put,
        StorageFaultPoint::Delete,
        StorageFaultPoint::Commit,
    ] {
        StorageFaultOperation::CloseConversation
            .assert_fault(point, StorageFaultSource::Unavailable)
            .await;
    }
}

#[tokio::test]
async fn codex_close_storage_deadlines_preserve_source_and_detector_phase() {
    for point in [StorageFaultPoint::Begin, StorageFaultPoint::Commit] {
        StorageFaultOperation::CloseConversation
            .assert_fault(point, StorageFaultSource::TimedOut)
            .await;
    }
}

#[tokio::test]
async fn codex_workspace_storage_failures_preserve_detector_phase() {
    for point in [
        StorageFaultPoint::Begin,
        StorageFaultPoint::Load,
        StorageFaultPoint::Put,
        StorageFaultPoint::Commit,
    ] {
        StorageFaultOperation::UpdateWorkspace
            .assert_fault(point, StorageFaultSource::Unavailable)
            .await;
    }
    for point in [
        StorageFaultPoint::Begin,
        StorageFaultPoint::Load,
        StorageFaultPoint::Put,
        StorageFaultPoint::Delete,
        StorageFaultPoint::Commit,
    ] {
        StorageFaultOperation::DeleteWorkspace
            .assert_fault(point, StorageFaultSource::Unavailable)
            .await;
    }
}

#[tokio::test]
async fn codex_storage_phase_mapping_preserves_conflict_ownership() {
    for operation in [
        StorageFaultOperation::Prompt,
        StorageFaultOperation::PromptStream,
        StorageFaultOperation::Abort,
        StorageFaultOperation::CloseConversation,
        StorageFaultOperation::UpdateWorkspace,
        StorageFaultOperation::DeleteWorkspace,
    ] {
        operation
            .assert_fault(StorageFaultPoint::Commit, StorageFaultSource::Conflict)
            .await;
    }
}

#[tokio::test]
async fn codex_storage_phase_mapping_preserves_committed_workspace_publication() {
    let CodexFixture {
        peer,
        agent,
        workspace,
        conversation,
        root,
    } = CodexFixture::build().await;
    let observed = std::panic::AssertUnwindSafe(async {
        let before = workspace.info().await.unwrap();
        let replacement = agent
            .update_workspace(
                UpdateWorkspaceRequest::new(
                    before.id().clone(),
                    before.revision(),
                    "committed replacement",
                    before.context().clone(),
                    before.defaults().clone(),
                )
                .unwrap(),
            )
            .await
            .expect("committed workspace update");
        assert_eq!(replacement.revision(), before.revision() + 1);
        assert_eq!(replacement.name(), "committed replacement");
        assert_eq!(
            workspace.info().await.expect_err("stale workspace").kind(),
            ErrorKind::Conflict
        );
        peer.reject("thread/delete", -32603, "secret native cleanup failure");
        agent
            .delete_workspace(
                DeleteWorkspaceRequest::new(replacement.id().clone(), replacement.revision())
                    .unwrap(),
            )
            .await
            .expect("committed deletion remains successful after native cleanup failure");
        assert_eq!(
            agent
                .workspace_info(before.id().clone())
                .await
                .expect_err("deleted workspace")
                .kind(),
            ErrorKind::NotFound
        );
        assert!(agent.list_workspaces().await.unwrap().is_empty());
    })
    .catch_unwind()
    .await;
    drop(conversation);
    drop(workspace);
    let stopped = tokio::time::timeout(Duration::from_secs(4), agent.shutdown()).await;
    peer.shutdown().await;
    let removed = std::fs::remove_dir_all(root);
    if let Err(panic) = observed {
        std::panic::resume_unwind(panic);
    }
    stopped
        .expect("Agent shutdown bound")
        .expect("Agent shutdown");
    removed.expect("fixture directory cleanup");
}

#[tokio::test]
async fn codex_persisted_failure_snapshot_restores_safe_diagnostics_and_rejects_old_versions() {
    let leaf = json!({"kind":"integration","context":{"operation":"prompt","phase":"cleanup"},
        "detail":{"kind":"deadline_elapsed","deadline":"lifecycle","timeout":{"seconds":1,"nanoseconds":25}},
        "http_status":null,"cause":null,"supplementary":[],"truncated":false});
    let failure = json!({"kind":"integration","context":{"operation":"prompt","phase":"model_generation"},
        "detail":{"kind":"transport_failure"},"http_status":503,"cause":leaf,"supplementary":[leaf],"truncated":true});
    let terminal_state = json!({"state":"terminal","turn_id":"turn-1","outcome":{"outcome":"failure","error":failure}});
    for version in [json!(4), json!(3), json!(5), Value::Null] {
        let raw = StateStore::connect(StateStoreConfig::Lance(LanceStateStoreConfig::memory()))
            .await
            .unwrap();
        let captured = Arc::new(std::sync::Mutex::new(None));
        let store = WaiterFaultStore {
            inner: raw.clone(),
            fault: WaiterFault::TerminalRecord {
                patch: json!({"version":version,"state":terminal_state}),
                captured: Arc::clone(&captured),
            },
            armed: Arc::new(AtomicBool::new(false)),
            attempts: Arc::new(AtomicUsize::new(0)),
        };
        let peer = CodexPeer::start().await;
        let baseline = tokio::runtime::Handle::current()
            .metrics()
            .num_alive_tasks();
        let mut fixture = CodexFixture::build_with_store(peer, store.clone()).await;
        let observed = std::panic::AssertUnwindSafe(async {
            let mut stream = fixture
                .conversation
                .prompt_stream(PromptRequest::new("recorded error").unwrap())
                .await
                .unwrap();
            let turn = fixture.peer.turn().await;
            store.armed.store(true, Ordering::SeqCst);
            fixture
                .peer
                .fail(
                    &turn,
                    json!({"httpConnectionFailed":{"httpStatusCode":503}}),
                )
                .await;
            let terminal = tokio::time::timeout(Duration::from_secs(5), stream.recv()).await;
            let eof = tokio::time::timeout(Duration::from_secs(3), stream.recv()).await;
            (terminal, eof)
        })
        .catch_unwind()
        .await;
        store.armed.store(false, Ordering::SeqCst);
        let prompt_key = StateKey::new(
            "agents_kit_codex_prompts_v1",
            fixture.conversation.id().as_str(),
        )
        .unwrap();
        fixture.revoke(baseline).await;
        let retained = tokio::time::timeout(Duration::from_secs(3), raw.load(prompt_key))
            .await
            .expect("record observation bound")
            .expect("record observation");
        let (terminal, eof) = match observed {
            Ok(value) => value,
            Err(panic) => std::panic::resume_unwind(panic),
        };
        let original = captured
            .lock()
            .unwrap()
            .clone()
            .expect("terminal snapshot captured");
        assert_eq!(original["version"], 4);
        assert!(!original.to_string().contains("secret-token"));
        let error = terminal
            .expect("terminal deadline")
            .expect("terminal event")
            .expect_err("failed record");
        assert!(eof.expect("EOF deadline").is_none());
        if version == 4 {
            assert_eq!(error.kind(), ErrorKind::Integration);
            assert_eq!(error.detail(), Some(&ErrorDetail::TransportFailure));
            assert_eq!(error.http_status(), Some(503));
            assert_eq!(error.context().phase, ErrorPhase::ModelGeneration);
            assert!(error.diagnostics_truncated());
            assert_eq!(error.cause().unwrap().context().phase, ErrorPhase::Cleanup);
            assert_eq!(
                error.cause().unwrap().detail(),
                Some(&ErrorDetail::DeadlineElapsed {
                    kind: agents_kit::error::DeadlineKind::Lifecycle,
                    timeout: Some(Duration::new(1, 25))
                })
            );
            assert_eq!(error.supplementary().len(), 1);
            assert_eq!(
                error.supplementary()[0].context().phase,
                ErrorPhase::Cleanup
            );
        } else {
            assert_eq!(error.kind(), ErrorKind::InvalidState);
            assert_eq!(error.context().phase, ErrorPhase::StateRead);
            let retained = retained.expect("unsupported record must not be deleted or repaired");
            assert_eq!(retained.record.value["state"], terminal_state);
            if version.is_null() {
                assert!(retained.record.value.get("version").is_none());
            } else {
                assert_eq!(retained.record.value["version"], version);
            }
        }
    }
}

#[tokio::test]
async fn codex_failed_turn_keeps_primary_diagnostics_when_waiter_cleanup_fails() {
    for interrupted in [false, true] {
        let raw = StateStore::connect(StateStoreConfig::Lance(LanceStateStoreConfig::memory()))
            .await
            .unwrap();
        let store = WaiterFaultStore {
            inner: raw,
            fault: WaiterFault::Retry,
            armed: Arc::new(AtomicBool::new(false)),
            attempts: Arc::new(AtomicUsize::new(0)),
        };
        let peer = CodexPeer::start().await;
        let baseline = tokio::runtime::Handle::current()
            .metrics()
            .num_alive_tasks();
        let mut fixture = CodexFixture::build_with_store(peer, store.clone()).await;
        let observed = std::panic::AssertUnwindSafe(async {
        let mut stream = fixture
            .conversation
            .prompt_stream(PromptRequest::new("failed cleanup").unwrap())
            .await
            .unwrap();
        let turn = fixture.peer.turn().await;
        store.armed.store(true, Ordering::SeqCst);
        fixture.peer.notify("turn/completed", json!({"threadId":"stream-thread", "turn":{
            "id":turn,"status":if interrupted { "interrupted" } else { "failed" },"items":[],
            "error":{"message":"secret-token","codexErrorInfo":{"httpConnectionFailed":{"httpStatusCode":503}}}
        }})).await;
        let terminal = tokio::time::timeout(Duration::from_secs(5), stream.recv()).await;
        let eof = tokio::time::timeout(Duration::from_secs(3), stream.recv()).await;
        (terminal, eof)
    })
    .catch_unwind()
    .await;
        store.armed.store(false, Ordering::SeqCst);
        fixture.revoke(baseline).await;
        let (terminal, eof) = match observed {
            Ok(value) => value,
            Err(panic) => std::panic::resume_unwind(panic),
        };
        let error = terminal
            .expect("terminal deadline")
            .expect("terminal event")
            .expect_err("native failure");
        assert!(eof.expect("EOF deadline").is_none());
        assert!(store.attempts.load(Ordering::SeqCst) > 0);
        let primary = if interrupted {
            assert_eq!(error.kind(), ErrorKind::Cancelled);
            assert_eq!(error.context().phase, ErrorPhase::Cancellation);
            error
                .cause()
                .expect("cleanup must preserve interruption cause")
        } else {
            &error
        };
        assert_eq!(primary.kind(), ErrorKind::Integration);
        assert_eq!(primary.detail(), Some(&ErrorDetail::TransportFailure));
        assert_eq!(primary.http_status(), Some(503));
        assert_eq!(primary.context().phase, ErrorPhase::ModelGeneration);
        assert!(!format!("{error:?}").contains("secret-token"));
        assert_eq!(error.supplementary().len(), 1);
        assert_eq!(error.supplementary()[0].kind(), ErrorKind::Timeout);
        assert_eq!(
            error.supplementary()[0].context().phase,
            ErrorPhase::Cleanup
        );
    }
}

#[tokio::test]
async fn codex_protocol_fixture_preserves_ordinary_terminal_prompt() {
    let mut fixture = CodexFixture::build().await;
    let mut prompt = Box::pin(
        fixture
            .conversation
            .prompt(PromptRequest::new("ordinary").expect("prompt")),
    );
    let turn = tokio::select! {
        turn = fixture.peer.turn() => turn,
        result = &mut prompt => panic!("prompt ended before peer acceptance: {result:?}"),
    };
    fixture.peer.complete(&turn, "ordinary terminal").await;
    let response = tokio::time::timeout(Duration::from_secs(3), &mut prompt)
        .await
        .expect("terminal bound")
        .expect("ordinary response");
    assert_eq!(response.output(), "ordinary terminal");
    drop(prompt);
    fixture.shutdown().await;
}

#[tokio::test]
async fn codex_prompt_stream_preserves_native_deltas_and_authoritative_terminal() {
    CodexFixture::build().await.stream_case().await;
}

#[tokio::test]
async fn lance_state_memory_codex_stream_preserves_deltas_and_terminal() {
    let store = StateStore::connect(StateStoreConfig::Lance(LanceStateStoreConfig::memory()))
        .await
        .expect("Lance memory store");
    CodexFixture::build_with_store(CodexPeer::start().await, store)
        .await
        .stream_case()
        .await;
}

#[tokio::test]
async fn lance_state_directory_codex_stream_preserves_deltas_and_terminal() {
    let directory = LanceStateDirectory::new();
    let store = StateStore::connect(directory.config())
        .await
        .expect("Lance directory store");
    CodexFixture::build_with_store(CodexPeer::start().await, store)
        .await
        .stream_case()
        .await;
}

impl CodexFixture {
    async fn stream_case(self) {
        let mut fixture = self;
        let schema = StructuredOutputRequest::new(json!({"type":"object","properties":{"answer":{"type":"string"}},"required":["answer"],"additionalProperties":false})).expect("schema");
        let mut stream = fixture
            .conversation
            .prompt_stream(
                PromptRequest::new("stream")
                    .expect("prompt")
                    .with_structured_output(schema),
            )
            .await
            .expect("native streaming supported");
        let turn = fixture.peer.turn().await;
        fixture.peer.notify("item/reasoning/textDelta", json!({"threadId":"stream-thread","turnId":turn,"itemId":"reasoning","delta":"private reasoning"})).await;
        let text = "🦀".repeat(5_000);
        fixture
            .peer
            .notify(
                "item/agentMessage/delta",
                json!({"threadId":"stream-thread","turnId":turn,"itemId":"answer","delta":text}),
            )
            .await;
        let mut observed = String::new();
        while observed.len() < text.len() {
            let Some(Ok(PromptEvent::OutputDelta { text: fragment })) =
                tokio::time::timeout(Duration::from_secs(3), stream.recv())
                    .await
                    .expect("real delta before completion")
            else {
                panic!("expected real delta")
            };
            assert!(fragment.len() <= 16 * 1024);
            observed.push_str(&fragment);
        }
        assert_eq!(observed, text);
        assert!(
            tokio::time::timeout(Duration::from_millis(25), stream.recv())
                .await
                .is_err()
        );
        fixture
            .peer
            .complete(&turn, "{\"answer\":\"authoritative\"}")
            .await;
        let Some(Ok(PromptEvent::Completed(response))) =
            tokio::time::timeout(Duration::from_secs(3), stream.recv())
                .await
                .expect("terminal bound")
        else {
            panic!("authoritative terminal")
        };
        assert_eq!(response.output(), "{\"answer\":\"authoritative\"}");
        assert_eq!(
            response.structured_output(),
            Some(&json!({"answer":"authoritative"}))
        );
        assert!(stream.recv().await.is_none());
        fixture.shutdown().await;
    }
}

#[tokio::test]
async fn codex_prompt_stream_drop_and_overflow_preserve_accepted_work() {
    for drop_observer in [true, false] {
        let mut fixture = CodexFixture::build().await;
        let mut stream = Some(
            fixture
                .conversation
                .prompt_stream(PromptRequest::new("accepted work").expect("prompt"))
                .await
                .expect("stream admission"),
        );
        let turn = fixture.peer.turn().await;
        if drop_observer {
            drop(stream.take());
        }
        for index in 0..128 {
            fixture.peer.notify("item/agentMessage/delta", json!({"threadId":"stream-thread","turnId":turn,"itemId":"answer","delta":format!("part {index}")})).await;
        }
        assert!(matches!(
            fixture
                .conversation
                .prompt(PromptRequest::new("cannot steal generation").expect("prompt"))
                .await,
            Err(error) if error.kind() == ErrorKind::Busy
        ));
        assert_eq!(fixture.peer.interrupts.load(Ordering::SeqCst), 0);
        fixture.peer.complete(&turn, "accepted terminal").await;
        fixture.finish_next_prompt().await;
        if let Some(mut stream) = stream {
            let mut fragments = 0;
            loop {
                match tokio::time::timeout(Duration::from_secs(3), stream.recv())
                    .await
                    .expect("bounded observation")
                {
                    Some(Ok(PromptEvent::OutputDelta { .. })) => fragments += 1,
                    Some(Err(error)) if error.kind() == ErrorKind::Integration => break,
                    outcome => panic!("overflow cannot claim completion: {outcome:?}"),
                }
            }
            assert!(fragments <= 64);
            assert!(stream.recv().await.is_none());
        }
        assert_eq!(fixture.peer.interrupts.load(Ordering::SeqCst), 0);
        fixture.shutdown().await;
    }
}

#[tokio::test]
async fn codex_prompt_stream_abort_settles_exact_generation_before_new_output() {
    let mut fixture = CodexFixture::build().await;
    let mut stream = fixture
        .conversation
        .prompt_stream(PromptRequest::new("abort").expect("prompt"))
        .await
        .expect("stream admission");
    let old_turn = fixture.peer.turn().await;
    fixture.peer.notify("item/agentMessage/delta", json!({"threadId":"stream-thread","turnId":old_turn,"itemId":"answer","delta":"old partial"})).await;
    assert!(
        matches!(tokio::time::timeout(Duration::from_secs(3), stream.recv()).await.expect("partial deadline"),
        Some(Ok(PromptEvent::OutputDelta { text })) if text == "old partial")
    );
    fixture.conversation.abort().await.expect("explicit abort");
    assert_eq!(fixture.peer.interrupts.load(Ordering::SeqCst), 1);
    assert!(matches!(
        tokio::time::timeout(Duration::from_secs(3), stream.recv())
            .await
            .expect("abort terminal deadline"),
        Some(Err(error)) if error.kind() == ErrorKind::Cancelled
    ));
    assert!(stream.recv().await.is_none());
    let mut next = fixture
        .conversation
        .prompt_stream(PromptRequest::new("new generation").expect("prompt"))
        .await
        .expect("next stream");
    let new_turn = fixture.peer.turn().await;
    assert_eq!(new_turn, "turn-2");
    fixture.peer.notify("item/agentMessage/delta", json!({"threadId":"stream-thread","turnId":old_turn,"itemId":"old-item","delta":"stale output"})).await;
    fixture.peer.notify("item/agentMessage/delta", json!({"threadId":"stream-thread","turnId":new_turn,"itemId":"new-item","delta":"new output"})).await;
    assert!(
        matches!(tokio::time::timeout(Duration::from_secs(3), next.recv()).await.expect("new delta deadline"),
        Some(Ok(PromptEvent::OutputDelta { text })) if text == "new output")
    );
    fixture.peer.complete(&new_turn, "new terminal").await;
    assert!(
        matches!(tokio::time::timeout(Duration::from_secs(3), next.recv()).await.expect("new terminal deadline"),
        Some(Ok(PromptEvent::Completed(response))) if response.output() == "new terminal")
    );
    assert!(next.recv().await.is_none());
    assert_eq!(fixture.peer.interrupts.load(Ordering::SeqCst), 1);
    fixture.shutdown().await;
}

#[tokio::test]
async fn codex_prompt_stream_delayed_abort_terminal_preserves_settled_generation() {
    let peer = CodexPeer::start_with(FirstStart::DeferredInterruptTerminal).await;
    let mut fixture = CodexFixture::build_with_peer(peer).await;
    let observed = NativeCleanup::observe(
        tokio::time::Instant::now() + Duration::from_secs(10),
        async {
            let mut stream = fixture
                .conversation
                .prompt_stream(PromptRequest::new("reconcile interrupted turn").expect("prompt"))
                .await
                .expect("stream admission");
            let old_turn = fixture.peer.turn().await;
            fixture
                .peer
                .notify(
                    "item/agentMessage/delta",
                    json!({
                        "threadId":"stream-thread", "turnId":old_turn,
                        "itemId":"answer", "delta":"accepted partial"
                    }),
                )
                .await;
            assert!(matches!(stream.recv().await,
                Some(Ok(PromptEvent::OutputDelta { text })) if text == "accepted partial"));

            // The peer acknowledges interruption and exposes its exact terminal
            // history, but sends no terminal event until the public owner settles.
            fixture
                .conversation
                .abort()
                .await
                .expect("receipt-reconciled abort");
            assert_eq!(fixture.peer.interrupts.load(Ordering::SeqCst), 1);
            assert!(matches!(stream.recv().await,
                Some(Err(error)) if error.kind() == ErrorKind::Cancelled));
            assert!(stream.recv().await.is_none());

            fixture
                .peer
                .notify(
                    "turn/completed",
                    json!({
                        "threadId":"stream-thread", "turn":{
                            "id":old_turn, "status":"interrupted", "items":[], "error":null
                        }
                    }),
                )
                .await;
            // A request queued behind the event proves the same event owner
            // processed it before the following prompt. No sleep is an oracle.
            fixture
                .peer
                .request(71, "currentTime/read", json!({"threadId":"stream-thread"}))
                .await;
            let response =
                tokio::time::timeout(Duration::from_secs(3), fixture.peer.responses.recv())
                    .await
                    .expect("delayed terminal must leave the native event owner responsive")
                    .expect("native response owner remains open");
            assert_eq!(response["id"], 71);
            assert!(response["result"]["currentTimeAt"].is_i64());
            assert!(response.get("error").is_none());
            fixture.finish_next_prompt().await;
            assert_eq!(fixture.peer.interrupts.load(Ordering::SeqCst), 1);
            assert_eq!(fixture.peer.thread_starts.load(Ordering::SeqCst), 1);
        },
    )
    .await;
    let mut cleanup = NativeCleanup::new(Duration::from_secs(3));
    cleanup.settle(fixture.conversation.close()).await;
    cleanup.settle(fixture.workspace.close()).await;
    cleanup.settle(fixture.agent.shutdown()).await;
    // Complete the peer's own bounded stop/abort/join before recording its
    // result. An outer observation timeout must not drop its joining owner.
    let peer_cleanup = std::panic::AssertUnwindSafe(fixture.peer.shutdown())
        .catch_unwind()
        .await;
    cleanup
        .settle(async {
            if let Err(panic) = peer_cleanup {
                std::panic::resume_unwind(panic);
            }
            Ok::<(), std::io::Error>(())
        })
        .await;
    cleanup
        .settle(async { std::fs::remove_dir_all(fixture.root) })
        .await;
    cleanup.finish(observed);
}

#[tokio::test]
async fn codex_prompt_stream_deadline_interrupts_once_and_retains_generation() {
    let mut fixture = CodexFixture::build().await;
    let mut stream = fixture
        .conversation
        .prompt_stream(
            PromptRequest::new("deadline")
                .expect("prompt")
                .with_timeout(Duration::from_millis(250))
                .expect("timeout"),
        )
        .await
        .expect("stream admission");
    let turn = fixture.peer.turn().await;
    fixture.peer.notify("item/agentMessage/delta", json!({"threadId":"stream-thread","turnId":turn,"itemId":"answer","delta":"before timeout"})).await;
    assert!(
        matches!(tokio::time::timeout(Duration::from_secs(3), stream.recv()).await.expect("partial deadline"),
        Some(Ok(PromptEvent::OutputDelta { text })) if text == "before timeout")
    );
    assert!(matches!(
        tokio::time::timeout(Duration::from_secs(3), stream.recv())
            .await
            .expect("prompt deadline remains active after returning stream"),
        Some(Err(error)) if error.kind() == ErrorKind::Timeout
    ));
    assert!(stream.recv().await.is_none());
    fixture.finish_next_prompt().await;
    assert_eq!(fixture.peer.interrupts.load(Ordering::SeqCst), 1);
    fixture.shutdown().await;
}

#[tokio::test]
async fn codex_prompt_stream_deadline_survives_held_start_receipt_without_replay() {
    let (release, held) = oneshot::channel();
    let peer = CodexPeer::start_with(FirstStart::Held(held)).await;
    let mut fixture = CodexFixture::build_with_peer(peer).await;
    let mut stream = fixture
        .conversation
        .prompt_stream(
            PromptRequest::new("held start receipt")
                .expect("prompt")
                .with_timeout(Duration::from_millis(250))
                .expect("timeout"),
        )
        .await
        .expect("stream admission");
    assert_eq!(fixture.peer.turn().await, "turn-1");
    assert!(matches!(
        tokio::time::timeout(Duration::from_secs(1), stream.recv())
            .await
            .expect("observer deadline includes native acceptance setup"),
        Some(Err(error)) if error.kind() == ErrorKind::Timeout
    ));
    assert!(stream.recv().await.is_none());
    assert!(matches!(
        fixture
            .conversation
            .prompt(PromptRequest::new("cannot replace ambiguous acceptance").expect("prompt"))
            .await,
        Err(error) if error.kind() == ErrorKind::Busy
    ));
    assert_eq!(fixture.peer.interrupts.load(Ordering::SeqCst), 0);
    release.send(()).expect("original start owner remains live");
    fixture.finish_next_prompt().await;
    assert_eq!(fixture.peer.interrupts.load(Ordering::SeqCst), 1);
    fixture.shutdown().await;
}

#[tokio::test]
async fn codex_prompt_stream_deadline_does_not_park_its_own_held_store_transaction() {
    let raw = StateStore::connect(StateStoreConfig::Lance(LanceStateStoreConfig::memory()))
        .await
        .expect("held transaction store");
    let entered = Arc::new(tokio::sync::Notify::new());
    let release = Arc::new(tokio::sync::Semaphore::new(0));
    let store = WaiterFaultStore {
        inner: raw,
        fault: WaiterFault::HeldCreation {
            entered: Arc::clone(&entered),
            release: Arc::clone(&release),
        },
        armed: Arc::new(AtomicBool::new(true)),
        attempts: Arc::new(AtomicUsize::new(0)),
    };
    let mut fixture = CodexFixture::build_with_store(CodexPeer::start().await, store).await;
    let mut stream = fixture
        .conversation
        .prompt_stream(
            PromptRequest::new("held caller storage")
                .expect("prompt")
                .with_timeout(Duration::from_millis(250))
                .expect("timeout"),
        )
        .await
        .expect("stream admission");
    tokio::time::timeout(Duration::from_secs(1), entered.notified())
        .await
        .expect("prepared write owns its transaction");
    assert!(matches!(
        tokio::time::timeout(Duration::from_secs(1), stream.recv())
            .await
            .expect("observer timeout cannot await a mutation behind its own parked transaction"),
        Some(Err(error)) if error.kind() == ErrorKind::Timeout
    ));
    assert!(stream.recv().await.is_none());
    assert!(matches!(
        fixture.peer.turns.try_recv(),
        Err(mpsc::error::TryRecvError::Empty)
    ));
    release.add_permits(1);
    let deadline = tokio::time::Instant::now() + Duration::from_secs(3);
    let mut next = loop {
        match tokio::time::timeout_at(
            deadline,
            fixture
                .conversation
                .prompt_stream(PromptRequest::new("after released transaction").expect("prompt")),
        )
        .await
        .expect("retained preparation cleanup bound")
        {
            Ok(stream) => break stream,
            Err(error) if error.kind() == ErrorKind::Busy => tokio::task::yield_now().await,
            Err(error) => panic!("expired preparation must settle before reuse: {error:?}"),
        }
    };
    let turn = fixture.peer.turn().await;
    assert_eq!(
        turn, "turn-1",
        "expired local preparation never dispatches native work"
    );
    fixture
        .peer
        .complete(&turn, "healthy after storage release")
        .await;
    assert!(matches!(
        tokio::time::timeout(Duration::from_secs(3), next.recv()).await.expect("next terminal"),
        Some(Ok(PromptEvent::Completed(response))) if response.output() == "healthy after storage release"
    ));
    assert!(next.recv().await.is_none());
    assert_eq!(fixture.peer.interrupts.load(Ordering::SeqCst), 0);
    fixture.shutdown().await;
}

#[tokio::test]
async fn codex_prompt_stream_early_delta_waits_for_exact_receipt_after_cancelled_recv() {
    let (release, held) = oneshot::channel();
    let peer = CodexPeer::start_with(FirstStart::EarlyDeltas {
        count: 1,
        release: Some(held),
        turn: None,
    })
    .await;
    let mut fixture = CodexFixture::build_with_peer(peer).await;
    let mut stream = fixture
        .conversation
        .prompt_stream(PromptRequest::new("one early native fragment").expect("prompt"))
        .await
        .expect("stream admission");
    let turn = fixture.peer.turn().await;
    // Cancellation of this pending read must retain both the admission gate
    // and the native fragment, without exposing unproven source ownership.
    assert!(
        tokio::time::timeout(Duration::from_millis(25), stream.recv())
            .await
            .is_err()
    );
    assert_eq!(fixture.peer.interrupts.load(Ordering::SeqCst), 0);
    release
        .send(())
        .expect("original native request still owns its response");
    assert!(matches!(
        tokio::time::timeout(Duration::from_secs(1), stream.recv()).await.expect("exact receipt releases retained output"),
        Some(Ok(PromptEvent::OutputDelta { text })) if text == "early 0"
    ));
    fixture
        .peer
        .complete(&turn, "authoritative native terminal")
        .await;
    assert!(matches!(
        tokio::time::timeout(Duration::from_secs(1), stream.recv()).await.expect("native terminal after gated text"),
        Some(Ok(PromptEvent::Completed(response))) if response.output() == "authoritative native terminal"
    ));
    assert!(stream.recv().await.is_none());
    fixture.finish_next_prompt().await;
    assert_eq!(fixture.peer.interrupts.load(Ordering::SeqCst), 0);
    fixture.shutdown().await;
}

#[tokio::test]
async fn codex_prompt_stream_early_wrong_turn_is_discarded_after_exact_receipt() {
    let (release, held) = oneshot::channel();
    let peer = CodexPeer::start_with(FirstStart::EarlyDeltas {
        count: 1,
        release: Some(held),
        turn: Some("foreign-turn".to_owned()),
    })
    .await;
    let mut fixture = CodexFixture::build_with_peer(peer).await;
    let mut stream = fixture
        .conversation
        .prompt_stream(PromptRequest::new("exact early owner").expect("prompt"))
        .await
        .expect("stream admission");
    let turn = fixture.peer.turn().await;
    assert!(
        tokio::time::timeout(Duration::from_millis(25), stream.recv())
            .await
            .is_err(),
        "unproven output must remain gated"
    );
    release.send(()).expect("original request remains owned");
    assert!(matches!(
        tokio::time::timeout(Duration::from_secs(1), stream.recv())
            .await
            .expect("mismatched gate must end observation"),
        Some(Err(error)) if error.kind() == ErrorKind::Integration
    ));
    assert!(
        stream.recv().await.is_none(),
        "foreign queued text must never become visible"
    );
    fixture
        .peer
        .complete(&turn, "owned original work continues")
        .await;
    fixture.finish_next_prompt().await;
    assert_eq!(fixture.peer.interrupts.load(Ordering::SeqCst), 0);
    fixture.shutdown().await;
}

#[tokio::test]
async fn codex_prompt_stream_unresolved_gate_does_not_hide_runtime_revocation() {
    let (_release, held) = oneshot::channel();
    let peer = CodexPeer::start_with(FirstStart::EarlyDeltas {
        count: 1,
        release: Some(held),
        turn: None,
    })
    .await;
    let baseline = tokio::runtime::Handle::current()
        .metrics()
        .num_alive_tasks();
    let mut fixture = CodexFixture::build_with_peer(peer).await;
    let mut stream = fixture
        .conversation
        .prompt_stream(PromptRequest::new("gated runtime drop").expect("prompt"))
        .await
        .expect("stream admission");
    fixture.peer.turn().await;
    assert!(
        tokio::time::timeout(Duration::from_millis(25), stream.recv())
            .await
            .is_err()
    );
    fixture.revoke(baseline).await;
    assert!(matches!(
        tokio::time::timeout(Duration::from_secs(1), stream.recv())
            .await
            .expect("reserved error cannot await gate admission"),
        Some(Err(error)) if error.kind() == ErrorKind::Closed
    ));
    assert!(stream.recv().await.is_none());
}

#[tokio::test]
async fn codex_prompt_stream_pre_receipt_flood_preserves_transport_and_accepted_work() {
    // The pin submits UserInput before constructing TurnStartResponse. Native
    // output may therefore precede the response that proves the accepted turn.
    let (release, receipt) = oneshot::channel();
    let peer = CodexPeer::start_with(FirstStart::EarlyDeltas {
        count: 128,
        release: Some(receipt),
        turn: None,
    })
    .await;
    let mut fixture = CodexFixture::build_with_peer(peer).await;
    let mut stream = fixture
        .conversation
        .prompt_stream(PromptRequest::new("early native output").expect("prompt"))
        .await
        .expect("stream admission");
    let turn = fixture.peer.turn().await;
    let observed = tokio::time::timeout(Duration::from_secs(1), async {
        let mut fragments = 0;
        loop {
            match stream.recv().await {
                Some(Ok(PromptEvent::OutputDelta { .. })) => fragments += 1,
                Some(Err(error)) if error.kind() == ErrorKind::Integration => break fragments,
                event => panic!("lost exact early ownership cannot claim completion: {event:?}"),
            }
        }
    })
    .await
    .expect("native reader must drain before the start receipt behind its output");
    assert_eq!(
        observed, 0,
        "unproven flood text must never cross the receipt gate"
    );
    assert!(stream.recv().await.is_none());
    release
        .send(())
        .expect("release original receipt after bounded overflow");
    fixture
        .peer
        .complete(&turn, "accepted despite observation loss")
        .await;
    fixture.finish_next_prompt().await;
    assert_eq!(fixture.peer.interrupts.load(Ordering::SeqCst), 0);
    fixture.shutdown().await;
}

#[tokio::test]
async fn codex_prompt_stream_requires_exact_root_thread_and_turn() {
    let mut fixture = CodexFixture::build().await;
    let mut stream = fixture
        .conversation
        .prompt_stream(PromptRequest::new("thread isolation").expect("prompt"))
        .await
        .expect("stream admission");
    let turn = fixture.peer.turn().await;
    fixture
        .peer
        .notify(
            "item/agentMessage/delta",
            json!({"threadId":"stream-thread","turnId":turn,"itemId":"root","delta":"root first"}),
        )
        .await;
    assert!(matches!(
        tokio::time::timeout(Duration::from_secs(3), stream.recv()).await.expect("root delta"),
        Some(Ok(PromptEvent::OutputDelta { text })) if text == "root first"
    ));
    fixture.peer.notify("item/agentMessage/delta", json!({"threadId":"child-thread","turnId":turn,"itemId":"child","delta":"child must not bleed"})).await;
    fixture
        .peer
        .notify(
            "item/agentMessage/delta",
            json!({"threadId":"stream-thread","turnId":turn,"itemId":"root","delta":"root second"}),
        )
        .await;
    assert!(matches!(
        tokio::time::timeout(Duration::from_secs(3), stream.recv()).await.expect("isolated root delta"),
        Some(Ok(PromptEvent::OutputDelta { text })) if text == "root second"
    ));
    fixture.peer.complete(&turn, "root terminal").await;
    assert!(matches!(
        tokio::time::timeout(Duration::from_secs(3), stream.recv()).await.expect("root terminal"),
        Some(Ok(PromptEvent::Completed(response))) if response.output() == "root terminal"
    ));
    assert!(stream.recv().await.is_none());
    fixture.shutdown().await;
}

impl WaiterFaultStore {
    async fn assert_timeout_intent(failures: usize) {
        let raw = StateStore::connect(StateStoreConfig::Lance(LanceStateStoreConfig::memory()))
            .await
            .expect("timeout intent store");
        let store = Self {
            inner: raw.clone(),
            fault: WaiterFault::TimeoutIntent { failures },
            armed: Arc::new(AtomicBool::new(true)),
            attempts: Arc::new(AtomicUsize::new(0)),
        };
        let peer = CodexPeer::start().await;
        let baseline = tokio::runtime::Handle::current()
            .metrics()
            .num_alive_tasks();
        let mut fixture = CodexFixture::build_with_store(peer, store.clone()).await;
        let mut notifications = fixture
            .conversation
            .notification_stream()
            .expect("notifications");
        let mut stream = fixture
            .conversation
            .prompt_stream(
                PromptRequest::new("timeout intent ownership")
                    .expect("prompt")
                    .with_timeout(Duration::from_millis(100))
                    .expect("deadline"),
            )
            .await
            .expect("stream admission");
        assert_eq!(fixture.peer.turn().await, "turn-1");
        assert!(matches!(
            tokio::time::timeout(Duration::from_secs(1), stream.recv())
                .await
                .expect("bounded timeout"),
            Some(Err(error)) if error.kind() == ErrorKind::Timeout
        ));
        assert!(stream.recv().await.is_none());
        if failures == 1 {
            tokio::time::timeout(Duration::from_secs(4), async {
                while fixture.peer.interrupts.load(Ordering::SeqCst) == 0 {
                    tokio::task::yield_now().await;
                }
            })
            .await
            .expect("transient intent failure must retry before exact native cancellation");
            assert!(store.attempts.load(Ordering::SeqCst) > 1);
            assert_eq!(fixture.peer.interrupts.load(Ordering::SeqCst), 1);
            drop(notifications);
            fixture.finish_next_prompt().await;
            fixture.shutdown().await;
        } else {
            assert!(tokio::time::timeout(Duration::from_secs(4), notifications.recv()).await
                .expect("permanent intent failure must invalidate observation before native completion")
                .is_none_or(|result| result.is_err_and(|error| error.kind() == ErrorKind::Closed)));
            let attempts = store.attempts.load(Ordering::SeqCst);
            assert!(attempts > 1);
            tokio::time::sleep(Duration::from_millis(100)).await;
            assert_eq!(
                store.attempts.load(Ordering::SeqCst),
                attempts,
                "no timeout-intent retries may be admitted after its lifecycle bound"
            );
            assert_eq!(
                fixture.peer.interrupts.load(Ordering::SeqCst),
                0,
                "failed durable intent cannot authorize native cancellation"
            );
            let record = raw
                .load(
                    StateKey::new(
                        "agents_kit_codex_prompts_v1",
                        fixture.conversation.id().as_str(),
                    )
                    .expect("key"),
                )
                .await
                .expect("retained state")
                .expect("original generation remains recovery owned");
            assert_eq!(record.record.value["waiter"], "waiting");
            drop(notifications);
            fixture.revoke(baseline).await;
        }
    }

    async fn assert_admitted_commit(waiter: &'static str) {
        let raw = StateStore::connect(StateStoreConfig::Lance(LanceStateStoreConfig::memory()))
            .await
            .expect("held commit store");
        let entered = Arc::new(tokio::sync::Notify::new());
        let release = Arc::new(tokio::sync::Semaphore::new(0));
        let completed = Arc::new(AtomicUsize::new(0));
        let store = Self {
            inner: raw.clone(),
            fault: WaiterFault::HeldCommit {
                waiter,
                entered: Arc::clone(&entered),
                release: Arc::clone(&release),
                completed: Arc::clone(&completed),
            },
            armed: Arc::new(AtomicBool::new(true)),
            attempts: Arc::new(AtomicUsize::new(0)),
        };
        let peer = CodexPeer::start().await;
        let baseline = tokio::runtime::Handle::current()
            .metrics()
            .num_alive_tasks();
        let mut fixture = CodexFixture::build_with_store(peer, store.clone()).await;
        let request = PromptRequest::new("hold original waiter commit").expect("prompt");
        let request = if waiter == "timed_out" {
            request
                .with_timeout(Duration::from_millis(100))
                .expect("prompt deadline")
        } else {
            request
        };
        let mut stream = fixture
            .conversation
            .prompt_stream(request)
            .await
            .expect("stream admission");
        let turn = fixture.peer.turn().await;
        if waiter == "lost" {
            fixture
                .peer
                .complete(&turn, "native terminal before cleanup")
                .await;
        }
        tokio::time::timeout(Duration::from_secs(1), entered.notified())
            .await
            .expect("original commit entered");
        let held_at = tokio::time::Instant::now();
        assert!(matches!(
            tokio::time::timeout(Duration::from_secs(5), stream.recv())
                .await
                .expect("observer error remains bounded while admitted commit is held"),
            Some(Err(error)) if error.kind() == ErrorKind::Timeout
        ));
        assert!(stream.recv().await.is_none());
        // Hold past both the user observation deadline and the configured
        // lifecycle retry bound. The admitted commit itself must survive.
        tokio::time::sleep_until(held_at + Duration::from_millis(3_250)).await;
        assert_eq!(completed.load(Ordering::SeqCst), 0);
        release.add_permits(1);
        tokio::time::timeout(Duration::from_secs(1), async {
            while completed.load(Ordering::SeqCst) == 0 {
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("deadline must retain and poll the exact admitted commit");
        assert_eq!(completed.load(Ordering::SeqCst), 1);
        assert_eq!(store.attempts.load(Ordering::SeqCst), 1);
        if waiter == "lost" {
            let retained = raw
                .load(
                    StateKey::new(
                        "agents_kit_codex_prompts_v1",
                        fixture.conversation.id().as_str(),
                    )
                    .expect("key"),
                )
                .await
                .expect("durable commit receipt")
                .expect("cleanup remains recovery owned after its deadline");
            assert_eq!(retained.record.value["waiter"], "lost");
        }
        fixture.revoke(baseline).await;
    }

    async fn assert_terminal(fault: WaiterFault) {
        for primary_failure in [false, true] {
            let raw = StateStore::connect(StateStoreConfig::Lance(LanceStateStoreConfig::memory()))
                .await
                .expect("waiter fault store");
            let store = WaiterFaultStore {
                inner: raw.clone(),
                fault: fault.clone(),
                armed: Arc::new(AtomicBool::new(false)),
                attempts: Arc::new(AtomicUsize::new(0)),
            };
            let peer = CodexPeer::start().await;
            let runtime = tokio::runtime::Handle::current();
            let baseline = runtime.metrics().num_alive_tasks();
            let mut fixture = CodexFixture::build_with_store(peer, store.clone()).await;
            let request = PromptRequest::new("terminal cleanup").expect("prompt");
            let request = if primary_failure {
                request.with_structured_output(
                    StructuredOutputRequest::new(json!({"type":"object"})).expect("schema"),
                )
            } else {
                request
            };
            let mut stream = fixture
                .conversation
                .prompt_stream(request)
                .await
                .expect("stream");
            let turn = fixture.peer.turn().await;
            store.armed.store(true, Ordering::SeqCst);
            fixture.peer.complete(&turn, "terminal text").await;
            let terminal = tokio::time::timeout(Duration::from_secs(5), stream.recv())
                .await
                .expect("terminal settlement bound");
            assert!(
                store.attempts.load(Ordering::SeqCst) > 0,
                "fault reached waiter settlement"
            );
            let record = raw
                .load(
                    StateKey::new(
                        "agents_kit_codex_prompts_v1",
                        fixture.conversation.id().as_str(),
                    )
                    .expect("key"),
                )
                .await
                .expect("retained prompt")
                .expect("durable failed cleanup");
            assert_eq!(record.record.value["waiter"], "delivering");
            if primary_failure {
                assert!(
                    matches!(terminal, Some(Err(error)) if error.kind() == ErrorKind::Protocol),
                    "primary output failure must survive cleanup failure"
                );
            } else if matches!(&fault, WaiterFault::ForeignOwner) {
                assert!(
                    matches!(terminal, Some(Err(error)) if error.kind() == ErrorKind::Conflict),
                    "definite ownership failure cannot claim Completed"
                );
            } else {
                assert!(
                    matches!(terminal, Some(Err(error)) if error.kind() == ErrorKind::Timeout),
                    "unsettled terminal waiter cannot claim Completed"
                );
            }
            assert!(stream.recv().await.is_none());
            store.armed.store(false, Ordering::SeqCst);
            // The failed runtime retains durable reconciliation evidence. Releasing
            // its public handles must still join/abort its accepted task ownership.
            drop(fixture.conversation);
            drop(fixture.workspace);
            drop(fixture.agent);
            tokio::time::timeout(Duration::from_secs(3), async {
                while runtime.metrics().num_alive_tasks() > baseline {
                    tokio::task::yield_now().await;
                }
            })
            .await
            .expect("failed terminal cannot detach native tasks");
            fixture.peer.shutdown().await;
            std::fs::remove_dir_all(fixture.root).expect("fixture directory cleanup");
        }
    }
}

#[tokio::test]
async fn codex_prompt_stream_terminal_deadline_retains_admitted_waiter_commit() {
    WaiterFaultStore::assert_admitted_commit("lost").await;
}

#[tokio::test]
async fn codex_prompt_stream_retries_transient_timeout_intent_before_native_abort() {
    WaiterFaultStore::assert_timeout_intent(1).await;
}

#[tokio::test]
async fn codex_prompt_stream_permanent_timeout_intent_failure_closes_runtime_observation() {
    WaiterFaultStore::assert_timeout_intent(usize::MAX).await;
}

#[tokio::test]
async fn codex_prompt_stream_deadline_retains_admitted_timeout_intent_commit() {
    WaiterFaultStore::assert_admitted_commit("timed_out").await;
}

#[tokio::test]
async fn codex_prompt_stream_waiter_retry_exhaustion_preserves_primary_error() {
    WaiterFaultStore::assert_terminal(WaiterFault::Retry).await;
}

#[tokio::test]
async fn codex_prompt_stream_definite_waiter_failure_cannot_claim_completed() {
    WaiterFaultStore::assert_terminal(WaiterFault::ForeignOwner).await;
}

#[tokio::test]
async fn codex_prompt_stream_last_handle_drop_releases_owned_tasks() {
    let peer = CodexPeer::start().await;
    let handle = tokio::runtime::Handle::current();
    let baseline = handle.metrics().num_alive_tasks();
    let mut fixture = CodexFixture::build_with_peer(peer).await;
    let mut stream = fixture
        .conversation
        .prompt_stream(PromptRequest::new("owned work").expect("prompt"))
        .await
        .expect("stream admission");
    let turn = fixture.peer.turn().await;
    fixture
        .peer
        .notify(
            "item/agentMessage/delta",
            json!({"threadId":"stream-thread","turnId":turn,"itemId":"answer","delta":"accepted"}),
        )
        .await;
    assert!(matches!(
        tokio::time::timeout(Duration::from_secs(3), stream.recv())
            .await
            .expect("partial deadline"),
        Some(Ok(PromptEvent::OutputDelta { .. }))
    ));
    assert!(
        handle.metrics().num_alive_tasks() > baseline,
        "accepted Kit work is independently alive"
    );
    let CodexFixture {
        peer,
        agent,
        workspace,
        conversation,
        root,
    } = fixture;
    drop(conversation);
    drop(workspace);
    drop(agent);
    tokio::time::timeout(Duration::from_secs(3), async {
        while handle.metrics().num_alive_tasks() > baseline {
            tokio::task::yield_now().await;
        }
    })
    .await
    .expect("last native runtime handle cannot detach accepted prompt or transport tasks");
    assert!(
        matches!(
            tokio::time::timeout(Duration::from_secs(3), stream.recv())
                .await
                .expect("revoked observer deadline"),
            Some(Err(_))
        ),
        "runtime drop cannot claim Completed"
    );
    assert!(stream.recv().await.is_none());
    peer.shutdown().await;
    std::fs::remove_dir_all(root).expect("fixture directory cleanup");
}

#[tokio::test]
async fn codex_prompt_stream_malformed_native_delta_fails_observation() {
    let mut fixture = CodexFixture::build().await;
    let mut stream = fixture
        .conversation
        .prompt_stream(PromptRequest::new("malformed delta").expect("prompt"))
        .await
        .expect("native streaming supported");
    let turn = fixture.peer.turn().await;
    fixture
        .peer
        .notify(
            "item/agentMessage/delta",
            json!({"threadId":"stream-thread","turnId":turn,"itemId":"answer","delta":4}),
        )
        .await;
    assert!(matches!(
        tokio::time::timeout(Duration::from_secs(3), stream.recv())
            .await
            .expect("malformed event bound"),
        Some(Err(error)) if error.kind() == ErrorKind::Protocol
    ));
    assert!(stream.recv().await.is_none());
    // Malformed protocol revokes the live runtime; graceful close cannot claim
    // success after the connection-wide owning error.
    drop(fixture.conversation);
    drop(fixture.workspace);
    let _ = fixture.agent.shutdown().await;
    fixture.peer.shutdown().await;
    std::fs::remove_dir_all(fixture.root).expect("fixture directory cleanup");
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum NotificationReceiptCase {
    CancelledCommit,
    LaterPublication,
    ResurrectedIdentity,
    SequenceGap,
    RollbackFailure,
}

impl WaiterFaultStore {
    async fn interrupted_notification_acknowledgment(case: NotificationReceiptCase) {
        let inner = StateStore::connect(StateStoreConfig::Lance(LanceStateStoreConfig::memory()))
            .await
            .unwrap();
        let entered = Arc::new(tokio::sync::Semaphore::new(0));
        let release = Arc::new(tokio::sync::Semaphore::new(0));
        let committed = Arc::new(AtomicUsize::new(0));
        let observe_next = Arc::new(AtomicBool::new(false));
        let restore_prefix = Arc::new(std::sync::Mutex::new(None));
        let sequence_gap = Arc::new(AtomicBool::new(false));
        let store = Self {
            inner,
            fault: WaiterFault::NotificationReceipt {
                observation: case != NotificationReceiptCase::CancelledCommit,
                cleanup_failure: case == NotificationReceiptCase::RollbackFailure,
                observe_next: Arc::clone(&observe_next),
                restore_prefix: Arc::clone(&restore_prefix),
                sequence_gap: Arc::clone(&sequence_gap),
                entered: Arc::clone(&entered),
                release: Arc::clone(&release),
                committed: Arc::clone(&committed),
            },
            armed: Arc::new(AtomicBool::new(false)),
            attempts: Arc::new(AtomicUsize::new(0)),
        };
        let peer = CodexPeer::start().await;
        let mut fixture = CodexFixture::build_with_store(peer, store.clone()).await;
        let mut receiver = fixture.conversation.notification_stream().unwrap();
        let observed = NativeCleanup::observe(tokio::time::Instant::now() + Duration::from_secs(10), async {
            let mut stream = fixture.conversation.prompt_stream(PromptRequest::new("notification receipt owner").unwrap()).await.unwrap();
            let turn = fixture.peer.turn().await;
            fixture.peer.notify("item/started", json!({
                "threadId":"stream-thread", "turnId":turn, "startedAtMs":1,
                "item":{"id":"receipt-command", "type":"commandExecution", "status":"inProgress",
                    "command":"printf receipt", "cwd":fixture.root,
                    "commandActions":[], "aggregatedOutput":null, "exitCode":null}
            })).await;
            let running = receiver.recv().await.unwrap().unwrap();
            assert!(matches!(running.kind(), ConversationNotificationKind::Process {state: ProcessState::Running, ..}));
            let key = StateKey::new("agents_kit_conversation_notifications_v1", fixture.conversation.id().as_str()).unwrap();
            let prefix = store.inner.load(key).await.unwrap().unwrap().record.value["pending"][0].clone();
            store.armed.store(true, Ordering::SeqCst);
            if case == NotificationReceiptCase::RollbackFailure {
                let received = tokio::time::timeout(Duration::from_secs(1), receiver.recv()).await;
                store.armed.store(false, Ordering::SeqCst);
                fixture.peer.complete(&turn, "notification terminal").await;
                assert!(matches!(stream.recv().await, Some(Ok(PromptEvent::Completed(response))) if response.output() == "notification terminal"));
                assert!(stream.recv().await.is_none());
                assert_eq!(store.attempts.load(Ordering::SeqCst), 1, "a failed rollback cannot authorize another receipt write");
                let error = received.expect("receipt rollback failure must terminate").expect("one terminal failure").expect_err("receipt conflict and cleanup uncertainty must survive");
                assert_eq!(error.kind(), ErrorKind::Conflict);
                assert_eq!(error.detail(), Some(&ErrorDetail::TransactionConflict));
                assert_eq!(error.context().operation, Operation::NotificationStream);
                assert!(error.supplementary().iter().any(|cleanup| cleanup.context().phase == ErrorPhase::Cleanup && cleanup.detail() == Some(&ErrorDetail::ServiceUnavailable)));
                assert!(receiver.recv().await.is_none());
                return;
            }
            {
                let receive = receiver.recv();
                tokio::pin!(receive);
                tokio::select! {
                    item = &mut receive => panic!("only running process has been published: {item:?}"),
                    permit = entered.acquire() => permit.unwrap().forget(),
                }
                // Drop the observer after the real acknowledgment applied, either
                // before its commit reply or during the subsequent exact read.
            }
            assert_eq!(committed.load(Ordering::SeqCst), 1);
            release.add_permits(1);
            fixture.peer.notify("item/completed", json!({
                "threadId":"stream-thread", "turnId":turn, "completedAtMs":2,
                "item":{"id":"receipt-command", "type":"commandExecution", "status":"completed",
                    "command":"printf receipt", "cwd":fixture.root,
                    "commandActions":[], "aggregatedOutput":"receipt", "exitCode":0}
            })).await;
            fixture.peer.complete(&turn, "notification terminal").await;
            assert!(matches!(stream.recv().await, Some(Ok(PromptEvent::Completed(response))) if response.output() == "notification terminal"));
            assert!(stream.recv().await.is_none());
            if matches!(case, NotificationReceiptCase::ResurrectedIdentity | NotificationReceiptCase::SequenceGap) {
                if case == NotificationReceiptCase::ResurrectedIdentity {
                    *restore_prefix.lock().unwrap() = Some(prefix);
                } else {
                    sequence_gap.store(true, Ordering::SeqCst);
                }
                let error = receiver.recv().await.expect("contradiction must terminate once").expect_err("receipt observation must preserve exact identities and publication sequence");
                assert_eq!(error.kind(), ErrorKind::InvalidState);
                assert!(receiver.recv().await.is_none());
                return;
            }
            let exited = receiver.recv().await.expect("the committed later item must survive").expect("receipt reconciliation must not reject legitimate journal advancement");
            assert_ne!(exited.id(), running.id());
            assert!(matches!(exited.kind(), ConversationNotificationKind::Process {state: ProcessState::Exited {exit_code: Some(0)}, ..}));
            assert_eq!(committed.load(Ordering::SeqCst), 1);
        }).await;
        store.armed.store(false, Ordering::SeqCst);
        observe_next.store(false, Ordering::SeqCst);
        restore_prefix.lock().unwrap().take();
        sequence_gap.store(false, Ordering::SeqCst);
        release.add_permits(1);
        let CodexFixture {
            conversation,
            workspace,
            agent,
            mut peer,
            root,
        } = fixture;
        let mut cleanup = NativeCleanup::new(Duration::from_secs(4));
        cleanup.settle(conversation.close()).await;
        cleanup
            .settle(async {
                while let Some(item) = receiver.recv().await {
                    item?;
                }
                Ok::<(), agents_kit::KitError>(())
            })
            .await;
        cleanup.settle(workspace.close()).await;
        cleanup.settle(agent.shutdown()).await;
        cleanup
            .settle(async {
                if let Some(stop) = peer.stop.take() {
                    let _ = stop.send(());
                }
                if let Some(mut task) = peer.task.take() {
                    let joined = tokio::time::timeout(Duration::from_secs(3), &mut task).await;
                    if joined.is_err() {
                        task.abort();
                        let _ = task.await;
                    }
                    joined
                        .expect("receipt fixture joins")
                        .expect("receipt fixture remains healthy");
                }
                Ok::<(), agents_kit::KitError>(())
            })
            .await;
        cleanup
            .settle(async { std::fs::remove_dir_all(root) })
            .await;
        cleanup.finish(observed);
    }
}

#[tokio::test]
async fn codex_notification_ack_commit_survives_cancelled_observer() {
    WaiterFaultStore::interrupted_notification_acknowledgment(
        NotificationReceiptCase::CancelledCommit,
    )
    .await;
}

#[tokio::test]
async fn codex_notification_ack_observation_allows_later_publication() {
    WaiterFaultStore::interrupted_notification_acknowledgment(
        NotificationReceiptCase::LaterPublication,
    )
    .await;
}

#[tokio::test]
async fn codex_notification_ack_observation_rejects_resurrected_identity() {
    WaiterFaultStore::interrupted_notification_acknowledgment(
        NotificationReceiptCase::ResurrectedIdentity,
    )
    .await;
}

#[tokio::test]
async fn codex_notification_ack_observation_rejects_unaccounted_sequence_gap() {
    WaiterFaultStore::interrupted_notification_acknowledgment(NotificationReceiptCase::SequenceGap)
        .await;
}

#[tokio::test]
async fn codex_notification_ack_conflict_preserves_rollback_failure() {
    WaiterFaultStore::interrupted_notification_acknowledgment(
        NotificationReceiptCase::RollbackFailure,
    )
    .await;
}

impl CreationObservationCase {
    async fn assert_observation(self) {
        let raw = StateStore::connect(StateStoreConfig::Lance(LanceStateStoreConfig::memory()))
            .await
            .expect("real Lance fixture store");
        let entered = Arc::new(tokio::sync::Semaphore::new(0));
        let release = Arc::new([
            tokio::sync::Semaphore::new(0),
            tokio::sync::Semaphore::new(0),
        ]);
        let committed = Arc::new(tokio::sync::Semaphore::new(0));
        let reconciled = Arc::new(tokio::sync::Semaphore::new(0));
        let conflicts = Arc::new(AtomicUsize::new(0));
        let attempts = Arc::new(AtomicUsize::new(0));
        let store = WaiterFaultStore {
            inner: raw,
            fault: WaiterFault::ThreadCreationObservation {
                case: self,
                reconciled: Arc::clone(&reconciled),
                entered: Arc::clone(&entered),
                release: Arc::clone(&release),
                committed: Arc::clone(&committed),
                conflicts: Arc::clone(&conflicts),
            },
            armed: Arc::new(AtomicBool::new(true)),
            attempts: Arc::clone(&attempts),
        };
        let (respond, response) = oneshot::channel();
        let mut respond = Some(respond);
        let peer = CodexPeer::start_with(FirstStart::ThreadObservation(response)).await;
        let thread_starts = Arc::clone(&peer.thread_starts);
        let config = AgentConfig::new(
            CodexConfig::tcp(peer.address, Duration::from_secs(3), Duration::from_secs(3))
                .unwrap()
                .into(),
            Duration::from_secs(3),
            NonZeroUsize::MIN,
        )
        .unwrap();
        let agent = AgentBuilder::create(config, AgentStorage::new(store))
            .build()
            .await
            .unwrap();
        let cwd = std::env::current_dir().unwrap();
        let context = WorkspaceContext::new(
            cwd.clone(),
            vec![WorkspaceRoot::new(cwd, WorkspaceRootAccess::ReadWrite).unwrap()],
            WorkspaceExecutionPolicy::new(
                WorkspaceSandboxMode::FullAccess,
                WorkspaceNetworkAccess::Enabled,
            ),
        )
        .unwrap();
        let workspace = agent
            .new_workspace(
                NewWorkspace::new("creation conflict", context, WorkspaceDefaults::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let mut conversation = None;
        let observed = NativeCleanup::observe(
            tokio::time::Instant::now() + Duration::from_secs(10),
            async {
                let (creation, ()) = tokio::join!(
                    workspace
                        .new_conversation(NewConversation::new(None, None, Vec::new()).unwrap()),
                    async {
                        // The notification alone can stage until the original native
                        // response is released. Thus the first writer is the event.
                        entered.acquire().await.unwrap().forget();
                        respond
                            .take()
                            .unwrap()
                            .send(())
                            .expect("original thread/start response");
                        entered.acquire().await.unwrap().forget();
                        let winner = usize::from(self == Self::ForegroundWins);
                        release[winner].add_permits(1);
                        committed.acquire().await.unwrap().forget();
                        release[1 - winner].add_permits(1);
                    },
                );
                assert_eq!(
                    attempts.load(Ordering::SeqCst),
                    2,
                    "both original-snapshot observation writes staged"
                );
                assert_eq!(
                    conflicts.load(Ordering::SeqCst),
                    1,
                    "the foreground receives the original real Lance commit conflict"
                );
                assert_eq!(
                    thread_starts.load(Ordering::SeqCst),
                    1,
                    "creation must never replay thread/start"
                );
                if !matches!(self, Self::EventWins | Self::ForegroundWins) {
                    let error = match creation {
                        Ok(created) => {
                            conversation = Some(created);
                            panic!(
                                "mismatched or unreadable obligation must not reconcile: {self:?}"
                            );
                        }
                        Err(error) => error,
                    };
                    assert_eq!(error.context().operation, Operation::NewConversation);
                    if self == Self::ReadbackUnavailable {
                        assert_eq!(error.detail(), Some(&ErrorDetail::TransactionConflict));
                        assert_eq!(error.context().phase, ErrorPhase::StateCommit);
                        assert!(
                            error
                                .supplementary()
                                .iter()
                                .any(|failure| failure.context().phase == ErrorPhase::StateRead
                                    && failure.detail() == Some(&ErrorDetail::ServiceUnavailable))
                        );
                    } else if matches!(self, Self::DifferentThread | Self::ChangedObligation) {
                        // Invalidation is the outer publication failure. Its
                        // original persistence failure must still own cleanup.
                        assert_eq!(error.kind(), ErrorKind::Closed);
                        assert_eq!(error.context().phase, ErrorPhase::Publication);
                        assert_eq!(error.supplementary().len(), 1);
                        let primary = &error.supplementary()[0];
                        assert_eq!(primary.kind(), ErrorKind::Integration);
                        assert_eq!(primary.detail(), Some(&ErrorDetail::TransactionConflict));
                        assert_eq!(primary.context().phase, ErrorPhase::StateCommit);
                        assert_eq!(primary.supplementary().len(), 1);
                        let cleanup = &primary.supplementary()[0];
                        assert_eq!(cleanup.kind(), ErrorKind::Conflict);
                        assert_eq!(cleanup.detail(), None);
                        assert_eq!(cleanup.context().phase, ErrorPhase::Cleanup);
                    } else {
                        assert_eq!(error.kind(), ErrorKind::Integration);
                        assert_eq!(error.detail(), Some(&ErrorDetail::TransactionConflict));
                        assert_eq!(error.context().phase, ErrorPhase::StateCommit);
                        assert!(error.supplementary().is_empty());
                    }
                    return;
                }
                let created = conversation.insert(creation.expect(
                    "one matching native creation must reconcile its observation commit conflict",
                ));
                assert_eq!(workspace.list_conversations().await.unwrap().len(), 1);
                assert_eq!(
                    workspace
                        .conversation_info(created.id())
                        .await
                        .unwrap()
                        .id(),
                    &created.id()
                );
            },
        )
        .await;
        // Settle admitted work even when a witness or the expected success fails.
        if let Some(respond) = respond {
            let _ = respond.send(());
        }
        release[0].add_permits(1);
        release[1].add_permits(1);
        reconciled.add_permits(1);
        let mut cleanup = NativeCleanup::new(Duration::from_secs(10));
        if let Some(conversation) = conversation {
            cleanup.settle(conversation.close()).await;
        }
        if matches!(self, Self::DifferentThread | Self::ChangedObligation) {
            cleanup
                .settle(async {
                    let error = workspace
                        .close()
                        .await
                        .expect_err("failed ownership cleanup invalidates this workspace");
                    assert_eq!(error.kind(), ErrorKind::Closed);
                    Ok::<(), std::convert::Infallible>(())
                })
                .await;
        } else {
            cleanup.settle(workspace.close()).await;
        }
        cleanup.settle(agent.shutdown()).await;
        cleanup
            .settle(async {
                peer.shutdown().await;
                Ok::<(), std::convert::Infallible>(())
            })
            .await;
        cleanup.finish(observed);
    }
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn codex_creation_reconciles_same_thread_observation_commit_conflict() {
    CreationObservationCase::EventWins
        .assert_observation()
        .await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn codex_creation_reconciles_notification_after_foreground_commit() {
    CreationObservationCase::ForegroundWins
        .assert_observation()
        .await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn codex_creation_rejects_different_thread_after_commit_conflict() {
    CreationObservationCase::DifferentThread
        .assert_observation()
        .await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn codex_creation_rejects_changed_obligation_after_commit_conflict() {
    CreationObservationCase::ChangedObligation
        .assert_observation()
        .await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn codex_creation_rejects_unchanged_obligation_after_commit_conflict() {
    CreationObservationCase::UnchangedObligation
        .assert_observation()
        .await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn codex_creation_preserves_conflict_when_readback_fails() {
    CreationObservationCase::ReadbackUnavailable
        .assert_observation()
        .await;
}

impl WaiterFaultStore {
    async fn assert_creation_failure(
        point: StorageFaultPoint,
        source: StorageFaultSource,
        cleanup_failure: bool,
    ) {
        let peer = CodexPeer::start().await;
        let starts = Arc::clone(&peer.thread_starts);
        let rollbacks = Arc::new(AtomicUsize::new(0));
        let attempts = Arc::new(AtomicUsize::new(0));
        let store = Self {
            inner: StateStore::connect(StateStoreConfig::Lance(LanceStateStoreConfig::memory()))
                .await
                .unwrap(),
            fault: WaiterFault::CreationFailure {
                point,
                source,
                cleanup_failure,
                native_starts: Arc::clone(&starts),
                rollbacks: Arc::clone(&rollbacks),
            },
            armed: Arc::new(AtomicBool::new(true)),
            attempts: Arc::clone(&attempts),
        };
        let config = AgentConfig::new(
            CodexConfig::tcp(peer.address, Duration::from_secs(3), Duration::from_secs(3))
                .unwrap()
                .into(),
            Duration::from_secs(3),
            NonZeroUsize::MIN,
        )
        .unwrap();
        let agent = AgentBuilder::create(config, AgentStorage::new(store))
            .build()
            .await
            .unwrap();
        let cwd = std::env::current_dir().unwrap();
        let context = WorkspaceContext::new(
            cwd.clone(),
            vec![WorkspaceRoot::new(cwd, WorkspaceRootAccess::ReadWrite).unwrap()],
            WorkspaceExecutionPolicy::new(
                WorkspaceSandboxMode::FullAccess,
                WorkspaceNetworkAccess::Enabled,
            ),
        )
        .unwrap();
        let workspace = agent
            .new_workspace(
                NewWorkspace::new("creation load", context, WorkspaceDefaults::empty()).unwrap(),
            )
            .await
            .unwrap();
        let observed = NativeCleanup::observe(
            tokio::time::Instant::now() + Duration::from_secs(10),
            async {
                let error = match workspace
                    .new_conversation(NewConversation::new(None, None, Vec::new()).unwrap())
                    .await
                {
                    Ok(conversation) => {
                        conversation.close().await.unwrap();
                        panic!("injected observation failure must not succeed");
                    }
                    Err(error) => error,
                };
                assert_eq!(
                    starts.load(Ordering::SeqCst),
                    1,
                    "never replay native creation"
                );
                assert_eq!(attempts.load(Ordering::SeqCst), 1);
                assert_eq!(
                    rollbacks.load(Ordering::SeqCst),
                    usize::from(point == StorageFaultPoint::Load),
                    "failed read must settle its transaction"
                );
                assert_eq!(error.context().operation, Operation::NewConversation);
                assert_eq!(error.context().phase, point.phase());
                match source {
                    StorageFaultSource::Unavailable => {
                        assert_eq!(error.detail(), Some(&ErrorDetail::ServiceUnavailable))
                    }
                    StorageFaultSource::TimedOut => {
                        assert_eq!(error.kind(), ErrorKind::Timeout);
                        assert!(matches!(
                            error.detail(),
                            Some(ErrorDetail::DeadlineElapsed { .. })
                        ));
                    }
                    StorageFaultSource::Conflict => {
                        assert_eq!(error.detail(), Some(&ErrorDetail::TransactionConflict))
                    }
                }
                if cleanup_failure {
                    assert!(
                        error
                            .supplementary()
                            .iter()
                            .any(|failure| failure.context().phase == ErrorPhase::Cleanup
                                && failure.detail() == Some(&ErrorDetail::ServiceUnavailable))
                    );
                }
            },
        )
        .await;
        let mut cleanup = NativeCleanup::new(Duration::from_secs(10));
        cleanup.settle(workspace.close()).await;
        cleanup.settle(agent.shutdown()).await;
        cleanup
            .settle(async {
                peer.shutdown().await;
                Ok::<(), std::convert::Infallible>(())
            })
            .await;
        cleanup.finish(observed);
    }
}

#[tokio::test]
async fn codex_creation_preserves_unavailable_load_and_settles_transaction() {
    WaiterFaultStore::assert_creation_failure(
        StorageFaultPoint::Load,
        StorageFaultSource::Unavailable,
        false,
    )
    .await;
}

#[tokio::test]
async fn codex_creation_preserves_timeout_load_and_settles_transaction() {
    WaiterFaultStore::assert_creation_failure(
        StorageFaultPoint::Load,
        StorageFaultSource::TimedOut,
        false,
    )
    .await;
}

#[tokio::test]
async fn codex_creation_preserves_load_conflict_and_rollback_failure() {
    WaiterFaultStore::assert_creation_failure(
        StorageFaultPoint::Load,
        StorageFaultSource::Conflict,
        true,
    )
    .await;
}

#[tokio::test]
async fn codex_creation_preserves_nonconflict_commit_failure_without_replay() {
    WaiterFaultStore::assert_creation_failure(
        StorageFaultPoint::Commit,
        StorageFaultSource::Unavailable,
        false,
    )
    .await;
}

impl CodexPeer {
    async fn settle_dropped(self, root: PathBuf, cleanup: &mut NativeCleanup, baseline: usize) {
        cleanup
            .settle(async {
                tokio::time::timeout(Duration::from_secs(3), async {
                    while tokio::runtime::Handle::current()
                        .metrics()
                        .num_alive_tasks()
                        > baseline
                    {
                        tokio::task::yield_now().await;
                    }
                })
                .await
            })
            .await;
        // Keep the peer outside the bounded Kit observation. Even a failed Kit
        // join observation must continue to the peer's owned stop/abort/join.
        let peer_cleanup = std::panic::AssertUnwindSafe(self.shutdown())
            .catch_unwind()
            .await;
        cleanup
            .settle(async {
                if let Err(panic) = peer_cleanup {
                    std::panic::resume_unwind(panic);
                }
                Ok::<(), std::io::Error>(())
            })
            .await;
        cleanup
            .settle(async { std::fs::remove_dir_all(root) })
            .await;
    }
}

#[derive(Clone, Copy, Debug)]
enum HistoricalTerminalCase {
    SeveralSettled,
    NextActive,
    ChangedOwner,
    DifferentOutcome,
    MatchingCause,
    DifferentCause,
    MissingHistory,
    DuplicateTurn,
    MissingClient,
    DuplicateClient,
    IncompleteHistory,
    IncompleteOther,
    ForeignHistory,
    ReadFailure,
    RollbackFailure,
    OrphanContinuation,
    MissingActive,
}

impl HistoricalTerminalCase {
    fn accepted(self) -> bool {
        matches!(
            self,
            Self::SeveralSettled | Self::NextActive | Self::ChangedOwner | Self::MatchingCause
        )
    }

    async fn run(self) {
        let store = StateStore::connect(StateStoreConfig::Lance(LanceStateStoreConfig::memory()))
            .await
            .unwrap();
        let peer = CodexPeer::start_with(FirstStart::DeferredInterruptTerminal).await;
        let baseline = tokio::runtime::Handle::current()
            .metrics()
            .num_alive_tasks();
        let controlled = WaiterFaultStore {
            inner: store.clone(),
            fault: WaiterFault::RollbackFailure,
            armed: Arc::new(AtomicBool::new(false)),
            attempts: Arc::new(AtomicUsize::new(0)),
        };
        let mut fixture = CodexFixture::build_with_store(peer, controlled.clone()).await;
        let observed = NativeCleanup::observe(tokio::time::Instant::now() + Duration::from_secs(20), async {
            let count = if matches!(self, Self::SeveralSettled) { 3 } else { 1 };
            let mut previous = Vec::new();
            let mut orphan = None;
            let mut notifications = fixture.conversation.notification_stream().unwrap();
            for index in 0..count {
                let mut stream = fixture.conversation.prompt_stream(PromptRequest::new(format!("generation {index}")).unwrap()).await.unwrap();
                let turn = fixture.peer.turn().await;
                fixture.peer.notify("item/agentMessage/delta", json!({"threadId":"stream-thread","turnId":turn,"itemId":"answer","delta":"accepted"})).await;
                assert!(matches!(stream.recv().await, Some(Ok(PromptEvent::OutputDelta { text })) if text == "accepted"));
                if matches!(self, Self::OrphanContinuation) {
                    fixture.peer.request(92, "item/commandExecution/requestApproval", json!({
                        "threadId":"stream-thread", "turnId":turn, "itemId":"command",
                        "startedAtMs":1, "command":"printf approved",
                        "availableDecisions":["accept", "cancel"]
                    })).await;
                    let notification = notifications.recv().await.unwrap().unwrap();
                    assert!(matches!(notification.kind(), ConversationNotificationKind::Interaction { .. }));
                    let mut page = store.list(StateListRequest::new("agents_kit_codex_continuations_v1").unwrap()).await.unwrap();
                    assert_eq!(page.records.len(), 1, "save the real outstanding native continuation");
                    let record = page.records.pop().unwrap().record;
                    assert_eq!(record.value["turn_id"], turn);
                    orphan = Some(record);
                }
                fixture.conversation.abort().await.expect("exact history reconciles interruption");
                assert!(matches!(stream.recv().await, Some(Err(error)) if error.kind() == ErrorKind::Cancelled));
                assert!(stream.recv().await.is_none());
                previous.push(turn);
            }
            if let Some(orphan) = orphan {
                assert!(store.load(orphan.key.clone()).await.unwrap().is_none(), "owned terminal cleanup removed the actual continuation");
                let mut transaction = store.begin_transaction().await.unwrap();
                transaction.put(orphan).await.unwrap();
                transaction.commit().await.unwrap();
            }
            drop(notifications);
            let mut current = None;
            if matches!(self, Self::NextActive | Self::MissingActive) {
                let mut stream = fixture.conversation.prompt_stream(PromptRequest::new("still active generation").unwrap()).await.unwrap();
                let turn = fixture.peer.turn().await;
                fixture.peer.notify("item/agentMessage/delta", json!({"threadId":"stream-thread","turnId":turn,"itemId":"active","delta":"current accepted"})).await;
                assert!(matches!(stream.recv().await, Some(Ok(PromptEvent::OutputDelta { text })) if text == "current accepted"));
                if matches!(self, Self::MissingActive) {
                    let key = StateKey::new("agents_kit_codex_prompts_v1", fixture.conversation.id().as_str()).unwrap();
                    let mut transaction = store.begin_transaction().await.unwrap();
                    assert!(transaction.load(key.clone()).await.unwrap().is_some(), "corruption removes an actual live generation");
                    transaction.delete(key).await.unwrap();
                    transaction.commit().await.unwrap();
                    // Native terminal evidence is complete and valid; the Kit
                    // owner has neither settled nor begun clearing this row.
                    previous = vec![turn.clone()];
                }
                current = Some((stream, turn));
            }
            let mut history = fixture.peer.history.lock().unwrap().clone();
            match self {
                Self::MatchingCause | Self::DifferentCause => history["turns"][0]["error"] = json!({"message":"private-history", "codexErrorInfo":"rateLimitExceeded"}),
                Self::MissingHistory => history["turns"] = json!([]),
                Self::DuplicateTurn => { let turn = history["turns"][0].clone(); history["turns"].as_array_mut().unwrap().push(turn); },
                Self::MissingClient => { history["turns"][0]["items"][0].as_object_mut().unwrap().remove("clientId"); },
                Self::DuplicateClient => { let user = history["turns"][0]["items"][0].clone(); history["turns"][0]["items"].as_array_mut().unwrap().push(user); },
                Self::IncompleteHistory => history["turns"][0]["itemsView"] = json!("summary"),
                Self::IncompleteOther => history["turns"].as_array_mut().unwrap().push(json!({"id":"other-terminal","status":"interrupted","itemsView":"summary","error":null,"items":[]})),
                Self::ForeignHistory => history["id"] = json!("different-thread"),
                Self::ReadFailure => fixture.peer.reject("thread/read", -32603, "test history unavailable"),
                Self::RollbackFailure => controlled.armed.store(true, Ordering::SeqCst),
                Self::MissingActive => history["turns"][1]["status"] = json!("interrupted"),
                Self::SeveralSettled | Self::NextActive | Self::ChangedOwner | Self::DifferentOutcome | Self::OrphanContinuation => {},
            }
            if matches!(self, Self::MatchingCause | Self::DifferentCause | Self::MissingHistory | Self::DuplicateTurn | Self::MissingClient | Self::DuplicateClient | Self::IncompleteHistory | Self::IncompleteOther | Self::ForeignHistory | Self::MissingActive) {
                *fixture.peer.history_override.lock().unwrap() = Some(history);
            }
            let release_history = if matches!(self, Self::ChangedOwner) {
                let (release, held) = oneshot::channel();
                *fixture.peer.held_history.lock().unwrap() = Some(held);
                Some(release)
            } else { None };
            for turn in &previous {
                let status = if matches!(self, Self::DifferentOutcome) { "completed" } else { "interrupted" };
                let error = match self {
                    Self::MatchingCause => json!({"message":"private-live", "codexErrorInfo":"rateLimitExceeded"}),
                    Self::DifferentCause => json!({"message":"private-live", "codexErrorInfo":"flexUnavailable"}),
                    _ => Value::Null,
                };
                fixture.peer.notify("turn/completed", json!({"threadId":"stream-thread","turn":{"id":turn,"status":status,"items":[],"error":error}})).await;
            }
            if let Some(release_history) = release_history {
                fixture.peer.history_entered.notified().await;
                let mut prompt = Box::pin(fixture.conversation.prompt(PromptRequest::new("admit while historical read is held").unwrap()));
                let key = StateKey::new("agents_kit_codex_prompts_v1", fixture.conversation.id().as_str()).unwrap();
                // Poll the real new prompt until its durable acceptance intent
                // exists. Its native request waits behind the held read response.
                loop {
                    tokio::select! {
                        result = &mut prompt => panic!("new prompt settled before dispatch release: {result:?}"),
                        snapshot = store.load(key.clone()) => {
                            if let Some(snapshot) = snapshot.unwrap()
                                && snapshot.record.value["state"]["state"] == "may_be_accepted" {
                                break;
                            }
                            tokio::task::yield_now().await;
                        }
                    }
                }
                release_history.send(()).expect("release original history observation");
                let turn = tokio::select! {
                    turn = fixture.peer.turn() => turn,
                    result = &mut prompt => panic!("new prompt lost to historical terminal: {result:?}"),
                };
                assert_eq!(turn, "turn-2");
                fixture.peer.complete(&turn, "changed owner exact result").await;
                let response = prompt.await.expect("new generation survives history owner change");
                assert_eq!(response.output(), "changed owner exact result");
            }
            if self.accepted() {
                fixture.peer.request(83, "currentTime/read", json!({"threadId":"stream-thread"})).await;
                let response = fixture.peer.responses.recv().await.expect("historical terminals keep event owner responsive");
                assert_eq!(response["id"], 83);
                assert!(response["result"]["currentTimeAt"].is_i64());
                if let Some((mut stream, turn)) = current.take() {
                    fixture.peer.complete(&turn, "current exact answer").await;
                    assert!(matches!(stream.recv().await, Some(Ok(PromptEvent::Completed(answer))) if answer.output() == "current exact answer"));
                    assert!(stream.recv().await.is_none());
                } else if !matches!(self, Self::ChangedOwner) {
                    let mut stream = fixture.conversation.prompt_stream(PromptRequest::new("after historical terminals").unwrap()).await.unwrap();
                    let turn = fixture.peer.turn().await;
                    assert_eq!(turn, format!("turn-{}", count + 1));
                    fixture.peer.complete(&turn, "subsequent exact answer").await;
                    assert!(matches!(stream.recv().await, Some(Ok(PromptEvent::Completed(answer))) if answer.output() == "subsequent exact answer"));
                    assert!(stream.recv().await.is_none());
                }
                assert_eq!(fixture.peer.interrupts.load(Ordering::SeqCst), count);
                assert_eq!(fixture.peer.thread_starts.load(Ordering::SeqCst), 1);
            } else {
                tokio::time::timeout(Duration::from_secs(3), async {
                    loop {
                        match fixture.agent.info().await {
                            Err(error) if error.kind() == ErrorKind::Closed => break,
                            Err(error) => panic!("unexpected hierarchy observation: {error:?}"),
                            Ok(_) => tokio::task::yield_now().await,
                        }
                    }
                }).await.expect("historical event invalidates hierarchy before shutdown");
                assert_eq!(fixture.peer.thread_starts.load(Ordering::SeqCst), 1);
                drop(current.take());
            }
        }).await;
        let mut cleanup = NativeCleanup::new(Duration::from_secs(10));
        if self.accepted() {
            cleanup.settle(fixture.conversation.close()).await;
            cleanup.settle(fixture.workspace.close()).await;
            cleanup.settle(fixture.agent.shutdown()).await;
        } else {
            cleanup
                .settle(async {
                    let error = fixture
                        .agent
                        .shutdown()
                        .await
                        .expect_err("contradictory historical terminal must fail closed");
                    assert!(
                        matches!(
                            error.kind(),
                            ErrorKind::InvalidState | ErrorKind::Protocol | ErrorKind::Integration
                        ),
                        "{self:?}: {error:?}"
                    );
                    assert_eq!(error.context().operation, Operation::Shutdown);
                    if matches!(self, Self::OrphanContinuation) {
                        assert_eq!(error.kind(), ErrorKind::InvalidState);
                        assert_eq!(
                            error.message(),
                            "historical prompt still owns an interaction continuation"
                        );
                    }
                    if matches!(self, Self::ReadFailure) {
                        assert_eq!(error.kind(), ErrorKind::Integration);
                        assert_eq!(error.detail(), Some(&ErrorDetail::RemoteInternal));
                        assert_eq!(error.context().phase, ErrorPhase::ResponseRead);
                    }
                    if matches!(self, Self::RollbackFailure) {
                        assert_eq!(error.kind(), ErrorKind::Integration);
                        assert_eq!(error.detail(), Some(&ErrorDetail::ServiceUnavailable));
                        assert_eq!(error.context().phase, ErrorPhase::Cleanup);
                        assert_eq!(controlled.attempts.load(Ordering::SeqCst), 1);
                    }
                    Ok::<(), std::io::Error>(())
                })
                .await;
            drop(fixture.conversation);
            drop(fixture.workspace);
        }
        fixture
            .peer
            .settle_dropped(fixture.root, &mut cleanup, baseline)
            .await;
        cleanup.finish(observed);
    }
}

#[tokio::test]
async fn codex_historical_terminals_survive_three_compacted_generations() {
    HistoricalTerminalCase::SeveralSettled.run().await;
}
#[tokio::test]
async fn codex_historical_terminal_preserves_next_active_generation() {
    HistoricalTerminalCase::NextActive.run().await;
}
#[tokio::test]
async fn codex_historical_terminal_revalidates_owner_changed_during_native_read() {
    HistoricalTerminalCase::ChangedOwner.run().await;
}
#[tokio::test]
async fn codex_historical_terminal_rejects_changed_outcome() {
    HistoricalTerminalCase::DifferentOutcome.run().await;
}
#[tokio::test]
async fn codex_historical_terminal_rejects_missing_native_turn() {
    HistoricalTerminalCase::MissingHistory.run().await;
}
#[tokio::test]
async fn codex_historical_terminal_rejects_duplicate_native_turn() {
    HistoricalTerminalCase::DuplicateTurn.run().await;
}
#[tokio::test]
async fn codex_historical_terminal_rejects_missing_native_generation() {
    HistoricalTerminalCase::MissingClient.run().await;
}
#[tokio::test]
async fn codex_historical_terminal_rejects_duplicate_native_generation() {
    HistoricalTerminalCase::DuplicateClient.run().await;
}
#[tokio::test]
async fn codex_historical_terminal_rejects_incomplete_native_history() {
    HistoricalTerminalCase::IncompleteHistory.run().await;
}
#[tokio::test]
async fn codex_historical_terminal_rejects_incomplete_other_native_turn() {
    HistoricalTerminalCase::IncompleteOther.run().await;
}
#[tokio::test]
async fn codex_historical_terminal_rejects_foreign_native_history() {
    HistoricalTerminalCase::ForeignHistory.run().await;
}
#[tokio::test]
async fn codex_historical_terminal_preserves_native_read_failure() {
    HistoricalTerminalCase::ReadFailure.run().await;
}
#[tokio::test]
async fn codex_historical_terminal_does_not_mask_missing_active_prompt() {
    HistoricalTerminalCase::MissingActive.run().await;
}

impl WaiterFaultStore {
    async fn assert_late_terminal_during_owned_clear(observation_error: bool) {
        let raw = StateStore::connect(StateStoreConfig::Lance(LanceStateStoreConfig::memory()))
            .await
            .unwrap();
        let entered = Arc::new(tokio::sync::Semaphore::new(0));
        let release = Arc::new(tokio::sync::Semaphore::new(0));
        let store = Self {
            inner: raw.clone(),
            fault: WaiterFault::HeldClear {
                entered: Arc::clone(&entered),
                release: Arc::clone(&release),
                observation_error,
            },
            armed: Arc::new(AtomicBool::new(false)),
            attempts: Arc::new(AtomicUsize::new(0)),
        };
        let peer = CodexPeer::start_with(FirstStart::DeferredInterruptTerminal).await;
        let baseline = tokio::runtime::Handle::current()
            .metrics()
            .num_alive_tasks();
        let mut fixture = CodexFixture::build_with_store(peer, store.clone()).await;
        let observed = NativeCleanup::observe(tokio::time::Instant::now() + Duration::from_secs(15), async {
            let mut stream = fixture.conversation.prompt_stream(PromptRequest::new("clear ownership").unwrap()).await.unwrap();
            let turn = fixture.peer.turn().await;
            fixture.peer.notify("item/agentMessage/delta", json!({"threadId":"stream-thread","turnId":turn,"itemId":"answer","delta":"accepted"})).await;
            assert!(matches!(stream.recv().await, Some(Ok(PromptEvent::OutputDelta { text })) if text == "accepted"));
            store.armed.store(true, Ordering::SeqCst);
            let mut abort = Box::pin(fixture.conversation.abort());
            tokio::select! {
                result = &mut abort => result.expect("abort receipt"),
                permit = entered.acquire() => { permit.unwrap().forget(); },
            }
            // The wrapped transaction has performed the real Lance delete and
            // retains the consuming commit observer. Native fact handling must
            // wait for this exact cleanup owner, not mistake absence for loss.
            let key = StateKey::new("agents_kit_codex_prompts_v1", fixture.conversation.id().as_str()).unwrap();
            while store.attempts.load(Ordering::SeqCst) == 0 { tokio::task::yield_now().await; }
            assert!(raw.load(key).await.unwrap().is_none());
            let (release_history, held) = oneshot::channel();
            *fixture.peer.held_history.lock().unwrap() = Some(held);
            fixture.peer.notify("turn/completed", json!({"threadId":"stream-thread","turn":{"id":turn,"status":"interrupted","items":[],"error":null}})).await;
            fixture.peer.history_entered.notified().await;
            fixture.peer.request(91, "currentTime/read", json!({"threadId":"stream-thread"})).await;
            release_history.send(()).unwrap();
            assert!(tokio::time::timeout(Duration::from_millis(50), fixture.peer.responses.recv()).await.is_err(), "event owner must retain the clearing boundary");
            release.add_permits(1);
            // The original abort observer may already have completed; dropping
            // its observation never revokes accepted work or repolls a result.
            drop(abort);
            assert!(matches!(stream.recv().await, Some(Err(error)) if error.kind() == ErrorKind::Cancelled));
            assert!(stream.recv().await.is_none());
            let response = fixture.peer.responses.recv().await.expect("terminal owner resumes after cleanup");
            assert_eq!(response["id"], 91);
            assert!(response["result"]["currentTimeAt"].is_i64());
            assert_eq!(store.attempts.load(Ordering::SeqCst), 1);
            assert_eq!(fixture.peer.interrupts.load(Ordering::SeqCst), 1);
            fixture.finish_next_prompt().await;
        }).await;
        release.add_permits(1);
        store.armed.store(false, Ordering::SeqCst);
        let mut cleanup = NativeCleanup::new(Duration::from_secs(10));
        cleanup.settle(fixture.conversation.close()).await;
        cleanup.settle(fixture.workspace.close()).await;
        cleanup.settle(fixture.agent.shutdown()).await;
        fixture
            .peer
            .settle_dropped(fixture.root, &mut cleanup, baseline)
            .await;
        cleanup.finish(observed);
    }
}

#[tokio::test]
async fn codex_historical_terminal_waits_for_owned_clear_commit() {
    WaiterFaultStore::assert_late_terminal_during_owned_clear(false).await;
}
#[tokio::test]
async fn codex_historical_terminal_waits_for_uncertain_clear_reconciliation() {
    WaiterFaultStore::assert_late_terminal_during_owned_clear(true).await;
}

#[tokio::test]
async fn codex_historical_terminal_rollback_failure_vetoes_reconciliation() {
    HistoricalTerminalCase::RollbackFailure.run().await;
}

#[tokio::test]
async fn codex_historical_terminal_rejects_orphaned_matching_continuation() {
    HistoricalTerminalCase::OrphanContinuation.run().await;
}

#[tokio::test]
async fn codex_selected_release_initialization_rejects_old_and_malformed_identity() {
    for (identity, expected) in [
        (json!("codex/0.162.1"), ErrorKind::InvalidConfig),
        (json!("codex/0.144.1"), ErrorKind::InvalidConfig),
        (Value::Null, ErrorKind::Protocol),
        (json!("invalid"), ErrorKind::Protocol),
    ] {
        let peer = CodexPeer::start().await;
        *peer.identity.lock().unwrap() = identity;
        let config = AgentConfig::new(
            CodexConfig::tcp(peer.address, Duration::from_secs(3), Duration::from_secs(3))
                .unwrap()
                .into(),
            Duration::from_secs(3),
            NonZeroUsize::new(1).unwrap(),
        )
        .unwrap();
        let store = StateStore::connect(StateStoreConfig::Lance(LanceStateStoreConfig::memory()))
            .await
            .unwrap();
        let result = AgentBuilder::create(config, AgentStorage::new(store))
            .build()
            .await;
        let error = match result {
            Err(error) => Some(error),
            Ok(agent) => {
                agent.shutdown().await.unwrap();
                None
            }
        };
        let starts = peer.thread_starts.load(Ordering::SeqCst);
        peer.shutdown().await;
        assert_eq!(starts, 0);
        assert_eq!(
            error.expect("invalid runtime identity must fail").kind(),
            expected
        );
    }
}

#[tokio::test]
async fn codex_interrupted_error_preserves_cancellation_and_redacted_cause() {
    for info in [
        Value::Null,
        json!("rateLimitExceeded"),
        json!("misalignmentPolicyViolation"),
    ] {
        let mut fixture = CodexFixture::build().await;
        let mut stream = fixture
            .conversation
            .prompt_stream(PromptRequest::new("interrupted").unwrap())
            .await
            .unwrap();
        let turn = fixture.peer.turn().await;
        let error = if info.is_null() {
            Value::Null
        } else {
            json!({"message":"secret-token", "codexErrorInfo":info, "misalignment":{
                "errorType":"private", "detailedExplanation":"secret-token", "steer":{"message":"secret-token"}, "reviewTarget":"secret-token"
            }})
        };
        fixture
            .peer
            .notify(
                "turn/completed",
                json!({"threadId":"stream-thread","turn":{
                    "id":turn,"status":"interrupted","items":[],"error":error
                }}),
            )
            .await;
        let result = tokio::time::timeout(Duration::from_secs(3), stream.recv()).await;
        fixture.shutdown().await;
        let error = result
            .unwrap()
            .unwrap()
            .expect_err("interruption cannot complete");
        assert_eq!(error.kind(), ErrorKind::Cancelled);
        assert_eq!(error.context().phase, ErrorPhase::Cancellation);
        if info.is_null() {
            assert!(error.cause().is_none());
        } else {
            let cause = error
                .cause()
                .expect("interruption retains normalized native cause");
            assert_eq!(cause.kind(), ErrorKind::Integration);
            assert_eq!(
                cause.detail(),
                Some(&if info == "rateLimitExceeded" {
                    ErrorDetail::RateLimited
                } else {
                    ErrorDetail::PolicyRejected
                })
            );
        }
        assert!(!format!("{error:?} {error}").contains("secret-token"));
    }
}

#[tokio::test]
async fn codex_input_blocking_policy_uses_selected_field() {
    for (blocking, timeout, expected) in [
        (None, Value::Null, None),
        (Some(Value::Null), json!(100), None),
        (Some(json!(true)), json!(100), None),
        (Some(json!(false)), Value::Null, Some(-32601)),
        (Some(json!(false)), json!(100), Some(-32601)),
        (Some(json!("false")), Value::Null, Some(-32602)),
        (Some(json!(true)), json!("100"), Some(-32602)),
    ] {
        let mut fixture = CodexFixture::build().await;
        let observed = std::panic::AssertUnwindSafe(async {
            let mut notifications = fixture.conversation.notification_stream().unwrap();
            let mut stream = fixture.conversation.prompt_stream(PromptRequest::new("input").unwrap()).await.unwrap();
            let turn = fixture.peer.turn().await;
            let mut params = json!({"threadId":"stream-thread","turnId":turn,"itemId":"input",
                "autoResolutionMs":timeout,"questions":[{"id":"choice","header":"Choice","question":"First line\nSecond line","isOther":false,"isSecret":false,"options":[{"label":"First\nOption","description":"description"}]}]});
            if let Some(blocking) = blocking { params["isBlocking"] = blocking; }
            fixture.peer.events.send(json!({"id":"input-callback","method":"item/tool/requestUserInput","params":params})).await.unwrap();
            let response = tokio::time::timeout(Duration::from_secs(3), async {
                tokio::select! {
                    response = fixture.peer.responses.recv() => response.unwrap(),
                    notification = notifications.recv() => {
                        let notification = notification.unwrap().unwrap();
                        assert!(expected.is_none(), "unsupported input published an actionable notification");
                        let ConversationNotificationKind::Interaction { body, response_schema, .. } = notification.kind() else { panic!("expected input"); };
                        assert!(body.contains("First line\nSecond line"));
                        assert_eq!(response_schema.as_ref().unwrap()["properties"]["answer"]["enum"], json!(["First\nOption"]));
                        let resolution = fixture.conversation.resolve_notification(notification.id().clone(), NotificationResolution::Submit { content: json!({"answer":"First\nOption"}) }).await;
                        assert!(matches!(resolution, Err(error) if error.kind() == ErrorKind::Conflict));
                        fixture.peer.responses.recv().await.unwrap()
                    }
                }
            }).await.unwrap();
            assert_eq!(response["id"], "input-callback");
            if let Some(code) = expected {
                assert_eq!(response["error"]["code"], code);
                assert!(tokio::time::timeout(Duration::from_millis(20), notifications.recv()).await.is_err());
            } else {
                assert_eq!(response["result"], json!({"answers":{"choice":{"answers":["First\nOption"]}}}));
            }
            fixture.peer.complete(&turn, "input settled").await;
            assert!(matches!(tokio::time::timeout(Duration::from_secs(3), stream.recv()).await.unwrap(), Some(Ok(PromptEvent::Completed(_)))));
        }).catch_unwind().await;
        let cleanup = fixture.settle().await;
        if let Err(panic) = observed {
            std::panic::resume_unwind(panic);
        }
        cleanup.unwrap();
    }
}

#[tokio::test]
async fn codex_stdin_approval_preserves_callback_and_one_shot_decisions() {
    for (kind, title, resolution, decision) in [
        (
            None,
            Some("Command approval"),
            NotificationResolution::Allow,
            "accept",
        ),
        (
            Some(json!("command")),
            Some("Command approval"),
            NotificationResolution::Allow,
            "accept",
        ),
        (
            Some(json!("writeStdin")),
            Some("Terminal input approval"),
            NotificationResolution::Allow,
            "accept",
        ),
        (
            Some(json!("writeStdin")),
            Some("Terminal input approval"),
            NotificationResolution::Deny {
                reason: "Denied".to_owned(),
            },
            "cancel",
        ),
        (
            Some(json!("writeStdin")),
            Some("Terminal input approval"),
            NotificationResolution::Dismiss {
                reason: "Dismissed".to_owned(),
            },
            "cancel",
        ),
        (
            Some(json!("unknown")),
            None,
            NotificationResolution::Allow,
            "",
        ),
        (Some(Value::Null), None, NotificationResolution::Allow, ""),
        (Some(json!(1)), None, NotificationResolution::Allow, ""),
    ] {
        let mut fixture = CodexFixture::build().await;
        let observed = std::panic::AssertUnwindSafe(async {
            let mut notifications = fixture.conversation.notification_stream().unwrap();
            let mut stream = fixture.conversation.prompt_stream(PromptRequest::new("approval").unwrap()).await.unwrap();
            let turn = fixture.peer.turn().await;
            let mut params = json!({"threadId":"stream-thread","turnId":turn,"itemId":"terminal","approvalId":"callback","startedAtMs":1,"availableDecisions":["accept","cancel"]});
            if let Some(kind) = kind { params["kind"] = kind; }
            fixture.peer.request(71, "item/commandExecution/requestApproval", params).await;
            let response = tokio::time::timeout(Duration::from_secs(3), async {
                tokio::select! {
                    response = fixture.peer.responses.recv() => response.unwrap(),
                    notification = notifications.recv() => {
                        let notification = notification.unwrap().unwrap();
                        let ConversationNotificationKind::Interaction { title: actual, .. } = notification.kind() else { panic!("expected approval"); };
                        assert_eq!(Some(actual.as_str()), title);
                        let result = fixture.conversation.resolve_notification(notification.id().clone(), resolution).await;
                        assert!(matches!(result, Err(error) if error.kind() == ErrorKind::Conflict));
                        fixture.peer.responses.recv().await.unwrap()
                    }
                }
            }).await.unwrap();
            assert_eq!(response["id"], 71);
            if title.is_some() { assert_eq!(response["result"], json!({"decision":decision})); }
            else { assert_eq!(response["error"]["code"], -32602); }
            fixture.peer.complete(&turn, "settled").await;
            assert!(matches!(tokio::time::timeout(Duration::from_secs(3), stream.recv()).await.unwrap(), Some(Ok(PromptEvent::Completed(_)))));
        }).catch_unwind().await;
        let cleanup = fixture.settle().await;
        if let Err(panic) = observed {
            std::panic::resume_unwind(panic);
        }
        cleanup.unwrap();
    }
}

#[tokio::test]
async fn codex_reasoning_overrides_reset_across_model_changes_and_reopen() {
    use agents_kit::model::{ModelSelector, ReasoningEffort};

    let peer = CodexPeer::start().await;
    *peer.models.lock().unwrap() = json!({"data":[
        {"model":"selected-model","displayName":"Selected","hidden":false,
         "supportedReasoningEfforts":[{"reasoningEffort":"low"},{"reasoningEffort":"medium"},{"reasoningEffort":"high"}],
         "defaultReasoningEffort":"medium","supportsPersonality":false,"isDefault":true},
        {"model":"alternate-model","displayName":"Alternate","hidden":false,
         "supportedReasoningEfforts":[{"reasoningEffort":"low"},{"reasoningEffort":"high"},{"reasoningEffort":"ultra"}],
         "defaultReasoningEffort":"low","supportsPersonality":false,"isDefault":false}
    ],"nextCursor":null});
    let CodexFixture {
        mut peer,
        agent,
        workspace,
        conversation,
        root,
    } = CodexFixture::build_with_peer(peer).await;
    let workspace_id = workspace.id().clone();
    let conversation_id = conversation.id().clone();
    let mut workspace = Some(workspace);
    let mut conversation = Some(conversation);
    let observed = std::panic::AssertUnwindSafe(async {
        let selections = [
            (None, Some("high"), None, Some("high")),
            (None, None, None, Some("medium")),
            (Some("alternate-model"), Some("ultra"), Some("alternate-model"), Some("ultra")),
            (Some("alternate-model"), None, None, Some("low")),
            (None, None, Some("selected-model"), Some("medium")),
        ];
        for (model, effort, expected_model, expected_effort) in selections {
            let mut request = PromptRequest::new("select exact effort").unwrap();
            if let Some(model) = model {
                request = request.with_model(ModelSelector::new(model).unwrap());
            }
            if let Some(effort) = effort {
                request = request.with_reasoning_effort(ReasoningEffort::new(effort).unwrap());
            }
            let mut stream = conversation.as_ref().unwrap().prompt_stream(request).await.unwrap();
            let turn = peer.turn().await;
            {
                let requests = peer.requests.lock().unwrap();
                let params = &requests.iter().rev().find(|request| request["method"] == "turn/start").unwrap()["params"];
                assert_eq!(params.get("model").and_then(Value::as_str), expected_model);
                assert_eq!(params.get("effort").and_then(Value::as_str), expected_effort);
                assert!(params.get("personality").is_none());
            }
            peer.complete(&turn, "exact selection output").await;
            assert!(matches!(stream.recv().await, Some(Ok(PromptEvent::Completed(response))) if response.output() == "exact selection output"));
            assert!(stream.recv().await.is_none());
        }
        workspace.take().unwrap().close().await.unwrap();
        drop(conversation.take());
        let reopened = workspace.insert(agent.get_workspace(workspace_id).await.unwrap());
        conversation = Some(reopened.get_conversation(conversation_id).await.unwrap());
        let mut stream = conversation.as_ref().unwrap().prompt_stream(PromptRequest::new("reopened default").unwrap()).await.unwrap();
        let turn = peer.turn().await;
        {
            let requests = peer.requests.lock().unwrap();
            let params = &requests.iter().rev().find(|request| request["method"] == "turn/start").unwrap()["params"];
            assert!(params.get("model").is_none());
            assert!(params.get("effort").is_none());
        }
        peer.complete(&turn, "reopened default output").await;
        assert!(matches!(stream.recv().await, Some(Ok(PromptEvent::Completed(response))) if response.output() == "reopened default output"));
        assert_eq!(peer.thread_starts.load(Ordering::SeqCst), 1);
    }).catch_unwind().await;
    let mut cleanup = NativeCleanup::new(Duration::from_secs(10));
    if let Some(conversation) = conversation {
        cleanup.settle(conversation.close()).await;
    }
    if let Some(workspace) = workspace {
        cleanup.settle(workspace.close()).await;
    }
    cleanup.settle(agent.shutdown()).await;
    peer.shutdown().await;
    cleanup
        .settle(async { std::fs::remove_dir_all(root) })
        .await;
    cleanup.finish(observed.map(Ok));
}

#[tokio::test]
async fn codex_reasoning_rejects_unadvertised_effort_and_unsourced_reset() {
    use agents_kit::model::{ModelSelector, ReasoningEffort};

    let mut fixture = CodexFixture::build().await;
    let observed = std::panic::AssertUnwindSafe(async {
        let error = fixture.conversation.prompt(
            PromptRequest::new("unadvertised effort").unwrap()
                .with_reasoning_effort(ReasoningEffort::new("ultra").unwrap()),
        ).await.expect_err("unadvertised effort must fail before native acceptance");
        assert_eq!(error.kind(), ErrorKind::InvalidInput);
        assert!(!fixture.peer.requests.lock().unwrap().iter().any(|request| request["method"] == "turn/start"));

        let mut stream = fixture.conversation.prompt_stream(
            PromptRequest::new("supported explicit selection").unwrap()
                .with_model(ModelSelector::new("selected-model").unwrap())
                .with_reasoning_effort(ReasoningEffort::medium()),
        ).await.unwrap();
        let turn = fixture.peer.turn().await;
        fixture.peer.complete(&turn, "accepted").await;
        assert!(matches!(stream.recv().await, Some(Ok(PromptEvent::Completed(response))) if response.output() == "accepted"));
        fixture.peer.models.lock().unwrap()["data"][0]["isDefault"] = json!(false);
        let error = fixture.conversation.prompt(PromptRequest::new("unsourced reset").unwrap()).await
            .expect_err("omission cannot preserve a sticky override without a sourced default");
        assert_eq!(error.kind(), ErrorKind::Unsupported);
        assert_eq!(fixture.peer.requests.lock().unwrap().iter().filter(|request| request["method"] == "turn/start").count(), 1);
    }).catch_unwind().await;
    let cleanup = fixture.settle().await;
    if let Err(panic) = observed {
        std::panic::resume_unwind(panic);
    }
    cleanup.unwrap();
}

#[tokio::test]
async fn codex_retired_personality_cannot_mutate_native_state() {
    let mut fixture = CodexFixture::build().await;
    let observed = std::panic::AssertUnwindSafe(async {
        let models = fixture.agent.list_models().await.unwrap();
        assert_eq!(models[0].selector().as_str(), "selected-model");
        assert!(
            models[0].personalities().is_empty(),
            "deprecated source flag cannot advertise a personality"
        );
        assert!(models.iter().all(|model| model.personalities().is_empty()));
        let workspace_info = fixture.workspace.info().await.unwrap();
        for name in ["none", "friendly", "pragmatic"] {
            let personality = agents_kit::model::PersonalitySelector::new(name).unwrap();
            let before = fixture.peer.requests.lock().unwrap().len();
            let error = fixture
                .conversation
                .prompt(
                    PromptRequest::new("unsupported")
                        .unwrap()
                        .with_personality(personality.clone()),
                )
                .await
                .expect_err("retired personality");
            assert_eq!(error.kind(), ErrorKind::Unsupported);
            assert_eq!(
                fixture.peer.requests.lock().unwrap().len(),
                before,
                "personality must fail before native mutation"
            );
            assert!(
                fixture.peer.turns.try_recv().is_err(),
                "personality must fail before native turn"
            );
            let result = fixture
                .workspace
                .new_conversation(
                    NewConversation::new(
                        None,
                        Some(WorkspaceDefaults::empty().with_personality(personality.clone())),
                        vec![],
                    )
                    .unwrap(),
                )
                .await;
            let error = match result {
                Err(error) => error,
                Ok(conversation) => {
                    conversation.close().await.unwrap();
                    panic!("retired defaults were accepted");
                }
            };
            assert_eq!(error.kind(), ErrorKind::Unsupported);
            assert_eq!(fixture.peer.requests.lock().unwrap().len(), before);
            let defaults = WorkspaceDefaults::empty().with_personality(personality);
            let created = fixture
                .agent
                .new_workspace(
                    NewWorkspace::new(
                        "retired defaults",
                        workspace_info.context().clone(),
                        defaults.clone(),
                    )
                    .unwrap(),
                )
                .await;
            let error = match created {
                Err(error) => error,
                Ok(workspace) => {
                    workspace.close().await.unwrap();
                    panic!("unsupported workspace personality accepted")
                }
            };
            assert_eq!(error.kind(), ErrorKind::Unsupported);
            let update = UpdateWorkspaceRequest::new(
                workspace_info.id().clone(),
                workspace_info.revision(),
                "retired defaults",
                workspace_info.context().clone(),
                defaults,
            )
            .unwrap();
            assert!(
                matches!(fixture.agent.check_workspace_update(&update).await,
                Err(error) if error.kind() == ErrorKind::Unsupported)
            );
            assert!(matches!(fixture.agent.update_workspace(update).await,
                Err(error) if error.kind() == ErrorKind::Unsupported));
            assert_eq!(
                fixture.workspace.info().await.unwrap().revision(),
                workspace_info.revision()
            );
            assert_eq!(fixture.peer.requests.lock().unwrap().len(), before);
        }
    })
    .catch_unwind()
    .await;
    fixture.finish_release(observed, None).await;
}

#[tokio::test]
async fn codex_persisted_personality_intent_rejects_reopen_before_connection() {
    for namespace in [
        "agents_kit_workspaces_v1",
        "agents_kit_conversations_v1",
        "agents_kit_codex_native_selection_v1",
    ] {
        let store = StateStore::connect(StateStoreConfig::Lance(LanceStateStoreConfig::memory()))
            .await
            .unwrap();
        let CodexFixture {
            mut peer,
            agent,
            workspace,
            conversation,
            root,
        } = CodexFixture::build_with_store(CodexPeer::start().await, store.clone()).await;
        let agent_id = agent.id();
        let config = AgentConfig::new(
            CodexConfig::tcp(peer.address, Duration::from_secs(3), Duration::from_secs(3))
                .unwrap()
                .into(),
            Duration::from_secs(3),
            NonZeroUsize::MIN,
        )
        .unwrap();
        let mut agent = Some(agent);
        let mut workspace = Some(workspace);
        let mut conversation = Some(conversation);
        let observed = NativeCleanup::observe(
            tokio::time::Instant::now() + Duration::from_secs(10),
            async {
                // Obtain a real persisted selection before simulating the prior
                // release's explicit personality in its unchanged durable format.
                let mut prompt = conversation
                    .as_ref()
                    .unwrap()
                    .prompt_stream(PromptRequest::new("select model").unwrap().with_model(
                        agents_kit::model::ModelSelector::new("selected-model").unwrap(),
                    ))
                    .await
                    .unwrap();
                let turn = peer.turn().await;
                peer.complete(&turn, "selected").await;
                assert!(matches!(
                    prompt.recv().await,
                    Some(Ok(PromptEvent::Completed(_)))
                ));
                workspace.take().unwrap().close().await.unwrap();
                drop(conversation.take());
                agent.take().unwrap().shutdown().await.unwrap();
                let mut page = store
                    .list(StateListRequest::new(namespace).unwrap())
                    .await
                    .unwrap();
                assert_eq!(page.records.len(), 1, "one durable intent in {namespace}");
                let key = page.records.pop().unwrap().record.key;
                let mut transaction = store.begin_transaction().await.unwrap();
                let mut record = transaction
                    .load(key.clone())
                    .await
                    .unwrap()
                    .expect("existing durable intent")
                    .record;
                let value = Arc::make_mut(&mut record.value);
                let field = if namespace == "agents_kit_codex_native_selection_v1" {
                    "selection"
                } else {
                    "defaults"
                };
                if value[field].is_null() {
                    value[field] =
                        json!({"model":null,"reasoning_effort":null,"knowledge_policy":null});
                }
                value[field]["personality"] = json!("friendly");
                transaction.put(record.clone()).await.unwrap();
                transaction.commit().await.unwrap();
                let before = peer.initializations.load(Ordering::SeqCst);
                let result =
                    AgentBuilder::reopen(config, AgentStorage::new(store.clone()), agent_id)
                        .build()
                        .await;
                let error = match result {
                    Err(error) => error,
                    Ok(reopened) => {
                        agent = Some(reopened);
                        panic!("persisted personality was silently discarded");
                    }
                };
                assert_eq!(error.kind(), ErrorKind::Unsupported, "{namespace}");
                assert_eq!(
                    peer.initializations.load(Ordering::SeqCst),
                    before,
                    "rejection precedes native attachment"
                );
                assert_eq!(
                    store.load(key).await.unwrap().unwrap().record.value,
                    record.value,
                    "caller intent is preserved"
                );
            },
        )
        .await;
        let mut cleanup = NativeCleanup::new(Duration::from_secs(10));
        if let Some(conversation) = conversation {
            cleanup.settle(conversation.close()).await;
        }
        if let Some(workspace) = workspace {
            cleanup.settle(workspace.close()).await;
        }
        if let Some(agent) = agent {
            cleanup.settle(agent.shutdown()).await;
        }
        peer.shutdown().await;
        cleanup
            .settle(async { std::fs::remove_dir_all(root) })
            .await;
        cleanup.finish(observed);
    }
}

#[tokio::test]
async fn codex_foreground_requires_active_controls_without_retired_fanout() {
    let peer = CodexPeer::start().await;
    *peer.features.lock().unwrap() = json!({"data":[{"name":"multi_agent","enabled":false},{"name":"multi_agent_v2","enabled":false}],"nextCursor":null});
    let fixture = CodexFixture::build_with_peer(peer).await;
    let requests = fixture.peer.requests.lock().unwrap().clone();
    fixture.shutdown().await;
    let start = requests
        .iter()
        .find(|request| request["method"] == "thread/start")
        .unwrap();
    assert_eq!(start["params"]["config"]["features.multi_agent"], false);
    assert_eq!(start["params"]["config"]["features.multi_agent_v2"], false);
    assert!(
        start["params"]["config"]
            .get("features.enable_fanout")
            .is_none()
    );
}

impl CodexFixture {
    fn release_notifications() -> Vec<(&'static str, Value, Option<ErrorKind>, &'static str)> {
        vec![
            (
                "thread/readState/changed",
                json!({"threadId":"stream-thread","readState":{"firstUnread":null,"revision":"opaque-revision"}}),
                None,
                "readState",
            ),
            (
                "thread/reverted",
                json!({"threadId":"stream-thread"}),
                Some(ErrorKind::InvalidState),
                "threadId",
            ),
            (
                "thread/queue/changed",
                json!({"threadId":"stream-thread"}),
                Some(ErrorKind::Unsupported),
                "threadId",
            ),
            (
                "thread/attachment/updated",
                json!({"threadId":"stream-thread","attachmentType":"reference","identityKey":"key","attachmentId":"attachment","operation":"created"}),
                None,
                "operation",
            ),
            (
                "thread/prediction/updated",
                json!({"threadId":"stream-thread","sourceTurnId":"turn-1","result":{"type":"completed","text":"prediction"}}),
                Some(ErrorKind::Unsupported),
                "result",
            ),
            (
                "project/changed",
                json!({"projectId":"project","changeType":"updated"}),
                None,
                "changeType",
            ),
            (
                "thread/project/updated",
                json!({"threadId":"stream-thread","projectId":"project"}),
                None,
                "projectId",
            ),
            (
                "thread/environment/connected",
                json!({"threadId":"stream-thread","environmentId":"environment"}),
                None,
                "environmentId",
            ),
            (
                "thread/environment/disconnected",
                json!({"threadId":"stream-thread","environmentId":"environment"}),
                None,
                "environmentId",
            ),
            (
                "autoApprovalReview/strictReviewRequired",
                json!({"threadId":"stream-thread","turnId":"turn-1","startedAtMs":1}),
                None,
                "startedAtMs",
            ),
            (
                "rawResponse/completed",
                json!({"threadId":"stream-thread","turnId":"turn-1","responseId":"response","usage":null,"usageMetadata":null}),
                None,
                "responseId",
            ),
            (
                "mcpServer/event/stream/notification",
                json!({"subscriptionId":"subscription","notification":{"method":"updated","params":{}}}),
                Some(ErrorKind::Unsupported),
                "notification",
            ),
            (
                "account/gatewayOAuth/changed",
                json!({"authUrl":"https://private.invalid","providerId":"provider","status":"started","error":null}),
                None,
                "status",
            ),
            (
                "modelProvider/authRecoveryStarted",
                json!({"threadId":"stream-thread","turnId":"turn-1","provider":"provider","message":"secret-token"}),
                None,
                "message",
            ),
            (
                "modelProvider/authRecoveryCompleted",
                json!({"threadId":"stream-thread","turnId":"turn-1","provider":"provider","message":"secret-token"}),
                None,
                "message",
            ),
            (
                "thread/realtime/item/started",
                json!({"threadId":"stream-thread","item":{"id":"item","realtimeSessionId":"session","type":"realtimeSessionStarted"}}),
                Some(ErrorKind::Unsupported),
                "item",
            ),
            (
                "thread/realtime/item/transcript/delta",
                json!({"threadId":"stream-thread","itemId":"item","delta":"not portable output"}),
                Some(ErrorKind::Unsupported),
                "delta",
            ),
            (
                "thread/realtime/item/completed",
                json!({"threadId":"stream-thread","item":{"id":"item","realtimeSessionId":"session","type":"realtimeSessionClosed","outcome":"ended"}}),
                Some(ErrorKind::Unsupported),
                "item",
            ),
        ]
    }

    async fn assert_release_event(method: &str, params: Value, expected: Option<ErrorKind>) {
        let mut fixture = Self::build().await;
        let observed = std::panic::AssertUnwindSafe(async {
            let mut notifications = fixture.conversation.notification_stream().unwrap();
            let mut stream = fixture.conversation.prompt_stream(PromptRequest::new("event").unwrap()).await.unwrap();
            let turn = fixture.peer.turn().await;
            fixture.peer.notify("item/agentMessage/delta", json!({"threadId":"stream-thread","turnId":turn,"itemId":"answer","delta":"accepted"})).await;
            assert!(matches!(tokio::time::timeout(Duration::from_secs(3), stream.recv()).await.unwrap(), Some(Ok(PromptEvent::OutputDelta { .. }))));
            if expected.is_none() {
                fixture.peer.notify("item/completed", json!({"threadId":"stream-thread","turnId":turn,"completedAtMs":1,
                    "item":{"id":"answer","type":"agentMessage","text":"actual terminal","phase":"final_answer"}})).await;
                fixture.peer.notify(method, params.clone()).await;
            }
            fixture.peer.notify(method, params).await;
            if let Some(expected) = expected {
                let error = tokio::time::timeout(Duration::from_secs(3), stream.recv()).await.expect("selected event must terminate honestly").unwrap().expect_err("event must not complete");
                assert_eq!(error.kind(), expected, "{method}");
                assert!(!format!("{error:?}").contains("secret-token"));
            } else {
                assert!(tokio::time::timeout(Duration::from_millis(25), stream.recv()).await.is_err(), "metadata must not complete or emit output");
                assert!(tokio::time::timeout(Duration::from_millis(25), notifications.recv()).await.is_err(), "private metadata cannot invent public notifications");
                fixture.peer.notify("turn/completed", json!({"threadId":"stream-thread","turn":{"id":turn,"status":"completed","items":[],"error":null}})).await;
                assert!(matches!(tokio::time::timeout(Duration::from_secs(3), stream.recv()).await.unwrap(), Some(Ok(PromptEvent::Completed(response))) if response.output() == "actual terminal"));
                assert!(stream.recv().await.is_none());
                assert!(tokio::time::timeout(Duration::from_millis(25), notifications.recv()).await.is_err(), "repeated metadata cannot publish after completion");
            }
        }).catch_unwind().await;
        let cleanup = fixture.settle().await;
        if let Err(panic) = observed {
            std::panic::resume_unwind(panic);
        }
        if expected.is_none() {
            cleanup.unwrap();
        }
    }
}

#[tokio::test]
async fn codex_selected_notification_additions_have_explicit_outcomes() {
    for (method, params, expected, _) in CodexFixture::release_notifications() {
        CodexFixture::assert_release_event(method, params, expected).await;
    }
}

#[tokio::test]
async fn codex_selected_notification_additions_reject_malformed_payloads() {
    for (method, mut params, _, field) in CodexFixture::release_notifications() {
        params[field] = json!([]);
        CodexFixture::assert_release_event(method, params, Some(ErrorKind::Protocol)).await;
    }
}

#[tokio::test]
async fn codex_read_state_positions_remain_private_until_authoritative_terminal() {
    for read_state in [
        json!({"revision":"opaque / revision"}),
        json!({"firstUnread":null,"revision":""}),
        json!({"firstUnread":{"type":"threadStart"},"revision":"not-a-number"}),
        json!({"firstUnread":{"type":"turn","turnId":"earlier-turn"},"revision":"historical"}),
    ] {
        CodexFixture::assert_release_event(
            "thread/readState/changed",
            json!({"threadId":"stream-thread","readState":read_state}),
            None,
        )
        .await;
    }
}

#[tokio::test]
async fn codex_read_state_rejects_malformed_nested_payloads() {
    for read_state in [
        None,
        Some(Value::Null),
        Some(json!([])),
        Some(json!("receipt")),
        Some(json!({})),
        Some(json!({"revision":null})),
        Some(json!({"revision":1})),
        Some(json!({"revision":"opaque","firstUnread":false})),
        Some(json!({"revision":"opaque","firstUnread":[]})),
        Some(json!({"revision":"opaque","firstUnread":{}})),
        Some(json!({"revision":"opaque","firstUnread":{"type":null}})),
        Some(json!({"revision":"opaque","firstUnread":{"type":"unknown"}})),
        Some(json!({"revision":"opaque","firstUnread":{"type":"turn"}})),
        Some(json!({"revision":"opaque","firstUnread":{"type":"turn","turnId":null}})),
        Some(json!({"revision":"opaque","firstUnread":{"type":"turn","turnId":1}})),
        Some(json!({"revision":"opaque","firstUnread":{"type":"turn","turnId":""}})),
    ] {
        let mut params = json!({"threadId":"stream-thread"});
        if let Some(read_state) = read_state {
            params["readState"] = read_state;
        }
        CodexFixture::assert_release_event(
            "thread/readState/changed",
            params,
            Some(ErrorKind::Protocol),
        )
        .await;
    }
}

#[tokio::test]
async fn codex_read_state_requires_valid_thread_identity() {
    for thread_id in [
        None,
        Some(Value::Null),
        Some(json!(1)),
        Some(json!("")),
        Some(json!(" thread ")),
    ] {
        let mut params = json!({"readState":{"revision":"opaque"}});
        if let Some(thread_id) = thread_id {
            params["threadId"] = thread_id;
        }
        CodexFixture::assert_release_event(
            "thread/readState/changed",
            params,
            Some(ErrorKind::Protocol),
        )
        .await;
    }
}

#[tokio::test]
async fn codex_async_agent_items_are_not_portable_final_answers() {
    for (field, value, expected) in [
        ("delivery", json!("async"), ErrorKind::Unsupported),
        (
            "questions",
            json!([{"title":"First line\nSecond line","options":["Option\nOne"]}]),
            ErrorKind::Unsupported,
        ),
        ("delivery", json!("unknown"), ErrorKind::Protocol),
        ("questions", json!([{"title":9}]), ErrorKind::Protocol),
    ] {
        let mut item =
            json!({"type":"agentMessage","id":"answer","phase":"final_answer","text":"not final"});
        item[field] = value;
        CodexFixture::assert_release_event(
            "item/completed",
            json!({"threadId":"stream-thread","turnId":"turn-1","completedAtMs":1,"item":item}),
            Some(expected),
        )
        .await;
    }
}

#[tokio::test]
async fn codex_function_output_is_private_non_answer_data() {
    CodexFixture::assert_release_event("item/completed", json!({"threadId":"stream-thread","turnId":"turn-1","completedAtMs":1,
        "item":{"type":"functionCallOutput","id":"output","name":"lookup","namespace":null,"output":[{"type":"input_text","text":"not final"}]}}), None).await;
}

impl CodexFixture {
    async fn recovered_result(
        status: &str,
        error: Value,
        items: Vec<Value>,
    ) -> Result<agents_kit::prompt::PromptResponse, agents_kit::KitError> {
        let peer = CodexPeer::start_with(FirstStart::RecoveredTurn {
            status: status.to_owned(),
            error,
            items,
        })
        .await;
        let fixture = Self::build_with_peer(peer).await;
        let observed = tokio::time::timeout(
            Duration::from_secs(3),
            fixture
                .conversation
                .prompt(PromptRequest::new("recover selected items").unwrap()),
        )
        .await;
        let cleanup = fixture.settle().await;
        let result = observed.expect("bounded history recovery");
        if result.is_ok() {
            cleanup.unwrap();
        }
        result
    }
}

#[tokio::test]
async fn codex_history_async_items_match_live_rejection() {
    for (field, value, expected) in [
        ("delivery", json!("async"), ErrorKind::Unsupported),
        ("questions", json!([]), ErrorKind::Unsupported),
        (
            "questions",
            json!([{"title":"private question", "options":null}]),
            ErrorKind::Unsupported,
        ),
        ("delivery", json!("unknown"), ErrorKind::Protocol),
        ("questions", json!([{"title":9}]), ErrorKind::Protocol),
        (
            "questions",
            json!([{"title":"question", "extra":true}]),
            ErrorKind::Protocol,
        ),
    ] {
        let mut item =
            json!({"type":"agentMessage","text":"not a final answer","phase":"final_answer"});
        item[field] = value;
        let error = CodexFixture::recovered_result("completed", Value::Null, vec![item])
            .await
            .expect_err("async history must not become a final answer");
        assert_eq!(error.kind(), expected);
    }
}

#[tokio::test]
async fn codex_function_output_shapes_match_live_and_history() {
    for output in [
        json!("private output"),
        json!([]),
        json!([
            {"type":"input_text","text":"private output"},
            {"type":"input_image","image_url":"data:private","detail":"original"},
            {"type":"input_image","file_id":"private-file"},
            {"type":"input_audio","audio_url":"private-audio"},
            {"type":"encrypted_content","encrypted_content":"private-ciphertext"}
        ]),
    ] {
        let item = json!({"type":"functionCallOutput","id":"output","name":"lookup","namespace":null,"output":output});
        for (method, time) in [
            ("item/started", "startedAtMs"),
            ("item/completed", "completedAtMs"),
        ] {
            let mut params = json!({"threadId":"stream-thread","turnId":"turn-1","item":item});
            params[time] = json!(1);
            CodexFixture::assert_release_event(method, params, None).await;
        }
        let answer = json!({"type":"agentMessage","text":"exact final", "phase":"final_answer", "delivery":null,"questions":null});
        let response = CodexFixture::recovered_result("completed", Value::Null, vec![answer, item])
            .await
            .unwrap();
        assert_eq!(response.output(), "exact final");
    }
    for item in [
        json!({"type":"functionCallOutput","name":"lookup","output":"text"}),
        json!({"type":"functionCallOutput","id":"output","output":"text"}),
        json!({"type":"functionCallOutput","id":"output","name":"lookup","namespace":4,"output":"text"}),
        json!({"type":"functionCallOutput","id":"output","name":"lookup","output":{}}),
        json!({"type":"functionCallOutput","id":"output","name":"lookup","output":[{"type":"input_image"}]}),
        json!({"type":"functionCallOutput","id":"output","name":"lookup","output":[{"type":"input_text","text":4}]}),
    ] {
        CodexFixture::assert_release_event(
            "item/completed",
            json!({"threadId":"stream-thread","turnId":"turn-1","completedAtMs":1,"item":item}),
            Some(ErrorKind::Protocol),
        )
        .await;
        assert_eq!(
            CodexFixture::recovered_result("completed", Value::Null, vec![item])
                .await
                .unwrap_err()
                .kind(),
            ErrorKind::Protocol
        );
    }
}

#[tokio::test]
async fn codex_permission_locations_reject_nonlocal_without_actionable_notification() {
    let mut cases = vec![
        (json!("file://remote-host/share/project"), -32601),
        (json!("file:///C:/project"), -32601),
        (json!("relative/path"), -32601),
        (json!(4), -32602),
    ];
    if std::path::MAIN_SEPARATOR == '/' {
        // The wire convention is Windows for any two leading separators,
        // including spellings that this host also considers absolute.
        for cwd in [
            r"C:\project",
            r"//remote-host/share/project",
            r"/\remote-host/share/project",
            r"\/remote-host/share/project",
            r"\\remote-host\share\project",
            r"\\?\C:\project",
            r"\\.\NUL",
        ] {
            cases.push((json!(cwd), -32601));
        }
        for cwd in ["//", "//server", "//server/", "///server/share"] {
            cases.push((json!(cwd), -32602));
        }
    }
    for (cwd, expected) in cases {
        let mut fixture = CodexFixture::build().await;
        let observed = std::panic::AssertUnwindSafe(async {
            let mut notifications = fixture.conversation.notification_stream().unwrap();
            let mut stream = fixture.conversation.prompt_stream(PromptRequest::new("permission location").unwrap()).await.unwrap();
            let turn = fixture.peer.turn().await;
            fixture.peer.request(75, "item/permissions/requestApproval", json!({"threadId":"stream-thread","turnId":turn,"itemId":"permissions","startedAtMs":1,"cwd":cwd,"permissions":{}})).await;
            let response = tokio::time::timeout(Duration::from_secs(3), fixture.peer.responses.recv()).await.unwrap().unwrap();
            assert_eq!(response["id"], 75);
            assert_eq!(response["error"]["code"], expected, "{cwd}");
            assert!(tokio::time::timeout(Duration::from_millis(25), notifications.recv()).await.is_err());
            fixture.peer.complete(&turn, "settled").await;
            assert!(matches!(stream.recv().await, Some(Ok(PromptEvent::Completed(_)))));
        }).catch_unwind().await;
        let cleanup = fixture.settle().await;
        if let Err(panic) = observed {
            std::panic::resume_unwind(panic);
        }
        cleanup.unwrap();
    }
}

#[tokio::test]
async fn codex_known_error_shapes_cannot_escape_as_unknown_errors() {
    for error in [
        json!({"message":"secret-token", "codexErrorInfo":{"rateLimitExceeded":{"invalid":true}}}),
        json!({"message":"secret-token", "codexErrorInfo":{"httpConnectionFailed":{"httpStatusCode":"503"}}}),
        json!({"message":"secret-token", "codexErrorInfo":{"rateLimitExceeded":null,"future":null}}),
        json!({"message":"secret-token", "codexErrorInfo":12}),
        json!({"message":"secret-token", "codexErrorInfo":[]}),
        json!({"message":"secret-token", "codexErrorInfo":"misalignmentPolicyViolation", "misalignment":{"steer":{}}}),
        json!({"message":"secret-token", "misalignment":{"reviewTarget":42}}),
        json!({"message":"secret-token", "misalignment":{"errorType":[]}}),
        json!({"message":"secret-token", "misalignment":{"detailedExplanation":false}}),
    ] {
        CodexFixture::assert_release_event("turn/completed", json!({"threadId":"stream-thread","turn":{"id":"turn-1","status":"failed","items":[],"error":error}}), Some(ErrorKind::Protocol)).await;
        let failure = CodexFixture::recovered_result("failed", error, vec![])
            .await
            .unwrap_err();
        assert_eq!(failure.kind(), ErrorKind::Protocol);
        assert!(!format!("{failure:?}").contains("secret-token"));
    }
}

#[tokio::test]
async fn codex_interrupted_history_preserves_normalized_cause() {
    let error = CodexFixture::recovered_result(
        "interrupted",
        json!({"message":"secret-token", "codexErrorInfo":"rateLimitExceeded"}),
        vec![],
    )
    .await
    .unwrap_err();
    assert_eq!(error.kind(), ErrorKind::Cancelled);
    assert_eq!(error.context().phase, ErrorPhase::Cancellation);
    let cause = error.cause().expect("history retains native cause");
    assert_eq!(cause.detail(), Some(&ErrorDetail::RateLimited));
    assert_eq!(cause.context().phase, ErrorPhase::ModelGeneration);
    assert!(!format!("{error:?}").contains("secret-token"));
}

#[tokio::test]
async fn codex_delayed_interruption_requires_matching_normalized_history_cause() {
    HistoricalTerminalCase::MatchingCause.run().await;
    HistoricalTerminalCase::DifferentCause.run().await;
}

#[tokio::test]
async fn codex_shared_item_callbacks_preserve_distinct_rpc_ids_and_no_resend() {
    let store = StateStore::connect(StateStoreConfig::Lance(LanceStateStoreConfig::memory()))
        .await
        .unwrap();
    let peer = CodexPeer::start().await;
    let mut fixture = CodexFixture::build_with_store(peer, store.clone()).await;
    let observed = NativeCleanup::observe(tokio::time::Instant::now() + Duration::from_secs(10), async {
        let mut notifications = fixture.conversation.notification_stream().unwrap();
        let mut stream = fixture.conversation.prompt_stream(PromptRequest::new("shared item").unwrap()).await.unwrap();
        let turn = fixture.peer.turn().await;
        for id in [json!(71), json!("71")] {
            fixture.peer.events.send(json!({"id":id,"method":"item/commandExecution/requestApproval", "params":{
                "threadId":"stream-thread","turnId":turn,"itemId":"same-item", "kind":"writeStdin",
                "startedAtMs":1, "availableDecisions":["accept","cancel"]
            }})).await.unwrap();
        }
        let notification = notifications.recv().await.unwrap().unwrap();
        loop {
            let page = store.list(StateListRequest::new("agents_kit_codex_continuations_v1").unwrap()).await.unwrap();
            if page.records.len() == 2 { break; }
            tokio::task::yield_now().await;
        }
        let result = fixture.conversation.resolve_notification(notification.id().clone(), NotificationResolution::Allow).await;
        assert!(matches!(result, Err(error) if error.kind() == ErrorKind::Conflict));
        let response = fixture.peer.responses.recv().await.unwrap();
        assert_eq!(response["id"], json!(71));
        assert_eq!(response["result"], json!({"decision":"accept"}));
        fixture.peer.notify("serverRequest/resolved", json!({"threadId":"stream-thread", "requestId":71})).await;
        let duplicate = fixture.conversation.resolve_notification(notification.id().clone(), NotificationResolution::Allow).await;
        assert!(matches!(duplicate, Err(error) if error.kind() == ErrorKind::Conflict));
        assert!(tokio::time::timeout(Duration::from_millis(25), fixture.peer.responses.recv()).await.is_err());
        fixture.conversation.abort().await.unwrap();
        assert!(matches!(stream.recv().await, Some(Err(error)) if error.kind() == ErrorKind::Cancelled));
        assert!(store.list(StateListRequest::new("agents_kit_codex_continuations_v1").unwrap()).await.unwrap().records.is_empty(), "terminal lifecycle settles both distinct callbacks");
        let late = fixture.conversation.resolve_notification(notification.id().clone(), NotificationResolution::Allow).await;
        assert!(matches!(late, Err(error) if matches!(error.kind(), ErrorKind::Conflict | ErrorKind::NotFound)));
        assert!(tokio::time::timeout(Duration::from_millis(25), fixture.peer.responses.recv()).await.is_err());
    }).await;
    let cleanup = fixture.settle().await;
    NativeCleanup::new(Duration::from_secs(10)).finish(observed);
    cleanup.unwrap();
}

#[tokio::test]
async fn codex_added_notifications_cannot_adopt_foreign_thread_ownership() {
    for (method, mut params, expected, _) in CodexFixture::release_notifications() {
        if params.get("threadId").is_some() {
            params["threadId"] = json!("foreign-thread");
            // Passive metadata and foreign history replacement do not acquire an
            // owner. Unsupported execution still requires an existing owner.
            let foreign_error =
                (expected == Some(ErrorKind::Unsupported)).then_some(ErrorKind::InvalidState);
            CodexFixture::release_event(method, params, foreign_error).await;
        }
    }
}

#[tokio::test]
async fn codex_error_bearing_interruption_allows_exact_reopen() {
    let peer = CodexPeer::start_with(FirstStart::DeferredInterruptTerminal).await;
    let CodexFixture {
        mut peer,
        agent,
        workspace,
        conversation,
        root,
    } = CodexFixture::build_with_peer(peer).await;
    let workspace_id = workspace.id().clone();
    let conversation_id = conversation.id().clone();
    let mut workspace = Some(workspace);
    let mut conversation = Some(conversation);
    let observed = NativeCleanup::observe(tokio::time::Instant::now() + Duration::from_secs(10), async {
        let mut stream = conversation.as_ref().unwrap().prompt_stream(PromptRequest::new("interrupt then reopen").unwrap()).await.unwrap();
        let turn = peer.turn().await;
        peer.notify("turn/completed", json!({"threadId":"stream-thread","turn":{
            "id":turn,"status":"interrupted","items":[],"error":{"message":"private-native-message","codexErrorInfo":"tooManyDenials"}
        }})).await;
        let error = stream.recv().await.unwrap().unwrap_err();
        assert_eq!(error.kind(), ErrorKind::Cancelled);
        assert_eq!(error.cause().unwrap().detail(), Some(&ErrorDetail::PolicyRejected));
        workspace.take().unwrap().close().await.unwrap();
        drop(conversation.take());
        let reopened = workspace.insert(agent.get_workspace(workspace_id).await.unwrap());
        let reopened = conversation.insert(reopened.get_conversation(conversation_id).await.unwrap());
        let mut next = reopened.prompt_stream(PromptRequest::new("reopened").unwrap()).await.unwrap();
        let next_turn = peer.turn().await;
        peer.complete(&next_turn, "exact reopened output").await;
        assert!(matches!(next.recv().await, Some(Ok(PromptEvent::Completed(response))) if response.output() == "exact reopened output"));
        assert_eq!(peer.thread_starts.load(Ordering::SeqCst), 1, "reopen retains native identity");
        {
            let requests = peer.requests.lock().unwrap();
            let start = &requests.iter().find(|request| request["method"] == "thread/start").unwrap()["params"];
            let resumes = requests.iter().filter(|request| request["method"] == "thread/resume").collect::<Vec<_>>();
            assert_eq!(resumes.len(), 1);
            let resume = &resumes[0]["params"];
            assert_eq!(resume["threadId"], "stream-thread");
            assert_eq!(resume["cwd"], json!(root));
            assert_eq!(resume["runtimeWorkspaceRoots"], json!([root]));
            assert_eq!(resume["permissions"], ":danger-full-access");
            assert_eq!(resume["excludeTurns"], true);
            for field in ["cwd", "runtimeWorkspaceRoots", "permissions", "config"] {
                assert_eq!(resume[field], start[field], "resume must preserve {field}");
            }
            assert_eq!(resume["config"]["features.multi_agent"], false);
            assert_eq!(resume["config"]["features.multi_agent_v2"], false);
            assert_eq!(resume["config"]["suppress_unstable_features_warning"], true);
            assert!(resume.get("sandbox").is_none());
            let lists = requests.iter().filter(|request| request["method"] == "thread/list").collect::<Vec<_>>();
            assert!(!lists.is_empty(), "reopen cleanup inspects native descendants");
            assert!(lists.iter().all(|request| request["params"].get("excludedThreadIds").is_none()));
        }
        assert!(peer.requests.lock().unwrap().iter().any(|request| request["method"] == "thread/read" && request["params"]["threadId"] == "stream-thread"));
    }).await;
    let mut cleanup = NativeCleanup::new(Duration::from_secs(10));
    if let Some(conversation) = conversation {
        cleanup.settle(conversation.close()).await;
    }
    if let Some(workspace) = workspace {
        cleanup.settle(workspace.close()).await;
    }
    cleanup.settle(agent.shutdown()).await;
    peer.shutdown().await;
    cleanup
        .settle(async { std::fs::remove_dir_all(root) })
        .await;
    cleanup.finish(observed);
}

#[tokio::test]
async fn codex_reopen_rejects_changed_effective_policy_before_publication() {
    for overrides in [
        json!({"sandbox":{"type":"readOnly","networkAccess":false}}),
        json!({"sandbox":{"type":"externalSandbox","networkAccess":"restricted"}}),
        json!({"activePermissionProfile":{"id":":read-only","extends":null}}),
        json!({"activePermissionProfile":{"id":":danger-full-access","extends":"other-profile"}}),
        json!({"activePermissionProfile":null}),
    ] {
        let CodexFixture {
            peer,
            agent,
            workspace,
            conversation,
            root,
        } = CodexFixture::build().await;
        let workspace_id = workspace.id().clone();
        let conversation_id = conversation.id().clone();
        let mut workspace = Some(workspace);
        let mut conversation = Some(conversation);
        let observed = NativeCleanup::observe(
            tokio::time::Instant::now() + Duration::from_secs(10),
            async {
                workspace.take().unwrap().close().await.unwrap();
                drop(conversation.take());
                *peer.resume_overrides.lock().unwrap() = overrides.as_object().unwrap().clone();
                let reopened = workspace.insert(agent.get_workspace(workspace_id).await.unwrap());
                match reopened.get_conversation(conversation_id).await {
                    Err(error) => assert_eq!(error.kind(), ErrorKind::InvalidState),
                    Ok(handle) => {
                        conversation = Some(handle);
                        panic!("mismatched effective policy must reject before handle publication");
                    }
                }
                assert_eq!(peer.thread_starts.load(Ordering::SeqCst), 1);
                let requests = peer.requests.lock().unwrap();
                assert_eq!(
                    requests
                        .iter()
                        .filter(|request| request["method"] == "thread/resume")
                        .count(),
                    1
                );
                assert!(
                    !requests
                        .iter()
                        .any(|request| request["method"] == "turn/start")
                );
            },
        )
        .await;
        peer.resume_overrides.lock().unwrap().clear();
        let mut cleanup = NativeCleanup::new(Duration::from_secs(10));
        if let Some(conversation) = conversation {
            cleanup.settle(conversation.close()).await;
        }
        if let Some(workspace) = workspace {
            cleanup.settle(workspace.close()).await;
        }
        cleanup.settle(agent.shutdown()).await;
        peer.shutdown().await;
        cleanup
            .settle(async { std::fs::remove_dir_all(root) })
            .await;
        cleanup.finish(observed);
    }
}

#[tokio::test]
async fn codex_shutdown_rejection_is_private_and_does_not_replay_resume() {
    let CodexFixture {
        peer,
        agent,
        workspace,
        conversation,
        root,
    } = CodexFixture::build().await;
    let workspace_id = workspace.id().clone();
    let conversation_id = conversation.id().clone();
    let mut workspace = Some(workspace);
    let mut conversation = Some(conversation);
    let observed = NativeCleanup::observe(
        tokio::time::Instant::now() + Duration::from_secs(10),
        async {
            workspace.take().unwrap().close().await.unwrap();
            drop(conversation.take());
            peer.rejections.lock().unwrap().insert(
                "thread/resume".to_owned(),
                json!({
                    "code":-32600,
                    "message":"secret-token native-private-path retry after reconnecting",
                    "data":{"reason":"serverShuttingDown"}
                }),
            );
            let reopened = workspace.insert(agent.get_workspace(workspace_id).await.unwrap());
            let error = match reopened.get_conversation(conversation_id).await {
                Err(error) => error,
                Ok(handle) => {
                    conversation = Some(handle);
                    panic!("shutdown rejection must not publish a conversation");
                }
            };
            assert_eq!(error.kind(), ErrorKind::Integration);
            assert_eq!(error.detail(), Some(&ErrorDetail::InvalidRequest));
            for text in [
                error.message().to_owned(),
                error.to_string(),
                format!("{error:?}"),
            ] {
                for private in [
                    "secret-token",
                    "native-private-path",
                    "retry after reconnecting",
                    "serverShuttingDown",
                ] {
                    assert!(!text.contains(private));
                }
            }
            tokio::time::sleep(Duration::from_millis(25)).await;
            let requests = peer.requests.lock().unwrap();
            assert_eq!(
                requests
                    .iter()
                    .filter(|request| request["method"] == "thread/resume")
                    .count(),
                1
            );
            assert!(
                !requests
                    .iter()
                    .any(|request| request["method"] == "turn/start")
            );
            assert_eq!(peer.thread_starts.load(Ordering::SeqCst), 1);
        },
    )
    .await;
    peer.rejections.lock().unwrap().clear();
    let mut cleanup = NativeCleanup::new(Duration::from_secs(10));
    if let Some(conversation) = conversation {
        cleanup.settle(conversation.close()).await;
    }
    if let Some(workspace) = workspace {
        cleanup.settle(workspace.close()).await;
    }
    cleanup.settle(agent.shutdown()).await;
    peer.shutdown().await;
    cleanup
        .settle(async { std::fs::remove_dir_all(root) })
        .await;
    cleanup.finish(observed);
}

#[tokio::test]
async fn codex_active_foreground_controls_remain_required_and_typed() {
    for (entries, expected) in [
        (
            json!([{"name":"multi_agent","enabled":false}]),
            ErrorKind::Protocol,
        ),
        (
            json!([{"name":"multi_agent","enabled":false},{"name":"multi_agent_v2","enabled":true}]),
            ErrorKind::Unsupported,
        ),
        (
            json!([{"name":"multi_agent","enabled":false},{"name":"multi_agent_v2","enabled":"false"}]),
            ErrorKind::Protocol,
        ),
        (
            json!([{"name":"multi_agent","enabled":false},{"name":"multi_agent","enabled":false},{"name":"multi_agent_v2","enabled":false}]),
            ErrorKind::Protocol,
        ),
    ] {
        let CodexFixture {
            peer,
            agent,
            workspace,
            conversation,
            root,
        } = CodexFixture::build().await;
        let workspace_id = workspace.id().clone();
        let mut workspace = Some(workspace);
        *peer.features.lock().unwrap() = json!({"data":entries,"nextCursor":null});
        let observed = NativeCleanup::observe(
            tokio::time::Instant::now() + Duration::from_secs(10),
            async {
                let id = conversation.id().clone();
                workspace.take().unwrap().close().await.unwrap();
                let workspace = workspace.insert(agent.get_workspace(workspace_id).await.unwrap());
                let result = workspace.get_conversation(id).await;
                let error = match result {
                    Err(error) => error,
                    Ok(conversation) => {
                        conversation.close().await.unwrap();
                        panic!("invalid active controls must fail");
                    }
                };
                assert_eq!(error.kind(), expected);
            },
        )
        .await;
        *peer.features.lock().unwrap() = json!({"data":[{"name":"multi_agent","enabled":false},{"name":"multi_agent_v2","enabled":false}],"nextCursor":null});
        let mut cleanup = NativeCleanup::new(Duration::from_secs(10));
        drop(conversation);
        if let Some(workspace) = workspace {
            cleanup.settle(workspace.close()).await;
        }
        cleanup.settle(agent.shutdown()).await;
        peer.shutdown().await;
        cleanup
            .settle(async { std::fs::remove_dir_all(root) })
            .await;
        cleanup.finish(observed);
    }
}

#[tokio::test]
async fn codex_partial_answer_phase_never_replaces_the_final_answer() {
    let partial = json!({"type":"agentMessage","id":"partial","text":"partial only","phase":"partial_answer"});
    CodexFixture::assert_release_event(
        "item/completed",
        json!({"threadId":"stream-thread","turnId":"turn-1","completedAtMs":1,"item":partial}),
        None,
    )
    .await;
    let final_answer =
        json!({"type":"agentMessage","id":"final","text":"exact final","phase":"final_answer"});
    let response = CodexFixture::recovered_result(
        "completed",
        Value::Null,
        vec![final_answer, partial.clone()],
    )
    .await
    .unwrap();
    assert_eq!(response.output(), "exact final");
    let error = CodexFixture::recovered_result("completed", Value::Null, vec![partial])
        .await
        .unwrap_err();
    assert_eq!(error.kind(), ErrorKind::NotYetImplemented);
}

#[tokio::test]
async fn codex_interaction_publication_stops_repeated_conflicts_at_deadline() {
    WaiterFaultStore::assert_interaction_publication(
        InteractionFaultPoint::Journal,
        StorageFaultSource::Conflict,
        false,
        usize::MAX,
    )
    .await;
}

#[tokio::test]
async fn codex_interaction_publication_reconciles_begin_and_prompt_load_conflicts() {
    for point in [
        InteractionFaultPoint::Begin,
        InteractionFaultPoint::PromptLoad,
    ] {
        WaiterFaultStore::assert_interaction_publication(
            point,
            StorageFaultSource::Conflict,
            false,
            1,
        )
        .await;
    }
}

#[tokio::test]
async fn codex_interaction_publication_deadline_rejects_late_staging() {
    WaiterFaultStore::assert_interaction_publication(
        InteractionFaultPoint::HeldStaging,
        StorageFaultSource::Conflict,
        false,
        1,
    )
    .await;
}

#[tokio::test]
async fn codex_interaction_publication_deadline_retains_admitted_commit() {
    WaiterFaultStore::assert_interaction_publication(
        InteractionFaultPoint::HeldCommit,
        StorageFaultSource::Conflict,
        false,
        1,
    )
    .await;
}

#[tokio::test]
async fn codex_interaction_publication_does_not_retry_ambiguous_commit() {
    WaiterFaultStore::assert_interaction_publication(
        InteractionFaultPoint::AmbiguousCommit,
        StorageFaultSource::Unavailable,
        false,
        1,
    )
    .await;
}

#[tokio::test]
async fn codex_interaction_publication_reloads_settled_duplicate_in_transaction() {
    let raw = StateStore::connect(StateStoreConfig::Lance(LanceStateStoreConfig::memory()))
        .await
        .unwrap();
    let armed = Arc::new(AtomicBool::new(false));
    let attempts = Arc::new(AtomicUsize::new(0));
    let store = WaiterFaultStore {
        inner: raw.clone(),
        armed: Arc::clone(&armed),
        attempts: Arc::clone(&attempts),
        fault: WaiterFault::InteractionPublication {
            point: InteractionFaultPoint::StaleDuplicate,
            source: StorageFaultSource::Conflict,
            owner_task: Arc::new(std::sync::Mutex::new(None)),
            failures: 1,
            rollback_failure: false,
            rollbacks: Arc::new(AtomicUsize::new(0)),
        },
    };
    let mut fixture = CodexFixture::build_with_store(CodexPeer::start().await, store).await;
    let observed = std::panic::AssertUnwindSafe(tokio::time::timeout(Duration::from_secs(3), async {
        let mut notifications = fixture.conversation.notification_stream().unwrap();
        let mut stream = fixture.conversation.prompt_stream(PromptRequest::new("duplicate approval").unwrap()).await.unwrap();
        let turn = fixture.peer.turn().await;
        let request = json!({"id":71,"method":"item/commandExecution/requestApproval","params":{
            "threadId":"stream-thread","turnId":turn,"itemId":"command","startedAtMs":1,"availableDecisions":["accept","cancel"]}});
        fixture.peer.events.send(request.clone()).await.unwrap();
        let notification = notifications.recv().await.unwrap().unwrap();
        assert_eq!(fixture.conversation.resolve_notification(notification.id().clone(), NotificationResolution::Allow).await.unwrap_err().kind(), ErrorKind::Conflict);
        assert_eq!(fixture.peer.responses.recv().await.unwrap(), json!({"id":71,"result":{"decision":"accept"}}));
        let before = raw.list(StateListRequest::new("agents_kit_codex_continuations_v1").unwrap()).await.unwrap();
        assert_eq!(before.records.len(), 1);
        assert_eq!(before.records[0].record.value["state"], "ambiguous");
        // A list snapshot may precede the resolution commit. Transactional load
        // still observes the current ambiguous continuation and resolving journal.
        armed.store(true, Ordering::SeqCst);
        fixture.peer.events.send(request).await.unwrap();
        let response = tokio::time::timeout(Duration::from_millis(250), fixture.peer.responses.recv()).await
            .expect("settled duplicate must receive rejection despite stale pending inventory").unwrap();
        assert_eq!(response["id"], 71);
        assert_eq!(response["error"]["code"], -32602);
        armed.store(false, Ordering::SeqCst);
        assert_eq!(attempts.load(Ordering::SeqCst), 1, "logical identity conflicts must not retry");
        let after = raw.list(StateListRequest::new("agents_kit_codex_continuations_v1").unwrap()).await.unwrap();
        assert_eq!(after.records, before.records, "duplicate cannot mutate settled continuation");
        fixture.peer.complete(&turn, "duplicate safely rejected").await;
        assert!(matches!(stream.recv().await, Some(Ok(PromptEvent::Completed(response))) if response.output() == "duplicate safely rejected"));
        assert!(stream.recv().await.is_none());
        assert!(fixture.peer.responses.try_recv().is_err());
    })).catch_unwind().await;
    armed.store(false, Ordering::SeqCst);
    let mut cleanup = NativeCleanup::new(Duration::from_secs(4));
    cleanup.settle(fixture.conversation.close()).await;
    cleanup.settle(fixture.workspace.close()).await;
    cleanup.settle(fixture.agent.shutdown()).await;
    cleanup
        .settle(async {
            fixture.peer.shutdown().await;
            Ok::<(), agents_kit::KitError>(())
        })
        .await;
    cleanup
        .settle(async { std::fs::remove_dir_all(fixture.root) })
        .await;
    cleanup.finish(observed);
}

#[tokio::test]
async fn codex_release_interrupted_error_retains_cancelled_primary_and_safe_cause() {
    for recovered in [false, true] {
        for streaming in [false, true] {
            let native_error = json!({"message":"secret-token", "codexErrorInfo":"tooManyDenials",
                "misalignment":{"errorType":"private-classification", "detailedExplanation":"secret-token", "steer":{"message":"secret-token"}}});
            let peer = CodexPeer::start_with(if recovered {
                FirstStart::RecoveredTurn {
                    status: "interrupted".into(),
                    error: native_error.clone(),
                    items: vec![],
                }
            } else {
                FirstStart::Ordinary
            })
            .await;
            let mut fixture = CodexFixture::build_with_peer(peer).await;
            let observed = std::panic::AssertUnwindSafe(async {
                let error = if streaming {
                    let mut stream = fixture.conversation.prompt_stream(PromptRequest::new("interrupt").unwrap()).await.unwrap();
                    let turn = fixture.peer.turn().await;
                    if !recovered {
                        fixture.peer.notify("turn/completed", json!({"threadId":"stream-thread","turn":{
                            "id":turn,"status":"interrupted","items":[],"error":native_error}})).await;
                    }
                    let error = tokio::time::timeout(Duration::from_secs(3), stream.recv()).await.unwrap().unwrap().unwrap_err();
                    assert!(stream.recv().await.is_none());
                    error
                } else {
                    let mut prompt = Box::pin(fixture.conversation.prompt(PromptRequest::new("interrupt").unwrap()));
                    let turn = tokio::select! { turn = fixture.peer.turn() => turn, result = &mut prompt => panic!("early {result:?}") };
                    if !recovered {
                        fixture.peer.notify("turn/completed", json!({"threadId":"stream-thread","turn":{
                            "id":turn,"status":"interrupted","items":[],"error":native_error}})).await;
                    }
                    tokio::time::timeout(Duration::from_secs(3), prompt).await.unwrap().unwrap_err()
                };

            assert_eq!(error.kind(), ErrorKind::Cancelled, "recovered={recovered}, streaming={streaming}");
            assert_eq!(error.context().operation, Operation::Prompt);
            assert_eq!(error.context().phase, ErrorPhase::Cancellation);
            let cause = error.cause().expect("native cancellation cause");
            assert_eq!(cause.kind(), ErrorKind::Integration);
            assert_eq!(cause.context().operation, Operation::Prompt);
            assert_eq!(cause.context().phase, ErrorPhase::ModelGeneration);
            assert_eq!(cause.detail(), Some(&ErrorDetail::PolicyRejected));
            assert_eq!(cause.http_status(), None);
            assert!(!format!("{error} {error:?}").contains("secret-token"));
            }).catch_unwind().await;
            fixture.finish_release(observed, None).await;
        }
    }
}