agents-kit 0.0.2

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
mod caller_shell;
mod codex_input_evidence;
mod custom_provider_evidence;
mod custom_provider_observation;
mod custom_provider_observation_tests;
mod knowledge_evidence;
mod native_cleanup;
mod opencode_question_evidence;

use std::collections::{BTreeMap, BTreeSet};
use std::future::Future;
use std::panic::AssertUnwindSafe;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

use futures_util::FutureExt;
use serde_json::{Value, json};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
use tokio::time::Instant;

use native_cleanup::NativeCleanup;
use opencode_question_evidence::readback::{FreshOutputExpectation, NativeQuestionReadback};
use opencode_question_evidence::{QuestionEvidence, QuestionExpectation, QuestionGrade};

#[tokio::test]
async fn codex_input_capture_file_boundary_and_deadline() {
    use codex_input_evidence::CodexInputObservation;
    let directory =
        std::env::temp_dir().join(format!("codex-rollout-control-{}", uuid::Uuid::new_v4()));
    std::fs::create_dir(&directory).unwrap();
    let home = std::fs::canonicalize(&directory).unwrap();
    let observed = NativeCleanup::observe(Instant::now() + Duration::from_secs(10), async {
        let sessions = home.join("sessions");
        std::fs::create_dir(&sessions).unwrap();
        let path = sessions.join("owned.jsonl");
        let bytes = b"{\"type\":\"example\"}\n";
        std::fs::write(&path, bytes).unwrap();
        let deadline = Instant::now() + Duration::from_secs(10);
        assert_eq!(
            CodexInputObservation::read_rollout(&home, &path, deadline)
                .await
                .unwrap(),
            bytes
        );
        assert!(
            CodexInputObservation::read_rollout(
                &home,
                std::path::Path::new("relative.jsonl"),
                deadline
            )
            .await
            .is_err()
        );
        let foreign = home.join("foreign.jsonl");
        std::fs::write(&foreign, bytes).unwrap();
        assert!(
            CodexInputObservation::read_rollout(&home, &foreign, deadline)
                .await
                .is_err()
        );
        assert!(
            CodexInputObservation::read_rollout(&home, &sessions, deadline)
                .await
                .is_err()
        );
        assert_eq!(
            CodexInputObservation::read_rollout(&home, &path, Instant::now())
                .await
                .unwrap_err(),
            "rollout_snapshot_deadline"
        );
        let metadata = std::fs::metadata(&path).unwrap();
        let replacement = sessions.join("replacement.jsonl");
        std::fs::write(&replacement, bytes).unwrap();
        std::fs::rename(&replacement, &path).unwrap();
        assert!(!CodexInputObservation::same_rollout_metadata(
            &metadata,
            &std::fs::metadata(&path).unwrap()
        ));
        #[cfg(unix)]
        {
            let link = sessions.join("linked.jsonl");
            std::os::unix::fs::symlink(&path, &link).unwrap();
            assert!(
                CodexInputObservation::read_rollout(&home, &link, deadline)
                    .await
                    .is_err()
            );
            let redirected = sessions.join("redirected");
            std::os::unix::fs::symlink(&sessions, &redirected).unwrap();
            assert!(
                CodexInputObservation::read_rollout(
                    &home,
                    &redirected.join("owned.jsonl"),
                    deadline
                )
                .await
                .is_err()
            );
        }
        std::fs::File::create(&path)
            .unwrap()
            .set_len(8 * 1024 * 1024 + 1)
            .unwrap();
        assert_eq!(
            CodexInputObservation::read_rollout(&home, &path, deadline)
                .await
                .unwrap_err(),
            "rollout_byte_bound"
        );
        let stderr = home.join("stderr.log");
        std::fs::write(&stderr, b"safe local warning").unwrap();
        assert_eq!(
            CodexInputObservation::read_stderr(&stderr, deadline)
                .await
                .unwrap(),
            b"safe local warning"
        );
        assert!(
            CodexInputObservation::read_stderr(&home.join("missing.log"), deadline)
                .await
                .is_err()
        );
        std::fs::File::create(&stderr)
            .unwrap()
            .set_len(1024 * 1024 + 1)
            .unwrap();
        assert_eq!(
            CodexInputObservation::read_stderr(&stderr, deadline)
                .await
                .unwrap_err(),
            "stderr_byte_bound"
        );
    })
    .await;
    let mut cleanup = NativeCleanup::new(Duration::from_secs(5));
    cleanup.settle(tokio::fs::remove_dir_all(&directory)).await;
    cleanup.finish(observed);
}

#[test]
fn codex_input_capture_preserves_original_callback_assertions() {
    use codex_input_evidence::CodexInputObservation;
    let mut observation = CodexInputObservation::default();
    observation.observe_native(&json!({"id":100,"method":"item/tool/requestUserInput",
        "params":{"isBlocking":false}}));
    observation.finish_native_forwarding(true);
    observation.observe_sdk(&json!({"id":100,"error":{"code":-32601}}));
    observation.finish_sdk_forwarding(true);
    observation.assert_nonblocking_response();
    assert_eq!(observation.snapshot()["callback_responses"], 1);
    assert!(
        std::panic::catch_unwind(AssertUnwindSafe(|| {
            observation.observe_native(&json!({"id":101,"method":"item/tool/requestUserInput",
            "params":{"isBlocking":false}}));
        }))
        .is_err()
    );
}

#[test]
fn codex_input_capture_records_passive_identity_and_forwarding() {
    use codex_input_evidence::CodexInputObservation;
    let caller_prompt = "Stay in Default mode. Call the native request_user_input tool exactly once with one question: id=choice, header=Choice, question=Choose a value?, options=[{label:First,description:First choice},{label:Second,description:Second choice}]. Do not imitate the tool call in text. After the tool returns, including cancellation or unsupported response, reply exactly INPUT_SETTLED. Do not call other tools.";
    let native_prompt = format!("Managed context:\n(none)\n\nUser request:\n{caller_prompt}");
    assert_eq!(caller_prompt.len(), 400);
    assert_eq!(native_prompt.len(), 439);
    let mut observation = CodexInputObservation::default();
    observation.prepare_expected(
        std::path::Path::new("/owned/cwd"),
        "gpt-6-luna",
        caller_prompt,
    );
    let frames = [
        (
            true,
            json!({"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true}}}),
        ),
        (
            false,
            json!({"id":1,"result":{"userAgent":"codex/0.163.0"}}),
        ),
        (
            true,
            json!({"id":2,"method":"thread/start","params":{"cwd":"/owned/cwd","config":{"features.multi_agent":false,"features.multi_agent_v2":false},"dynamicTools":[]}}),
        ),
        (
            false,
            json!({"id":2,"result":{"thread":{"id":"thread-a","cwd":"/owned/cwd","path":"/owned/home/sessions/run.jsonl","parentThreadId":null},"model":"gpt-6-luna"}}),
        ),
        (
            true,
            json!({"id":3,"method":"experimentalFeature/list","params":{"threadId":"thread-a"}}),
        ),
        (
            false,
            json!({"id":3,"result":{"data":[{"name":"default_mode_request_user_input","enabled":true},{"name":"multi_agent","enabled":false},{"name":"multi_agent_v2","enabled":false}],"nextCursor":null}}),
        ),
        (
            true,
            json!({"id":4,"method":"turn/start","params":{"threadId":"thread-a","clientUserMessageId":"generation-a","cwd":"/owned/cwd","model":"gpt-6-luna","input":[{"type":"text","text":native_prompt,"textElements":[]}]}}),
        ),
        (
            false,
            json!({"id":4,"result":{"turn":{"id":"turn-a","status":"inProgress"}}}),
        ),
        (
            false,
            json!({"method":"turn/completed","params":{"threadId":"thread-a","turn":{"id":"turn-a","status":"completed","error":null,"items":[]}}}),
        ),
    ];
    for (sdk, frame) in &frames {
        if *sdk {
            observation.observe_sdk(frame);
            observation.finish_sdk_forwarding(true);
        } else {
            observation.observe_native(frame);
            observation.finish_native_forwarding(true);
        }
    }
    let snapshot = observation.snapshot();
    assert_eq!(snapshot["frames"][6]["submission"]["prompt"]["bytes"], 439);
    assert_eq!(
        snapshot["frames"][6]["submission"]["prompt"]["fingerprint"],
        "116bb674842d77b5"
    );
    assert_eq!(
        snapshot["wire_complete"], true,
        "the exact empty-context native rendering must bind to the original caller input"
    );
    assert_eq!(
        snapshot["prompt_binding"]["rendering"],
        "empty_managed_context"
    );
    assert_eq!(snapshot["prompt_binding"]["caller"]["bytes"], 400);
    assert_eq!(
        snapshot["prompt_binding"]["native"],
        snapshot["frames"][6]["submission"]["prompt"]
    );
    assert_eq!(snapshot["prompt_binding"]["exact"], true);
    assert_eq!(snapshot["frames"].as_array().unwrap().len(), 9);
    assert_eq!(
        snapshot["effective_features"]["default_mode_request_user_input"],
        true
    );
    assert_eq!(
        observation.rollout_path(),
        Some(std::path::PathBuf::from("/owned/home/sessions/run.jsonl"))
    );
    assert!(!snapshot.to_string().contains(caller_prompt));
    assert!(!snapshot.to_string().contains(&native_prompt));
    for wrong_prompt in [
        caller_prompt.to_owned(),
        format!("Managed context:\nchanged\n\nUser request:\n{caller_prompt}"),
        format!("{native_prompt} "),
        format!("{native_prompt}extra"),
    ] {
        let mut wrong = CodexInputObservation::default();
        wrong.prepare_expected(
            std::path::Path::new("/owned/cwd"),
            "gpt-6-luna",
            caller_prompt,
        );
        for (sdk, frame) in &frames {
            let mut frame = frame.clone();
            if frame["method"] == "turn/start" {
                frame["params"]["input"][0]["text"] = json!(wrong_prompt);
            }
            if *sdk {
                wrong.observe_sdk(&frame);
                wrong.finish_sdk_forwarding(true);
            } else {
                wrong.observe_native(&frame);
                wrong.finish_native_forwarding(true);
            }
        }
        assert_eq!(wrong.snapshot()["wire_complete"], false);
        assert_eq!(wrong.snapshot()["prompt_binding"]["exact"], false);
    }
    for (id, include_turns, turns) in [(5, false, None), (6, true, Some(json!([])))] {
        observation.observe_sdk(&json!({"id":id,"method":"thread/read","params":{"threadId":"thread-a","includeTurns":include_turns}}));
        observation.finish_sdk_forwarding(true);
        let mut result = json!({"thread":{"id":"thread-a"}});
        if let Some(turns) = turns {
            result["thread"]["turns"] = turns;
        }
        observation.observe_native(&json!({"id":id,"result":result}));
        observation.finish_native_forwarding(true);
        assert_eq!(observation.snapshot()["wire_complete"], true);
    }
    observation.observe_sdk(&json!({"id":7,"method":"thread/read","params":{"threadId":"thread-a","includeTurns":true}}));
    observation.finish_sdk_forwarding(true);
    observation.observe_native(&json!({"id":7,"result":{"thread":{"id":"thread-a"}}}));
    observation.finish_native_forwarding(true);
    assert_eq!(observation.snapshot()["wire_complete"], false);
    observation.mark_incomplete("control-forwarding-failure");
    assert_eq!(observation.snapshot()["capture_complete"], false);
}

#[test]
fn codex_input_capture_reads_correlated_rollout_without_native_prose() {
    use codex_input_evidence::CodexInputObservation;
    let make_observation = |callback: bool| {
        let mut observation = CodexInputObservation::default();
        for (sdk, frame) in [
            (
                true,
                json!({"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true}}}),
            ),
            (
                false,
                json!({"id":1,"result":{"userAgent":"codex/0.163.0"}}),
            ),
            (
                true,
                json!({"id":2,"method":"thread/start","params":{"cwd":"/owned/cwd","config":{},"dynamicTools":[]}}),
            ),
            (
                false,
                json!({"id":2,"result":{"thread":{"id":"thread-a","cwd":"/owned/cwd","path":"/owned/home/sessions/run.jsonl","parentThreadId":null},"model":"gpt-6-luna"}}),
            ),
            (
                true,
                json!({"id":3,"method":"experimentalFeature/list","params":{"threadId":"thread-a"}}),
            ),
            (
                false,
                json!({"id":3,"result":{"data":[{"name":"default_mode_request_user_input","enabled":true},{"name":"multi_agent","enabled":false},{"name":"multi_agent_v2","enabled":false}],"nextCursor":null}}),
            ),
            (
                true,
                json!({"id":4,"method":"turn/start","params":{"threadId":"thread-a","clientUserMessageId":"generation-a","cwd":"/owned/cwd","model":"gpt-6-luna","input":[{"type":"text","text":"Managed context:\n(none)\n\nUser request:\nunchanged prompt","textElements":[]}]}}),
            ),
            (
                false,
                json!({"id":4,"result":{"turn":{"id":"turn-a","status":"inProgress"}}}),
            ),
            (
                false,
                json!({"method":"turn/completed","params":{"threadId":"thread-a","turn":{"id":"turn-a","status":"completed","error":null,"items":[]}}}),
            ),
        ] {
            if frame["method"] == "turn/start" {
                observation.prepare_expected(
                    std::path::Path::new("/owned/cwd"),
                    "gpt-6-luna",
                    "unchanged prompt",
                );
            }
            if callback && frame["method"] == "turn/completed" {
                observation.observe_native(&json!({"id":100,"method":"item/tool/requestUserInput","params":{"threadId":"thread-a","turnId":"turn-a","itemId":"call-a","isBlocking":false,"questions":[]}}));
                observation.finish_native_forwarding(true);
                observation.observe_sdk(&json!({"id":100,"error":{"code":-32601}}));
                observation.finish_sdk_forwarding(true);
            }
            if sdk {
                observation.observe_sdk(&frame);
                observation.finish_sdk_forwarding(true);
            } else {
                observation.observe_native(&frame);
                observation.finish_native_forwarding(true);
            }
        }
        observation.observe_stderr(b"");
        observation
    };
    let mut observation = make_observation(false);
    let arguments = json!({"questions":[{"id":"choice","header":"Choice","question":"private question","options":[{"label":"First","description":"one"},{"label":"Second","description":"two"}]}]}).to_string();
    let records = vec![
        json!({"type":"session_meta","payload":{"id":"thread-a","session_id":"thread-a","cwd":"/owned/cwd","cli_version":"0.163.0","source":"vscode","parent_thread_id":null}}),
        json!({"type":"turn_context","payload":{"turn_id":"turn-a","model":"gpt-6-luna","cwd":"/owned/cwd","collaboration_mode":{"mode":"default"}}}),
        json!({"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"Managed context:\n(none)\n\nUser request:\nunchanged prompt"}]}}),
        json!({"type":"response_item","payload":{"type":"function_call","name":"request_user_input","call_id":"call-a","arguments":arguments}}),
        json!({"type":"response_item","payload":{"type":"function_call_output","call_id":"call-a","output":"request_user_input requires non-empty options for every question"}}),
        json!({"type":"response_item","payload":{"type":"reasoning","summary":[{"text":"private reasoning"}]}}),
        json!({"type":"event_msg","payload":{"type":"task_complete","turn_id":"turn-a","last_agent_message":"INPUT_SETTLED","error":null}}),
    ];
    let encode = |records: &[Value]| {
        let mut bytes = Vec::new();
        for record in records {
            serde_json::to_writer(&mut bytes, record).unwrap();
            bytes.push(b'\n');
        }
        bytes
    };
    let bytes = encode(&records);
    observation
        .observe_rollout(&bytes)
        .expect("own bounded rollout is correlated");
    let snapshot = observation.snapshot();
    assert_eq!(snapshot["rollout"]["complete"], true);
    assert_eq!(snapshot["rollout"]["calls"].as_array().unwrap().len(), 1);
    assert_eq!(
        snapshot["rollout"]["calls"][0]["output"]["error_class"],
        "missing_options"
    );
    let exported = snapshot.to_string();
    for private in [
        "private question",
        "private reasoning",
        "request_user_input requires non-empty options for every question",
        "unchanged prompt",
    ] {
        assert!(!exported.contains(private));
    }
    assert_eq!(
        snapshot["capture_complete"], true,
        "absence of callback is evidence, not capture loss"
    );
    assert!(
        std::panic::catch_unwind(AssertUnwindSafe(
            || observation.assert_nonblocking_response()
        ))
        .is_err()
    );

    let mut completed_callback = records.clone();
    completed_callback[4]["payload"]["output"] = json!("{\"answers\":{}}");
    let mut observed = make_observation(true);
    observed
        .observe_rollout(&encode(&completed_callback))
        .unwrap();
    observed.assert_nonblocking_response();
    assert_eq!(observed.snapshot()["capture_complete"], true);
    assert_eq!(observed.snapshot()["rollout"]["callback_correlated"], true);
    assert_eq!(observed.snapshot()["callback_responses"], 1);
    // RequestUserInput is transient in pinned native policy; its absence is not a lost callback.
    assert!(
        observed.snapshot()["rollout"]["request_user_input_events"]
            .as_array()
            .unwrap()
            .is_empty()
    );
    completed_callback.insert(4, json!({"type":"event_msg","payload":{"type":"request_user_input","call_id":"call-a","turn_id":"turn-a","isBlocking":false,"questions":[]}}));
    let mut observed = make_observation(true);
    observed
        .observe_rollout(&encode(&completed_callback))
        .unwrap();
    assert_eq!(
        observed.snapshot()["rollout"]["request_user_input_events"]
            .as_array()
            .unwrap()
            .len(),
        1
    );
    assert_eq!(observed.snapshot()["capture_complete"], true);
    let mut no_call = records.clone();
    no_call.remove(4);
    no_call.remove(3);
    let mut observed = make_observation(false);
    observed.observe_rollout(&encode(&no_call)).unwrap();
    assert_eq!(observed.snapshot()["capture_complete"], true);
    assert!(
        observed.snapshot()["rollout"]["calls"]
            .as_array()
            .unwrap()
            .is_empty()
    );
    assert!(
        std::panic::catch_unwind(AssertUnwindSafe(|| observed.assert_nonblocking_response()))
            .is_err()
    );

    // Pinned app-server selects paginated history for new persisted root threads.
    // A full root file starts ordinal zero and contains every consecutive record.
    let mut paginated = records.clone();
    paginated[0]["payload"]["history_mode"] = json!("paginated");
    paginated.insert(1, json!({"type":"world_state","payload":{"full":true,"state":{"private_system_context":"must not be retained"}}}));
    let usage = json!({"input_tokens":10,"cached_input_tokens":0,"output_tokens":2,"reasoning_output_tokens":0,"total_tokens":12});
    paginated.insert(paginated.len() - 1, json!({"type":"token_usage_record","payload":{
        "thread_id":"thread-a","session_id":"thread-a","turn_id":"turn-a","root_turn_id":"turn-a","response_id":"response-private",
        "usage":usage,"turn_token_usage":usage,"thread_token_usage":usage}}));
    for (ordinal, record) in paginated.iter_mut().enumerate() {
        record["ordinal"] = json!(ordinal);
        record["timestamp"] = json!("2026-10-22T18:00:00.000Z");
    }
    let mut observed = make_observation(false);
    observed
        .observe_rollout(&encode(&paginated))
        .expect("complete paginated native root history must be captured");
    assert_eq!(observed.snapshot()["capture_complete"], true);
    assert_eq!(observed.snapshot()["rollout"]["history_mode"], "paginated");
    assert_eq!(observed.snapshot()["rollout"]["ordinals_complete"], true);
    assert_eq!(
        observed.snapshot()["rollout"]["record_kinds"]["world_state"],
        1
    );
    assert_eq!(
        observed.snapshot()["rollout"]["record_kinds"]["token_usage_record"],
        1
    );
    for private in [
        "private_system_context",
        "must not be retained",
        "response-private",
    ] {
        assert!(!observed.snapshot().to_string().contains(private));
    }

    for (index, ordinal) in [
        (0, json!(1)),
        (2, json!(1)),
        (2, json!(3)),
        (2, json!(-1)),
        (2, json!(1.5)),
        (2, json!("2")),
        (2, Value::Null),
    ] {
        let mut changed = paginated.clone();
        changed[index]["ordinal"] = ordinal;
        let mut observed = make_observation(false);
        assert_eq!(
            observed.observe_rollout(&encode(&changed)),
            Err("rollout_ordinal_discontinuity")
        );
    }
    let mut changed = paginated.clone();
    changed[2].as_object_mut().unwrap().remove("ordinal");
    let mut observed = make_observation(false);
    assert_eq!(
        observed.observe_rollout(&encode(&changed)),
        Err("rollout_ordinal_discontinuity")
    );
    for marker in [
        "history_base",
        "forked_from_ordinal_exclusive",
        "subagent_history_start_ordinal",
    ] {
        let mut changed = paginated.clone();
        changed[0]["payload"][marker] = json!(4);
        assert!(
            make_observation(false)
                .observe_rollout(&encode(&changed))
                .is_err()
        );
    }
    let mut changed = records.clone();
    changed[0]["ordinal"] = json!(0);
    assert_eq!(
        make_observation(false).observe_rollout(&encode(&changed)),
        Err("rollout_legacy_ordinal")
    );
    let usage_index = paginated.len() - 2;
    for key in ["thread_id", "session_id", "turn_id", "root_turn_id"] {
        let mut changed = paginated.clone();
        changed[usage_index]["payload"][key] = json!("foreign");
        assert_eq!(
            make_observation(false).observe_rollout(&encode(&changed)),
            Err("rollout_token_usage_identity_or_shape")
        );
    }
    let mut changed = paginated.clone();
    changed[1]["payload"]["state"] = json!([]);
    assert_eq!(
        make_observation(false).observe_rollout(&encode(&changed)),
        Err("rollout_world_state_shape")
    );

    // Native invalid arguments/errors remain complete facts; they are not observer parse failures.
    for arguments in ["{", "{}", "{\"questions\":[{\"options\":[]}]}"] {
        let mut changed = records.clone();
        changed[3]["payload"]["arguments"] = json!(arguments);
        let mut observed = make_observation(false);
        observed.observe_rollout(&encode(&changed)).unwrap();
        assert_eq!(observed.snapshot()["rollout"]["complete"], true);
        assert_eq!(
            observed.snapshot()["rollout"]["calls"][0]["argument_shape"]["json_valid"],
            arguments != "{"
        );
    }
    for options in [Value::Null, json!([])] {
        let mut changed = records.clone();
        changed[3]["payload"]["arguments"] = json!(json!({"questions":[{"id":"choice","header":"Choice","question":"private question","options":options}]}).to_string());
        let mut observed = make_observation(false);
        observed.observe_rollout(&encode(&changed)).unwrap();
        let shape = observed.snapshot()["rollout"]["calls"][0]["argument_shape"].clone();
        assert_eq!(shape["typed_fields_valid"], true);
        assert_eq!(shape["all_options_nonempty"], false);
    }
    for (output, class) in [
        (
            "request_user_input is unavailable in Default mode",
            "unavailable_default_mode",
        ),
        (
            "request_user_input can only be used by the root thread",
            "non_root_thread",
        ),
        (
            "failed to parse function arguments: private parse detail",
            "argument_parse_error",
        ),
        ("arbitrary native prose", "unknown"),
    ] {
        let mut changed = records.clone();
        changed[4]["payload"]["output"] = json!(output);
        let mut observed = make_observation(false);
        observed.observe_rollout(&encode(&changed)).unwrap();
        assert_eq!(
            observed.snapshot()["rollout"]["calls"][0]["output"]["error_class"],
            class
        );
        assert!(!observed.snapshot().to_string().contains(output));
    }
    let mut changed = records.clone();
    changed[4]["payload"]["output"] = json!([
        {"type":"input_text","text":"first private result"},
        {"type":"input_audio","audio_url":"private audio"},
        {"type":"encrypted_content","encrypted_content":"private encrypted text"},
        {"type":"input_text","text":"last private result"}
    ]);
    let mut observed = make_observation(false);
    observed.observe_rollout(&encode(&changed)).unwrap();
    let output = observed.snapshot()["rollout"]["calls"][0]["output"].clone();
    assert_eq!(output["kind"], "content_items");
    assert_eq!(output["items"].as_array().unwrap().len(), 4);
    assert_eq!(output["items"][1]["kind"], "input_audio");
    assert_eq!(output["items"][2]["kind"], "encrypted_content");
    assert!(!observed.snapshot().to_string().contains("private"));

    // Wrong native identity, ambiguous call pairing, incomplete files, and routed paths cannot qualify.
    let mut invalid = Vec::new();
    for (index, key, value) in [
        (0, "id", "foreign"),
        (0, "session_id", "foreign"),
        (1, "turn_id", "foreign"),
        (1, "model", "foreign"),
        (1, "cwd", "/foreign"),
        (4, "call_id", "foreign"),
        (6, "turn_id", "foreign"),
    ] {
        let mut changed = records.clone();
        changed[index]["payload"][key] = json!(value);
        invalid.push(encode(&changed));
    }
    for wrong_prompt in [
        "wrong prompt",
        "unchanged prompt",
        "Managed context:\nchanged\n\nUser request:\nunchanged prompt",
        "Managed context:\n(none)\n\nUser request:\nunchanged prompt ",
        "Managed context:\n(none)\n\nUser request:\nunchanged promptextra",
    ] {
        let mut changed = records.clone();
        changed[2]["payload"]["content"][0]["text"] = json!(wrong_prompt);
        invalid.push(encode(&changed));
    }
    let mut changed = records.clone();
    changed.insert(4, changed[3].clone());
    invalid.push(encode(&changed));
    let mut changed = records.clone();
    changed.insert(5, changed[4].clone());
    invalid.push(encode(&changed));
    let mut changed = records.clone();
    changed.remove(4);
    invalid.push(encode(&changed));
    let mut changed = records.clone();
    changed[3]["payload"]["type"] = json!("custom_tool_call");
    invalid.push(encode(&changed));
    let mut changed = records.clone();
    changed[0]["payload"]["history_base"] = json!({"reference":"foreign"});
    invalid.push(encode(&changed));
    let mut changed = bytes.clone();
    changed.pop();
    invalid.push(changed);
    invalid.push(b"{not JSON}\n".to_vec());
    invalid.push(vec![b'x'; 8 * 1_048_576 + 1]);
    for bytes in invalid {
        let mut observed = make_observation(false);
        assert!(observed.observe_rollout(&bytes).is_err());
        assert_eq!(observed.snapshot()["capture_complete"], false);
    }
    let mut observed = make_observation(false);
    observed.observe_native(&json!({"id":100,"method":"item/tool/requestUserInput","params":{"threadId":"thread-a","turnId":"turn-a","itemId":"wrong-call","isBlocking":false}}));
    observed.finish_native_forwarding(true);
    assert_eq!(
        observed.observe_rollout(&bytes),
        Err("rollout_callback_identity_mismatch")
    );

    let mut observed = make_observation(false);
    observed.observe_native(
        &json!({"method":"thread/tokenUsage/updated","params":{"threadId":"thread-a"}}),
    );
    assert_eq!(
        observed.snapshot()["wire_complete"],
        false,
        "unsettled forwarding is incomplete"
    );
    observed.finish_native_forwarding(false);
    assert_eq!(observed.snapshot()["wire_complete"], false);
    let mut observed = make_observation(false);
    observed.observe_stderr(b"failed to flush rollout before completing turn: private error");
    assert_eq!(observed.snapshot()["capture_complete"], false);
    assert!(!observed.snapshot().to_string().contains("private error"));
    let mut observed = make_observation(false);
    observed.observe_stderr(
        b"failed to append rollout writer; reopening and retrying: private first error",
    );
    assert!(
        observed.snapshot()["failures"]
            .as_array()
            .unwrap()
            .iter()
            .any(|reason| reason == "native_rollout_persistence_warning")
    );
    assert!(
        !observed
            .snapshot()
            .to_string()
            .contains("private first error")
    );

    let path = std::env::temp_dir().join(format!(
        "codex-input-evidence-{}.json",
        uuid::Uuid::new_v4()
    ));
    observation.record_cleanup(true, true);
    let written = observation.export_after_cleanup(&path, false, true);
    let body = std::fs::read(&path);
    let duplicate = observation.export_after_cleanup(&path, false, true);
    let removed = std::fs::remove_file(&path);
    written.unwrap();
    removed.unwrap();
    assert!(duplicate.is_err());
    let exported: Value = serde_json::from_slice(&body.unwrap()).unwrap();
    assert_eq!(exported["capture_complete"], true);
    assert_eq!(exported["scenario_succeeded"], false);
    assert_eq!(exported["hierarchy_cleanup_succeeded"], true);
    assert_eq!(exported["process_cleanup_succeeded"], true);
    assert!(
        observation
            .export_after_cleanup(std::path::Path::new("relative.json"), false, true)
            .is_err()
    );
}

#[test]
fn knowledge_capture_retains_ordered_original_request() {
    use knowledge_evidence::KnowledgeEvidence;
    use providers_kit::generation::{GenerateRequest, Message};

    let mut evidence = KnowledgeEvidence::default();
    evidence.prepare(
        "secondary",
        [
            "DB",
            "AGENT_A",
            "WORKSPACE",
            "CONVERSATION",
            "REOPEN",
            "AGENT_B",
        ]
        .map(str::to_owned),
        [1, 0, 0, 0, 0, 1],
    );
    let request = GenerateRequest::new(vec![
        Message::system(vec![providers_kit::generation::ContentPart::Text {
            text: "DB reference".to_owned(),
        }])
        .unwrap(),
        Message::user_text("AGENT_B question").unwrap(),
    ])
    .unwrap();
    evidence.request(
        &providers_kit::ModelId::new("exact-model").unwrap(),
        &request,
        false,
    );
    let snapshot = evidence.snapshot("knowledge-test", false, true);
    assert_eq!(
        snapshot["phases"][0]["request_counts"],
        serde_json::json!([1, 0, 0, 0, 0, 1])
    );
    assert_eq!(
        snapshot["phases"][0]["requests"][0]["messages"],
        serde_json::json!([
            {"role":"system", "text_parts":["DB reference"]}, {"role":"user", "text_parts":["AGENT_B question"]}
        ])
    );
}

#[test]
fn knowledge_capture_retains_asserted_phase() {
    use knowledge_evidence::KnowledgeEvidence;
    use providers_kit::ModelId;
    use providers_kit::generation::{
        FinishReason, GenerateRequest, GenerateResponse, Message, Usage,
    };

    let mut evidence = KnowledgeEvidence::default();
    evidence.prepare(
        "primary",
        [
            "DB",
            "AGENT_A",
            "WORKSPACE",
            "CONVERSATION",
            "REOPEN",
            "AGENT_B",
        ]
        .map(str::to_owned),
        [0; 6],
    );
    evidence.request(
        &providers_kit::ModelId::new("exact-model").unwrap(),
        &GenerateRequest::new(vec![Message::user_text("question").unwrap()]).unwrap(),
        false,
    );
    let response = Ok(GenerateResponse {
        model: ModelId::new("exact-model").unwrap(),
        message: Message::assistant_text("unchanged").unwrap(),
        finish_reason: Some(FinishReason::Stop),
        citations: Vec::new(),
        artifacts: Vec::new(),
        hosted_tool_outputs: Vec::new(),
        usage: Usage::default(),
    });
    evidence.response(&response);
    evidence.agent_output("unchanged");
    evidence.assert_phase();
    let snapshot = evidence.snapshot("knowledge-test", true, true);
    assert_eq!(snapshot["phases"].as_array().unwrap().len(), 1);
    assert_eq!(snapshot["phases"][0]["assertions_succeeded"], true);
    assert_eq!(snapshot["phases"][0]["provider_text"], "unchanged");
}

#[test]
fn knowledge_capture_exports_failed_phase_original_outputs() {
    use knowledge_evidence::KnowledgeEvidence;
    use providers_kit::ModelId;
    use providers_kit::generation::{
        FinishReason, GenerateRequest, GenerateResponse, Message, Usage,
    };

    let mut evidence = KnowledgeEvidence::default();
    evidence.prepare(
        "secondary",
        [
            "DB",
            "AGENT_A",
            "WORKSPACE",
            "CONVERSATION",
            "REOPEN",
            "AGENT_B",
        ]
        .map(str::to_owned),
        [0; 6],
    );
    evidence.request(
        &providers_kit::ModelId::new("exact-model").unwrap(),
        &GenerateRequest::new(vec![Message::user_text("question").unwrap()]).unwrap(),
        false,
    );
    let response = Ok(GenerateResponse {
        model: ModelId::new("exact-model").unwrap(),
        message: Message::assistant_text("wrong native answer").unwrap(),
        finish_reason: Some(FinishReason::Stop),
        citations: Vec::new(),
        artifacts: Vec::new(),
        hosted_tool_outputs: Vec::new(),
        usage: Usage::default(),
    });
    evidence.response(&response);
    evidence.agent_output("wrong native answer");
    let path =
        std::env::temp_dir().join(format!("knowledge-evidence-{}.json", uuid::Uuid::new_v4()));
    let exported = evidence.export_after_cleanup(&path, "knowledge-test", false, true);
    let bytes = std::fs::read(&path);
    let removed = std::fs::remove_file(&path);
    exported.unwrap();
    removed.unwrap();
    let snapshot: serde_json::Value = serde_json::from_slice(&bytes.unwrap()).unwrap();
    assert_eq!(snapshot["scenario_succeeded"], false);
    assert_eq!(snapshot["scenario_cleanup_succeeded"], true);
    assert_eq!(
        snapshot["phases"][0]["provider_text"],
        "wrong native answer"
    );
    assert_eq!(snapshot["phases"][0]["agent_text"], "wrong native answer");
    assert_eq!(snapshot["phases"][0]["assertions_succeeded"], false);
}

#[test]
fn knowledge_capture_bounds_original_request_without_mutating_it() {
    use knowledge_evidence::KnowledgeEvidence;
    use providers_kit::generation::{GenerateRequest, Message};
    let mut evidence = KnowledgeEvidence::default();
    evidence.prepare(
        "primary",
        [
            "DB",
            "AGENT_A",
            "WORKSPACE",
            "CONVERSATION",
            "REOPEN",
            "AGENT_B",
        ]
        .map(str::to_owned),
        [0; 6],
    );
    let text = "x".repeat(65_537);
    let request = GenerateRequest::new(vec![Message::user_text(text.clone()).unwrap()]).unwrap();
    evidence.request(
        &providers_kit::ModelId::new("exact-model").unwrap(),
        &request,
        false,
    );
    let snapshot = evidence.snapshot("knowledge-test", false, true);
    assert_eq!(snapshot["capture_complete"], false);
    assert_eq!(snapshot["capture_failure"], "request_text_bound");
    assert!(
        snapshot["phases"][0]["requests"]
            .as_array()
            .unwrap()
            .is_empty()
    );
    assert!(
        matches!(&request.messages()[0].content()[0], providers_kit::generation::ContentPart::Text {text: actual} if actual == &text)
    );
}

#[test]
fn knowledge_capture_retains_complete_provider_error_prefix_without_agent_output() {
    use knowledge_evidence::KnowledgeEvidence;
    use providers_kit::error::{ErrorKind, ErrorPhase, Operation};
    use providers_kit::generation::{GenerateRequest, Message};
    let mut evidence = KnowledgeEvidence::default();
    assert_eq!(
        evidence.snapshot("knowledge-test", false, true)["capture_complete"],
        false
    );
    evidence.prepare(
        "primary",
        [
            "DB",
            "AGENT_A",
            "WORKSPACE",
            "CONVERSATION",
            "REOPEN",
            "AGENT_B",
        ]
        .map(str::to_owned),
        [0; 6],
    );
    evidence.request(
        &providers_kit::ModelId::new("exact-model").unwrap(),
        &GenerateRequest::new(vec![Message::user_text("question").unwrap()]).unwrap(),
        false,
    );
    let result = Err(providers_kit::KitError::new(
        ErrorKind::Transport,
        Operation::Generate,
        ErrorPhase::RequestSend,
    ));
    evidence.response(&result);
    let snapshot = evidence.snapshot("knowledge-test", false, true);
    assert_eq!(snapshot["capture_complete"], true);
    assert_eq!(snapshot["phases"][0]["provider_error_kind"], "Transport");
    assert_eq!(snapshot["phases"][0]["response_received"], true);
    assert!(snapshot["phases"][0]["agent_text"].is_null());
    assert!(matches!(&result, Err(error) if error.kind() == ErrorKind::Transport));
    evidence.response(&Err(providers_kit::KitError::new(
        ErrorKind::Timeout,
        Operation::Generate,
        ErrorPhase::RequestSend,
    )));
    let duplicate = evidence.snapshot("knowledge-test", false, true);
    assert_eq!(duplicate["capture_complete"], false);
    assert_eq!(duplicate["capture_failure"], "duplicate_response");
    assert_eq!(duplicate["phases"][0]["provider_error_kind"], "Transport");
}

#[tokio::test]
async fn knowledge_capture_export_failure_cannot_replace_primary_failure() {
    use knowledge_evidence::KnowledgeEvidence;
    let evidence = KnowledgeEvidence::default();
    let path =
        std::env::temp_dir().join(format!("knowledge-evidence-{}.json", uuid::Uuid::new_v4()));
    std::fs::write(&path, b"original evidence").unwrap();
    let mut cleanup = NativeCleanup::new(Duration::from_secs(1));
    cleanup
        .settle(async { evidence.export_after_cleanup(&path, "knowledge-test", false, true) })
        .await;
    let bytes = std::fs::read(&path);
    let removed = std::fs::remove_file(&path);
    let observed: Result<Result<(), tokio::time::error::Elapsed>, Box<dyn std::any::Any + Send>> =
        Err(Box::new("original scenario failure".to_owned()));
    let failed =
        std::panic::catch_unwind(AssertUnwindSafe(|| cleanup.finish(observed))).unwrap_err();
    removed.unwrap();
    assert_eq!(bytes.unwrap(), b"original evidence");
    assert_eq!(
        failed.downcast_ref::<String>().unwrap(),
        "original scenario failure"
    );
}

#[tokio::test]
async fn custom_anthropic_tap_retains_normalization_rule_without_changing_error() {
    use custom_provider_evidence::{AnthropicEvidence, CloudPhase};
    use futures_util::StreamExt;
    use providers_kit::error::{ErrorKind, ErrorPhase, Operation, ResponseViolation};
    use providers_kit::generation::{GenerateEvent, GenerateEventStream, GenerateRequest, Message};
    use providers_kit::{KitError, ModelId};
    use std::sync::Mutex;

    let model = ModelId::new("claude-sonnet-5-5").unwrap();
    let request =
        GenerateRequest::new(vec![Message::user_text("PRIVATE_PROMPT").unwrap()]).unwrap();
    let evidence = Arc::new(Mutex::new(AnthropicEvidence::new(model.as_str())));
    let generation = evidence
        .lock()
        .unwrap()
        .begin(CloudPhase::Initial, &model, &request, true);
    let error = KitError::new(
        ErrorKind::InvalidResponse(ResponseViolation::ProtocolViolation {
            rule: "nonempty_generation",
        }),
        Operation::GenerateStream,
        ErrorPhase::Normalize,
    );
    let kind = error.kind();
    let context = *error.context();
    let source = GenerateEventStream::new(futures_util::stream::iter([
        Ok(GenerateEvent::ThinkingDelta {
            delta: "PRIVATE_REASONING".to_owned(),
        }),
        Err(error),
    ]));
    let mut observed = AnthropicEvidence::inspect_stream(&evidence, generation, source);
    assert!(
        matches!(observed.next().await, Some(Ok(GenerateEvent::ThinkingDelta { delta })) if delta == "PRIVATE_REASONING")
    );
    let returned = observed.next().await.unwrap().unwrap_err();
    assert_eq!(returned.kind(), kind);
    assert_eq!(*returned.context(), context);
    assert!(observed.next().await.is_none());
    let snapshot = evidence.lock().unwrap().snapshot(false, true);
    assert!(!snapshot.to_string().contains("PRIVATE_"));
    assert_eq!(
        snapshot["generations"][0]["error"]["protocol_rule"],
        "nonempty_generation"
    );
    assert_eq!(snapshot["generations"][0]["error"]["phase"], "Normalize");
    assert_eq!(snapshot["capture_complete"], true);
}

#[test]
fn custom_anthropic_tap_retains_acquisition_error_before_any_event() {
    use custom_provider_evidence::{AnthropicEvidence, CloudPhase};
    use providers_kit::error::{ErrorKind, ErrorPhase, Operation, ResponseViolation};
    use providers_kit::generation::{GenerateRequest, Message};
    use providers_kit::{KitError, ModelId};

    let model = ModelId::new("claude-sonnet-5-5").unwrap();
    let request =
        GenerateRequest::new(vec![Message::user_text("PRIVATE_PROMPT").unwrap()]).unwrap();
    let mut evidence = AnthropicEvidence::new(model.as_str());
    let generation = evidence.begin(CloudPhase::Reopened, &model, &request, true);
    let error = KitError::new(
        ErrorKind::InvalidResponse(ResponseViolation::ProtocolViolation {
            rule: "original_normalization_rule",
        }),
        Operation::GenerateStream,
        ErrorPhase::Normalize,
    );
    evidence.acquisition_error(generation, &error);
    let snapshot = evidence.snapshot(false, true);
    assert_eq!(snapshot["generations"][0]["acquisition_error"], true);
    assert_eq!(snapshot["generations"][0]["phase"], "reopened");
    assert_eq!(
        snapshot["generations"][0]["error"]["protocol_rule"],
        "original_normalization_rule"
    );
    assert_eq!(snapshot["generations"][0]["event_count"], 0);
    assert_eq!(snapshot["generations"][0]["events"]["error"], 0);
}

#[tokio::test]
async fn custom_anthropic_tap_preserves_text_and_incomplete_stream() {
    use custom_provider_evidence::{AnthropicEvidence, CloudPhase};
    use futures_util::StreamExt;
    use providers_kit::ModelId;
    use providers_kit::generation::{GenerateEvent, GenerateEventStream, GenerateRequest, Message};
    use std::sync::Mutex;

    let model = ModelId::new("claude-sonnet-5-5").unwrap();
    let request =
        GenerateRequest::new(vec![Message::user_text("PRIVATE_PROMPT").unwrap()]).unwrap();
    let evidence = Arc::new(Mutex::new(AnthropicEvidence::new(model.as_str())));
    let generation = evidence
        .lock()
        .unwrap()
        .begin(CloudPhase::Initial, &model, &request, true);
    let source = GenerateEventStream::new(futures_util::stream::iter([
        Ok(GenerateEvent::Started { model }),
        Ok(GenerateEvent::ContentDelta {
            delta: "PRIVATE_TEXT_é".to_owned(),
        }),
    ]));
    let mut observed = AnthropicEvidence::inspect_stream(&evidence, generation, source);
    assert!(matches!(
        observed.next().await,
        Some(Ok(GenerateEvent::Started { .. }))
    ));
    assert!(
        matches!(observed.next().await, Some(Ok(GenerateEvent::ContentDelta { delta })) if delta == "PRIVATE_TEXT_é")
    );
    assert!(observed.next().await.is_none());
    let snapshot = evidence.lock().unwrap().snapshot(false, true);
    assert_eq!(snapshot["capture_complete"], false);
    assert_eq!(snapshot["generations"][0]["terminal"], "pending");
    assert_eq!(
        snapshot["generations"][0]["delta_text_bytes"],
        "PRIVATE_TEXT_é".len()
    );
    assert!(!snapshot.to_string().contains("PRIVATE_"));
}

#[tokio::test]
async fn custom_anthropic_tap_preserves_completion_and_detects_events_after_terminal() {
    use custom_provider_evidence::{AnthropicEvidence, CloudPhase};
    use futures_util::StreamExt;
    use providers_kit::ModelId;
    use providers_kit::generation::{
        FinishReason, GenerateEvent, GenerateEventStream, GenerateRequest, GenerateResponse,
        Message, Usage,
    };
    use std::sync::Mutex;

    let model = ModelId::new("claude-sonnet-5-5").unwrap();
    let request =
        GenerateRequest::new(vec![Message::user_text("PRIVATE_PROMPT").unwrap()]).unwrap();
    let evidence = Arc::new(Mutex::new(AnthropicEvidence::new(model.as_str())));
    assert_eq!(
        evidence.lock().unwrap().snapshot(false, true)["capture_complete"],
        false
    );
    let generation = evidence
        .lock()
        .unwrap()
        .begin(CloudPhase::Initial, &model, &request, true);
    let response = GenerateResponse {
        model,
        message: Message::assistant_text(" PRIVATE_OUTPUT_é\n").unwrap(),
        finish_reason: Some(FinishReason::Stop),
        citations: Vec::new(),
        artifacts: Vec::new(),
        hosted_tool_outputs: Vec::new(),
        usage: Usage::default(),
    };
    let expected = response.clone();
    let source = GenerateEventStream::new(futures_util::stream::iter([
        Ok(GenerateEvent::Completed(Box::new(response))),
        Ok(GenerateEvent::ContentDelta {
            delta: "AFTER_TERMINAL".to_owned(),
        }),
    ]));
    let mut observed = AnthropicEvidence::inspect_stream(&evidence, generation, source);
    assert!(
        matches!(observed.next().await, Some(Ok(GenerateEvent::Completed(response))) if *response == expected)
    );
    let snapshot = evidence.lock().unwrap().snapshot(true, false);
    assert_eq!(snapshot["capture_complete"], true);
    assert_eq!(snapshot["scenario_cleanup_succeeded"], false);
    assert_eq!(
        snapshot["generations"][0]["completed_text_bytes"],
        " PRIVATE_OUTPUT_é\n".len()
    );
    assert_eq!(snapshot["generations"][0]["finish_reason"], "stop");
    assert!(!snapshot.to_string().contains("PRIVATE_"));
    assert!(
        matches!(observed.next().await, Some(Ok(GenerateEvent::ContentDelta { delta })) if delta == "AFTER_TERMINAL")
    );
    assert!(observed.next().await.is_none());
    let snapshot = evidence.lock().unwrap().snapshot(false, true);
    assert_eq!(snapshot["capture_complete"], false);
    assert_eq!(snapshot["capture_failure"], "event_after_terminal");
}

#[tokio::test]
async fn custom_anthropic_tap_drop_releases_unpolled_stream_without_forwarding_task() {
    use custom_provider_evidence::AnthropicEvidence;
    use providers_kit::KitError;
    use providers_kit::generation::{GenerateEvent, GenerateEventStream};
    use std::sync::Mutex;

    let held = Arc::new(AtomicBool::new(false));
    let weak = Arc::downgrade(&held);
    let source = futures_util::stream::unfold(held, |held| async move {
        held.store(true, Ordering::SeqCst);
        std::future::pending::<()>().await;
        Some((
            Ok::<GenerateEvent, KitError>(GenerateEvent::ContentDelta {
                delta: "unused".to_owned(),
            }),
            held,
        ))
    });
    let evidence = Arc::new(Mutex::new(AnthropicEvidence::new("claude-sonnet-5-5")));
    let observed =
        AnthropicEvidence::inspect_stream(&evidence, None, GenerateEventStream::new(source));
    assert!(!weak.upgrade().unwrap().load(Ordering::SeqCst));
    drop(observed);
    assert!(weak.upgrade().is_none());
}

#[tokio::test]
async fn custom_anthropic_tap_preserves_closed_provider_and_fresh_phase_ownership() {
    use custom_provider_evidence::{AnthropicEvidence, CloudPhase};
    use custom_provider_observation::ObservedProvider;
    use providers_kit::config::{AnthropicConfig, ApiKey, ProviderKind, TransportConfig};
    use providers_kit::error::ErrorKind;
    use providers_kit::generation::{GenerateRequest, Message};
    use providers_kit::{ModelBackend, ModelId, Provider, ProviderBackend, ProviderConfig};
    use std::sync::Mutex;

    let model_id = ModelId::new("claude-sonnet-5-5").unwrap();
    let evidence = Arc::new(Mutex::new(AnthropicEvidence::new(model_id.as_str())));
    let request =
        GenerateRequest::new(vec![Message::user_text("PRIVATE_PROMPT").unwrap()]).unwrap();
    for phase in [CloudPhase::Initial, CloudPhase::Reopened] {
        let provider = Provider::from_config(ProviderConfig::new(
            ProviderKind::Anthropic(AnthropicConfig::new(
                ApiKey::new("synthetic-test-key").unwrap(),
            )),
            TransportConfig::default(),
        ))
        .unwrap();
        let tapped = ObservedProvider::anthropic(provider, Arc::clone(&evidence));
        let model = tapped.model(model_id.clone()).unwrap();
        let selected_matches = model.model_id() == &model_id;
        let shutdown = tapped.shutdown().await;
        let error = match phase {
            CloudPhase::Initial => match model.generate_stream(&request).await {
                Ok(_) => panic!("closed lower Provider must reject streaming"),
                Err(error) => error,
            },
            CloudPhase::Reopened => model.generate(&request).await.unwrap_err(),
        };
        evidence
            .lock()
            .unwrap()
            .phase_cleanup(phase, shutdown.is_ok());
        assert!(shutdown.is_ok());
        assert!(selected_matches);
        assert_eq!(error.kind(), ErrorKind::Closed);
    }
    let snapshot = evidence.lock().unwrap().snapshot(false, true);
    assert_eq!(snapshot["capture_complete"], true);
    assert_eq!(snapshot["provider_shutdown"].as_array().unwrap().len(), 2);
    for (index, phase) in ["initial", "reopened"].into_iter().enumerate() {
        assert_eq!(snapshot["provider_shutdown"][index]["phase"], phase);
        assert_eq!(snapshot["provider_shutdown"][index]["succeeded"], true);
        assert_eq!(snapshot["generations"][index]["phase"], phase);
        assert_eq!(snapshot["phase_cleanup"][index]["succeeded"], true);
    }
}

#[test]
fn custom_anthropic_tap_bounds_diagnostics_without_retaining_payloads() {
    use custom_provider_evidence::{AnthropicEvidence, CloudPhase};
    use providers_kit::error::{ErrorKind, ErrorPhase, Operation, ResponseViolation};
    use providers_kit::generation::{GenerateEvent, GenerateRequest, Message};
    use providers_kit::{KitError, ModelId};

    let model = ModelId::new("claude-sonnet-5-5").unwrap();
    let request =
        GenerateRequest::new(vec![Message::user_text("PRIVATE_PROMPT").unwrap()]).unwrap();
    let error = KitError::new(
        ErrorKind::InvalidResponse(ResponseViolation::ProtocolViolation {
            rule: "unsafe\nrule",
        }),
        Operation::GenerateStream,
        ErrorPhase::Normalize,
    );
    let mut evidence = AnthropicEvidence::new(model.as_str());
    let generation = evidence.begin(CloudPhase::Initial, &model, &request, true);
    evidence.acquisition_error(generation, &error);
    assert_eq!(
        evidence.snapshot(false, true)["capture_failure"],
        "protocol_rule_bound"
    );
    assert!(
        !evidence
            .snapshot(false, true)
            .to_string()
            .contains("unsafe")
    );

    let mut evidence = AnthropicEvidence::new(model.as_str());
    let generation = evidence.begin(CloudPhase::Initial, &model, &request, true);
    evidence.observe(
        generation,
        &Ok(GenerateEvent::ContentDelta {
            delta: "x".repeat(1_048_577),
        }),
    );
    let snapshot = evidence.snapshot(false, true);
    assert_eq!(snapshot["capture_failure"], "text_observation_bound");
    assert_eq!(snapshot["generations"][0]["delta_text_bytes"], 1_048_576);
    assert!(snapshot.to_string().len() < 2_048);

    let mut evidence = AnthropicEvidence::new(model.as_str());
    for _ in 0..13 {
        evidence.begin(CloudPhase::Initial, &model, &request, true);
    }
    assert_eq!(
        evidence.snapshot(false, true)["capture_failure"],
        "generation_bound"
    );
    assert_eq!(
        evidence.snapshot(false, true)["generations"]
            .as_array()
            .unwrap()
            .len(),
        12
    );
    let oversized_model = AnthropicEvidence::new(&"x".repeat(1_025));
    assert_eq!(
        oversized_model.snapshot(false, true)["capture_failure"],
        "selected_model_bound"
    );
    assert_eq!(
        oversized_model.snapshot(false, true)["configured_model"],
        ""
    );
}

#[tokio::test]
async fn custom_anthropic_tap_private_export_does_not_overwrite_or_replace_primary_failure() {
    use custom_provider_evidence::AnthropicEvidence;

    let path = std::env::temp_dir().join(format!("custom-tap-{}.json", uuid::Uuid::new_v4()));
    let evidence = AnthropicEvidence::new("claude-sonnet-5-5");
    evidence.export_after_cleanup(&path, false, true).unwrap();
    let retained = std::fs::read(&path).unwrap();
    #[cfg(unix)]
    let mode = {
        use std::os::unix::fs::PermissionsExt;
        std::fs::metadata(&path).unwrap().permissions().mode() & 0o777
    };
    let mut cleanup = NativeCleanup::new(Duration::from_secs(1));
    cleanup
        .settle(async { evidence.export_after_cleanup(&path, false, true) })
        .await;
    let unchanged = std::fs::read(&path).unwrap() == retained;
    std::fs::remove_file(&path).unwrap();
    let failed = !cleanup.diagnostics().is_empty();
    let primary = std::panic::catch_unwind(AssertUnwindSafe(|| {
        cleanup.finish::<()>(Err(Box::new("original observation failure")));
    }))
    .unwrap_err();
    assert!(failed);
    assert!(unchanged);
    assert_eq!(
        primary.downcast_ref::<&str>().copied(),
        Some("original observation failure")
    );
    #[cfg(unix)]
    assert_eq!(mode, 0o600);
    let value: Value = serde_json::from_slice(&retained).unwrap();
    assert_eq!(value["scenario_cleanup_succeeded"], true);
    assert_eq!(value["capture_complete"], false);
}

struct EvidenceFixture {
    pending: Value,
    assistant: Value,
    user: Value,
    providers: Value,
    completed: Value,
}

impl EvidenceFixture {
    const PROMPT: &str = "Issue the specified question, then copy its fresh custom answer exactly.";
    const ANSWER: &str = "independent-fresh-answer-927";
    const MODEL: &str = "Configured Model";

    fn new() -> Self {
        let questions = json!([{"header":"Continue","question":"Continue?","multiple":false,
            "options":[{"label":"Yes","description":"Continue"},{"label":"No","description":"Stop"}]}]);
        let pending = json!([{"id":"que_001","sessionID":"ses_001", "questions":questions,
            "tool":{"messageID":"msg_200","callID":"call_001"}}]);
        let user = json!({"info":{"id":"msg_100","sessionID":"ses_001","role":"user",
            "model":{"providerID":"provider","modelID":"model"}},
            "parts":[{"id":"prt_100","sessionID":"ses_001","messageID":"msg_100","type":"text","text":Self::PROMPT}]});
        let assistant = json!({"info":{"id":"msg_200","sessionID":"ses_001","role":"assistant",
            "parentID":"msg_100","providerID":"provider","modelID":"model","time":{"created":10}},
            "parts":[{"id":"prt_200","sessionID":"ses_001","messageID":"msg_200","type":"tool",
                "callID":"call_001","tool":"question","state":{"status":"running","input":{"questions":questions}}}]});
        let providers = json!({"connected":["provider"],"all":[{"id":"provider","models":{"model":{
            "id":"model","providerID":"provider","name":Self::MODEL}}}]});
        let mut tool = assistant.clone();
        tool["info"]["time"]["completed"] = json!(20);
        tool["info"]["finish"] = json!("tool-calls");
        tool["parts"][0]["state"] = json!({"status":"completed","input":{"questions":questions},
            "output":format!("User has answered your questions: \"Continue?\"=\"{}\". You can now continue with the user's answers in mind.",Self::ANSWER),
            "metadata":{"answers":[[Self::ANSWER]],"truncated":false},"time":{"start":10,"end":20}});
        let terminal = json!({"info":{"id":"msg_300","sessionID":"ses_001","role":"assistant",
            "parentID":"msg_100","providerID":"provider","modelID":"model","time":{"created":21,"completed":30},"finish":"stop"},
            "parts":[{"id":"prt_300","sessionID":"ses_001","messageID":"msg_300","type":"text","text":Self::ANSWER}]});
        let completed = json!([user.clone(), tool, terminal]);
        Self {
            pending,
            assistant,
            user,
            providers,
            completed,
        }
    }

    fn descriptions(&mut self, yes: &str, no: &str) {
        for (index, description) in [yes, no].into_iter().enumerate() {
            self.pending[0]["questions"][0]["options"][index]["description"] = json!(description);
            self.assistant["parts"][0]["state"]["input"]["questions"][0]["options"][index]["description"] =
                json!(description);
            self.completed[1]["parts"][0]["state"]["input"]["questions"][0]["options"][index]["description"] =
                json!(description);
        }
    }

    fn begin(&self) -> Result<QuestionEvidence, String> {
        let pending = serde_json::to_vec(&self.pending).unwrap();
        let assistant = serde_json::to_vec(&self.assistant).unwrap();
        QuestionEvidence::begin(
            &pending,
            &assistant,
            &serde_json::to_vec(&self.user).unwrap(),
            &serde_json::to_vec(&self.providers).unwrap(),
            QuestionExpectation::new("ses_001", Self::PROMPT, Self::MODEL),
        )
    }

    fn recovered_prompt(native_output: &str) -> Self {
        let mut fixture = Self::new();
        fixture.pending = json!([]);
        fixture.completed[1]["info"]["error"] =
            json!({"name":"MessageAbortedError","data":{"message":"PRIVATE_OLD_ERROR"}});
        fixture.completed[1]["parts"][0]["state"] =
            json!({"status":"error","input":{"PRIVATE_OLD_INPUT":true}});
        fixture.completed.as_array_mut().unwrap().truncate(2);
        fixture.completed.as_array_mut().unwrap().extend([
            json!({"info":{"id":"msg_400","sessionID":"ses_001","role":"user",
                "time":{"created":30},"model":{"providerID":"provider","modelID":"model"}},
                "parts":[{"id":"prt_400","sessionID":"ses_001","messageID":"msg_400","type":"text",
                    "text":"Do not call any tool. Reply with exactly PRIVATE_RECOVERED_TOKEN and nothing else."}]}),
            json!({"info":{"id":"msg_500","sessionID":"ses_001","role":"assistant",
                "parentID":"msg_400","providerID":"provider","modelID":"model",
                "time":{"created":40,"completed":50},"finish":"stop"},
                "parts":[{"id":"prt_500","sessionID":"ses_001","messageID":"msg_500","type":"text","text":native_output}]}),
        ]);
        fixture
    }

    fn pending_mismatch_context(&self) -> Value {
        let error = match self.begin() {
            Ok(_) => panic!("typed question mismatch must remain an error"),
            Err(error) => error,
        };
        assert!(
            error.starts_with("native pending question differs from the original typed question")
        );
        assert!(
            error.len() <= 4096,
            "typed question diagnostic must be bounded"
        );
        assert!(error.is_ascii(), "native Unicode must be escaped");
        assert!(!error.chars().any(char::is_control));
        let (_, context) = error
            .split_once("; typed_question=")
            .expect("typed mismatch must identify expected and observed fields");
        serde_json::from_str(context).expect("typed mismatch context must be complete JSON")
    }

    fn tool_mismatch_context(&self) -> Value {
        let error = match self.begin() {
            Ok(_) => panic!("tool identity/input mismatch must remain an error"),
            Err(error) => error,
        };
        assert!(error.starts_with("native question tool identity or arguments differ"));
        assert!(error.len() <= 4096, "tool input diagnostic must be bounded");
        assert!(error.is_ascii(), "native Unicode must be escaped");
        assert!(!error.chars().any(char::is_control));
        let (_, context) = error
            .split_once("; tool_input=")
            .expect("tool mismatch must identify exact branch and bounded input context");
        serde_json::from_str(context).expect("tool mismatch context must be complete JSON")
    }

    fn grade(&self, portable: &str) -> Result<QuestionGrade, String> {
        self.begin()?.assess(
            &serde_json::to_vec(&self.completed).unwrap(),
            Self::ANSWER,
            portable,
        )
    }
}

#[test]
fn exact_native_question_and_copy_produce_both_successful_grades() {
    let fixture = EvidenceFixture::new();
    assert!(
        fixture
            .grade(EvidenceFixture::ANSWER)
            .unwrap()
            .model_exact_copy()
    );
    assert_eq!(
        QuestionEvidence::pending_origin(&serde_json::to_vec(&fixture.pending).unwrap()).unwrap(),
        ("ses_001".to_owned(), "msg_200".to_owned())
    );
    assert_eq!(
        QuestionEvidence::parent_user(&serde_json::to_vec(&fixture.assistant).unwrap()).unwrap(),
        "msg_100"
    );
    assert!(QuestionEvidence::require_no_pending(b"[]").is_ok());
    assert!(
        QuestionEvidence::require_no_pending(&serde_json::to_vec(&fixture.pending).unwrap())
            .is_err()
    );
    assert!(QuestionEvidence::require_no_pending(b"{}").is_err());
}

#[test]
fn question_description_copy_is_nonblocking_only_with_exact_native_inputs() {
    for (yes, no, expected) in [
        (" Continue", " Stop", [false, false]),
        ("Continue", "Stop", [true, true]),
        ("continue", "Stop", [false, true]),
        ("Continue", "Stop!", [true, false]),
        ("Continue ", "prefix Stop", [false, false]),
        ("", "", [false, false]),
        ("\nContinue\t", "\"Stop\"", [false, false]),
    ] {
        let mut fixture = EvidenceFixture::new();
        fixture.descriptions(yes, no);
        let original_pending = fixture.pending.clone();
        let original_assistant = fixture.assistant.clone();
        let original_completed = fixture.completed.clone();
        let grade = fixture
            .grade(EvidenceFixture::ANSWER)
            .expect("unchanged native descriptions must not fail the Kit scenario");
        let grade = serde_json::to_value(grade).unwrap();
        assert_eq!(grade["model_exact_copy"], true);
        assert_eq!(grade["model_yes_description_exact_copy"], expected[0]);
        assert_eq!(grade["model_no_description_exact_copy"], expected[1]);
        assert_eq!(fixture.pending, original_pending);
        assert_eq!(fixture.assistant, original_assistant);
        assert_eq!(fixture.completed, original_completed);
    }
}

#[test]
fn question_description_changes_between_native_observations_remain_blocking() {
    for boundary in ["pending", "running", "completed"] {
        for description in [
            Some(json!("Continue")),
            Some(Value::Null),
            Some(json!(true)),
            None,
        ] {
            let mut fixture = EvidenceFixture::new();
            fixture.descriptions(" Continue", " Stop");
            let option = match boundary {
                "pending" => &mut fixture.pending[0]["questions"][0]["options"][0],
                "running" => {
                    &mut fixture.assistant["parts"][0]["state"]["input"]["questions"][0]["options"]
                        [0]
                }
                "completed" => {
                    &mut fixture.completed[1]["parts"][0]["state"]["input"]["questions"][0]["options"]
                        [0]
                }
                _ => unreachable!(),
            };
            match description {
                Some(value) => option["description"] = value,
                None => {
                    option.as_object_mut().unwrap().remove("description");
                }
            }
            assert!(
                fixture.grade(EvidenceFixture::ANSWER).is_err(),
                "{boundary}"
            );
        }
    }
    for (index, actual) in [(0, "continuE"), (1, "stop")] {
        let mut fixture = EvidenceFixture::new();
        fixture.assistant["parts"][0]["state"]["input"]["questions"][0]["options"][index]["description"] =
            json!(actual);
        let context = fixture.tool_mismatch_context();
        let description = &context["fields"][format!("description{index}")];
        assert_eq!(description["kind"], "string");
        assert_eq!(description["matches"], false);
        assert_eq!(description["text"]["preview"], actual);
        assert_eq!(description["text"]["bytes"], actual.len());
        assert_eq!(description["text"]["truncated"], false);
    }
    let mut fixture = EvidenceFixture::new();
    fixture.descriptions(" Continue", " Stop");
    fixture.completed[2]["parts"][0]["text"] = json!("native output differs");
    assert!(fixture.grade(EvidenceFixture::ANSWER).is_err());
}

#[test]
fn sdk_correct_native_answer_with_model_wrong_answer_preserves_failed_quality_grade() {
    let mut fixture = EvidenceFixture::new();
    let raw = "```\n</think>\n\nContinuing...";
    fixture.completed[2]["parts"][0]["text"] = json!(raw);
    let grade = fixture
        .grade(raw)
        .expect("exact native/portable fidelity remains Kit-correct");
    assert!(!grade.model_exact_copy());
    // Exercises serialization only; this deterministic target is not the live
    // receipt log consumed by the canonical verifier.
    grade.emit("deterministic-quality-control", "1.19.3");
}

#[test]
fn terminal_text_uses_part_identity_order_without_trimming_or_synthetic_text() {
    let mut fixture = EvidenceFixture::new();
    let base = fixture.completed[2]["parts"][0].clone();
    let mut last = base.clone();
    last["id"] = json!("prt_303");
    last["text"] = json!("\nright ");
    let mut first = base.clone();
    first["id"] = json!("prt_301");
    first["text"] = json!(" left");
    first["ignored"] = json!(true);
    let mut synthetic = base;
    synthetic["id"] = json!("prt_302");
    synthetic["text"] = json!("MUST NOT LEAK");
    synthetic["synthetic"] = json!(true);
    fixture.completed[2]["parts"] = json!([last, synthetic, first]);
    assert!(!fixture.grade(" left\nright ").unwrap().model_exact_copy());
    assert!(fixture.grade("left\nright").is_err());
}

#[test]
fn complete_empty_native_terminal_is_fidelity_success_and_failed_copy_quality() {
    let mut fixture = EvidenceFixture::new();
    fixture.completed[2]["parts"] = json!([]);
    assert!(!fixture.grade("").unwrap().model_exact_copy());
    assert!(fixture.grade(EvidenceFixture::ANSWER).is_err());
}

#[test]
fn pending_question_missing_duplicate_wrong_shape_and_disabled_custom_fail() {
    for replacement in [
        json!([]),
        json!([
            EvidenceFixture::new().pending[0].clone(),
            EvidenceFixture::new().pending[0].clone()
        ]),
    ] {
        let mut fixture = EvidenceFixture::new();
        fixture.pending = replacement;
        assert!(fixture.begin().is_err());
    }
    for (pointer, value) in [
        ("/0/questions/0/header", json!("wrong")),
        ("/0/questions/0/custom", json!(false)),
        ("/0/questions/0/multiple", json!(true)),
        ("/0/questions/0/options/0/label", json!("wrong")),
        ("/0/sessionID", json!("ses_foreign")),
        ("/0/tool/callID", json!("wrong")),
        ("/0/tool/messageID", json!("msg_stale")),
        ("/0/id", json!("que_bad ")),
    ] {
        let mut fixture = EvidenceFixture::new();
        if pointer.ends_with("/custom") {
            fixture.pending[0]["questions"][0]["custom"] = value;
        } else {
            *fixture.pending.pointer_mut(pointer).unwrap() = value;
        }
        assert!(fixture.begin().is_err(), "{pointer}");
    }
}

#[test]
fn pending_question_mismatch_reports_each_field_without_accepting_it() {
    for (field, observed, expected) in [
        ("/header", json!("ContinuE"), json!("Continue")),
        ("/question", json!("Continue!"), json!("Continue?")),
        ("/options/0/label", json!("YES"), json!("Yes")),
        ("/options/1/label", json!("NO"), json!("No")),
        ("/multiple", json!(true), json!(false)),
        ("/custom", json!(false), json!(true)),
    ] {
        let mut fixture = EvidenceFixture::new();
        fixture.pending[0]["questions"][0]["custom"] = json!(true);
        *fixture.pending[0]["questions"][0]
            .pointer_mut(field)
            .unwrap() = observed.clone();
        let context = fixture.pending_mismatch_context();
        assert_eq!(
            context["expected"].pointer(field),
            Some(&expected),
            "{field}"
        );
        let actual = context["observed"].pointer(field).unwrap();
        if let Some(text) = observed.as_str() {
            assert_eq!(actual["preview"], observed, "{field}");
            assert_eq!(actual["bytes"], json!(text.len()), "{field}");
            assert_eq!(actual["truncated"], false, "{field}");
        } else {
            assert_eq!(*actual, observed, "{field}");
        }
        assert_eq!(context["observed"]["option_count"], 2);
        assert_eq!(context["observed"]["options_truncated"], false);
    }
}

#[test]
fn pending_question_mismatch_reports_option_cardinality_and_order() {
    for count in [0, 1, 3, 4096] {
        let mut fixture = EvidenceFixture::new();
        let option = fixture.pending[0]["questions"][0]["options"][0].clone();
        fixture.pending[0]["questions"][0]["options"] = json!(vec![option; count]);
        let context = fixture.pending_mismatch_context();
        assert_eq!(context["observed"]["option_count"], json!(count));
        assert_eq!(
            context["observed"]["options"].as_array().unwrap().len(),
            count.min(2)
        );
        assert_eq!(context["observed"]["options_truncated"], json!(count > 2));
    }
    let mut fixture = EvidenceFixture::new();
    fixture.pending[0]["questions"][0]["options"]
        .as_array_mut()
        .unwrap()
        .swap(0, 1);
    let context = fixture.pending_mismatch_context();
    assert_eq!(context["observed"]["option_count"], 2);
    assert_eq!(context["observed"]["options"][0]["label"]["preview"], "No");
    assert_eq!(context["observed"]["options"][1]["label"]["preview"], "Yes");
    assert_eq!(context["expected"]["options"][0]["label"], "Yes");
    assert_eq!(context["expected"]["options"][1]["label"], "No");
}

#[test]
fn pending_question_mismatch_bounds_hostile_text_and_excludes_unrelated_bodies() {
    let mut fixture = EvidenceFixture::new();
    let hostile = "\u{10ffff}\u{202e}\u{0}\n\r\t\"\\秘密".repeat(4096);
    for field in ["header", "question"] {
        fixture.pending[0]["questions"][0][field] = json!(hostile);
    }
    for option in fixture.pending[0]["questions"][0]["options"]
        .as_array_mut()
        .unwrap()
    {
        option["label"] = json!(hostile);
        option["description"] = json!(hostile);
    }
    fixture.pending[0]["questions"][0]["options"].as_array_mut().unwrap().push(
        json!({"label":"unreported-extra-option", "description":"unreported-extra-description"}),
    );
    fixture.pending[0]["credentials"] = json!("unrelated-pending-secret");
    fixture.assistant = json!({"private":"unrelated-assistant-secret"});
    fixture.user = json!({"private":"unrelated-user-secret"});
    fixture.providers = json!({"credentials":"unrelated-provider-secret"});
    let context = fixture.pending_mismatch_context();
    for field in [
        "/header",
        "/question",
        "/options/0/label",
        "/options/0/description",
        "/options/1/label",
        "/options/1/description",
    ] {
        let actual = context["observed"].pointer(field).unwrap();
        assert_eq!(actual["bytes"], json!(hostile.len()));
        assert_eq!(actual["truncated"], true);
        let preview = actual["preview"].as_str().unwrap();
        assert!(preview.len() <= 320);
        assert!(preview.starts_with(r"\u{10ffff}\u{202e}\u{0}\n\r\t"));
        assert!(!preview.chars().any(char::is_control));
    }
    let rendered = context.to_string();
    for secret in [
        "unreported-extra-option",
        "unreported-extra-description",
        "unrelated-pending-secret",
        "unrelated-assistant-secret",
        "unrelated-user-secret",
        "unrelated-provider-secret",
        "que_001",
        "ses_001",
        "msg_200",
        "call_001",
    ] {
        assert!(
            !rendered.contains(secret),
            "non-allowlisted evidence must be excluded"
        );
    }
    assert_eq!(context["observed"]["option_count"], 3);
    assert_eq!(context["observed"]["options_truncated"], true);
}

#[test]
fn pending_question_diagnostic_truncation_does_not_normalize_the_oracle() {
    for count in [31, 32, 33] {
        let mut fixture = EvidenceFixture::new();
        fixture.pending[0]["questions"][0]["header"] = json!("é".repeat(count));
        let context = fixture.pending_mismatch_context();
        let header = &context["observed"]["header"];
        assert_eq!(header["bytes"], json!(2 * count));
        assert_eq!(header["preview"], json!(r"\u{e9}".repeat(count.min(32))));
        assert_eq!(header["truncated"], json!(count > 32));
    }
    let fixture = EvidenceFixture::new();
    assert!(fixture.begin().is_ok(), "omitted custom still means true");
    let mut fixture = EvidenceFixture::new();
    fixture.pending[0]["questions"][0]["custom"] = json!(true);
    assert!(
        fixture.begin().is_ok(),
        "explicit true still satisfies the original oracle"
    );
    fixture.pending[0]["questions"][0]["custom"] = json!(false);
    assert_eq!(
        fixture.pending_mismatch_context()["observed"]["custom"],
        false
    );
    fixture.pending[0]["questions"][0]["custom"] = Value::Null;
    assert!(
        fixture.begin().is_err(),
        "null must not acquire omission semantics"
    );
}

#[test]
fn explicit_null_flags_cannot_impersonate_valid_omission_defaults() {
    let mut fixture = EvidenceFixture::new();
    fixture.pending[0]["questions"][0]["custom"] = Value::Null;
    assert!(fixture.begin().is_err());
    let mut fixture = EvidenceFixture::new();
    fixture.completed[2]["parts"][0]["synthetic"] = Value::Null;
    assert!(fixture.grade(EvidenceFixture::ANSWER).is_err());
}

#[test]
fn native_root_and_tool_correlation_cannot_be_inferred_from_matching_text() {
    for (pointer, value) in [
        ("/info/parentID", json!("msg_foreign")),
        ("/info/modelID", json!("other")),
        ("/info/sessionID", json!("ses_foreign")),
        ("/parts/0/messageID", json!("msg_foreign")),
        ("/parts/0/state/input/questions/0/question", json!("Wrong?")),
        ("/parts/0/id", json!("prt_200 ")),
    ] {
        let mut fixture = EvidenceFixture::new();
        *fixture.assistant.pointer_mut(pointer).unwrap() = value;
        assert!(fixture.begin().is_err(), "{pointer}");
    }
    for parent in [Value::Null, json!("msg_parent"), json!(17)] {
        let mut fixture = EvidenceFixture::new();
        fixture.user["info"]["parentID"] = parent;
        assert!(fixture.begin().is_err());
    }
    let mut fixture = EvidenceFixture::new();
    fixture.user["parts"][0]["text"] = json!("stale prompt");
    assert!(fixture.begin().is_err());
}

#[test]
fn native_tool_mismatch_identifies_each_branch_without_exposing_identity() {
    for (pointer, value, expected) in [
        (
            "/parts/0/callID",
            json!("private-foreign-call"),
            [false, true, true],
        ),
        (
            "/parts/0/tool",
            json!("private-other-tool"),
            [true, false, true],
        ),
        (
            "/parts/0/state/input/questions/0/question",
            json!("Wrong?"),
            [true, true, false],
        ),
    ] {
        let mut fixture = EvidenceFixture::new();
        *fixture.assistant.pointer_mut(pointer).unwrap() = value;
        let context = fixture.tool_mismatch_context();
        assert_eq!(context["call_id_matches"], expected[0]);
        assert_eq!(context["tool_name_matches"], expected[1]);
        assert_eq!(context["input_matches"], expected[2]);
        assert_eq!(context["state"], "running");
        assert_eq!(context["fields"]["custom"]["kind"], "missing");
        assert_eq!(context["fields"]["custom"]["matches"], true);
        let rendered = context.to_string();
        for excluded in [
            "private-foreign-call",
            "private-other-tool",
            "call_001",
            "msg_200",
            "ses_001",
        ] {
            assert!(!rendered.contains(excluded));
        }
    }
}

#[test]
fn native_tool_mismatch_preserves_absent_default_and_extra_field_distinctions() {
    let mut fixture = EvidenceFixture::new();
    fixture.pending[0]["questions"][0]["custom"] = json!(true);
    assert!(
        fixture.begin().is_ok(),
        "pending default does not add an input field"
    );
    for (value, kind) in [
        (json!(true), "boolean"),
        (Value::Null, "null"),
        (json!("true"), "string"),
    ] {
        let mut fixture = EvidenceFixture::new();
        fixture.assistant["parts"][0]["state"]["input"]["questions"][0]["custom"] = value.clone();
        let context = fixture.tool_mismatch_context();
        assert_eq!(context["input_matches"], false);
        assert_eq!(context["fields"]["custom"]["kind"], kind);
        assert_eq!(context["fields"]["custom"]["matches"], false);
        assert_eq!(context["fields"]["entry"]["extra"], 1);
        if value.is_boolean() {
            assert_eq!(context["fields"]["custom"]["value"], value);
        }
    }
    let mut fixture = EvidenceFixture::new();
    fixture.assistant["parts"][0]["state"]["input"]["questions"][0]
        .as_object_mut()
        .unwrap()
        .remove("multiple");
    let context = fixture.tool_mismatch_context();
    assert_eq!(context["fields"]["multiple"]["kind"], "missing");
    assert_eq!(context["fields"]["multiple"]["matches"], false);
    for (value, kind) in [
        (json!(true), "boolean"),
        (Value::Null, "null"),
        (json!("false"), "string"),
    ] {
        let mut fixture = EvidenceFixture::new();
        fixture.assistant["parts"][0]["state"]["input"]["questions"][0]["multiple"] = value;
        let context = fixture.tool_mismatch_context();
        assert_eq!(context["fields"]["multiple"]["kind"], kind);
        assert_eq!(context["fields"]["multiple"]["matches"], false);
    }
    let mut fixture = EvidenceFixture::new();
    fixture.assistant["parts"][0]["state"]["input"]["unreported-secret-key"] =
        json!({"secret":"unreported-value"});
    let context = fixture.tool_mismatch_context();
    assert_eq!(context["fields"]["root"]["extra"], 1);
    assert!(!context.to_string().contains("unreported"));
    for (value, kind) in [
        (Value::Null, "null"),
        (json!(false), "boolean"),
        (json!(7), "number"),
        (json!("unreported-root-string"), "string"),
        (json!([]), "array"),
        (json!({}), "object"),
    ] {
        let mut fixture = EvidenceFixture::new();
        fixture.assistant["parts"][0]["state"]["input"] = value;
        let context = fixture.tool_mismatch_context();
        assert_eq!(context["fields"]["root"]["kind"], kind);
        assert_eq!(context["fields"]["questions"]["kind"], "missing");
        assert!(!context.to_string().contains("unreported-root-string"));
    }
}

#[test]
fn native_tool_mismatch_reports_exact_strings_order_and_cardinality() {
    for (path, field, expected) in [
        ("/header", "header", "Continue"),
        ("/question", "question", "Continue?"),
        ("/options/0/label", "label0", "Yes"),
        ("/options/0/description", "description0", "Continue"),
        ("/options/1/label", "label1", "No"),
        ("/options/1/description", "description1", "Stop"),
    ] {
        let mut fixture = EvidenceFixture::new();
        let changed = format!("{expected} ");
        *fixture.assistant["parts"][0]["state"]["input"]["questions"][0]
            .pointer_mut(path)
            .unwrap() = json!(changed);
        let context = fixture.tool_mismatch_context();
        assert_eq!(context["fields"][field]["matches"], false);
        assert_eq!(context["fields"][field]["text"]["preview"], changed);
        assert_eq!(
            context["fields"][field]["text"]["bytes"],
            expected.len() + 1
        );
        assert_eq!(context["fields"][field]["text"]["truncated"], false);
    }
    let mut fixture = EvidenceFixture::new();
    fixture.assistant["parts"][0]["state"]["input"]["questions"][0]["options"]
        .as_array_mut()
        .unwrap()
        .swap(0, 1);
    let context = fixture.tool_mismatch_context();
    assert_eq!(context["fields"]["options"]["count"], 2);
    assert_eq!(context["fields"]["label0"]["matches"], false);
    assert_eq!(context["fields"]["label0"]["text"]["preview"], "No");
    for options in [
        json!([]),
        json!([{"label":"Yes","description":"Continue"}]),
        json!(null),
    ] {
        let mut fixture = EvidenceFixture::new();
        fixture.assistant["parts"][0]["state"]["input"]["questions"][0]["options"] = options;
        let context = fixture.tool_mismatch_context();
        assert_eq!(context["fields"]["options"]["matches"], false);
        assert_eq!(context["fields"]["option1"]["kind"], "missing");
    }
    for count in [31, 32, 33] {
        let mut fixture = EvidenceFixture::new();
        fixture.assistant["parts"][0]["state"]["input"]["questions"][0]["header"] =
            json!("é".repeat(count));
        let context = fixture.tool_mismatch_context();
        assert_eq!(context["fields"]["header"]["text"]["bytes"], 2 * count);
        assert_eq!(context["fields"]["header"]["text"]["truncated"], count > 32);
    }
}

#[test]
fn native_tool_mismatch_bounds_hostile_inputs_without_changing_rejection() {
    let mut fixture = EvidenceFixture::new();
    let hostile = "\u{10ffff}\u{202e}\u{0}\n\r\t\"\\秘密".repeat(4096);
    for path in [
        "/header",
        "/question",
        "/options/0/label",
        "/options/0/description",
        "/options/1/label",
        "/options/1/description",
    ] {
        *fixture.assistant["parts"][0]["state"]["input"]["questions"][0]
            .pointer_mut(path)
            .unwrap() = json!(hostile);
    }
    fixture.assistant["parts"][0]["state"]["input"]["questions"][0]["options"]
        .as_array_mut()
        .unwrap()
        .push(json!({"private-extra-key":"private-extra-value"}));
    fixture.assistant["parts"][0]["state"]["input"]["questions"][0]["private-entry-key"] =
        json!(hostile);
    fixture.assistant["parts"][0]["state"]["input"]["private-root-key"] = json!(hostile);
    fixture.assistant["info"]["private-attribute"] = json!("unrelated-assistant-secret");
    fixture.user["private-attribute"] = json!("unrelated-user-secret");
    fixture.providers["private-attribute"] = json!("unrelated-provider-secret");
    let context = fixture.tool_mismatch_context();
    assert_eq!(context["input_matches"], false);
    assert_eq!(context["fields"]["root"]["extra"], 1);
    assert_eq!(context["fields"]["entry"]["extra"], 1);
    assert_eq!(context["fields"]["options"]["count"], 3);
    for name in [
        "header",
        "question",
        "label0",
        "description0",
        "label1",
        "description1",
    ] {
        assert_eq!(context["fields"][name]["text"]["bytes"], hostile.len());
        assert_eq!(context["fields"][name]["text"]["truncated"], true);
        let preview = context["fields"][name]["text"]["preview"].as_str().unwrap();
        assert!(preview.len() <= 320);
        assert!(preview.starts_with(r"\u{10ffff}\u{202e}\u{0}\n\r\t"));
    }
    for path in [
        "/header",
        "/question",
        "/options/0/label",
        "/options/0/description",
        "/options/1/label",
        "/options/1/description",
    ] {
        *fixture.assistant["parts"][0]["state"]["input"]["questions"][0]
            .pointer_mut(path)
            .unwrap() = json!("\u{10ffff}".repeat(33));
    }
    let maximum_previews = fixture.tool_mismatch_context();
    assert_eq!(
        maximum_previews["fields"]["header"]["text"]["preview"],
        r"\u{10ffff}".repeat(32)
    );
    assert_eq!(
        maximum_previews["fields"]["header"]["text"]["truncated"],
        true
    );
    let rendered = context.to_string();
    for excluded in [
        "private-extra-key",
        "private-extra-value",
        "private-entry-key",
        "private-root-key",
        "unrelated-assistant-secret",
        "unrelated-user-secret",
        "unrelated-provider-secret",
        "que_001",
        "ses_001",
        "msg_200",
        "call_001",
    ] {
        assert!(
            !rendered.contains(excluded),
            "non-allowlisted evidence must stay absent"
        );
    }
}

#[test]
fn configured_native_model_requires_one_connected_consistent_inventory_match() {
    for variant in 0..4 {
        let mut fixture = EvidenceFixture::new();
        match variant {
            0 => fixture.providers["connected"] = json!([]),
            1 => {
                fixture.providers["all"][0]["models"]["other"] =
                    json!({"id":"other","providerID":"provider","name":EvidenceFixture::MODEL})
            }
            2 => fixture.providers["all"][0]["models"]["model"]["providerID"] = json!("foreign"),
            3 => {
                let duplicate = fixture.providers["all"][0].clone();
                fixture.providers["all"]
                    .as_array_mut()
                    .unwrap()
                    .push(duplicate);
            }
            _ => unreachable!(),
        }
        assert!(fixture.begin().is_err());
    }
}

#[test]
fn completed_answer_missing_wrong_duplicate_or_stale_fails_sdk_grade() {
    for value in [
        Value::Null,
        json!([]),
        json!([["stale-answer"]]),
        json!([[EvidenceFixture::ANSWER, EvidenceFixture::ANSWER]]),
        json!([[EvidenceFixture::ANSWER], [EvidenceFixture::ANSWER]]),
    ] {
        let mut fixture = EvidenceFixture::new();
        fixture.completed[1]["parts"][0]["state"]["metadata"]["answers"] = value;
        assert!(fixture.grade(EvidenceFixture::ANSWER).is_err());
    }
    for pointer in ["output", "status"] {
        let mut fixture = EvidenceFixture::new();
        fixture.completed[1]["parts"][0]["state"][pointer] = json!("wrong");
        assert!(fixture.grade(EvidenceFixture::ANSWER).is_err());
    }
    for status in ["pending", "running", "error"] {
        let mut fixture = EvidenceFixture::new();
        fixture.completed[1]["parts"][0]["state"]["status"] = json!(status);
        assert!(fixture.grade(EvidenceFixture::ANSWER).is_err());
    }
    let mut fixture = EvidenceFixture::new();
    fixture.completed[1]["parts"][0]["state"]["time"]["compacted"] = json!(18);
    assert!(fixture.grade(EvidenceFixture::ANSWER).is_err());
    for value in [Value::Null, json!(true)] {
        let mut fixture = EvidenceFixture::new();
        fixture.completed[1]["parts"][0]["state"]["metadata"]["truncated"] = value;
        assert!(fixture.grade(EvidenceFixture::ANSWER).is_err());
    }
    let mut fixture = EvidenceFixture::new();
    fixture.completed[1]["parts"][0]["state"]["metadata"]
        .as_object_mut()
        .unwrap()
        .remove("truncated");
    assert!(fixture.grade(EvidenceFixture::ANSWER).is_err());
}

#[test]
fn incomplete_duplicate_foreign_or_stale_terminal_cannot_supply_fidelity() {
    for (pointer, value) in [
        ("/2/info/time/completed", Value::Null),
        ("/2/info/finish", json!("length")),
        ("/2/info/parentID", json!("msg_foreign")),
        ("/2/info/sessionID", json!("ses_foreign")),
        ("/2/info/modelID", json!("wrong")),
        ("/2/parts/0/text", json!("native mismatch")),
        ("/1/parts/0/callID", json!("call_foreign")),
        ("/0/parts/0/text", json!("changed original prompt")),
    ] {
        let mut fixture = EvidenceFixture::new();
        *fixture.completed.pointer_mut(pointer).unwrap() = value;
        assert!(fixture.grade(EvidenceFixture::ANSWER).is_err(), "{pointer}");
    }
    let mut fixture = EvidenceFixture::new();
    fixture.completed[2]["info"]["id"] = json!("msg_150");
    fixture.completed[2]["parts"][0]["messageID"] = json!("msg_150");
    assert!(
        fixture.grade(EvidenceFixture::ANSWER).is_err(),
        "terminal before Question must fail"
    );
    for index in [0, 1, 2] {
        let mut fixture = EvidenceFixture::new();
        let duplicate = fixture.completed[index].clone();
        fixture.completed.as_array_mut().unwrap().push(duplicate);
        assert!(fixture.grade(EvidenceFixture::ANSWER).is_err());
    }
    let mut fixture = EvidenceFixture::new();
    fixture.completed.as_array_mut().unwrap().pop();
    assert!(fixture.grade(EvidenceFixture::ANSWER).is_err());
}

#[test]
fn extra_tool_calls_and_part_identity_collisions_fail_even_with_a_correct_answer() {
    let mut fixture = EvidenceFixture::new();
    let mut extra = fixture.completed[1]["parts"][0].clone();
    extra["id"] = json!("prt_201");
    extra["callID"] = json!("call_second");
    fixture.completed[1]["parts"]
        .as_array_mut()
        .unwrap()
        .push(extra);
    assert!(fixture.grade(EvidenceFixture::ANSWER).is_err());
    let mut fixture = EvidenceFixture::new();
    fixture.completed[2]["parts"][0]["id"] = json!("prt_200");
    assert!(fixture.grade(EvidenceFixture::ANSWER).is_err());
    for error in [Value::Null, json!({"name":"UnknownError"})] {
        let mut fixture = EvidenceFixture::new();
        fixture.completed[2]["info"]["error"] = error;
        assert!(fixture.grade(EvidenceFixture::ANSWER).is_err());
    }
}

#[test]
fn malformed_and_incomplete_json_never_counts_as_complete_native_evidence() {
    let fixture = EvidenceFixture::new();
    assert!(QuestionEvidence::pending_origin(b"[{\"id\":").is_err());
    assert!(QuestionEvidence::parent_user(b"{}").is_err());
    assert!(
        fixture
            .begin()
            .unwrap()
            .assess(b"[", EvidenceFixture::ANSWER, EvidenceFixture::ANSWER)
            .is_err()
    );
    for answer in ["", "Yes", "No", "question"] {
        assert!(
            fixture
                .begin()
                .unwrap()
                .assess(
                    &serde_json::to_vec(&fixture.completed).unwrap(),
                    answer,
                    EvidenceFixture::ANSWER
                )
                .is_err()
        );
    }
}

struct ReadbackProbe {
    endpoint: String,
    requests: Arc<std::sync::Mutex<Vec<String>>>,
    held_read: Arc<tokio::sync::Notify>,
    task: tokio::task::JoinHandle<std::io::Result<()>>,
}

#[test]
fn captured_history_preserves_wrapped_native_text_and_detects_portable_repair() {
    let prompt =
        "Do not call any tool. Reply with exactly PRIVATE_RECOVERED_TOKEN and nothing else.";
    for native in [
        "<execute>PRIVATE_RECOVERED_TOKEN</execute>",
        " PRIVATE_RECOVERED_TOKEN\n",
    ] {
        let fixture = EvidenceFixture::recovered_prompt(native);
        let expectation = QuestionExpectation::new("ses_001", prompt, "model");
        let before = fixture.completed.clone();
        let (context, retained) = expectation
            .prompt_output(
                &fixture.completed,
                "provider",
                "PRIVATE_RECOVERED_TOKEN",
                native,
            )
            .unwrap();
        assert_eq!(retained, native);
        assert_eq!(context["native_equals_portable"], true);
        assert_eq!(context["native_equals_expected"], false);
        assert_eq!(context["portable_equals_expected"], false);
        assert_eq!(context["foreground_http_body_observed"], false);
        assert_eq!(fixture.completed, before);
        assert!(!context.to_string().contains("PRIVATE"));
        let (context, retained) = expectation
            .prompt_output(
                &fixture.completed,
                "provider",
                "PRIVATE_RECOVERED_TOKEN",
                "PRIVATE_RECOVERED_TOKEN",
            )
            .unwrap();
        assert_eq!(retained, native);
        assert_eq!(context["native_equals_portable"], false);
        assert_eq!(context["native_equals_expected"], false);
        assert_eq!(context["portable_equals_expected"], true);
    }
}

#[tokio::test]
async fn captured_history_failure_keeps_original_assertion_and_cleanup() {
    let cleanup_ran = Arc::new(AtomicBool::new(false));
    let observed = NativeCleanup::observe(Instant::now() + Duration::from_secs(2), async {
        let primary = std::panic::catch_unwind(|| {
            assert_eq!(
                "<execute>TOKEN</execute>", "TOKEN",
                "original Lance exact-output failure"
            );
        });
        let capture = QuestionExpectation::new("ses_001", "prompt", "model").prompt_output(
            &json!({"malformed":"history"}),
            "provider",
            "TOKEN",
            "<execute>TOKEN</execute>",
        );
        assert_eq!(capture.unwrap_err(), "messages_shape");
        if let Err(primary) = primary {
            std::panic::resume_unwind(primary);
        }
    })
    .await;
    let mut cleanup = NativeCleanup::new(Duration::from_secs(2));
    cleanup
        .settle(async {
            cleanup_ran.store(true, Ordering::SeqCst);
            Ok::<(), std::io::Error>(())
        })
        .await;
    let panic =
        std::panic::catch_unwind(AssertUnwindSafe(|| cleanup.finish(observed))).unwrap_err();
    assert!(cleanup_ran.load(Ordering::SeqCst));
    assert!(
        panic
            .downcast_ref::<String>()
            .unwrap()
            .contains("original Lance exact-output failure")
    );
}

#[tokio::test]
async fn recovery_output_readback_distinguishes_native_parity_from_exact_copy() {
    for (native, portable, equal) in [
        (
            "PRIVATE\\_RECOVERED\\_TOKEN",
            "PRIVATE\\_RECOVERED\\_TOKEN",
            true,
        ),
        (
            "PRIVATE_RECOVERED_TOKEN",
            "PRIVATE\\_RECOVERED\\_TOKEN",
            false,
        ),
    ] {
        let fixture = EvidenceFixture::recovered_prompt(native);
        let (probe, _) = ReadbackProbe::complete_question_fixture(&fixture, None).await;
        let endpoint = probe.endpoint.clone();
        let requests = probe.requests.clone();
        probe.observe(async {
            let reader = NativeQuestionReadback::new(&endpoint, Instant::now() + Duration::from_secs(5)).await;
            let context = reader.prompt_output(
                "Do not call any tool. Reply with exactly PRIVATE_RECOVERED_TOKEN and nothing else.",
                "provider", "model", "PRIVATE_RECOVERED_TOKEN", portable,
            ).await.unwrap();
            assert_eq!(context["capture"], "complete");
            assert_eq!(context["native_equals_portable"], equal);
            assert_eq!(context["native_equals_expected"], native == "PRIVATE_RECOVERED_TOKEN");
            assert_eq!(context["portable_equals_expected"], false);
            assert_eq!(context["matching_users"], 1);
            assert_eq!(context["terminal_count"], 1);
            assert_eq!(context["native"]["bytes"], native.len());
            assert_eq!(*requests.lock().unwrap(), [
                "GET /global/health", "GET /experimental/session", "GET /session/ses_001/message",
            ]);
            assert!(!context.to_string().contains("PRIVATE"));
            assert!(!context.to_string().contains("msg_"));
            assert!(!context.to_string().contains("ses_"));
        }).await;
    }
}

#[tokio::test]
async fn recovery_output_readback_rejects_ambiguous_foreign_or_incomplete_terminals() {
    for variant in 0..15 {
        let mut fixture = EvidenceFixture::recovered_prompt("PRIVATE_RECOVERED_TOKEN");
        match variant {
            0 => {
                let mut duplicate = fixture.completed[2].clone();
                duplicate["info"]["id"] = json!("msg_401");
                duplicate["parts"][0]["id"] = json!("prt_401");
                duplicate["parts"][0]["messageID"] = json!("msg_401");
                fixture.completed.as_array_mut().unwrap().push(duplicate);
            }
            1 => {
                let mut duplicate = fixture.completed[3].clone();
                duplicate["info"]["id"] = json!("msg_501");
                duplicate["parts"][0]["id"] = json!("prt_501");
                duplicate["parts"][0]["messageID"] = json!("msg_501");
                fixture.completed.as_array_mut().unwrap().push(duplicate);
            }
            2 => fixture.completed[3]["info"]["parentID"] = json!("msg_100"),
            3 => fixture.completed[3]["info"]["modelID"] = json!("foreign"),
            4 => fixture.completed[3]["parts"][0]["messageID"] = json!("msg_400"),
            5 => fixture.completed[3]["info"]["time"]["completed"] = Value::Null,
            6 => fixture.completed[3]["info"]["finish"] = json!("length"),
            7 => fixture.completed[3]["info"]["error"] = json!({"name":"APIError"}),
            8 => fixture.completed[3]["parts"][0]["id"] = json!("prt_400"),
            9 => fixture.completed = json!({"not":"a message inventory"}),
            10 => {
                fixture.completed[2]["info"]["model"]["providerID"] = json!("foreign");
                fixture.completed[3]["info"]["providerID"] = json!("foreign");
            }
            11 => fixture.completed[3]["info"]["time"]["created"] = json!(20),
            12 => {
                let mut later = fixture.completed[3].clone();
                later["info"]["id"] = json!("msg_600");
                later["info"]["time"] = json!({"created":60,"completed":70});
                later["info"]["finish"] = json!("tool-calls");
                later["parts"] = json!([]);
                fixture.completed.as_array_mut().unwrap().push(later);
            }
            13 => fixture.completed[3]["info"]["id"] = json!("malformed"),
            14 => fixture.completed[2]["info"]["time"] = Value::Null,
            _ => unreachable!(),
        }
        let (probe, _) = ReadbackProbe::complete_question_fixture(&fixture, None).await;
        let endpoint = probe.endpoint.clone();
        probe.observe(async {
            let reader = NativeQuestionReadback::new(&endpoint, Instant::now() + Duration::from_secs(5)).await;
            assert!(reader.prompt_output(
                "Do not call any tool. Reply with exactly PRIVATE_RECOVERED_TOKEN and nothing else.",
                "provider", "model", "PRIVATE_RECOVERED_TOKEN", "PRIVATE_RECOVERED_TOKEN",
            ).await.is_err(), "variant {variant} must not establish parity");
        }).await;
    }
}

#[tokio::test]
async fn recovery_output_readback_preserves_native_part_order_and_exact_text() {
    let mut fixture = EvidenceFixture::recovered_prompt("unused");
    fixture.completed[3]["parts"] = json!([
        {"id":"prt_503","sessionID":"ses_001","messageID":"msg_500","type":"text","text":"_TOKEN ","ignored":true},
        {"id":"prt_504","sessionID":"ses_001","messageID":"msg_500","type":"text","text":"PRIVATE_SYNTHETIC","synthetic":true},
        {"id":"prt_501","sessionID":"ses_001","messageID":"msg_500","type":"text","text":" PRIVATE_"},
        {"id":"prt_502","sessionID":"ses_001","messageID":"msg_500","type":"text","text":"RECOVERED"},
    ]);
    // The earlier tool step deliberately has a lexically greater ID and a later
    // array position. Creation time, not either incidental order, is authority.
    fixture.completed.as_array_mut().unwrap().push(json!({
        "info":{"id":"msg_900","sessionID":"ses_001","role":"assistant",
            "parentID":"msg_400","providerID":"provider","modelID":"model",
            "time":{"created":35,"completed":39},"finish":"tool-calls"},
        "parts":[],
    }));
    let (probe, _) = ReadbackProbe::complete_question_fixture(&fixture, None).await;
    let endpoint = probe.endpoint.clone();
    probe
        .observe(async {
            let reader =
                NativeQuestionReadback::new(&endpoint, Instant::now() + Duration::from_secs(5))
                    .await;
            let context = reader.prompt_output(
            "Do not call any tool. Reply with exactly PRIVATE_RECOVERED_TOKEN and nothing else.",
            "provider", "model", "PRIVATE_RECOVERED_TOKEN", " PRIVATE_RECOVERED_TOKEN ",
        ).await.unwrap();
            assert_eq!(context["native_equals_portable"], true);
            assert_eq!(context["native_equals_expected"], false);
            assert_eq!(
                context["native"]["fingerprint"],
                context["portable"]["fingerprint"]
            );
            assert_ne!(
                context["native"]["fingerprint"],
                context["expected"]["fingerprint"]
            );
            assert!(!context.to_string().contains("PRIVATE"));
        })
        .await;
}

#[tokio::test]
async fn recovery_output_readback_timeout_preserves_original_assertion_and_cleanup() {
    let fixture = EvidenceFixture::recovered_prompt("PRIVATE_RECOVERED_TOKEN");
    let (probe, _) =
        ReadbackProbe::complete_question_fixture(&fixture, Some("/session/ses_001/message")).await;
    let endpoint = probe.endpoint.clone();
    let requests = probe.requests.clone();
    let held_read = probe.held_read.clone();
    probe
        .observe(async {
            let reader =
                NativeQuestionReadback::new(&endpoint, Instant::now() + Duration::from_secs(5))
                    .await;
            let original = std::panic::catch_unwind(|| assert_eq!("actual", "expected"))
                .expect_err("original exact-copy assertion must fail");
            let original_text = original.downcast_ref::<String>().unwrap().clone();
            let mut primary = Some(original);
            let mut capture = Box::pin(reader.prompt_output(
            "Do not call any tool. Reply with exactly PRIVATE_RECOVERED_TOKEN and nothing else.",
            "provider", "model", "PRIVATE_RECOVERED_TOKEN", "PRIVATE_RECOVERED_TOKEN",
        ));
            tokio::select! {
                result = &mut capture => panic!("capture unexpectedly completed: {result:?}"),
                _ = held_read.notified() => {}
            }
            let diagnostic = NativeCleanup::observe(Instant::now(), capture).await;
            assert!(matches!(diagnostic, Ok(Err(_))));
            let mut cleanup = NativeCleanup::new(Duration::from_secs(1));
            let mut settled = false;
            cleanup
                .settle(async {
                    settled = true;
                    Err::<(), _>("supplementary cleanup failure")
                })
                .await;
            let restored = std::panic::catch_unwind(AssertUnwindSafe(|| {
                cleanup.finish::<()>(Err(primary.take().unwrap()));
            }))
            .unwrap_err();
            assert!(settled);
            assert_eq!(restored.downcast_ref::<String>(), Some(&original_text));
            assert_eq!(
                *requests.lock().unwrap(),
                [
                    "GET /global/health",
                    "GET /experimental/session",
                    "GET /session/ses_001/message",
                ]
            );
        })
        .await;
}

impl ReadbackProbe {
    async fn start(response: Vec<u8>) -> Self {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let endpoint = format!("http://{}", listener.local_addr().unwrap());
        let task = tokio::spawn(async move {
            let (mut socket, _) = listener.accept().await?;
            let mut buffer = [0_u8; 4096];
            let read = socket.read(&mut buffer).await?;
            if read == 0 {
                return Err(std::io::Error::from(std::io::ErrorKind::UnexpectedEof));
            }
            socket.write_all(&response).await?;
            socket.shutdown().await
        });
        Self {
            endpoint,
            task,
            requests: Arc::new(std::sync::Mutex::new(Vec::new())),
            held_read: Arc::new(tokio::sync::Notify::new()),
        }
    }

    async fn complete_question_fixture(
        fixture: &EvidenceFixture,
        held_route: Option<&str>,
    ) -> (Self, Arc<AtomicBool>) {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let endpoint = format!("http://{}", listener.local_addr().unwrap());
        let responses = BTreeMap::from([
            ("/global/health", json!({"healthy":true,"version":"1.19.3"})),
            ("/experimental/session", json!([{"id":"ses_001"}])),
            ("/question", fixture.pending.clone()),
            (
                "/session/ses_001/message/msg_200",
                fixture.assistant.clone(),
            ),
            ("/session/ses_001/message/msg_100", fixture.user.clone()),
            ("/provider", fixture.providers.clone()),
            ("/session/ses_001/message", fixture.completed.clone()),
        ]);
        let completed = Arc::new(AtomicBool::new(false));
        let observed_completion = completed.clone();
        let requests = Arc::new(std::sync::Mutex::new(Vec::new()));
        let recorded = requests.clone();
        let held_read = Arc::new(tokio::sync::Notify::new());
        let held_seen = held_read.clone();
        let held_route = held_route.map(str::to_owned);
        let task = tokio::spawn(async move {
            loop {
                let (mut socket, _) = listener.accept().await?;
                let mut request = Vec::new();
                while !request.windows(4).any(|bytes| bytes == b"\r\n\r\n") {
                    let mut chunk = [0_u8; 1024];
                    let count = socket.read(&mut chunk).await?;
                    if count == 0 || request.len() + count > 4096 {
                        return Err(std::io::Error::from(std::io::ErrorKind::InvalidData));
                    }
                    request.extend_from_slice(&chunk[..count]);
                }
                let request = std::str::from_utf8(&request).map_err(std::io::Error::other)?;
                let mut words = request
                    .lines()
                    .next()
                    .unwrap_or_default()
                    .split_whitespace();
                let method = words.next().unwrap_or_default();
                let target = words.next().unwrap_or_default();
                let url = reqwest::Url::parse(&format!("http://localhost{target}"))
                    .map_err(std::io::Error::other)?;
                if !url
                    .query_pairs()
                    .any(|(key, value)| key == "directory" && value == env!("CARGO_MANIFEST_DIR"))
                {
                    return Err(std::io::Error::from(std::io::ErrorKind::InvalidInput));
                }
                let route = url.path();
                recorded.lock().unwrap().push(format!("{method} {route}"));
                if held_route.as_deref() == Some(route) {
                    held_seen.notify_one();
                    std::future::pending::<()>().await;
                }
                let value = responses.get(route);
                let (status, value) = match (method, route, value) {
                    ("GET", "/question", Some(_)) if observed_completion.load(Ordering::SeqCst) => {
                        ("200 OK", json!([]))
                    }
                    ("GET", _, Some(value)) => ("200 OK", value.clone()),
                    _ => ("404 Not Found", json!({"error":"unknown test-local route"})),
                };
                let body = serde_json::to_vec(&value).map_err(std::io::Error::other)?;
                let header = format!(
                    "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                    body.len()
                );
                socket.write_all(header.as_bytes()).await?;
                socket.write_all(&body).await?;
                socket.shutdown().await?;
            }
        });
        (
            Self {
                endpoint,
                task,
                requests,
                held_read,
            },
            completed,
        )
    }

    async fn observe(self, observation: impl Future<Output = ()>) {
        let observed = AssertUnwindSafe(observation).catch_unwind().await;
        // This single fixture task only accepts/reads/writes this one socket.
        // Stop it after observation, and retain its handle through the join.
        self.task.abort();
        let joined = self.task.await;
        let mut cleanup = NativeCleanup::new(Duration::from_secs(5));
        cleanup
            .settle(async {
                match joined {
                    Ok(Ok(())) => Ok(()),
                    Ok(Err(error))
                        if matches!(
                            error.kind(),
                            std::io::ErrorKind::BrokenPipe | std::io::ErrorKind::ConnectionReset
                        ) =>
                    {
                        Ok(())
                    }
                    Ok(Err(error)) => Err(error.to_string()),
                    Err(error) if error.is_cancelled() => Ok(()),
                    Err(error) => Err(error.to_string()),
                }
            })
            .await;
        cleanup.finish(observed.map(Ok));
    }
}

#[tokio::test]
async fn native_readback_rejects_incomplete_bodies_and_paginated_evidence_before_grading() {
    let health = br#"{"healthy":true,"version":"1.19.3"}"#;
    let paginated = [format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nX-Next-Cursor: next\r\nConnection: close\r\n\r\n", health.len()).into_bytes(), health.to_vec()].concat();
    let mut oversized = health.to_vec();
    oversized.resize((16 << 20) + 1, b' ');
    let oversized = [
        format!(
            "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
            oversized.len()
        )
        .into_bytes(),
        oversized,
    ]
    .concat();
    for response in [
        b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\nConnection: close\r\n\r\n{\"healthy\":true"
            .to_vec(),
        paginated,
        oversized,
    ] {
        let probe = ReadbackProbe::start(response).await;
        let endpoint = probe.endpoint.clone();
        probe
            .observe(async {
                let result = AssertUnwindSafe(NativeQuestionReadback::new(
                    &endpoint,
                    Instant::now() + Duration::from_secs(5),
                ))
                .catch_unwind()
                .await;
                assert!(
                    result.is_err(),
                    "incomplete or paginated native evidence must not yield a reader"
                );
            })
            .await;
    }
}

#[tokio::test]
async fn native_readback_accepts_a_complete_health_response() {
    let body = br#"{"healthy":true,"version":"1.19.3"}"#;
    let response = format!(
        "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
        body.len()
    )
    .into_bytes();
    let probe = ReadbackProbe::start([response, body.to_vec()].concat()).await;
    let endpoint = probe.endpoint.clone();
    probe
        .observe(async {
            let reader =
                NativeQuestionReadback::new(&endpoint, Instant::now() + Duration::from_secs(5))
                    .await;
            assert_eq!(reader.version(), "1.19.3");
        })
        .await;
}

#[tokio::test]
async fn complete_native_readback_preserves_pending_to_completed_identity_and_answer() {
    let fixture = EvidenceFixture::new();
    let (probe, completed) = ReadbackProbe::complete_question_fixture(&fixture, None).await;
    let endpoint = probe.endpoint.clone();
    probe
        .observe(async {
            let reader =
                NativeQuestionReadback::new(&endpoint, Instant::now() + Duration::from_secs(5))
                    .await;
            assert_eq!(
                reader.sessions().await,
                BTreeSet::from(["ses_001".to_owned()])
            );
            let session = reader.created_session(&BTreeSet::new()).await;
            let evidence = reader
                .pending(&session, EvidenceFixture::PROMPT, EvidenceFixture::MODEL)
                .await;
            completed.store(true, Ordering::SeqCst);
            let grade = reader
                .completed(
                    evidence,
                    &session,
                    EvidenceFixture::ANSWER,
                    EvidenceFixture::ANSWER,
                )
                .await;
            assert!(grade.model_exact_copy());
            assert_eq!(reader.version(), "1.19.3");
        })
        .await;
}

#[tokio::test]
async fn failed_question_capture_distinguishes_native_state_without_regrading() {
    for (state, text, error) in [
        (None, "", false),
        (Some("running"), "", false),
        (Some("completed"), "answer", false),
        (Some("error"), "", true),
    ] {
        let mut fixture = EvidenceFixture::new();
        if let Some(state) = state {
            fixture.completed[1]["parts"][0]["state"]["status"] = json!(state);
        }
        fixture.completed[2]["parts"][0]["text"] = json!(text);
        if error {
            fixture.completed[2]["info"]["error"] =
                json!({"name":"APIError","data":{"message":"PRIVATE ERROR"}});
        }
        if state.is_none() {
            fixture.completed.as_array_mut().unwrap().remove(1);
            fixture.pending = json!([]);
        }
        let (probe, _) = ReadbackProbe::complete_question_fixture(&fixture, None).await;
        let endpoint = probe.endpoint.clone();
        let requests = probe.requests.clone();
        probe
            .observe(async {
                let reader =
                    NativeQuestionReadback::new(&endpoint, Instant::now() + Duration::from_secs(5))
                        .await;
                assert_eq!(
                    requests.lock().unwrap().len(),
                    1,
                    "ordinary reader setup adds no failure reads"
                );
                let mut primary = None;
                let report = reader
                    .capture_failure(
                        "ses_001",
                        EvidenceFixture::PROMPT,
                        &mut primary,
                        Box::new("original failure"),
                    )
                    .await;
                let context: Value = serde_json::from_str(&report).unwrap();
                assert_eq!(context["capture"], "complete");
                assert_eq!(context["question_tool_calls"], usize::from(state.is_some()));
                assert_eq!(
                    context["pending_same_session"],
                    usize::from(state.is_some())
                );
                if let Some(state) = state {
                    assert_eq!(context["assistants"][0]["question_states"][state], 1);
                }
                let terminal = context["assistants"].as_array().unwrap().last().unwrap();
                assert_eq!(terminal["text_bytes"], text.len());
                assert_eq!(terminal["completion"], "present");
                assert_eq!(terminal["finish"], "stop");
                assert_eq!(terminal["error"], if error { "api" } else { "absent" });
                assert_eq!(
                    primary.take().unwrap().downcast_ref::<&str>(),
                    Some(&"original failure")
                );
                assert_eq!(
                    *requests.lock().unwrap(),
                    [
                        "GET /global/health",
                        "GET /session/ses_001/message",
                        "GET /question"
                    ]
                );
                assert!(
                    !report.contains("PRIVATE ERROR")
                        && !report.contains("ses_001")
                        && !report.contains("msg_")
                );
            })
            .await;
    }
}

#[tokio::test]
async fn failed_question_capture_retains_counts_and_field_kinds_when_typed_shape_fails() {
    for (multiple, kind, valid) in [
        (None, "missing", false),
        (Some(Value::Null), "null", false),
        (Some(json!("PRIVATE MULTIPLE")), "invalid", false),
        (Some(json!(false)), "false", true),
        (Some(json!(true)), "true", true),
    ] {
        let mut fixture = EvidenceFixture::new();
        for question in [
            &mut fixture.pending[0]["questions"][0],
            &mut fixture.completed[1]["parts"][0]["state"]["input"]["questions"][0],
        ] {
            match &multiple {
                Some(value) => question["multiple"] = value.clone(),
                None => {
                    question.as_object_mut().unwrap().remove("multiple");
                }
            }
        }
        assert_eq!(
            QuestionEvidence::pending_origin(&serde_json::to_vec(&fixture.pending).unwrap())
                .is_ok(),
            valid,
            "diagnostic counting must not change strict decoding"
        );
        if multiple != Some(json!(false)) {
            assert!(
                fixture.begin().is_err(),
                "the exact false oracle remains blocking"
            );
        }
        let (probe, _) = ReadbackProbe::complete_question_fixture(&fixture, None).await;
        let endpoint = probe.endpoint.clone();
        probe
            .observe(async {
                let reader =
                    NativeQuestionReadback::new(&endpoint, Instant::now() + Duration::from_secs(5))
                        .await;
                let mut primary = None;
                let report = reader
                    .capture_failure(
                        "ses_001",
                        EvidenceFixture::PROMPT,
                        &mut primary,
                        Box::new("original failure"),
                    )
                    .await;
                let context: Value = serde_json::from_str(&report).unwrap();
                assert_eq!(context["pending_questions"], 1);
                assert_eq!(context["pending_same_session"], 1);
                assert_eq!(context["questions_snapshot"], "after_failure");
                assert_eq!(
                    context["capture"],
                    if valid { "complete" } else { "incomplete" }
                );
                assert_eq!(
                    context["questions_read"],
                    if valid { "complete" } else { "questions_shape" }
                );
                for observed_kind in ["missing", "null", "invalid", "false", "true"] {
                    assert_eq!(
                        context["pending_multiple"][observed_kind],
                        usize::from(observed_kind == kind)
                    );
                    assert_eq!(
                        context["assistants"][0]["question_multiple"][observed_kind],
                        usize::from(observed_kind == kind)
                    );
                }
                assert_eq!(context["assistants"][0]["question_states"]["completed"], 1);
                assert!(report.len() <= 4096);
                for secret in [
                    "PRIVATE",
                    "ses_",
                    "msg_",
                    "que_",
                    "call_",
                    "Continue?",
                    EvidenceFixture::PROMPT,
                ] {
                    assert!(!report.contains(secret), "diagnostics leaked {secret}");
                }
                assert_eq!(
                    primary.take().unwrap().downcast_ref::<&str>(),
                    Some(&"original failure")
                );
            })
            .await;
    }
}

#[tokio::test]
async fn failed_question_capture_distinguishes_empty_ambiguous_and_invalid_inventories() {
    let fixture = EvidenceFixture::new();
    let mut foreign = fixture.pending[0].clone();
    foreign["id"] = json!("que_PRIVATE");
    foreign["sessionID"] = json!("ses_PRIVATE");
    for (inventory, count, same_session, valid) in [
        (json!([]), Some(0), Some(0), true),
        (json!([fixture.pending[0], foreign]), Some(2), Some(1), true),
        (json!([null]), Some(1), Some(0), false),
        (json!({"PRIVATE":"BODY"}), None, None, false),
    ] {
        let mut fixture = EvidenceFixture::new();
        fixture.pending = inventory;
        assert!(
            QuestionEvidence::pending_origin(&serde_json::to_vec(&fixture.pending).unwrap())
                .is_err()
        );
        let (probe, _) = ReadbackProbe::complete_question_fixture(&fixture, None).await;
        let endpoint = probe.endpoint.clone();
        probe
            .observe(async {
                let reader =
                    NativeQuestionReadback::new(&endpoint, Instant::now() + Duration::from_secs(5))
                        .await;
                let mut primary = None;
                let report = reader
                    .capture_failure(
                        "ses_001",
                        EvidenceFixture::PROMPT,
                        &mut primary,
                        Box::new("original failure"),
                    )
                    .await;
                let context: Value = serde_json::from_str(&report).unwrap();
                assert_eq!(context["pending_questions"], json!(count));
                assert_eq!(context["pending_same_session"], json!(same_session));
                assert_eq!(context["questions_snapshot"], "after_failure");
                assert_eq!(
                    context["questions_read"],
                    if valid { "complete" } else { "questions_shape" }
                );
                assert_eq!(
                    context["capture"],
                    if valid { "complete" } else { "incomplete" }
                );
                assert!(primary.is_some());
                for secret in ["PRIVATE", "BODY", "ses_", "que_"] {
                    assert!(!report.contains(secret));
                }
            })
            .await;
    }
}

#[tokio::test]
async fn failed_question_capture_labels_later_inventory_without_replacing_original_panic() {
    let mut fixture = EvidenceFixture::new();
    fixture.pending[0]["questions"][0]
        .as_object_mut()
        .unwrap()
        .remove("multiple");
    let (probe, completed) = ReadbackProbe::complete_question_fixture(&fixture, None).await;
    let endpoint = probe.endpoint.clone();
    let requests = probe.requests.clone();
    probe
        .observe(async {
            let reader =
                NativeQuestionReadback::new(&endpoint, Instant::now() + Duration::from_secs(5))
                    .await;
            let failure = match AssertUnwindSafe(reader.pending(
                "ses_001",
                EvidenceFixture::PROMPT,
                EvidenceFixture::MODEL,
            ))
            .catch_unwind()
            .await
            {
                Ok(_) => panic!("omitted multiple must still reject pending evidence"),
                Err(failure) => failure,
            };
            let original = failure.downcast_ref::<String>().unwrap().clone();
            assert!(original.contains("native question must have one exact tool origin"));
            assert!(original.contains("missing field `multiple`"));
            completed.store(true, Ordering::SeqCst);
            let mut primary = None;
            let report = reader
                .capture_failure("ses_001", EvidenceFixture::PROMPT, &mut primary, failure)
                .await;
            let context: Value = serde_json::from_str(&report).unwrap();
            assert_eq!(context["questions_snapshot"], "after_failure");
            assert_eq!(
                context["pending_questions"], 0,
                "later native state is not the original failed snapshot"
            );
            assert_eq!(
                primary.take().unwrap().downcast_ref::<String>(),
                Some(&original)
            );
            assert_eq!(
                *requests.lock().unwrap(),
                [
                    "GET /global/health",
                    "GET /question",
                    "GET /session/ses_001/message",
                    "GET /question"
                ]
            );
        })
        .await;
}

#[tokio::test]
async fn failed_question_capture_bounds_hostile_rows_and_reports_missing_correlation() {
    for malformed in [false, true] {
        let mut fixture = EvidenceFixture::new();
        fixture.pending = json!([]);
        let mut messages = vec![fixture.user.clone()];
        for index in 0..64 {
            let mut assistant = fixture.completed[2].clone();
            let id = format!("msg_{:04}", index + 200);
            assistant["info"]["id"] = json!(id);
            assistant["parts"][0]["messageID"] = json!(id);
            assistant["parts"][0]["text"] = json!("PRIVATE OUTPUT".repeat(1000));
            assistant["info"]["finish"] = json!("PRIVATE FINISH".repeat(1000));
            assistant["info"]["error"] =
                json!({"name":"PRIVATE ERROR","private_key":"DO NOT EMIT"});
            messages.push(assistant);
        }
        if malformed {
            messages[0]["parts"][0]["text"] = json!("a different prompt");
        }
        fixture.completed = json!(messages);
        let (probe, _) = ReadbackProbe::complete_question_fixture(&fixture, None).await;
        let endpoint = probe.endpoint.clone();
        probe
            .observe(async {
                let reader =
                    NativeQuestionReadback::new(&endpoint, Instant::now() + Duration::from_secs(5))
                        .await;
                let mut primary = None;
                let report = reader
                    .capture_failure(
                        "ses_001",
                        EvidenceFixture::PROMPT,
                        &mut primary,
                        Box::new("original failure"),
                    )
                    .await;
                let context: Value = serde_json::from_str(&report).unwrap();
                if malformed {
                    assert_eq!(context["capture"], "incomplete");
                    assert_eq!(context["reason"], "root_correlation");
                } else {
                    assert_eq!(context["capture"], "complete");
                    assert_eq!(context["assistant_count"], 64);
                    assert_eq!(context["assistant_summaries_omitted"], 60);
                    assert_eq!(context["assistants"].as_array().unwrap().len(), 4);
                    assert_eq!(context["question_tool_calls"], 0);
                    assert_eq!(context["pending_same_session"], 0);
                }
                assert!(report.len() <= 4 * 1024);
                for secret in [
                    "PRIVATE",
                    "DO NOT EMIT",
                    "private_key",
                    "msg_",
                    "ses_",
                    EvidenceFixture::PROMPT,
                ] {
                    assert!(!report.contains(secret));
                }
                assert!(
                    primary.is_some(),
                    "diagnostics cannot turn the scenario failure into success"
                );
            })
            .await;
    }
}

#[tokio::test]
async fn failed_question_capture_keeps_primary_when_original_deadline_drops_reads() {
    let fixture = EvidenceFixture::new();
    let (probe, _) = ReadbackProbe::complete_question_fixture(&fixture, Some("/question")).await;
    let endpoint = probe.endpoint.clone();
    let requests = probe.requests.clone();
    let held_read = probe.held_read.clone();
    probe
        .observe(async {
            let reader =
                NativeQuestionReadback::new(&endpoint, Instant::now() + Duration::from_secs(5))
                    .await;
            let mut primary = None;
            let mut capture = Box::pin(reader.capture_failure(
                "ses_001",
                EvidenceFixture::PROMPT,
                &mut primary,
                Box::new("original failure"),
            ));
            tokio::select! {
                result = &mut capture => panic!("capture completed before its held read: {result}"),
                _ = held_read.notified() => {}
            }
            let observed = NativeCleanup::observe(Instant::now(), capture).await;
            assert!(
                matches!(observed, Ok(Err(_))),
                "the original cutoff must cancel diagnostic observation"
            );
            let failure = primary
                .take()
                .expect("the failure must outlive the dropped read");
            let mut cleanup = NativeCleanup::new(Duration::from_secs(1));
            let mut settled = false;
            cleanup
                .settle(async {
                    settled = true;
                    Ok::<(), ()>(())
                })
                .await;
            let restored =
                std::panic::catch_unwind(AssertUnwindSafe(|| cleanup.finish::<()>(Err(failure))));
            assert!(settled);
            assert_eq!(
                restored.unwrap_err().downcast_ref::<&str>(),
                Some(&"original failure")
            );
            assert_eq!(
                *requests.lock().unwrap(),
                [
                    "GET /global/health",
                    "GET /session/ses_001/message",
                    "GET /question"
                ]
            );
        })
        .await;
}

#[tokio::test]
async fn failed_question_capture_reports_transport_and_shape_failures_without_masking_primary() {
    let mut fixture = EvidenceFixture::new();
    fixture.completed = json!({"private_key":"PRIVATE BODY"});
    let (probe, _) = ReadbackProbe::complete_question_fixture(&fixture, None).await;
    let endpoint = probe.endpoint.clone();
    let requests = probe.requests.clone();
    probe
        .observe(async {
            let reader =
                NativeQuestionReadback::new(&endpoint, Instant::now() + Duration::from_secs(5))
                    .await;
            let mut primary = None;
            let report = reader
                .capture_failure(
                    "ses_001",
                    EvidenceFixture::PROMPT,
                    &mut primary,
                    Box::new("first failure"),
                )
                .await;
            assert_eq!(
                serde_json::from_str::<Value>(&report).unwrap()["reason"],
                "messages_shape"
            );
            assert!(!report.contains("PRIVATE BODY"));
            let missing = reader
                .capture_failure(
                    "ses_missing",
                    EvidenceFixture::PROMPT,
                    &mut primary,
                    Box::new("later failure"),
                )
                .await;
            let context: Value = serde_json::from_str(&missing).unwrap();
            assert_eq!(context["capture"], "incomplete");
            assert_eq!(context["messages"], "http_status");
            assert!(!missing.contains("ses_missing"));
            assert_eq!(
                primary.take().unwrap().downcast_ref::<&str>(),
                Some(&"first failure")
            );
            assert_eq!(
                requests
                    .lock()
                    .unwrap()
                    .iter()
                    .filter(|request| request.as_str() == "GET /session/ses_missing/message")
                    .count(),
                1
            );
        })
        .await;
}

#[test]
fn fresh_reopen_expectation_preserves_exact_text_and_bounds() {
    for expected in ["PENDING_INTERACTION_REOPENED-123", "a*é\n"] {
        let fresh = FreshOutputExpectation::new(expected.to_owned());
        assert_eq!(fresh.expected(), expected);
        assert_eq!(
            fresh.prompt(),
            format!("Do not call any tool. Reply with exactly {expected} and nothing else.")
        );
    }
    let maximum = "é".repeat(128);
    assert_eq!(
        FreshOutputExpectation::new(maximum.clone()).expected(),
        maximum
    );
    for invalid in [String::new(), "é".repeat(129)] {
        let rejected = std::panic::catch_unwind(|| FreshOutputExpectation::new(invalid));
        assert!(rejected.is_err());
    }
}

#[tokio::test]
async fn fresh_reopen_capture_observes_success_without_manufacturing_failure() {
    let mut fixture = EvidenceFixture::new();
    fixture.completed[0]["info"]["time"] = json!({"created":1});
    let (probe, _) = ReadbackProbe::complete_question_fixture(&fixture, None).await;
    let endpoint = probe.endpoint.clone();
    probe
        .observe(async {
            let deadline = Instant::now() + Duration::from_secs(5);
            let observed = NativeCleanup::observe(deadline, async {
                assert_eq!(
                    fixture.completed[2]["parts"][0]["text"],
                    EvidenceFixture::ANSWER
                );
            })
            .await;
            let capture = NativeCleanup::observe(deadline, async {
                let reader = NativeQuestionReadback::new(&endpoint, deadline).await;
                reader
                    .prompt_output(
                        EvidenceFixture::PROMPT,
                        "provider",
                        "model",
                        EvidenceFixture::ANSWER,
                        EvidenceFixture::ANSWER,
                    )
                    .await
            })
            .await;
            let context = capture.unwrap().unwrap().unwrap();
            let report = context.to_string();
            assert_eq!(context["capture"], "complete");
            assert_eq!(context["kind"], "native_terminal_snapshot");
            assert_eq!(context["foreground_http_body_observed"], false);
            assert_eq!(context["portable_equals_expected"], true);
            assert_eq!(context["matching_users"], 1);
            assert_eq!(context["terminal_count"], 1);
            assert_eq!(context["model_matches_configured"], true);
            assert_eq!(context["native_equals_expected"], true);
            assert_eq!(context["native_equals_portable"], true);
            assert!(!report.contains(EvidenceFixture::ANSWER));
            NativeCleanup::new(Duration::from_secs(1)).finish(observed);
        })
        .await;
}

#[tokio::test]
async fn fresh_reopen_capture_elapsed_deadline_preserves_assertion_and_cleanup() {
    for matches_expected in [true, false] {
        let fixture = EvidenceFixture::new();
        let (probe, _) = ReadbackProbe::complete_question_fixture(&fixture, None).await;
        let endpoint = probe.endpoint.clone();
        let requests = probe.requests.clone();
        probe
            .observe(async {
                let observed =
                    NativeCleanup::observe(Instant::now() + Duration::from_secs(5), async {
                        assert!(matches_expected, "retained exact-output failure");
                    })
                    .await;
                let deadline = Instant::now();
                let capture = NativeCleanup::observe(deadline, async {
                    let reader = NativeQuestionReadback::new(&endpoint, deadline).await;
                    reader
                        .prompt_output(
                            EvidenceFixture::PROMPT,
                            "provider",
                            "model",
                            EvidenceFixture::ANSWER,
                            EvidenceFixture::ANSWER,
                        )
                        .await
                })
                .await;
                assert!(!matches!(capture, Ok(Ok(_))));
                assert!(requests.lock().unwrap().is_empty());
                let mut cleanup = NativeCleanup::new(Duration::from_secs(1));
                let mut settled = false;
                cleanup
                    .settle(async {
                        settled = true;
                        Ok::<(), ()>(())
                    })
                    .await;
                let finished = std::panic::catch_unwind(AssertUnwindSafe(|| {
                    cleanup.finish(observed);
                }));
                assert!(settled);
                if matches_expected {
                    assert!(finished.is_ok());
                } else {
                    let failure = finished.unwrap_err();
                    let message = failure
                        .downcast_ref::<&str>()
                        .copied()
                        .or_else(|| failure.downcast_ref::<String>().map(String::as_str));
                    assert_eq!(message, Some("retained exact-output failure"));
                }
            })
            .await;
    }
}

#[tokio::test]
async fn fresh_reopen_capture_setup_failure_keeps_success_and_cleanup() {
    let body = json!({"healthy": "PRIVATE_NATIVE_HEALTH_PROSE", "version": "1.19.3"}).to_string();
    let response = format!(
        "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
        body.len()
    );
    let probe = ReadbackProbe::start(response.into_bytes()).await;
    let endpoint = probe.endpoint.clone();
    probe
        .observe(async {
            let deadline = Instant::now() + Duration::from_secs(5);
            let observed = NativeCleanup::observe(deadline, async {}).await;
            let capture = NativeCleanup::observe(deadline, async {
                NativeQuestionReadback::new(&endpoint, deadline).await;
            })
            .await;
            assert!(capture.is_err());
            let mut cleanup = NativeCleanup::new(Duration::from_secs(1));
            let mut settled = false;
            cleanup
                .settle(async {
                    settled = true;
                    Ok::<(), ()>(())
                })
                .await;
            cleanup.finish(observed);
            assert!(settled);
        })
        .await;
}

#[tokio::test]
async fn fresh_reopen_capture_setup_redacts_native_health_without_replacing_primary() {
    let native_marker = "PRIVATE_NATIVE_HEALTH_PROSE";
    let body = json!({"healthy":native_marker,"version":"1.19.3"}).to_string();
    let response = format!(
        "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
        body.len()
    );
    let probe = ReadbackProbe::start(response.into_bytes()).await;
    let endpoint = probe.endpoint.clone();
    probe
        .observe(async {
            let original = std::panic::catch_unwind(|| {
                assert_eq!("No", "FRESH_REOPEN_TOKEN", "original exact-output failure");
            })
            .unwrap_err();
            let original_message = original.downcast_ref::<String>().unwrap().clone();
            // Match the live caller's ownership: the first failure is saved before
            // reader setup and remains outside the cancellable observation.
            let mut primary = Some(original);
            let deadline = Instant::now() + Duration::from_secs(5);
            let setup = NativeCleanup::observe(deadline, async {
                NativeQuestionReadback::new(&endpoint, deadline).await;
            })
            .await;
            let setup_failure = setup.expect_err("malformed native health must fail setup");
            let setup_message = setup_failure
                .downcast_ref::<String>()
                .map(String::as_str)
                .or_else(|| setup_failure.downcast_ref::<&str>().copied())
                .expect("setup failure must retain a safe diagnostic message");
            assert!(
                !setup_message.contains(native_marker),
                "reader setup exposed arbitrary native health prose"
            );
            assert!(setup_message.len() < 256);

            let mut cleanup = NativeCleanup::new(Duration::from_secs(1));
            let mut settled = false;
            cleanup
                .settle(async {
                    settled = true;
                    Ok::<(), ()>(())
                })
                .await;
            let restored = std::panic::catch_unwind(AssertUnwindSafe(|| {
                cleanup.finish::<()>(Err(primary.take().expect("original failure stays owned")));
            }));
            assert!(settled);
            assert_eq!(
                restored.unwrap_err().downcast_ref::<String>(),
                Some(&original_message)
            );
        })
        .await;
}

#[tokio::test]
async fn fresh_reopen_capture_links_output_without_printing_native_content() {
    for parent in ["msg_100", "msg_stale"] {
        let mut fixture = EvidenceFixture::new();
        fixture.completed[0]["info"]["time"] = json!({"created":1});
        fixture.completed[2]["info"]["parentID"] = json!(parent);
        fixture.completed[2]["parts"][0]["text"] = json!("PRIVATE NATIVE ANSWER");
        let (probe, _) = ReadbackProbe::complete_question_fixture(&fixture, None).await;
        let endpoint = probe.endpoint.clone();
        let requests = probe.requests.clone();
        probe
            .observe(async {
                let reader =
                    NativeQuestionReadback::new(&endpoint, Instant::now() + Duration::from_secs(5))
                        .await;
                let captured = reader
                    .prompt_output(
                        EvidenceFixture::PROMPT,
                        "provider",
                        "model",
                        EvidenceFixture::ANSWER,
                        "PRIVATE NATIVE ANSWER",
                    )
                    .await;
                let context = if parent == "msg_100" {
                    let context =
                        captured.expect("matching parent must establish the terminal snapshot");
                    assert_eq!(context["capture"], "complete");
                    assert_eq!(context["kind"], "native_terminal_snapshot");
                    assert_eq!(context["foreground_http_body_observed"], false);
                    assert_eq!(context["matching_users"], 1);
                    assert_eq!(context["terminal_count"], 1);
                    assert_eq!(context["model_matches_configured"], true);
                    assert_eq!(context["native_equals_portable"], true);
                    assert_eq!(context["native_equals_expected"], false);
                    assert_eq!(context["finish"], "stop");
                    context
                } else {
                    // The retained live snapshot contract refuses attribution to
                    // a stale parent; a diagnostic summary cannot establish parity.
                    let reason =
                        captured.expect_err("stale parent must not establish native parity");
                    assert_eq!(reason, "terminal_missing");
                    json!({"capture":"incomplete","reason":reason})
                };
                let report = context.to_string();
                for secret in [
                    "PRIVATE",
                    "msg_",
                    "ses_",
                    "prt_",
                    EvidenceFixture::PROMPT,
                    // Exact serialized values avoid matching the intentional
                    // model_matches_configured schema key.
                    "\"provider\"",
                    "\"model\"",
                    EvidenceFixture::ANSWER,
                ] {
                    assert!(!report.contains(secret), "diagnostic leaked {secret}");
                }
                assert!(report.len() < 4096);
                assert_eq!(
                    *requests.lock().unwrap(),
                    [
                        "GET /global/health",
                        "GET /experimental/session",
                        "GET /session/ses_001/message"
                    ]
                );
            })
            .await;
    }
}

#[tokio::test]
async fn fresh_reopen_capture_refuses_ambiguous_or_invalid_evidence() {
    for malformed in [
        "duplicate_user",
        "duplicate_part",
        "foreign_part",
        "unknown_finish",
    ] {
        let mut fixture = EvidenceFixture::new();
        fixture.completed[0]["info"]["time"] = json!({"created":1});
        match malformed {
            "duplicate_user" => {
                let mut user = fixture.completed[0].clone();
                user["info"]["id"] = json!("msg_other");
                user["parts"][0]["id"] = json!("prt_other");
                user["parts"][0]["messageID"] = json!("msg_other");
                fixture.completed.as_array_mut().unwrap().push(user);
            }
            "duplicate_part" => fixture.completed[2]["parts"][0]["id"] = json!("prt_100"),
            "foreign_part" => fixture.completed[2]["parts"][0]["sessionID"] = json!("ses_foreign"),
            "unknown_finish" => fixture.completed[2]["info"]["finish"] = json!("unknown"),
            _ => unreachable!(),
        }
        let (probe, _) = ReadbackProbe::complete_question_fixture(&fixture, None).await;
        let endpoint = probe.endpoint.clone();
        probe
            .observe(async {
                let reader =
                    NativeQuestionReadback::new(&endpoint, Instant::now() + Duration::from_secs(5))
                        .await;
                let captured = reader
                    .prompt_output(
                        EvidenceFixture::PROMPT,
                        "provider",
                        "model",
                        EvidenceFixture::ANSWER,
                        "No",
                    )
                    .await;
                // Unknown completion is no longer only a nonterminal summary: the
                // authoritative snapshot rejects it, like the other invalid evidence.
                assert!(captured.is_err(), "{malformed}: {captured:?}");
            })
            .await;
    }
}