gate4agent-shell-native 0.4.6

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

mod efficiency;
mod provider_supervisor;

pub use efficiency::ShellEfficiencyFacts;
// Re-exported so a caller of `ShellEfficiencyFacts::record_foreground_probe`
// (e.g. `gate4agent-runtime-native`, which does not itself depend on the
// `gate4agent` crate) can name the type of the value it is handing in
// without picking up a new dependency edge for it.
pub use gate4agent::pty::ForegroundProbeTiming;
pub use provider_supervisor::{
    NativeProviderExecutor, NativeProviderExit, NativeProviderOperation,
    NativeProviderOperationError, NativeProviderResultPoll, PhysicalExitAck,
    ProviderOperationKey, ProviderOperationSnapshot, ProviderSupervisor,
    ProviderSupervisorBuildError, ProviderSupervisorFault, ProviderSupervisorFaultKind,
    ProviderStopCause, ProviderSupervisorSnapshot, ProviderSupervisorState,
    ProviderSupervisorTick, DEFAULT_PROVIDER_STOP_GRACE,
    MAX_PROVIDER_FORCE_STOP_ATTEMPTS, MAX_PROVIDER_STOP_SIGNAL_ATTEMPTS,
    MAX_PROVIDER_SUPERVISOR_EVENTS, MAX_PROVIDER_SUPERVISOR_OPERATIONS,
    MAX_PROVIDER_SUPERVISOR_OUTCOMES_PER_TICK, MAX_PROVIDER_SUPERVISOR_TOMBSTONES,
    MAX_PROVIDER_SUPERVISOR_WORK_PER_TICK,
};

use gate4agent::acp::protocol::{McpServerConfig, SessionMode};
use gate4agent::agent::{is_agent_foreground_wrapper, is_expected_agent_process, ReadinessStatus};
use gate4agent::pty::cli::codex::strip_ansi_codes;
use gate4agent::pty::cli::{create_pipeline, ClassificationPipeline, MessageClass, ParsedMessage};
use gate4agent::pty::event::PtyMouseProtocolEncoding;
use gate4agent::pty::{
    PtyAttachment, PtyEvent, PtyEventEnvelope, PtyEventReceiver, PtyForegroundObservation,
    PtyReplayCursor, PtySession, PtyTerminalSnapshot, RateLimitDetector, VteParser,
};
use gate4agent::{
    AcpSession, AcpSessionOptions, AgentEvent, CliTool, HostDecisionAuthority, HostPolicy,
    HostRequestDecision, HostRequestOutcome, LaunchRequest, OperatorPermissionChoice,
    PipeProcessOptions, PipeSession, PromptFraming,
    ReadinessIntent, ReadinessPermit, ReadinessTracker, RpcId, RuntimePlatform, SessionConfig,
    StopReason,
};
use gate4agent_adapters::{
    build_resume_plan_for_identity, builtin_adapter_registry, AdapterRuntimeRegistry,
    CodexPtySessionIdentityExtractor, KimiPtySessionIdentityExtractor, OneShotSessionPersistence,
};
use gate4agent_catalog::{
    approval_level_resolution, ApprovalLevelResolution, AgentRegistry, AgentSpec, EnvMutation,
    McpServerSpec, ModeId,
};
use gate4agent_shell_one_shot::NativeOneShotSession;
use gate4agent_types::{
    AdapterFamily, AgentCommand, AgentId, AgentInstanceId, ApprovalLevel, CapabilityProbeFailure,
    ContextWindowUsage as ProviderContextWindowUsage, ControlEffect,
    ControlObservation, EffectEnvelope, ForegroundProcess, ForegroundProcessKind,
    ForegroundRequirement, HostDecisionAuthority as ProviderHostDecisionAuthority,
    HostRequestDecision as ProviderHostRequestDecision,
    HostRequestOutcome as ProviderHostRequestOutcome, InputAction, ObservationEnvelope,
    OperationId, OperatorGateInput,
    OperatorGateKind, OperatorGateOption, OperatorGateOptionSemantics, OperatorGateState,
    OperatorGateSubject, PipeProtocol,
    PreparedInputKind, PromptPayload, ProviderAvailableCommand, ProviderConfigChoice,
    ProviderConfigOption, ProviderConfigOptionKind, ProviderEvent, ProviderInteractionKind,
    ProviderInteractionOption, ProviderInteractionResponse, ProviderInteractionTarget,
    ProviderModeInfo, ProviderPlanPriority,
    ProviderPlanStatus, ProviderPlanStep,
    ProviderRateLimitKind, ProviderRuntimeCapability, ProviderRuntimePolicy,
    ProviderSessionIdentity, ProviderSessionKey, ProviderStopReason,
    ProviderSource, PtyScreenState, ResumeLaunchRequest, SessionGeneration, StartRequest,
    TerminalFrame, TerminalMouseProtocolEncoding, TerminalSize, TokenUsage, TransportKind,
    OPERATOR_GATE_OPTIONS_MAX, WORKING_DIRECTORY_MAX_BYTES,
};
use std::collections::{BTreeMap, VecDeque};
use std::ffi::{OsStr, OsString};
use std::path::PathBuf;
use std::sync::Mutex;
use std::time::{Duration, Instant};
use tokio::sync::broadcast;
use uuid::Uuid;

const INSTANCE_LAUNCH_ARGS_MAX: usize = 128;
const INSTANCE_LAUNCH_ARG_MAX_BYTES: usize = 65_536;
const INSTANCE_LAUNCH_ARGS_TOTAL_MAX_BYTES: usize = 262_144;
const RESERVED_CLAUDE_LAUNCH_FLAGS: &[&str] = &[
    "--continue",
    "--print",
    "--prompt",
    "--prompt-interactive",
    "--resume",
    "--session-id",
    "-c",
    "-p",
    "-r",
];

/// Translates a resolved [`McpServerSpec`] into the one ACP `session/new`
/// stdio entry the agent should register
/// (`gate4agent::acp::protocol::McpServerConfig`). This is the ACP half of
/// the same door a PTY child gets by installing the identical spec's `env`
/// pairs into its own OS environment instead
/// (`gate4agent-runtime-native::launch_profiles::NativeMcpServerLaunchOverlay`):
/// the spec is resolved once, in-process, by `gate4agent-runtime-native` and
/// handed down here as a typed value through `NativeSpawnOverlay`/
/// `NativeEffectRequest` -- never a wire type, and never re-read out of a
/// well-known environment key. This crate cannot depend on
/// `gate4agent-runtime-native` (the dependency runs the other way), which is
/// why the spec type itself lives one level below both, in
/// `gate4agent-catalog`.
///
/// Server naming, program path, args, and every environment entry are
/// entirely the caller's concern; this function does not interpret them.
fn mcp_server_acp_entry(spec: &McpServerSpec) -> McpServerConfig {
    McpServerConfig::stdio(
        spec.name().to_owned(),
        spec.program().to_string_lossy().into_owned(),
        spec.args()
            .iter()
            .map(|arg| arg.to_string_lossy().into_owned())
            .collect::<Vec<_>>(),
        spec.env()
            .iter()
            .map(|(key, value)| (key.to_string_lossy().into_owned(), value.to_string_lossy().into_owned()))
            .collect::<Vec<_>>(),
    )
}

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct NativeSessionKey {
    pub instance_id: AgentInstanceId,
    pub generation: SessionGeneration,
}

struct NativeSpawnRequest {
    agent_id: AgentId,
    transport: TransportKind,
    request: StartRequest,
    runtime_policy: ProviderRuntimePolicy,
    launch_extra_args: Vec<OsString>,
    instance_extra_args: Vec<OsString>,
    resumed_provider_session: Option<gate4agent_types::ProviderSessionIdentity>,
    one_shot_session_persistence: OneShotSessionPersistence,
}

struct OwnedPtySession {
    session: PtySession,
    spawn_operation_id: OperationId,
    last_terminal_sequence: u64,
    terminal_stale_published: bool,
    runtime_policy: ProviderRuntimePolicy,
    provider: Option<OwnedPtyProvider>,
    /// Set once at the spawn site and never mutated -- this is what lets
    /// `reclassify_foreground` resolve the session's `AgentSpec` from
    /// `NativeEffectShell::catalog` without holding a borrow of `session`
    /// across the same loop iteration it awaits `observe_foreground` on.
    agent_id: AgentId,
    last_screen_gate: Option<OperatorGateState>,
    last_screen_failure: Option<&'static str>,
    last_foreground_verdict: Option<ForegroundVerdict>,
    last_screen_state: PtyScreenState,
    /// Whether this generation's merged state has ever been `Ready` WITH
    /// something on screen. Text crash/missing-command markers are only
    /// trustworthy before this flips -- see the gate in
    /// `collect_terminal_frames`. The screen-content half is load-bearing:
    /// `Ready` is proved by foreground process identity and so arrives
    /// within a frame or two of spawn, while the terminal is still blank,
    /// and arming on a blank frame retires the failure detector before any
    /// failure text can exist. Never reset in place; a new generation gets
    /// a fresh `OwnedPtySession`, so `false` is simply this field's initial
    /// value at the spawn site.
    ever_reached_ready: bool,
    /// Whether any frame of this generation has carried non-blank screen
    /// text yet. Read by the process-only path in `reclassify_foreground`,
    /// which has no snapshot of its own to test and would otherwise arm
    /// `ever_reached_ready` on a blank screen.
    screen_had_content: bool,
    /// `None` means disarmed -- the session reached `Ready` and stays
    /// unprobed until its text disagrees again. See
    /// `NativeEffectShell::reclassify_foreground` for the cadence this
    /// drives.
    next_foreground_probe: Option<Instant>,
}

struct OwnedPtyProvider {
    source: ProviderSource,
    receiver: PtyEventReceiver,
    replay: VecDeque<PtyEventEnvelope>,
    pending_events: VecDeque<ProviderEvent>,
    utf8: Utf8ChunkDecoder,
    pipeline: Mutex<ClassificationPipeline>,
    rate_limits: RateLimitFeed,
    kimi_identity: Option<KimiPtySessionIdentityExtractor>,
    semantic_events: bool,
    provider_session_started: bool,
    next_provider_sequence: u64,
}

/// Buffers ANSI-stripped PTY output across output chunks before running
/// rate-limit detection over it.
///
/// PTY reads are chunked arbitrarily -- neither the OS nor this crate's
/// own reader loop promises "one call per terminal row" or even "one call
/// per escape sequence". Two separate problems follow from that, and this
/// type exists to solve both rather than hoping a caller's chunk
/// boundaries are ever polite:
///
/// - An ANSI escape sequence split across two chunks must still be
///   recognized as one escape, not leak its tail bytes into the visible
///   text as a false line-break in the middle of `\x1b[m`. `VteParser`
///   already solves this -- its own `vte::Parser` state machine persists
///   across calls, so an escape completes correctly regardless of where
///   a chunk boundary falls -- this type just keeps ONE `VteParser` alive
///   for the provider's whole lifetime instead of a fresh, stateless one
///   per chunk (which would forget an escape's first half).
/// - A LOGICAL LINE (e.g. codex's `/status` quota-state row) can itself
///   be split across chunks at a point that is not inside any escape.
///   `VteParser::parse` only returns the printable text produced by the
///   bytes handed to THAT call, so two separate calls can each return one
///   half of the same row, and neither half alone matches the quota-state
///   pattern. This type accumulates cleaned text across calls and runs
///   detection over everything seen so far, keeping whatever has not yet
///   been confirmed complete (the tail after the last newline) instead of
///   discarding a still-forming row.
struct RateLimitFeed {
    detector: RateLimitDetector,
    vte: VteParser,
    buffer: String,
}

impl RateLimitFeed {
    fn new_for_tool(tool: CliTool) -> Self {
        Self {
            detector: RateLimitDetector::new_for_tool(tool),
            vte: VteParser::new(),
            buffer: String::new(),
        }
    }

    /// Strip ANSI from one more raw PTY chunk, fold it into the pending
    /// line buffer, and run detection over everything accumulated so far
    /// -- not just the newest chunk, since a match can straddle a chunk
    /// boundary. Lines already terminated by `\n` are then dropped from
    /// the buffer regardless of whether they matched: a later chunk
    /// cannot retroactively extend a row that has already ended. The
    /// unterminated tail (a row still in progress) is always kept -- but
    /// see `RATE_LIMIT_FEED_BUFFER_MAX_BYTES` for what happens when that
    /// tail itself grows unreasonably large.
    fn detect(&mut self, raw: &str) -> Option<gate4agent::core::types::RateLimitInfo> {
        let cleaned = self.vte.parse(raw);
        self.buffer.push_str(&cleaned);
        let info = self.detector.detect(&self.buffer);
        if let Some(last_newline) = self.buffer.rfind('\n') {
            self.buffer.drain(..=last_newline);
        } else if self.buffer.len() > RATE_LIMIT_FEED_BUFFER_MAX_BYTES {
            // A full-screen redraw (codex's main screen, not `/status`)
            // can run for a long time using only cursor-addressing escapes
            // and never emit a `\n` at all, so "no newline yet" cannot be
            // trusted to mean "a row is still in progress" indefinitely.
            // No real quota-state or refusal line approaches this length;
            // past it, keep only the tail so an indefinitely long redraw
            // cannot grow this buffer for the life of the session.
            let mut cut = self.buffer.len() - RATE_LIMIT_FEED_BUFFER_MAX_BYTES;
            while !self.buffer.is_char_boundary(cut) {
                cut += 1;
            }
            self.buffer.drain(..cut);
        }
        info
    }
}

/// Well past the longest quota-state or refusal line this detector
/// recognizes (all under 200 bytes); see `RateLimitFeed::detect`.
const RATE_LIMIT_FEED_BUFFER_MAX_BYTES: usize = 8192;

#[derive(Default)]
struct Utf8ChunkDecoder {
    pending: Vec<u8>,
}

impl Utf8ChunkDecoder {
    fn push(&mut self, bytes: &[u8]) -> String {
        self.pending.extend_from_slice(bytes);
        let mut decoded = String::new();
        loop {
            match std::str::from_utf8(&self.pending) {
                Ok(text) => {
                    decoded.push_str(text);
                    self.pending.clear();
                    break;
                }
                Err(error) => {
                    let valid = error.valid_up_to();
                    if valid > 0 {
                        let text = std::str::from_utf8(&self.pending[..valid])
                            .expect("validated UTF-8 prefix");
                        decoded.push_str(text);
                        self.pending.drain(..valid);
                        continue;
                    }
                    let Some(invalid) = error.error_len() else {
                        break;
                    };
                    decoded.push('\u{fffd}');
                    self.pending.drain(..invalid.min(self.pending.len()));
                }
            }
        }
        decoded
    }

    fn clear(&mut self) {
        self.pending.clear();
    }
}

struct OwnedProviderSession<S> {
    source: ProviderSource,
    session: S,
    events: broadcast::Receiver<AgentEvent>,
    pending_events: VecDeque<AgentEvent>,
    /// Already wire-typed `ProviderEvent`s seeded at the spawn site with no
    /// `AgentEvent` counterpart to carry them through `pending_events` --
    /// today, only `ProviderEvent::SessionIdentityObserved` for a freshly
    /// spawned ACP session (see the `TransportKind::Acp` arm of
    /// `spawn_native`). Drained by `drain_provider_stream` immediately after
    /// `pending_events` empties and before the live broadcast stream, so an
    /// event seeded here lands right after whatever `pending_events` seeded
    /// (`AgentEvent::SessionStart`, chiefly) rather than racing it.
    pending_provider_events: VecDeque<ProviderEvent>,
    next_provider_sequence: u64,
    observed_exit_code: Option<i32>,
    runtime_policy: ProviderRuntimePolicy,
}

/// Executes native effects and returns exactly one completion observation for
/// each accepted effect. Logical lifecycle state remains owned by the engine.
pub struct NativeEffectShell {
    catalog: AgentRegistry,
    legacy_adapters: AdapterRuntimeRegistry<CliTool>,
    pty_sessions: BTreeMap<NativeSessionKey, OwnedPtySession>,
    pipe_sessions: BTreeMap<NativeSessionKey, OwnedProviderSession<PipeSession>>,
    one_shot_sessions: BTreeMap<NativeSessionKey, OwnedProviderSession<NativeOneShotSession>>,
    acp_sessions: BTreeMap<NativeSessionKey, OwnedProviderSession<AcpSession>>,
    pending_observations: VecDeque<ObservationEnvelope>,
    /// Plain efficiency facts from `collect_terminal_frames` and
    /// `reclassify_foreground` -- see `ShellEfficiencyFacts`'s own doc
    /// comment for why this crate stops at plain facts rather than
    /// computing a distribution itself.
    efficiency_facts: ShellEfficiencyFacts,
}

impl NativeEffectShell {
    pub fn new(catalog: AgentRegistry) -> Self {
        Self::new_with_runtime_adapters(catalog, builtin_legacy_adapter_runtimes())
    }

    /// Builds a native shell with consumer-provided compatibility runtimes.
    ///
    /// The runtime registry is deliberately separate from the declarative
    /// catalog: both the adapter family and revision must resolve before a
    /// process is spawned.
    pub fn new_with_runtime_adapters(
        catalog: AgentRegistry,
        legacy_adapters: AdapterRuntimeRegistry<CliTool>,
    ) -> Self {
        Self {
            catalog,
            legacy_adapters,
            pty_sessions: BTreeMap::new(),
            pipe_sessions: BTreeMap::new(),
            one_shot_sessions: BTreeMap::new(),
            acp_sessions: BTreeMap::new(),
            pending_observations: VecDeque::new(),
            efficiency_facts: ShellEfficiencyFacts::default(),
        }
    }

    /// Hand the caller everything `collect_terminal_frames` and
    /// `reclassify_foreground` recorded since the last call, and reset the
    /// facts back to empty. Called once per worker-loop iteration by
    /// `gate4agent-runtime-native::publish_shell_observations`, the only
    /// place with somewhere to fold these into a distribution.
    pub fn take_efficiency_facts(&mut self) -> ShellEfficiencyFacts {
        self.efficiency_facts.take()
    }

    pub fn active_session_count(&self) -> usize {
        self.pty_sessions.len()
            + self.pipe_sessions.len()
            + self.one_shot_sessions.len()
            + self.acp_sessions.len()
    }

    pub fn spawn_operation_id(&self, key: NativeSessionKey) -> Option<OperationId> {
        self.pty_sessions
            .get(&key)
            .map(|owned| owned.spawn_operation_id)
    }

    pub fn terminal_snapshot(&self, key: NativeSessionKey) -> Result<PtyTerminalSnapshot, String> {
        self.pty_sessions
            .get(&key)
            .ok_or_else(|| missing_session_message(key))?
            .session
            .terminal_snapshot()
            .map_err(|error| error.to_string())
    }

    pub async fn execute(&mut self, envelope: EffectEnvelope) -> ObservationEnvelope {
        self.execute_with_environment(envelope, Vec::new()).await
    }

    /// Backward-compatible name for PTY-only callers. OneShot launches now
    /// receive the same shell-owned mutations.
    pub async fn execute_with_pty_env(
        &mut self,
        envelope: EffectEnvelope,
        pty_env: Vec<EnvMutation>,
    ) -> ObservationEnvelope {
        self.execute_with_environment(envelope, pty_env).await
    }

    /// Execute an effect with shell-owned environment injected only into a
    /// newly spawned provider process. The canonical start request cannot set
    /// these authority variables itself.
    pub async fn execute_with_environment(
        &mut self,
        envelope: EffectEnvelope,
        environment: Vec<EnvMutation>,
    ) -> ObservationEnvelope {
        self.execute_with_launch_overlay(envelope, environment, Vec::new())
            .await
    }

    /// Execute an effect with host-only environment and optional PTY argv
    /// applied only to a newly spawned provider process.
    pub async fn execute_with_launch_overlay(
        &mut self,
        envelope: EffectEnvelope,
        environment: Vec<EnvMutation>,
        extra_args: Vec<OsString>,
    ) -> ObservationEnvelope {
        self.execute_with_launch_overlay_and_persistence(
            envelope,
            environment,
            extra_args,
            OneShotSessionPersistence::Ephemeral,
        )
        .await
    }

    /// Execute an effect with host-only launch mutations and an explicit
    /// OneShotText session persistence policy.
    pub async fn execute_with_launch_overlay_and_persistence(
        &mut self,
        envelope: EffectEnvelope,
        environment: Vec<EnvMutation>,
        extra_args: Vec<OsString>,
        one_shot_session_persistence: OneShotSessionPersistence,
    ) -> ObservationEnvelope {
        self.execute_with_launch_context(
            envelope,
            environment,
            extra_args,
            one_shot_session_persistence,
            None,
        )
        .await
    }

    pub async fn execute_with_launch_context(
        &mut self,
        envelope: EffectEnvelope,
        environment: Vec<EnvMutation>,
        extra_args: Vec<OsString>,
        one_shot_session_persistence: OneShotSessionPersistence,
        mcp_server: Option<McpServerSpec>,
    ) -> ObservationEnvelope {
        let EffectEnvelope {
            operation_id,
            instance_id,
            generation,
            effect,
        } = envelope;
        let key = NativeSessionKey {
            instance_id,
            generation,
        };

        let observation = {
            match effect {
                ControlEffect::Spawn {
                    agent_id,
                    transport,
                    runtime_policy,
                    request,
                } => {
                    self.spawn_native(
                        key,
                        operation_id,
                        NativeSpawnRequest {
                            agent_id,
                            transport,
                            request,
                            runtime_policy,
                            launch_extra_args: Vec::new(),
                            instance_extra_args: extra_args,
                            resumed_provider_session: None,
                            one_shot_session_persistence,
                        },
                        environment,
                        mcp_server,
                    )
                    .await
                }
                ControlEffect::SpawnResume {
                    agent_id,
                    transport,
                    provider_session,
                    runtime_policy,
                    request,
                } => {
                    self.spawn_resume(
                        key,
                        operation_id,
                        agent_id,
                        transport,
                        provider_session,
                        runtime_policy,
                        request,
                        environment,
                        extra_args,
                        one_shot_session_persistence,
                    )
                    .await
                }
                ControlEffect::Stop { force } => self.stop_native(key, force).await,
                ControlEffect::WriteInput {
                    input,
                    required_foreground,
                } => match self.pty_sessions.get(&key) {
                    Some(owned) => match required_foreground {
                        ForegroundRequirement::Any
                            if matches!(
                                input.kind(),
                                PreparedInputKind::TerminalText
                                    | PreparedInputKind::TerminalBytes
                                    | PreparedInputKind::TerminalControl
                            ) =>
                        {
                            match owned.session.send_terminal_input(input).await {
                                Ok(()) => ControlObservation::InputCompleted,
                                Err(error) => ControlObservation::InputFailed {
                                    message: error.to_string(),
                                },
                            }
                        }
                        ForegroundRequirement::Shell
                            if input.kind() == PreparedInputKind::ShellCommand =>
                        {
                            if !owned.runtime_policy.semantic_readiness {
                                ControlObservation::InputFailed {
                                    message: "semantic shell input is not admitted by the provider runtime policy"
                                        .to_owned(),
                                }
                            } else {
                                match owned.session.send_shell_input(input).await {
                                    Ok(()) => ControlObservation::InputCompleted,
                                    Err(error) => ControlObservation::InputFailed {
                                        message: error.to_string(),
                                    },
                                }
                            }
                        }
                        ForegroundRequirement::Agent { agent_id }
                            if matches!(
                                input.kind(),
                                PreparedInputKind::InsertDraft
                                    | PreparedInputKind::SubmitPrompt
                                    | PreparedInputKind::AgentCommand
                            ) && &agent_id == owned.session.agent_id() =>
                        {
                            if !owned.runtime_policy.semantic_readiness
                                || !owned.runtime_policy.structured_prompt
                            {
                                return completion_observation(
                                    operation_id,
                                    instance_id,
                                    generation,
                                    ControlObservation::InputFailed {
                                        message: "semantic input is not admitted by the provider runtime policy"
                                            .to_owned(),
                                    },
                                );
                            }
                            let intent = match input.kind() {
                                PreparedInputKind::InsertDraft
                                | PreparedInputKind::AgentCommand => ReadinessIntent::DraftPaste,
                                PreparedInputKind::SubmitPrompt => ReadinessIntent::FollowupPrompt,
                                PreparedInputKind::ShellCommand
                                | PreparedInputKind::TerminalText
                                | PreparedInputKind::TerminalBytes
                                | PreparedInputKind::TerminalControl => unreachable!(),
                            };
                            let Some(spec) = self.catalog.get(&agent_id).cloned() else {
                                return completion_observation(
                                    operation_id,
                                    instance_id,
                                    generation,
                                    ControlObservation::InputFailed {
                                        message: "session agent disappeared from native catalog"
                                            .to_owned(),
                                    },
                                );
                            };
                            match wait_for_readiness(&owned.session, &spec, intent, false).await {
                                Ok(permit) => {
                                    let result = if input.kind() == PreparedInputKind::AgentCommand
                                    {
                                        owned.session.send_agent_command_input(input, permit).await
                                    } else {
                                        owned.session.send_prepared_input(input, permit).await
                                    };
                                    match result {
                                        Ok(()) => ControlObservation::InputCompleted,
                                        Err(error) => ControlObservation::InputFailed {
                                            message: error.to_string(),
                                        },
                                    }
                                }
                                Err(message) => ControlObservation::InputFailed { message },
                            }
                        }
                        required_foreground => ControlObservation::InputFailed {
                            message: format!(
                                "prepared input kind {:?} does not satisfy route {:?}",
                                input.kind(),
                                required_foreground
                            ),
                        },
                    },
                    None => ControlObservation::InputFailed {
                        message: "typed PTY input requires a PTY session".to_owned(),
                    },
                },
                ControlEffect::SubmitPrompt { prompt } => match self.acp_sessions.get(&key) {
                    Some(owned) if !owned.runtime_policy.structured_prompt => {
                        ControlObservation::InputFailed {
                            message: "structured prompt is not admitted by the provider runtime policy"
                                .to_owned(),
                        }
                    }
                    Some(owned) => match owned.session.start_prompt(&prompt).await {
                        Ok(()) => ControlObservation::InputCompleted,
                        Err(error) => ControlObservation::InputFailed {
                            message: error.to_string(),
                        },
                    },
                    None => ControlObservation::InputFailed {
                        message: "semantic follow-up prompts require an ACP session".to_owned(),
                    },
                },
                ControlEffect::Interrupt => match self.acp_sessions.get(&key) {
                    Some(owned) => match owned.session.cancel().await {
                        Ok(()) => ControlObservation::InputCompleted,
                        Err(error) => ControlObservation::InputFailed {
                            message: error.to_string(),
                        },
                    },
                    None => ControlObservation::InputFailed {
                        message: "semantic interrupt requires an ACP session".to_owned(),
                    },
                },
                ControlEffect::ResolveInteraction { target, response } => {
                    resolve_acp_interaction_observation(
                        self.acp_sessions.get(&key).map(|owned| &owned.session),
                        target,
                        response,
                    )
                }
                ControlEffect::SetSessionMode { mode_id } => {
                    set_acp_session_mode_observation(
                        self.acp_sessions.get(&key).map(|owned| &owned.session),
                        mode_id,
                    )
                    .await
                }
                ControlEffect::SetSessionConfigOption {
                    option_id,
                    value_json,
                } => {
                    set_acp_session_config_option_observation(
                        self.acp_sessions.get(&key).map(|owned| &owned.session),
                        option_id,
                        value_json,
                    )
                    .await
                }
                ControlEffect::SetSessionModel { model_id } => {
                    set_acp_session_model_observation(
                        self.acp_sessions.get(&key).map(|owned| &owned.session),
                        model_id,
                    )
                }
                ControlEffect::Resize { size } if !size.is_valid() => {
                    ControlObservation::ResizeFailed {
                        message: "terminal size is outside the supported range".to_owned(),
                    }
                }
                ControlEffect::Resize { size } => match self.pty_sessions.get(&key) {
                    Some(owned) => match owned.session.resize(size.rows, size.columns).await {
                        Ok(()) => ControlObservation::ResizeCompleted { size },
                        Err(error) => ControlObservation::ResizeFailed {
                            message: error.to_string(),
                        },
                    },
                    None => ControlObservation::ResizeFailed {
                        message: "terminal resize requires a PTY session".to_owned(),
                    },
                },
                ControlEffect::ObserveForeground => match self.pty_sessions.get(&key) {
                    Some(owned) => match owned.session.observe_foreground().await {
                        Ok(observation) => ControlObservation::ForegroundObserved {
                            process: canonical_foreground(
                                owned.session.agent_id().clone(),
                                &observation,
                            ),
                        },
                        Err(error) => ControlObservation::ForegroundFailed {
                            message: error.to_string(),
                        },
                    },
                    None => ControlObservation::ForegroundFailed {
                        message: "foreground observation requires a PTY session".to_owned(),
                    },
                },
                ControlEffect::ProbeCapabilities { .. } => {
                    ControlObservation::CapabilityProbeFailed {
                        failure: CapabilityProbeFailure::ExecutorUnavailable,
                    }
                }
                ControlEffect::DiscoverHistory { .. } | ControlEffect::LoadHistory { .. } => {
                    ControlObservation::HistoryFailed {
                        message: "history effects require the dedicated native history authority"
                            .to_owned(),
                    }
                }
                ControlEffect::AuthorizeResume { .. } => ControlObservation::ResumeFailed {
                    message: "resume authorization requires the dedicated native authority"
                        .to_owned(),
                },
            }
        };

        completion_observation(operation_id, instance_id, generation, observation)
    }

    async fn spawn_native(
        &mut self,
        key: NativeSessionKey,
        operation_id: OperationId,
        spawn: NativeSpawnRequest,
        pty_env: Vec<EnvMutation>,
        mcp_server: Option<McpServerSpec>,
    ) -> ControlObservation {
        let NativeSpawnRequest {
            agent_id,
            transport,
            request,
            runtime_policy,
            mut launch_extra_args,
            instance_extra_args,
            resumed_provider_session,
            one_shot_session_persistence,
        } = spawn;
        if let Err(message) =
            validate_instance_launch_arguments(&agent_id, transport, &instance_extra_args)
        {
            return ControlObservation::SpawnFailed { message };
        }
        if let Err(message) = validate_spawn_runtime_policy(
            runtime_policy,
            transport,
            request.initial_prompt.is_some(),
            resumed_provider_session.is_some(),
        ) {
            return ControlObservation::SpawnFailed { message };
        }
        if self.session_exists(key) {
            return ControlObservation::SpawnFailed {
                message: format!(
                    "native session {:?}/{:?} already exists",
                    key.instance_id, key.generation
                ),
            };
        }
        if !request.terminal_size.is_valid() {
            return ControlObservation::SpawnFailed {
                message: "terminal size is outside the supported range".to_owned(),
            };
        }
        if request.working_directory.is_empty()
            || request.working_directory.len() > WORKING_DIRECTORY_MAX_BYTES
            || request.working_directory.contains('\0')
        {
            return ControlObservation::SpawnFailed {
                message: "working directory is invalid".to_owned(),
            };
        }
        let Some(spec) = self.catalog.get(&agent_id).cloned() else {
            return ControlObservation::SpawnFailed {
                message: format!("agent '{agent_id}' is absent from native catalog"),
            };
        };
        let working_dir = PathBuf::from(&request.working_directory);

        match transport {
            TransportKind::Pty if !spec.capabilities.transports.pty => {
                ControlObservation::SpawnFailed {
                    message: format!("agent '{agent_id}' does not support PTY transport"),
                }
            }
            TransportKind::Pty => {
                // Only the interactive PTY path renders anything to color;
                // the Pipe/OneShotText arm below spawns a plain pipe with
                // no terminal device behind it, so `pty_env` is left as the
                // caller passed it there.
                let pty_env = with_pty_terminal_capability_defaults(pty_env);
                let fresh_provider_session = prepare_fresh_pty_provider_session(
                    spec.capabilities.transports.pty_adapter.as_ref(),
                    resumed_provider_session.is_some(),
                    runtime_policy.provider_session_identity,
                    &mut launch_extra_args,
                );
                launch_extra_args.extend(instance_extra_args);
                let mut authoritative_provider_session = resumed_provider_session
                    .clone()
                    .or(fresh_provider_session);
                let probe_kimi_identity = should_probe_pty_identity(
                    runtime_policy,
                    spec.capabilities.transports.pty_adapter.as_ref(),
                    authoritative_provider_session.is_some(),
                    "kimi",
                );
                let probe_codex_identity = should_probe_pty_identity(
                    runtime_policy,
                    spec.capabilities.transports.pty_adapter.as_ref(),
                    authoritative_provider_session.is_some(),
                    "codex",
                );
                // This is the last point before the OS-level PTY spawn where
                // the program and its arguments are still plain, structured
                // data (`spec.launch.program`/`fixed_args` are catalog
                // constants; `launch_extra_args` is the dynamic, per-session
                // portion). Provider secrets are environment-only by this
                // repo's own convention (never argv, see `gate4agent/CLAUDE.md`),
                // so `fixed_args` needs no redaction; `launch_extra_args`
                // still gets a defensive per-token credential-shape check
                // in case a provider CLI's own argv convention differs.
                // The initial prompt itself is arbitrary-length user text,
                // not an operational argument, so only its presence is
                // logged, never its contents.
                tracing::info!(
                    agent_id = %agent_id,
                    instance_id = ?key.instance_id,
                    generation = ?key.generation,
                    terminal_size = ?request.terminal_size,
                    program = %spec.launch.program,
                    fixed_args = ?spec.launch.fixed_args,
                    extra_args = ?redact_provider_arguments(&launch_extra_args),
                    has_initial_prompt = request.initial_prompt.is_some(),
                    "spawning provider process over a PTY",
                );
                match PtySession::spawn_agent_with_size(
                    &spec,
                    LaunchRequest {
                        working_dir,
                        env: pty_env,
                        platform: RuntimePlatform::current(),
                        prompt: request.initial_prompt,
                        session_options: request.session_options,
                        extra_args: launch_extra_args,
                    },
                    request.terminal_size.rows,
                    request.terminal_size.columns,
                )
                .await
                {
                Ok(mut session) => {
                    if probe_kimi_identity {
                        match probe_fresh_kimi_session_identity(&session, &spec).await {
                            Ok(Some(identity)) => authoritative_provider_session = Some(identity),
                            Ok(None) => {}
                            Err(error) => {
                                let message = match session.shutdown().await {
                                    Ok(_) => error,
                                    Err(shutdown_error) => {
                                        format!("{error}; PTY cleanup failed: {shutdown_error}")
                                    }
                                };
                                return ControlObservation::SpawnFailed { message };
                            }
                        }
                    }
                    if probe_codex_identity {
                        match probe_fresh_codex_session_identity(&session, &spec).await {
                            Ok(Some(identity)) => authoritative_provider_session = Some(identity),
                            Ok(None) => {}
                            Err(error) => {
                                let message = match session.shutdown().await {
                                    Ok(_) => error,
                                    Err(shutdown_error) => {
                                        format!("{error}; PTY cleanup failed: {shutdown_error}")
                                    }
                                };
                                return ControlObservation::SpawnFailed { message };
                            }
                        }
                    }
                    if let Err(error) = deliver_pending_initial_prompt(&mut session, &spec).await {
                        let message = match session.shutdown().await {
                            Ok(_) => error,
                            Err(shutdown_error) => {
                                format!("{error}; PTY cleanup failed: {shutdown_error}")
                            }
                        };
                        return ControlObservation::SpawnFailed { message };
                    }
                    let process_id = session.root_pid();
                    let provider = match spec.capabilities.transports.pty_adapter.as_ref() {
                        _ if !should_attach_pty_provider_stream(runtime_policy) => None,
                        Some(adapter) => {
                            let tool = match self
                                .legacy_adapters
                                .resolve(AdapterFamily::PtySemantic, adapter)
                            {
                                Ok(tool) => *tool,
                                Err(error) => {
                                    let _ = session.shutdown().await;
                                    return ControlObservation::SpawnFailed {
                                        message: error.to_string(),
                                    };
                                }
                            };
                            match session.attach_events(session.beginning_cursor()) {
                                Ok(attachment) => {
                                    let mut pending_events = VecDeque::new();
                                    let mut provider_session_started = false;
                                    if let Some(identity) = authoritative_provider_session {
                                        pending_events.push_back(ProviderEvent::SessionStarted {
                                            session_id: identity.id.clone(),
                                            model: String::new(),
                                            tools: Vec::new(),
                                        });
                                        pending_events.push_back(
                                            ProviderEvent::SessionIdentityObserved { identity },
                                        );
                                        provider_session_started = true;
                                    }
                                    let is_kimi = tool == CliTool::KimiCode;
                                    Some(OwnedPtyProvider {
                                        source: ProviderSource {
                                            family: AdapterFamily::PtySemantic,
                                            binding: adapter.clone(),
                                        },
                                        receiver: attachment.receiver,
                                        replay: attachment.replay.into(),
                                        pending_events,
                                        utf8: Utf8ChunkDecoder::default(),
                                        pipeline: Mutex::new(create_pipeline(tool)),
                                        rate_limits: RateLimitFeed::new_for_tool(tool),
                                        kimi_identity: (runtime_policy.provider_session_identity
                                            && is_kimi
                                            && !provider_session_started)
                                            .then(KimiPtySessionIdentityExtractor::default),
                                        semantic_events: runtime_policy.semantic_readiness,
                                        provider_session_started,
                                        next_provider_sequence: 1,
                                    })
                                }
                                Err(error) => {
                                    let _ = session.shutdown().await;
                                    return ControlObservation::SpawnFailed {
                                        message: error.to_string(),
                                    };
                                }
                            }
                        }
                        None => None,
                    };
                    self.pty_sessions.insert(
                        key,
                        OwnedPtySession {
                            session,
                            spawn_operation_id: operation_id,
                            last_terminal_sequence: 0,
                            terminal_stale_published: false,
                            runtime_policy,
                            provider,
                            agent_id,
                            last_screen_gate: None,
                            last_screen_failure: None,
                            last_foreground_verdict: None,
                            last_screen_state: PtyScreenState::default(),
                            ever_reached_ready: false,
                            screen_had_content: false,
                            // Armed immediately -- the first
                            // `reclassify_foreground` tick after spawn
                            // probes this session right away rather than
                            // waiting a full `FOREGROUND_RECLASSIFY_INTERVAL`.
                            next_foreground_probe: Some(Instant::now()),
                        },
                    );
                    ControlObservation::Spawned { process_id }
                }
                    Err(error) => {
                        let message = error.to_string();
                        tracing::warn!(
                            agent_id = %agent_id,
                            instance_id = ?key.instance_id,
                            generation = ?key.generation,
                            program = %spec.launch.program,
                            fixed_args = ?spec.launch.fixed_args,
                            cause = %message,
                            "provider process failed to start",
                        );
                        ControlObservation::SpawnFailed { message }
                    }
                }
            }
            TransportKind::Pipe => {
                let Some(pipe_spec) = spec.capabilities.transports.pipe.as_ref() else {
                    return ControlObservation::SpawnFailed {
                        message: format!("agent '{agent_id}' does not support Pipe transport"),
                    };
                };
                let prompt = request.initial_prompt.unwrap_or_default();
                if pipe_spec.protocol == PipeProtocol::OneShotText {
                    let Some(binding) = spec.capabilities.adapters.one_shot.as_ref() else {
                        return ControlObservation::SpawnFailed {
                            message: format!(
                                "agent '{agent_id}' does not declare OneShot capability"
                            ),
                        };
                    };
                    if binding != &pipe_spec.adapter {
                        return ControlObservation::SpawnFailed {
                            message: format!(
                                "agent '{agent_id}' has mismatched OneShot transport bindings"
                            ),
                        };
                    }
                    return match NativeOneShotSession::spawn_with_environment_and_persistence(
                        &spec,
                        binding,
                        &prompt,
                        request.session_options.as_ref(),
                        &working_dir,
                        &pty_env,
                        one_shot_session_persistence,
                    )
                    .await
                    {
                        Ok(session) => {
                            let process_id = session.process_id();
                            let events = session.subscribe();
                            self.one_shot_sessions.insert(
                                key,
                                OwnedProviderSession {
                                    source: ProviderSource {
                                        family: AdapterFamily::OneShot,
                                        binding: binding.clone(),
                                    },
                                    session,
                                    events,
                                    pending_events: VecDeque::new(),
                                    pending_provider_events: VecDeque::new(),
                                    next_provider_sequence: 1,
                                    observed_exit_code: None,
                                    runtime_policy,
                                },
                            );
                            ControlObservation::Spawned { process_id }
                        }
                        Err(error) => ControlObservation::SpawnFailed {
                            message: error.to_string(),
                        },
                    };
                }
                let tool = match self
                    .legacy_adapters
                    .resolve(AdapterFamily::Pipe, &pipe_spec.adapter)
                {
                    Ok(tool) => *tool,
                    Err(error) => {
                        return ControlObservation::SpawnFailed {
                            message: error.to_string(),
                        }
                    }
                };
                let source = ProviderSource {
                    family: AdapterFamily::Pipe,
                    binding: pipe_spec.adapter.clone(),
                };
                let config = SessionConfig {
                    tool,
                    working_dir,
                    env_vars: Vec::new(),
                    name: None,
                };
                if resumed_provider_session.is_some() && pipe_spec.launch_override.is_some() {
                    return ControlObservation::SpawnFailed {
                        message: format!(
                            "agent '{agent_id}' cannot resume through a catalog launch override"
                        ),
                    };
                }
                let mut options = PipeProcessOptions::default();
                if let Some(identity) = resumed_provider_session.as_ref() {
                    options.claude.resume_session_id = Some(identity.id.clone());
                }
                let spawned = match pipe_spec.launch_override.as_ref() {
                    Some(launch) => {
                        PipeSession::spawn_with_launch(
                            config,
                            &prompt,
                            launch,
                            pipe_spec.prompt_delivery,
                        )
                        .await
                    }
                    None => {
                        PipeSession::spawn(config, &prompt, options).await
                    }
                };
                match spawned {
                    Ok(session) => {
                        let process_id = session.process_id();
                        let events = session.subscribe();
                        let pending_events = if pipe_spec.protocol == PipeProtocol::SemanticNdjson {
                            VecDeque::from([AgentEvent::SessionStart {
                                session_id: session.session_id().to_owned(),
                                model: String::new(),
                                tools: Vec::new(),
                            }])
                        } else {
                            VecDeque::new()
                        };
                        self.pipe_sessions.insert(
                            key,
                            OwnedProviderSession {
                                source,
                                session,
                                events,
                                pending_events,
                                pending_provider_events: VecDeque::new(),
                                next_provider_sequence: 1,
                                observed_exit_code: None,
                                runtime_policy,
                            },
                        );
                        ControlObservation::Spawned { process_id }
                    }
                    Err(error) => ControlObservation::SpawnFailed {
                        message: error.to_string(),
                    },
                }
            }
            TransportKind::Acp => {
                let Some(acp_spec) = spec.capabilities.transports.acp else {
                    return ControlObservation::SpawnFailed {
                        message: format!("agent '{agent_id}' does not support ACP transport"),
                    };
                };
                let tool = match self
                    .legacy_adapters
                    .resolve(AdapterFamily::Acp, &acp_spec.adapter)
                {
                    Ok(tool) => *tool,
                    Err(error) => {
                        return ControlObservation::SpawnFailed {
                            message: error.to_string(),
                        }
                    }
                };
                let source = ProviderSource {
                    family: AdapterFamily::Acp,
                    binding: acp_spec.adapter.clone(),
                };
                // ACP is the transport this project opens programmatically --
                // unlike a PTY, there is no human at a terminal to pick
                // permission flags. Measured live: both running ACP adapters
                // (claude, codex) came up with no `--permission-mode` flag
                // reaching them at all and no permission request ever
                // appearing, because `npx`-wrapped specs never receive one
                // (`applicable_approval_args`, `src/acp/spawn.rs`) -- the
                // adapter simply started in its own default, confirmed on
                // the wire as `mode:Mode="auto"`, which approves itself.
                // Argv was fiction for ACP; the level lives in `session/
                // set_mode` instead now, for every provider, npx-wrapped or
                // the vendor's own binary alike -- one mechanism per
                // transport (`applicable_approval_args` never forwards an
                // approval flag to an ACP-spawned process any more).
                //
                // `required_acp_mode` resolves the concrete ACP mode id this
                // level needs from `gate4agent_catalog::approval_level_
                // resolution`'s own `acp_mode_id` column, and refuses BEFORE
                // a process is even spawned whenever no mechanism exists to
                // enforce the request: `ApprovalLevelResolution::Unsupported`
                // (today, `grok`/`kimi` at `ReadOnly`), or a `Supported` row
                // this catalog has no sourced ACP mode id for yet (today,
                // every level on `codex`/`grok`/`kimi` except `Unmanaged`).
                // Silently proceeding either way would spawn the vendor's
                // own default instead -- a wider authority than requested,
                // the exact defect this rewrite closes. `Unmanaged` is the
                // one level that legitimately resolves to "apply nothing" --
                // it imposes nothing by definition.
                let acp_mode_id = match required_acp_mode(&agent_id, request.approval_level) {
                    Ok(mode_id) => mode_id,
                    Err(message) => return ControlObservation::SpawnFailed { message },
                };
                // The MCP-server door (gate4agent-arc-mailbox-and-task-layer
                // Slice A(ii)): `mcp_server` carries the node's resolved MCP
                // server overlay whenever one was prepared for this spawn,
                // transport-agnostic same as every other launch-profile
                // mutation -- see `mcp_server_acp_entry`'s own doc comment.
                // `None` when the node prepared none, which keeps
                // `mcp_servers` empty and changes nothing else.
                let mcp_servers: Vec<McpServerConfig> =
                    mcp_server.as_ref().map(mcp_server_acp_entry).into_iter().collect();
                if !mcp_servers.is_empty() {
                    // State-change line: this is the point measured live to
                    // be silently empty on the wire before the ACP v1 shape
                    // fix (`McpServerConfig`, `src/acp/protocol.rs`) -- a
                    // nameless, map-shaped entry the agent's own adapter
                    // dropped before ever registering it, so `tools/list`
                    // never ran. Names only, never `env` (may carry
                    // tokens/endpoints).
                    tracing::info!(
                        agent_id = %agent_id,
                        instance_id = ?key.instance_id,
                        mcp_server_names = ?mcp_servers.iter().map(McpServerConfig::name).collect::<Vec<_>>(),
                        "acp session/new carries {} mcp server(s)",
                        mcp_servers.len(),
                    );
                }
                // Codex station network_access first slice: argv-only `-c`
                // overlays arrive as instance_extra_args (same channel as
                // catalog windows_wsl_setup). Merge after approval flags.
                let mut approval_level_args =
                    acp_approval_level_args(&agent_id, request.approval_level);
                for argument in &instance_extra_args {
                    approval_level_args.push(argument.to_string_lossy().into_owned());
                }
                let acp_options = AcpSessionOptions {
                    host_policy: host_policy_for_approval_level(request.approval_level),
                    // Empty for an agent that announced an `acp_mode_id` for
                    // this level: that one is applied through
                    // `session/set_mode` below, once the handshake is up,
                    // and its argv stays clean (see this branch's own
                    // comment above and `applicable_approval_args`,
                    // `src/acp/spawn.rs`). An agent that announced NO mode
                    // has no such mechanism -- measured 2026-09-09, kimi
                    // announces none at any level, so an empty argv left it
                    // running at the vendor's own default and it refused
                    // every `g4a_*` MCP tool call at its OWN approval
                    // prompt without ever sending the host a
                    // `session/request_permission`. For that shape argv is
                    // the only lever there is. Codex `-c` network overlays
                    // may still append via `instance_extra_args` above.
                    approval_level_args,
                    defer_permission_requests: defers_permission_requests(
                        &agent_id,
                        request.approval_level,
                    ),
                    mcp_servers,
                    ..AcpSessionOptions::default()
                };
                let spawned = match acp_spec.launch_override.as_ref() {
                    Some(launch) => {
                        AcpSession::spawn_with_launch(tool, &working_dir, acp_options, launch)
                            .await
                    }
                    None => AcpSession::spawn(tool, &working_dir, acp_options).await,
                };
                match spawned {
                    Ok(session) => {
                        if let Some(mode_id) = acp_mode_id.as_ref() {
                            if let Err(message) =
                                apply_acp_approval_mode(&session, mode_id, request.approval_level)
                                    .await
                            {
                                let _ = session.kill().await;
                                return ControlObservation::SpawnFailed { message };
                            }
                        }
                        let process_id = session.process_id();
                        let events = session.subscribe();
                        let session_id = session
                            .acp_session_id()
                            .await
                            .unwrap_or_else(|| session.session_id().to_owned());
                        // Binds a freshly created record from `IdentityPending`
                        // to `Live` (`gate4agent-node`'s `reconcile_managed_
                        // record` on `ProviderEvent::SessionIdentityObserved`)
                        // as soon as the session exists, mirroring the PTY
                        // path's own identity seeding
                        // (`prepare_fresh_pty_provider_session`/
                        // `probe_fresh_*_session_identity`) for the transport
                        // ACP's own spec makes this a protocol MUST for:
                        // `session/new` MUST return a `sessionId`, and both
                        // shipped adapters map it onto the provider's own
                        // durable session id (`AcpSession::
                        // provider_reported_session_id`'s own doc comment).
                        //
                        // Gated on `runtime_policy.provider_session_identity`
                        // -- the same capability the PTY path checks before
                        // treating any identity as authoritative -- so a
                        // spawn that never asked for identity tracking stays
                        // silent rather than warning on every ACP session
                        // whose caller has no interest in one.
                        //
                        // `provider_reported_session_id` (NOT `session_id`
                        // above) is the signal here: `session_id` already
                        // falls back to the host-local id the moment the
                        // agent's `session/new` response carries no
                        // `sessionId`, so it can never itself distinguish "the
                        // agent reported one" from "the agent violated ACP's
                        // MUST and this build filled in its own" -- exactly
                        // the distinction the `IdentityPending` refusal
                        // downstream depends on.
                        let identity_observed = if runtime_policy.provider_session_identity {
                            match session.provider_reported_session_id().await {
                                Some(id) => Some(ProviderEvent::SessionIdentityObserved {
                                    identity: ProviderSessionIdentity {
                                        key: ProviderSessionKey::SessionId,
                                        id,
                                        transcript_path: None,
                                    },
                                }),
                                None => {
                                    tracing::warn!(
                                        agent_id = %agent_id,
                                        adapter = %acp_spec.adapter.id,
                                        "ACP session/new returned no sessionId; provider \
                                         session identity stays IdentityPending",
                                    );
                                    None
                                }
                            }
                        } else {
                            None
                        };
                        if let Some(prompt) = request.initial_prompt {
                            if let Err(error) = session.start_prompt(&prompt).await {
                                let _ = session.kill().await;
                                return ControlObservation::SpawnFailed {
                                    message: error.to_string(),
                                };
                            }
                        }
                        // Read before `session` moves into the map below.
                        let announced_mode = session.current_mode_id();
                        self.acp_sessions.insert(
                            key,
                            OwnedProviderSession {
                                source,
                                session,
                                events,
                                pending_events: {
                                    let mut seeded = VecDeque::from([AgentEvent::SessionStart {
                                        session_id,
                                        model: String::new(),
                                        tools: Vec::new(),
                                    }]);
                                    // Announce the mode catalogue once, at
                                    // session start.
                                    //
                                    // `ModeCatalog` reaches the operator only
                                    // from a `ModeChanged`, so without this it
                                    // is emitted solely when a mode CHANGES --
                                    // and an operator cannot change a mode
                                    // without knowing an id, which is what the
                                    // catalogue carries. That is a closed
                                    // loop: the one thing needed to ask is
                                    // only published in reply to asking.
                                    //
                                    // Both halves are handshake facts, not
                                    // inventions: `available_modes` is the
                                    // list the agent returned from
                                    // `session/new`, and `current_mode_id` is
                                    // what it said it is in right now. Seeding
                                    // them as a `ModeChanged` is a small
                                    // misnomer -- nothing changed -- but the
                                    // payload is the state, and the operator
                                    // needs the state before it can ever
                                    // change.
                                    if let Some(mode_id) = announced_mode {
                                        seeded.push_back(AgentEvent::ModeChanged { mode_id });
                                    }
                                    seeded
                                },
                                pending_provider_events: VecDeque::from_iter(identity_observed),
                                next_provider_sequence: 1,
                                observed_exit_code: None,
                                runtime_policy,
                            },
                        );
                        ControlObservation::Spawned { process_id }
                    }
                    Err(error) => ControlObservation::SpawnFailed {
                        message: error.to_string(),
                    },
                }
            }
        }
    }

    async fn spawn_resume(
        &mut self,
        key: NativeSessionKey,
        operation_id: OperationId,
        agent_id: AgentId,
        transport: TransportKind,
        provider_session: gate4agent_types::ProviderSessionIdentity,
        runtime_policy: ProviderRuntimePolicy,
        request: ResumeLaunchRequest,
        pty_env: Vec<EnvMutation>,
        instance_extra_args: Vec<OsString>,
        one_shot_session_persistence: OneShotSessionPersistence,
    ) -> ControlObservation {
        if let Err(message) = validate_spawn_runtime_policy(
            runtime_policy,
            transport,
            request.initial_prompt.is_some(),
            true,
        ) {
            return ControlObservation::SpawnFailed { message };
        }
        if let Err(error) = request.validate() {
            return ControlObservation::SpawnFailed {
                message: error.to_string(),
            };
        }
        let Some(spec) = self.catalog.get(&agent_id) else {
            return ControlObservation::SpawnFailed {
                message: format!("agent '{agent_id}' is absent from native catalog"),
            };
        };
        let Some(binding) = spec.capabilities.adapters.resume.as_ref() else {
            return ControlObservation::SpawnFailed {
                message: format!("agent '{agent_id}' does not declare Resume capability"),
            };
        };
        let plan = match build_resume_plan_for_identity(&binding.id, &provider_session) {
            Ok(Some(plan)) => plan,
            Ok(None) => {
                return ControlObservation::SpawnFailed {
                    message: format!("agent '{agent_id}' has no live Resume plan"),
                }
            }
            Err(error) => {
                return ControlObservation::SpawnFailed {
                    message: error.to_string(),
                }
            }
        };
        if transport == TransportKind::Pipe {
            let Some(pipe) = spec.capabilities.transports.pipe.as_ref() else {
                return ControlObservation::SpawnFailed {
                    message: format!("agent '{agent_id}' does not support Pipe transport"),
                };
            };
            if pipe.protocol != PipeProtocol::StructuredJsonl {
                return ControlObservation::SpawnFailed {
                    message: format!(
                        "agent '{agent_id}' does not expose a resumable structured Pipe contract"
                    ),
                };
            }
        }
        let start = StartRequest {
            working_directory: request.working_directory,
            terminal_size: request.terminal_size,
            initial_prompt: request.initial_prompt,
            // A resume reattaches to a provider session that already has a
            // process running with whatever argv it was originally spawned
            // with -- there is no fresh CLI invocation here to apply an
            // approval level to, the same reasoning that leaves
            // `session_options` unset on a resume above.
            session_options: None,
            approval_level: ApprovalLevel::default(),
        };
        self.spawn_native(
            key,
            operation_id,
            NativeSpawnRequest {
                agent_id,
                transport,
                request: start,
                runtime_policy,
                launch_extra_args: if transport == TransportKind::Pty {
                    plan.args.into_iter().map(OsString::from).collect()
                } else {
                    Vec::new()
                },
                instance_extra_args,
                resumed_provider_session: Some(provider_session),
                one_shot_session_persistence,
            },
            pty_env,
            None,
        )
        .await
    }

    async fn stop_native(&mut self, key: NativeSessionKey, force: bool) -> ControlObservation {
        if let Some(owned) = self.pty_sessions.remove(&key) {
            let shutdown = owned.session.shutdown().await;
            return match shutdown {
                Ok(outcome) => ControlObservation::StopCompleted {
                    forced: force || outcome.termination.is_some(),
                    exit_code: outcome.exit_code,
                    // The last classification this session ever computed --
                    // stamped through unchanged, same as every other frame;
                    // nothing observes this session again after this point.
                    final_terminal: Some(terminal_frame(outcome.terminal, owned.last_screen_state.clone())),
                },
                Err(error) => {
                    eprintln!(
                        "[gate4agent-shell-native] PTY stop failed for {key:?} (force={force}): {error}",
                    );
                    ControlObservation::StopFailed {
                        message: error.to_string(),
                    }
                }
            };
        }
        if let Some(owned) = self.pipe_sessions.remove(&key) {
            // `PipeSession::stop` reads `force`: `false` waits up to
            // `PIPE_GRACEFUL_STOP_BOUND_SECS` for the process to exit on its
            // own (stdin is already closed by spawn time for every
            // supported CLI, so this is "let the run finish" rather than a
            // new signal) before falling back to a kill; `true` kills
            // immediately, same as the old unconditional `kill()` call this
            // replaces. `Err(_) if reader_finished()` below is the race
            // where a `force = true` kill loses to the process already
            // having exited on its own between the map lookup and the kill
            // attempt -- `stop`'s own graceful path already reports that
            // case as `Ok` with `forced: false`, so this arm is only ever
            // reached on the `force = true` side of `stop`.
            return match owned.session.stop(force).await {
                Ok(outcome) => ControlObservation::StopCompleted {
                    forced: outcome.forced,
                    exit_code: outcome.exit_code.or(owned.observed_exit_code),
                    final_terminal: None,
                },
                Err(_) if owned.session.reader_finished() => ControlObservation::StopCompleted {
                    forced: false,
                    exit_code: owned.observed_exit_code,
                    final_terminal: None,
                },
                Err(error) => ControlObservation::StopFailed {
                    message: error.to_string(),
                },
            };
        }
        if let Some(mut owned) = self.one_shot_sessions.remove(&key) {
            return match owned.session.kill().await {
                Ok(()) => ControlObservation::StopCompleted {
                    forced: true,
                    exit_code: owned.observed_exit_code,
                    final_terminal: None,
                },
                Err(_) if owned.session.reader_finished() => ControlObservation::StopCompleted {
                    forced: false,
                    exit_code: owned.observed_exit_code,
                    final_terminal: None,
                },
                Err(error) => ControlObservation::StopFailed {
                    message: error.to_string(),
                },
            };
        }
        if let Some(owned) = self.acp_sessions.remove(&key) {
            // `AcpSession::stop` reads `force`: `false` closes stdin and
            // waits up to `ACP_GRACEFUL_STOP_BOUND_SECS` for the adapter to
            // exit on its own before falling back to a kill; `true` kills
            // immediately, same as the old unconditional `kill()` call this
            // replaces. `Err(_) if reader_finished()` below is the race
            // where a `force = true` kill loses to the process already
            // having exited on its own between the map lookup and the kill
            // attempt -- `stop`'s own graceful path already reports that
            // case as `Ok` with `forced: false`, so this arm is only ever
            // reached on the `force = true` side of `stop`.
            return match owned.session.stop(force).await {
                Ok(outcome) => ControlObservation::StopCompleted {
                    forced: outcome.forced,
                    exit_code: outcome.exit_code.or(owned.observed_exit_code),
                    final_terminal: None,
                },
                Err(_) if owned.session.reader_finished() => ControlObservation::StopCompleted {
                    forced: false,
                    exit_code: owned.observed_exit_code,
                    final_terminal: None,
                },
                Err(error) => ControlObservation::StopFailed {
                    message: error.to_string(),
                },
            };
        }
        // A kill this function skips entirely -- nothing owns `key` in any
        // transport map -- must say so out loud: silently returning
        // `StopFailed` here left no trail at the point where the skip
        // actually happened, only a message string several layers removed
        // from anyone watching this process's own output.
        eprintln!("[gate4agent-shell-native] stop skipped: no session owns {key:?} in any transport map");
        ControlObservation::StopFailed {
            message: missing_session_message(key),
        }
    }

    fn session_exists(&self, key: NativeSessionKey) -> bool {
        self.pty_sessions.contains_key(&key)
            || self.pipe_sessions.contains_key(&key)
            || self.one_shot_sessions.contains_key(&key)
            || self.acp_sessions.contains_key(&key)
    }

    /// Convert naturally exited PTY children into generation-bound lifecycle
    /// observations. Runtime ticks call this before accepting new commands.
    pub async fn collect_exits(&mut self) -> Vec<ObservationEnvelope> {
        let completed: Vec<_> = self
            .pty_sessions
            .iter()
            .filter_map(|(key, owned)| owned.session.reader_finished().then_some(*key))
            .collect();
        let mut observations = Vec::with_capacity(completed.len());
        for key in completed {
            let owned = self
                .pty_sessions
                .remove(&key)
                .expect("completed key came from the owned session map");
            let last_screen_state = owned.last_screen_state.clone();
            let (exit_code, final_terminal) = match owned.session.shutdown().await {
                Ok(outcome) => (
                    outcome.exit_code,
                    Some(terminal_frame(outcome.terminal, last_screen_state)),
                ),
                Err(_) => (None, None),
            };
            observations.push(ObservationEnvelope {
                operation_id: None,
                instance_id: key.instance_id,
                generation: key.generation,
                observation: ControlObservation::ProcessExited {
                    exit_code,
                    final_terminal,
                },
            });
        }
        collect_provider_exits(&mut self.pipe_sessions, &mut observations, |session| {
            session.reader_finished()
        });
        collect_provider_exits(&mut self.one_shot_sessions, &mut observations, |session| {
            session.reader_finished()
        });
        collect_provider_exits(&mut self.acp_sessions, &mut observations, |session| {
            session.reader_finished()
        });
        observations
    }

    /// Drain normalized provider events without mixing them with replaceable
    /// terminal frames. Broadcast lag is converted into an explicit stale gap.
    pub fn collect_provider_events(&mut self) -> Vec<ObservationEnvelope> {
        let mut observations = self.pending_observations.drain(..).collect::<Vec<_>>();
        for (key, owned) in &mut self.pty_sessions {
            if let Some(provider) = &mut owned.provider {
                drain_pty_provider(*key, provider, &mut observations);
            }
        }
        collect_provider_map(&mut self.pipe_sessions, &mut observations, |_| Vec::new());
        collect_provider_map(&mut self.one_shot_sessions, &mut observations, |_| Vec::new());
        // Retire deferred permission requests whose deadline has passed,
        // BEFORE draining -- so the `RpcIncomingRequest` each expiry emits is
        // picked up by the very same drain rather than waiting a whole tick
        // to be reported.
        //
        // This call is what makes the deadline real. Without it a deferred
        // request has a `deadline` field nobody ever reads, and a session
        // whose operator never answers waits forever on a promise the code
        // makes and never keeps -- the agent blocked on a permission it will
        // never be told about. Deferral is only safe because this runs on
        // every tick; nothing else in the process calls it.
        for owned in self.acp_sessions.values() {
            owned.session.expire_deadlines();
        }
        collect_provider_map(&mut self.acp_sessions, &mut observations, AcpSession::available_modes);
        observations
    }

    /// Capture only changed terminal frames. Snapshot failures become an
    /// explicit stale observation once, until a later successful frame heals it.
    ///
    /// The sequence is checked BEFORE the capture, not after. This runs on
    /// the per-session worker tick (20ms, so ~50 times a second per live
    /// PTY session), and `terminal_state` is not a cheap read: it renders
    /// the visible screen twice and clones the whole `vt100::Screen` to
    /// walk its scrollback row by row. Asking it first and comparing
    /// sequences afterwards meant every idle session rebuilt its entire
    /// screen fifty times a second purely to discover nothing had changed,
    /// and then dropped the result -- with a couple of dozen sessions open
    /// that is the machine's time, all of it wasted. `terminal_sequence`
    /// answers the same question by reading one integer.
    pub fn collect_terminal_frames(&mut self) -> Vec<ObservationEnvelope> {
        let mut observations = Vec::new();
        // Split borrows taken up front: the loop below needs a mutable
        // borrow of `pty_sessions` for its whole body, and `efficiency_facts`
        // is a disjoint field this function also writes to on every branch
        // -- see `ShellEfficiencyFacts`'s own doc comment for why this crate
        // is the one recording facts rather than a distribution.
        let pty_sessions = &mut self.pty_sessions;
        let efficiency_facts = &mut self.efficiency_facts;
        for (key, owned) in pty_sessions {
            if terminal_state_capture_should_skip(
                owned.session.terminal_sequence(),
                owned.last_terminal_sequence,
            ) {
                efficiency_facts.record_terminal_state_skip();
                continue;
            }
            let capture_start = Instant::now();
            let terminal_state = owned.session.terminal_state();
            efficiency_facts.record_terminal_state_capture(capture_start.elapsed());
            match terminal_state {
                Ok(snapshot) if snapshot.sequence > owned.last_terminal_sequence => {
                    owned.last_terminal_sequence = snapshot.sequence;
                    owned.terminal_stale_published = false;

                    // `snapshot.contents` is already in memory for the
                    // `TerminalFrame` below, so both text matchers run for
                    // free here -- no extra syscall, no extra capture.
                    owned.last_screen_gate = startup_operator_gate(&snapshot.contents);
                    // `screen_failure`'s markers are crash SHAPES, and as
                    // raw bytes those are indistinguishable from an agent
                    // choosing to render the same text while explaining or
                    // running someone else's failure. Before this
                    // generation has ever rendered its own UI, nothing else
                    // could have put a crash banner on the screen, so the
                    // marker genuinely means the CLI failed to come up;
                    // once it has been `Ready`, the identical bytes are
                    // ordinary content, not state, so the matcher is not
                    // even run.
                    owned.last_screen_failure =
                        screen_failure_for_generation(&snapshot.contents, owned.ever_reached_ready);
                    let merged = classify_pty_screen_state(
                        owned.last_foreground_verdict.as_ref(),
                        owned.last_screen_gate.as_ref(),
                        owned.last_screen_failure,
                    );
                    // Arm the crash-marker window only on a `Ready` that had
                    // SOMETHING on screen. `Ready` is proved by foreground
                    // process identity, so it lands within a frame or two of
                    // spawn, while the terminal is still blank -- measured at
                    // frame 2 for all four providers. Arming on that blank
                    // frame closed the window before any failure text could
                    // exist: Grok without a key prints `API key required` at
                    // frame 4 and sat at `Ready` forever, because the matcher
                    // for it was never reached. A blank screen is not evidence
                    // the agent came up, so it must not retire the detector.
                    if !snapshot.contents.trim().is_empty() {
                        owned.screen_had_content = true;
                    }
                    if merged == PtyScreenState::Ready && owned.screen_had_content {
                        owned.ever_reached_ready = true;
                    }
                    if merged != owned.last_screen_state {
                        if foreground_probe_rearms_immediately(&owned.last_screen_state, &merged) {
                            owned.next_foreground_probe = Some(Instant::now());
                        }
                        owned.last_screen_state = merged.clone();
                        observations.push(ObservationEnvelope {
                            operation_id: None,
                            instance_id: key.instance_id,
                            generation: key.generation,
                            observation: ControlObservation::ScreenState {
                                state: merged.clone(),
                            },
                        });
                    }

                    let frame = terminal_frame(snapshot, merged);
                    efficiency_facts.record_terminal_frame_published(terminal_frame_byte_len(&frame));
                    observations.push(ObservationEnvelope {
                        operation_id: None,
                        instance_id: key.instance_id,
                        generation: key.generation,
                        observation: ControlObservation::TerminalFrame { frame },
                    });
                }
                Ok(_) => {}
                Err(error) if !owned.terminal_stale_published => {
                    owned.terminal_stale_published = true;
                    observations.push(ObservationEnvelope {
                        operation_id: None,
                        instance_id: key.instance_id,
                        generation: key.generation,
                        observation: ControlObservation::TerminalStale {
                            message: error.to_string(),
                        },
                    });
                }
                Err(_) => {}
            }
        }
        observations
    }

    /// Refresh the foreground half of `PtyScreenState` for whichever
    /// sessions are due, per `next_foreground_probe`.
    ///
    /// Deliberately not folded into `collect_terminal_frames`: that method
    /// is synchronous and only pays for a real capture when the terminal
    /// sequence says the screen changed, but
    /// `PtySession::observe_foreground_timed` is async and walks the live OS
    /// process tree
    /// (`CreateToolhelp32Snapshot` on Windows) unconditionally every time
    /// it is called. Running that walk once per changed frame would scale
    /// a syscall with output rate -- exactly the cost
    /// `collect_terminal_frames`'s own sequence gate exists to avoid. The
    /// cost here is bounded by the count of sessions NOT currently
    /// `Ready`, never by output rate and never by total session count: a
    /// session that reaches `Ready` disarms itself (see
    /// `foreground_probe_schedule`) and is never probed again until its
    /// text disagrees.
    pub async fn reclassify_foreground(&mut self) -> Vec<ObservationEnvelope> {
        let catalog = &self.catalog;
        let now = Instant::now();
        let due: Vec<NativeSessionKey> = self
            .pty_sessions
            .iter()
            .filter(|(_, owned)| owned.next_foreground_probe.is_some_and(|at| now >= at))
            .map(|(key, _)| *key)
            .collect();

        let mut observations = Vec::new();
        for key in due {
            let Some(owned) = self.pty_sessions.get_mut(&key) else {
                continue;
            };
            let probe_result = owned.session.observe_foreground_timed().await;
            match probe_result {
                Ok((observation, timing)) => {
                    // Recorded on success only: `timing` covers all three
                    // components (queue, lock wait, walk) exactly when the
                    // walk itself ran to completion and returned a real
                    // observation. On error (see below) the walk may have
                    // failed partway through, in the mutex, or never been
                    // dispatched at all (`spawn_blocking` panicked), so
                    // there is no single component that is reliably "the
                    // cost of this probe" to attribute a failure to -- unlike
                    // `terminal_state_capture`, which always completes or
                    // never starts, a foreground probe can fail after
                    // dispatch, after acquiring the lock, or during the walk,
                    // and only the success path knows which.
                    self.efficiency_facts.record_foreground_probe(timing);
                    let verdict = match catalog.get(&owned.agent_id) {
                        Some(spec) => resolve_foreground_verdict(
                            spec,
                            &observation,
                            RuntimePlatform::current(),
                        ),
                        // The catalog is loaded once at startup and does not
                        // shrink at runtime; this branch exists only so a
                        // hypothetical gap fails toward the conservative
                        // "not confirmed as the agent" reading rather than
                        // panicking or silently keeping a stale verdict.
                        None => ForegroundVerdict::Foreign {
                            process: observation.observed_process.clone(),
                        },
                    };
                    owned.last_foreground_verdict = Some(verdict);
                    let merged = classify_pty_screen_state(
                        owned.last_foreground_verdict.as_ref(),
                        owned.last_screen_gate.as_ref(),
                        owned.last_screen_failure,
                    );
                    // A foreground-only transition into `Ready` (text was
                    // already clean; only the process signal was missing)
                    // must ALSO close the `screen_failure` window for
                    // future text passes -- see `collect_terminal_frames`.
                    if merged == PtyScreenState::Ready && owned.screen_had_content {
                        owned.ever_reached_ready = true;
                    }
                    if merged != owned.last_screen_state {
                        owned.last_screen_state = merged.clone();
                        observations.push(ObservationEnvelope {
                            operation_id: None,
                            instance_id: key.instance_id,
                            generation: key.generation,
                            observation: ControlObservation::ScreenState { state: merged },
                        });
                    }
                    owned.next_foreground_probe =
                        match foreground_probe_schedule(&owned.last_screen_state) {
                            ForegroundProbeSchedule::Disarmed => None,
                            ForegroundProbeSchedule::Armed => {
                                Some(now + FOREGROUND_RECLASSIFY_INTERVAL)
                            }
                        };
                }
                Err(_) => {
                    // A failed OS process-tree walk is `Unknown`'s territory
                    // -- it says nothing was confirmed, not that the
                    // process is wrong. Leave whatever verdict/state is
                    // already recorded alone and simply try again next
                    // cadence rather than fabricating a `NotAgent` verdict
                    // or a `Ready` one.
                    owned.next_foreground_probe = Some(now + FOREGROUND_RECLASSIFY_INTERVAL);
                }
            }
        }
        observations
    }
}

/// ConPTY does not populate `TERM`/`COLORTERM` in the environment it hands
/// to a spawned child; a provider CLI reads exactly those two variables to
/// decide whether the terminal in front of it renders color, so a
/// Windows-hosted PTY session comes up monochrome unless something else
/// supplies them. These are the values truecolor-capable terminals
/// (xterm.js, WezTerm, ...) advertise about themselves.
const PTY_TERM_DEFAULT_KEY: &str = "TERM";
const PTY_TERM_DEFAULT_VALUE: &str = "xterm-256color";
const PTY_COLORTERM_DEFAULT_KEY: &str = "COLORTERM";
const PTY_COLORTERM_DEFAULT_VALUE: &str = "truecolor";

/// Fill in the PTY terminal-capability defaults above for whichever of the
/// two keys the caller has not already mutated. A caller-supplied
/// `EnvMutation` for `TERM`/`COLORTERM` -- whether it sets or removes the
/// variable -- always wins: this only appends a default into a gap, it
/// never overwrites or reorders an existing entry.
fn with_pty_terminal_capability_defaults(mut pty_env: Vec<EnvMutation>) -> Vec<EnvMutation> {
    let already_mutated = |env: &[EnvMutation], key: &str| {
        env.iter()
            .any(|mutation| mutation.key.as_os_str() == OsStr::new(key))
    };
    if !already_mutated(&pty_env, PTY_TERM_DEFAULT_KEY) {
        pty_env.push(EnvMutation {
            key: OsString::from(PTY_TERM_DEFAULT_KEY),
            value: Some(OsString::from(PTY_TERM_DEFAULT_VALUE)),
        });
    }
    if !already_mutated(&pty_env, PTY_COLORTERM_DEFAULT_KEY) {
        pty_env.push(EnvMutation {
            key: OsString::from(PTY_COLORTERM_DEFAULT_KEY),
            value: Some(OsString::from(PTY_COLORTERM_DEFAULT_VALUE)),
        });
    }
    pty_env
}

fn missing_session_message(key: NativeSessionKey) -> String {
    format!(
        "native session {:?}/{:?} does not exist",
        key.instance_id, key.generation
    )
}

/// Map the spawn request's `ApprovalLevel` to the ACP host authority mode
/// that answers `session/request_permission` for the SAME session -- the
/// PTY transport lets a human at the keyboard pick their own agent's
/// permission flags (see `gate4agent_catalog::LaunchRequest`, which carries
/// no approval axis at all), but ACP is opened by this process with nobody
/// at a terminal, so it is the one transport where `approval_level` also has
/// to steer the host side of the session, not just the spawned process's own
/// argv (`approval_level_args`).
///
/// `FullAuto` must never land on a refusing `HostPolicy` (`ReadOnly` or
/// `Deny`): that combination launches the process believing it holds full
/// autonomy while every host permission request it makes gets silently
/// refused, which is worse than either policy alone -- so `FullAuto` maps to
/// `HostPolicy::Yolo`, the one mode that grants everything without asking.
/// `ReadOnly` maps to `HostPolicy::ReadOnly` for the same reason in reverse.
///
/// `Moderate` has no dedicated `HostPolicy` variant -- ACP's four host modes
/// are coarser than the three managed `ApprovalLevel` steps -- so it falls
/// back to `HostPolicy::Auto`, the same mode `Unmanaged` ("impose nothing")
/// uses. Both already mean "allow reads, writes, and execution, but decide
/// per request rather than blanket-granting" (see `HostPolicy::Auto`'s own
/// doc comment), which is the correct non-extreme default whether the
/// request asked for a deliberate middle ground or asked for nothing to be
/// imposed at all.
fn host_policy_for_approval_level(level: ApprovalLevel) -> HostPolicy {
    match level {
        ApprovalLevel::FullAuto => HostPolicy::Yolo,
        ApprovalLevel::ReadOnly => HostPolicy::ReadOnly,
        ApprovalLevel::Moderate | ApprovalLevel::Unmanaged => HostPolicy::Auto,
    }
}

/// Whether a session at this approval level parks a `session/request_
/// permission` for an operator instead of answering it from policy on the
/// spot (`AcpSessionOptions::defer_permission_requests`).
///
/// Reads `asks_for_permission` straight off
/// `gate4agent_catalog::approval_level_resolution` -- the provider's own
/// vendor mode, declared beside its flag -- rather than matching on the
/// `ApprovalLevel`'s name. That distinction used to matter in practice: this
/// function previously matched on the level alone and assumed `ReadOnly`
/// never asks, but claude's `ReadOnly` launched `--permission-mode default`,
/// claude's own **interactive** mode, which asks about everything. A live
/// run under that flag produced a completed tool call and zero
/// `host-request-observed` because deferral was off for the one level that
/// was actually asking. `approval_level_resolution`'s `ReadOnly` row for
/// claude now launches `plan` (which genuinely never asks) instead, so the
/// caller (this transport's own ACP spawn branch) must already have refused
/// the spawn outright for any provider `approval_level_resolution` marks
/// `Unsupported` for this level -- see that call site -- before this
/// function is reached; `Unsupported` here is defensive-only and defers,
/// the conservative choice, rather than assuming silence.
///
/// `Unmanaged` always resolves `asks_for_permission: false` -- it decides
/// `session/request_permission` immediately (auto-approve) rather than
/// parking it, since some providers' ACP clients won't wait out a deferred
/// decision (kimi reports the call as refused). The managed levels'
/// `asks_for_permission` still varies per provider and per level -- that is
/// a fact about today's four providers' vendor modes, not a rule this
/// function encodes; a fifth provider or a vendor mode change could shift it
/// without this function's logic changing at all, which is the point of
/// reading the catalog instead of the level.
fn defers_permission_requests(agent_id: &AgentId, level: ApprovalLevel) -> bool {
    match approval_level_resolution(agent_id, level) {
        ApprovalLevelResolution::Supported {
            asks_for_permission,
            ..
        } => asks_for_permission,
        ApprovalLevelResolution::Unsupported => true,
    }
}

/// How long [`apply_acp_approval_mode`] waits, after a successful
/// `session/set_mode` RPC ack, for the agent's own `current_mode_update`
/// notification to corroborate it. Bounded because the notification is
/// documented as optional -- `AcpSession::set_mode`'s own doc comment: "an
/// agent is not required to also send one after acking this call" -- so an
/// agent that never sends it must never stall a spawn indefinitely. The RPC
/// ack itself (checked before this wait starts) is the authoritative
/// confirmation; this wait is corroboration only, and a timeout here does
/// not undo it.
const ACP_MODE_CONFIRMATION_TIMEOUT: Duration = Duration::from_secs(5);

/// Resolve the concrete ACP mode id [`apply_acp_approval_mode`] must confirm
/// and apply for `agent_id` at `level`, or the exact refusal message when no
/// mechanism exists to enforce it at all.
///
/// Outcomes:
/// - `Ok(Some(id))` — catalog named a sourced `acp_mode_id`; spawn applies it
///   via `session/set_mode` (claude/codex managed levels today).
/// - `Ok(None)` for [`ApprovalLevel::Unmanaged`] — imposes nothing.
/// - `Ok(None)` when the level is `Supported` with `acp_mode_id: None` **and**
///   non-empty vendor `args` — argv is the only lever left (grok FullAuto /
///   Moderate; kimi FullAuto). `acp_approval_level_args` carries those flags
///   into the process ahead of the ACP subcommand.
/// - `Err` for [`ApprovalLevelResolution::Unsupported`] (e.g. grok ReadOnly)
///   or a `Supported` row with neither mode id nor flags (kimi Moderate /
///   ReadOnly today): refuse rather than launch at the vendor default
///   (`mode:Mode="auto"`), which approves itself.
fn required_acp_mode(agent_id: &AgentId, level: ApprovalLevel) -> Result<Option<ModeId>, String> {
    let (acp_mode_id, carries_argv_flags) = match approval_level_resolution(agent_id, level) {
        ApprovalLevelResolution::Unsupported => (None, false),
        ApprovalLevelResolution::Supported { acp_mode_id, args, .. } => {
            (acp_mode_id, !args.is_empty())
        }
    };
    match (acp_mode_id, level) {
        (Some(mode_id), _) => Ok(Some(mode_id)),
        (None, ApprovalLevel::Unmanaged) => Ok(None),
        // No mode, but the level carries vendor flags: `acp_approval_level_args`
        // puts those in the agent's own argv, so the level IS applied and this
        // is not a launch at the vendor's default. The refusal below exists to
        // stop a session running at wider authority than asked for -- it must
        // not also block the one mechanism that narrows it. Measured
        // 2026-09-09: kimi announces no ACP modes at all, so before this every
        // level but `Unmanaged` refused outright and its own `--yolo` was
        // unreachable.
        (None, _) if carries_argv_flags => Ok(None),
        (None, _) => Err(format!(
            "agent '{agent_id}' has no verified ACP mode for {level:?} and the level carries no \
             vendor flags to apply through argv either; refusing rather than launching at the \
             vendor's own (wider-authority) default"
        )),
    }
}

/// The vendor approval flags an ACP-spawned agent needs in its own argv.
///
/// Exactly the complement of [`required_acp_mode`]: a level that resolved an
/// `acp_mode_id` is applied over the wire by `session/set_mode`, so that
/// agent's argv stays clean and this returns nothing. A level that resolved
/// NO mode has no wire mechanism at all, and returning nothing there means
/// launching at the vendor's own default -- the exact wider-authority defect
/// the mode machinery exists to close, just reached from the other side.
///
/// Measured 2026-09-09: every kimi row carries `acp_mode_id: None` (kimi.exe
/// 0.29.0 announces no modes), so kimi ran at its own default and refused
/// every `g4a_*` MCP tool call at its internal approval prompt without ever
/// sending the host a `session/request_permission` -- unreachable by policy,
/// by deferral, and by `set_mode` alike. Its `FullAuto` row already carries
/// the flag that turns that gate off (`--yolo`); it simply never reached the
/// process.
fn acp_approval_level_args(agent_id: &AgentId, level: ApprovalLevel) -> Vec<String> {
    match approval_level_resolution(agent_id, level) {
        ApprovalLevelResolution::Supported { args, acp_mode_id: None, .. } => args,
        ApprovalLevelResolution::Supported { acp_mode_id: Some(_), .. } => Vec::new(),
        ApprovalLevelResolution::Unsupported => Vec::new(),
    }
}

/// Named refusal for [`apply_acp_approval_mode`]: `level` resolved a real
/// catalog `acp_mode_id`, but this agent's own `session/new` handshake never
/// announced a mode with that id -- so the mechanism that would apply it
/// (`session/set_mode`) has nothing to call. Refusing by name, carrying
/// exactly what the agent DID offer, is the alternative to the defect this
/// whole rewrite exists to close: silently leaving the session running at
/// whichever mode the agent came up in on its own.
#[derive(Debug)]
struct ApprovalLevelNotOfferedByAgent {
    level: ApprovalLevel,
    offered: Vec<String>,
}

impl std::fmt::Display for ApprovalLevelNotOfferedByAgent {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            formatter,
            "ApprovalLevelNotOfferedByAgent {{ level: {:?}, offered: {:?} }}",
            self.level, self.offered
        )
    }
}

/// `None` when `offered` (the agent's own `session/new` mode catalog) names
/// `mode_id`; `Some(message)` -- an [`ApprovalLevelNotOfferedByAgent`],
/// stringified -- when it does not. A free function, independent of a live
/// [`AcpSession`], so the refusal can be exercised directly against a
/// fixture mode list rather than only through a real spawn.
fn approval_level_not_offered_message(
    level: ApprovalLevel,
    mode_id: &ModeId,
    offered: &[SessionMode],
) -> Option<String> {
    if offered.iter().any(|mode| mode.id == mode_id.as_str()) {
        None
    } else {
        Some(
            ApprovalLevelNotOfferedByAgent {
                level,
                offered: offered.iter().map(|mode| mode.id.clone()).collect(),
            }
            .to_string(),
        )
    }
}

/// Apply `mode_id` to a freshly handshaken ACP session (Item 2 of the
/// `session/set_mode` approval-level rewrite): refuse by name
/// (`approval_level_not_offered_message`) when the agent's own `session/new`
/// mode catalog never named this id, otherwise call `session/set_mode` and
/// wait, bounded by [`ACP_MODE_CONFIRMATION_TIMEOUT`], for the agent's own
/// `current_mode_update` to corroborate it -- only then is the session
/// considered up at the requested level.
///
/// The RPC ack from `AcpSession::set_mode` is the authoritative
/// confirmation (it already updates the session's own cached
/// `current_mode_id` synchronously on success, and an agent rejecting an
/// unknown mode id returns an RPC error there, not a silent no-op); the wait
/// on this function's own subscription is corroboration only. A provider
/// that never sends `current_mode_update` at all -- permitted by the ACP
/// spec -- times out here and the spawn still proceeds, because the RPC ack
/// that already succeeded is not undone by a notification that was never
/// guaranteed in the first place.
async fn apply_acp_approval_mode(
    session: &AcpSession,
    mode_id: &ModeId,
    level: ApprovalLevel,
) -> Result<(), String> {
    if let Some(message) =
        approval_level_not_offered_message(level, mode_id, &session.available_modes())
    {
        return Err(message);
    }

    // Subscribed BEFORE `set_mode` is sent, so a fast `current_mode_update`
    // cannot race ahead of this receiver's creation and be missed.
    let mut confirmation = session.subscribe();
    session
        .set_mode(mode_id.as_str())
        .await
        .map_err(|error| format!("session/set_mode to '{mode_id}' failed: {error}"))?;

    let _ = tokio::time::timeout(ACP_MODE_CONFIRMATION_TIMEOUT, async {
        loop {
            match confirmation.recv().await {
                Ok(AgentEvent::ModeChanged { mode_id: changed }) if changed == mode_id.as_str() => {
                    return;
                }
                Ok(_) => continue,
                Err(_) => return,
            }
        }
    })
    .await;

    Ok(())
}

fn validate_spawn_runtime_policy(
    policy: ProviderRuntimePolicy,
    transport: TransportKind,
    has_initial_prompt: bool,
    is_resume: bool,
) -> Result<(), String> {
    policy
        .validate()
        .map_err(|error| format!("provider runtime policy is invalid: {error}"))?;
    // ACP speaks a structured protocol over stdio, not a PTY -- none of the
    // capabilities below describe anything that exists for it; they all
    // gate inferring provider state from terminal text. The transport-
    // support gate for ACP already lives in the kernel
    // (`spec.capabilities.transports.acp.is_some()`), so this PTY-semantic
    // policy simply does not apply here. Mirrors `gate4agent-runtime-native`'s
    // `validate_effect_runtime_policy`, which enforces the same rule one
    // layer up.
    if transport != TransportKind::Acp {
        require_runtime_capability(policy, ProviderRuntimeCapability::RawPtyLifecycle)?;
        if transport != TransportKind::Pty {
            require_runtime_capability(policy, ProviderRuntimeCapability::SemanticReadiness)?;
        }
        if has_initial_prompt {
            require_runtime_capability(policy, ProviderRuntimeCapability::SemanticReadiness)?;
            require_runtime_capability(policy, ProviderRuntimeCapability::StructuredPrompt)?;
        }
        if is_resume && has_initial_prompt {
            require_runtime_capability(policy, ProviderRuntimeCapability::ProviderSessionIdentity)?;
            require_runtime_capability(policy, ProviderRuntimeCapability::SemanticResume)?;
        }
    }
    Ok(())
}


fn is_codex_config_c_overlay_args(arguments: &[OsString]) -> bool {
    if arguments.is_empty() || arguments.len() % 2 != 0 {
        return false;
    }
    arguments.chunks_exact(2).all(|pair| {
        pair[0].as_os_str() == "-c"
            && pair[1]
                .to_str()
                .is_some_and(|value| !value.is_empty() && value.contains('=') && !value.contains('\0'))
    })
}

fn validate_instance_launch_arguments(
    agent_id: &AgentId,
    transport: TransportKind,
    arguments: &[OsString],
) -> Result<(), String> {
    if arguments.is_empty() {
        return Ok(());
    }
    let acp_codex_c_overlay = transport == TransportKind::Acp
        && agent_id.as_str() == "codex"
        && is_codex_config_c_overlay_args(arguments);
    if transport != TransportKind::Pty && !acp_codex_c_overlay {
        return Err(
            "native instance launch arguments require PTY transport (or Codex -c overlays on ACP)"
                .to_owned(),
        );
    }
    if arguments.len() > INSTANCE_LAUNCH_ARGS_MAX {
        return Err("native instance launch argument count exceeds its bound".to_owned());
    }
    let mut total_bytes = 0usize;
    for argument in arguments {
        let argument = argument.to_string_lossy();
        if argument.contains('\0') {
            return Err("native instance launch argument is invalid".to_owned());
        }
        if argument.len() > INSTANCE_LAUNCH_ARG_MAX_BYTES {
            return Err("native instance launch argument exceeds its bound".to_owned());
        }
        total_bytes = total_bytes.saturating_add(argument.len());
        if total_bytes > INSTANCE_LAUNCH_ARGS_TOTAL_MAX_BYTES {
            return Err("native instance launch argument payload exceeds its bound".to_owned());
        }
        if agent_id.as_str() == "claude"
            && RESERVED_CLAUDE_LAUNCH_FLAGS.iter().any(|reserved| {
                argument == *reserved
                    || (reserved.starts_with("--")
                        && argument
                            .strip_prefix(reserved)
                            .is_some_and(|suffix| suffix.starts_with('=')))
                    || (reserved.len() == 2
                        && argument
                            .strip_prefix(reserved)
                            .is_some_and(|suffix| {
                                !suffix.is_empty() && !suffix.starts_with('-')
                            }))
            })
        {
            return Err(
                "native instance launch arguments conflict with Claude session, resume, or prompt authority"
                    .to_owned(),
            );
        }
    }
    Ok(())
}

/// True if `value` has the shape of a bearer credential rather than an
/// ordinary CLI flag, path, or session identifier.
///
/// Gate4Agent's own secrets are environment-only and never argv (see
/// `gate4agent/CLAUDE.md`), so this should not fire for anything this repo
/// itself constructs. It exists as defense-in-depth against a provider CLI
/// whose own argv convention accepts a credential positionally. The check is
/// deliberately keyword/prefix-based rather than an entropy heuristic: a
/// generic "long hex/base64 string" rule would also catch legitimate,
/// diagnostically valuable arguments such as a resume session UUID -- which
/// is also why [`has_prefixed_hex64_credential_shape`] requires the leading
/// `<prefix>_` before it will call a bare hex string a credential at all.
fn argument_looks_like_credential(value: &str) -> bool {
    const CREDENTIAL_PREFIXES: &[&str] = &["sk-", "sk_", "ghp_", "gho_", "ghs_", "xox", "bearer "];
    const CREDENTIAL_MARKERS: &[&str] = &[
        "apikey", "api_key", "api-key", "secret", "password", "passwd", "token=",
    ];
    let lower = value.to_ascii_lowercase();
    CREDENTIAL_PREFIXES
        .iter()
        .any(|prefix| lower.starts_with(prefix))
        || CREDENTIAL_MARKERS
            .iter()
            .any(|marker| lower.contains(marker))
        || has_prefixed_hex64_credential_shape(&lower)
}

/// True if `value` is exactly a short lowercase-alphanumeric prefix (2-8
/// characters), an underscore, and 64 lowercase hex characters -- the shape
/// every gate4agent-owned or caller-owned bearer credential uses (e.g. the
/// hatchery operator token, `g4aho_` + 64 hex, or the H3B local-capability
/// token, `g4ah3_` + 64 hex), regardless of which prefix a particular caller
/// picks. A bare 64-hex digest with no prefix is deliberately excluded: a
/// commit hash, a SHA-256 checksum, or a session digest is legitimate,
/// diagnostically valuable argument text, not a credential.
fn has_prefixed_hex64_credential_shape(lower: &str) -> bool {
    let Some((prefix, digest)) = lower.split_once('_') else {
        return false;
    };
    (2..=8).contains(&prefix.len())
        && prefix
            .bytes()
            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
        && digest.len() == 64
        && digest
            .bytes()
            .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
}

/// Renders one provider-CLI argument for a log line: verbatim unless it
/// matches [`argument_looks_like_credential`], in which case it is replaced
/// with a fixed placeholder rather than printed.
fn redact_provider_argument(value: &OsStr) -> String {
    let text = value.to_string_lossy();
    if argument_looks_like_credential(&text) {
        "[redacted-credential-shaped-argument]".to_owned()
    } else {
        text.into_owned()
    }
}

/// Renders a full provider-CLI argument list for a log line, redacting any
/// individual argument that looks like a credential.
fn redact_provider_arguments(values: &[OsString]) -> Vec<String> {
    values.iter().map(|value| redact_provider_argument(value)).collect()
}

fn require_runtime_capability(
    policy: ProviderRuntimePolicy,
    capability: ProviderRuntimeCapability,
) -> Result<(), String> {
    if policy.admits(capability) {
        Ok(())
    } else {
        Err(format!(
            "provider runtime capability {capability:?} is not admitted"
        ))
    }
}

fn should_attach_pty_provider_stream(policy: ProviderRuntimePolicy) -> bool {
    policy.semantic_readiness || policy.provider_session_identity
}

fn should_probe_pty_identity(
    policy: ProviderRuntimePolicy,
    adapter: Option<&gate4agent_types::AdapterBinding>,
    authoritative_identity_present: bool,
    expected_adapter: &str,
) -> bool {
    !authoritative_identity_present
        && policy.semantic_readiness
        && policy.structured_prompt
        && policy.provider_session_identity
        && adapter.is_some_and(|adapter| adapter.id.as_str() == expected_adapter)
}

fn prepare_fresh_pty_provider_session(
    adapter: Option<&gate4agent_types::AdapterBinding>,
    is_resume: bool,
    identity_permitted: bool,
    launch_extra_args: &mut Vec<OsString>,
) -> Option<ProviderSessionIdentity> {
    let adapter = adapter?;
    if is_resume || !identity_permitted || adapter.id.as_str() != "claude-code" {
        return None;
    }
    let identity = ProviderSessionIdentity {
        key: ProviderSessionKey::SessionId,
        id: Uuid::new_v4().to_string(),
        transcript_path: None,
    };
    launch_extra_args.push(OsString::from("--session-id"));
    launch_extra_args.push(OsString::from(&identity.id));
    Some(identity)
}

fn drain_pty_provider(
    key: NativeSessionKey,
    provider: &mut OwnedPtyProvider,
    observations: &mut Vec<ObservationEnvelope>,
) {
    while let Some(event) = provider.pending_events.pop_front() {
        push_provider_observation(key, provider, event, observations);
    }

    loop {
        let envelope = match provider.replay.pop_front() {
            Some(envelope) => Some(envelope),
            None => provider.receiver.try_recv().unwrap_or_default(),
        };
        let Some(envelope) = envelope else {
            break;
        };
        match envelope.event {
            PtyEvent::Output(data) => {
                let raw = provider.utf8.push(&data);
                if raw.is_empty() {
                    continue;
                }
                if provider.semantic_events {
                    if let Some(info) = provider.rate_limits.detect(&raw) {
                        push_provider_observation(
                            key,
                            provider,
                            rate_limit_event(info),
                            observations,
                        );
                    }
                }
                let identity = provider
                    .kimi_identity
                    .as_mut()
                    .and_then(|extractor| extractor.push(&raw));
                if let Some(identity) = identity {
                    if !provider.provider_session_started {
                        push_provider_observation(
                            key,
                            provider,
                            ProviderEvent::SessionStarted {
                                session_id: identity.id.clone(),
                                model: String::new(),
                                tools: Vec::new(),
                            },
                            observations,
                        );
                        provider.provider_session_started = true;
                    }
                    push_provider_observation(
                        key,
                        provider,
                        ProviderEvent::SessionIdentityObserved { identity },
                        observations,
                    );
                }
                if provider.semantic_events {
                    let messages = provider
                        .pipeline
                        .get_mut()
                        .unwrap_or_else(|poisoned| poisoned.into_inner())
                        .process(&raw);
                    for message in messages {
                        if let Some(event) = parsed_provider_event(message) {
                            push_provider_observation(key, provider, event, observations);
                        }
                    }
                }
            }
            PtyEvent::DataGap {
                from_sequence,
                to_sequence,
                ..
            } => {
                provider.utf8.clear();
                if let Some(extractor) = &mut provider.kimi_identity {
                    extractor.reset_stream();
                }
                provider
                    .pipeline
                    .get_mut()
                    .unwrap_or_else(|poisoned| poisoned.into_inner())
                    .clear();
                let missed = to_sequence
                    .checked_sub(from_sequence)
                    .and_then(|difference| difference.checked_add(1));
                if let Some((source_sequence, missed)) = missed.and_then(|missed| {
                    reserve_provider_gap_sequence(&mut provider.next_provider_sequence, missed)
                        .map(|source_sequence| (source_sequence, missed))
                }) {
                    observations.push(ObservationEnvelope {
                        operation_id: None,
                        instance_id: key.instance_id,
                        generation: key.generation,
                        observation: ControlObservation::ProviderGap {
                            source: provider.source.clone(),
                            source_sequence,
                            missed,
                        },
                    });
                }
            }
            PtyEvent::ReaderError { message } | PtyEvent::OperatorActionRequired { message } => {
                push_provider_observation(
                    key,
                    provider,
                    ProviderEvent::Error { message },
                    observations,
                );
            }
            PtyEvent::Started
            | PtyEvent::Resized(_)
            | PtyEvent::ForegroundProcess(_)
            | PtyEvent::SnapshotAvailable { .. }
            | PtyEvent::Exited { .. } => {}
        }
    }
}

fn push_provider_observation(
    key: NativeSessionKey,
    provider: &mut OwnedPtyProvider,
    event: ProviderEvent,
    observations: &mut Vec<ObservationEnvelope>,
) {
    let sequence = provider.next_provider_sequence;
    provider.next_provider_sequence = provider.next_provider_sequence.saturating_add(1);
    observations.push(ObservationEnvelope {
        operation_id: None,
        instance_id: key.instance_id,
        generation: key.generation,
        observation: ControlObservation::ProviderEvent {
            source: provider.source.clone(),
            sequence,
            event,
        },
    });
}

fn reserve_provider_gap_sequence(next_sequence: &mut u64, missed: u64) -> Option<u64> {
    if missed == 0 {
        return None;
    }
    let Some(source_sequence) = missed
        .checked_sub(1)
        .and_then(|offset| next_sequence.checked_add(offset))
    else {
        *next_sequence = u64::MAX;
        return None;
    };
    let Some(next) = source_sequence.checked_add(1) else {
        *next_sequence = u64::MAX;
        return None;
    };
    *next_sequence = next;
    Some(source_sequence)
}

fn parsed_provider_event(message: ParsedMessage) -> Option<ProviderEvent> {
    match message.class {
        MessageClass::AiResponse => Some(ProviderEvent::Text {
            text: message.content,
            is_delta: message.metadata.is_partial,
        }),
        MessageClass::ThinkingIndicator => Some(ProviderEvent::Thinking {
            text: message.content,
        }),
        MessageClass::Error => Some(ProviderEvent::Error {
            message: message.content,
        }),
        MessageClass::PromptReady => Some(ProviderEvent::Ready),
        MessageClass::ToolApproval => Some(ProviderEvent::InteractionRequested {
            request_id: None,
            interaction_kind: ProviderInteractionKind::Approval,
            tool_name: message
                .metadata
                .tool_name
                .unwrap_or_else(|| "unknown".to_owned()),
            // A PTY screen has no structured title or option list to read
            // off it the way ACP's `session/request_permission` does --
            // this source has none, not a dropped one.
            title: None,
            prompt: message.content,
            options: Vec::new(),
            agent_id: None,
        }),
        MessageClass::InfoMessage
        | MessageClass::UiElement
        | MessageClass::UserEcho
        | MessageClass::Menu
        | MessageClass::Raw => None,
    }
}

fn rate_limit_event(info: gate4agent::core::types::RateLimitInfo) -> ProviderEvent {
    ProviderEvent::RateLimited {
        limit_type: provider_rate_limit_kind(info.limit_type),
        resets_at: info.resets_at.map(|value| value.to_rfc3339()),
        usage_percent: info.usage_percent.map(|value| value.to_string()),
        raw_message: info.raw_message,
    }
}

/// Map `gate4agent`'s `HostRequestDecision`/`HostDecisionAuthority` onto
/// this crate's wire-typed `ProviderHostRequestDecision`/
/// `ProviderHostDecisionAuthority` -- `gate4agent-types` cannot depend on
/// `gate4agent` (see that crate's own `CLAUDE.md`), so the conversion lives
/// here, the shell that already depends on both. A plain match, not
/// `format!("{:?}", ..)`: the wire carries the typed value itself.
fn provider_host_request_decision(decision: HostRequestDecision) -> ProviderHostRequestDecision {
    match decision {
        HostRequestDecision::Granted { by } => {
            ProviderHostRequestDecision::Granted { by: provider_host_decision_authority(by) }
        }
        HostRequestDecision::Denied { by } => {
            ProviderHostRequestDecision::Denied { by: provider_host_decision_authority(by) }
        }
        HostRequestDecision::Deferred => ProviderHostRequestDecision::Deferred,
    }
}

fn provider_host_decision_authority(by: HostDecisionAuthority) -> ProviderHostDecisionAuthority {
    match by {
        HostDecisionAuthority::Gate => ProviderHostDecisionAuthority::Gate,
        HostDecisionAuthority::Policy => ProviderHostDecisionAuthority::Policy,
        HostDecisionAuthority::Operator => ProviderHostDecisionAuthority::Operator,
        HostDecisionAuthority::DeadlinePolicy => ProviderHostDecisionAuthority::DeadlinePolicy,
    }
}

/// Map `gate4agent`'s `HostRequestOutcome` onto this crate's wire-typed
/// `ProviderHostRequestOutcome` -- same reason `provider_host_request_
/// decision` exists rather than a `From` impl on either side. Carried
/// through verbatim, the same convention `reason` already follows on this
/// mapping: bounding happens at `ProviderEvent::validate_ingress`
/// (`PROVIDER_EVENT_TEXT_MAX_BYTES`, rejecting rather than truncating), not
/// here.
fn provider_host_request_outcome(outcome: HostRequestOutcome) -> ProviderHostRequestOutcome {
    match outcome {
        HostRequestOutcome::Executed => ProviderHostRequestOutcome::Executed,
        HostRequestOutcome::Failed { error } => ProviderHostRequestOutcome::Failed { error },
    }
}

/// Map the detector's own `RateLimitType` onto the wire-typed
/// `ProviderRateLimitKind`. A plain match, not `format!("{:?}", ..)`: the
/// wire carries the typed value itself, not a Debug-rendering of it.
fn provider_rate_limit_kind(
    limit_type: gate4agent::core::types::RateLimitType,
) -> ProviderRateLimitKind {
    use gate4agent::core::types::RateLimitType;
    match limit_type {
        RateLimitType::Session => ProviderRateLimitKind::Session,
        RateLimitType::Daily => ProviderRateLimitKind::Daily,
        RateLimitType::Weekly => ProviderRateLimitKind::Weekly,
        RateLimitType::Unknown => ProviderRateLimitKind::Unknown,
    }
}

/// `mode_catalogue` reads the mode catalogue off `owned.session` for
/// transports that have one -- only `AcpSession::available_modes()` does
/// (see `provider_event`'s doc comment); `collect_provider_map`'s two
/// non-ACP call sites pass `|_| Vec::new()` since their `AgentEvent` stream
/// never carries `ModeChanged` in the first place.
fn collect_provider_map<S>(
    sessions: &mut BTreeMap<NativeSessionKey, OwnedProviderSession<S>>,
    observations: &mut Vec<ObservationEnvelope>,
    mode_catalogue: impl Fn(&S) -> Vec<SessionMode>,
) {
    for (key, owned) in sessions {
        let available_modes = mode_catalogue(&owned.session);
        drain_provider_stream(
            *key,
            &owned.source,
            &mut owned.events,
            &mut owned.pending_events,
            &mut owned.pending_provider_events,
            &mut owned.next_provider_sequence,
            Some(&mut owned.observed_exit_code),
            observations,
            &available_modes,
        );
    }
}

/// Pushes one already-sequenced `ProviderEvent` onto `observations`, sharing
/// the same per-session `next_provider_sequence` counter regardless of which
/// of `drain_provider_stream`'s three sources (`pending_events` mapped
/// through `provider_event`, raw `pending_provider_events`, or the live
/// broadcast stream) produced it -- so sequence numbers stay contiguous
/// across all three.
fn push_sequenced_provider_event(
    key: NativeSessionKey,
    source: &ProviderSource,
    next_provider_sequence: &mut u64,
    observations: &mut Vec<ObservationEnvelope>,
    event: ProviderEvent,
) {
    let sequence = *next_provider_sequence;
    *next_provider_sequence = next_provider_sequence.saturating_add(1);
    observations.push(ObservationEnvelope {
        operation_id: None,
        instance_id: key.instance_id,
        generation: key.generation,
        observation: ControlObservation::ProviderEvent {
            source: source.clone(),
            sequence,
            event,
        },
    });
}

fn drain_provider_stream(
    key: NativeSessionKey,
    source: &ProviderSource,
    events: &mut broadcast::Receiver<AgentEvent>,
    pending_events: &mut VecDeque<AgentEvent>,
    pending_provider_events: &mut VecDeque<ProviderEvent>,
    next_provider_sequence: &mut u64,
    mut observed_exit_code: Option<&mut Option<i32>>,
    observations: &mut Vec<ObservationEnvelope>,
    available_modes: &[SessionMode],
) {
    loop {
        // `pending_events` (seeded `AgentEvent`s, e.g. `SessionStart`) drains
        // first and fully, in order; only once it is empty does
        // `pending_provider_events` (seeded raw `ProviderEvent`s, e.g.
        // `SessionIdentityObserved`, with no `AgentEvent` counterpart to
        // carry them) get a turn, and only once THAT is empty does this fall
        // through to the live broadcast stream -- so anything seeded at the
        // spawn site always reaches `observations` ahead of anything the
        // provider itself emits afterwards, and in the exact relative order
        // the spawn site seeded it in.
        if let Some(event) = pending_events.pop_front() {
            match event {
                AgentEvent::Exited { code } => {
                    if let Some(exit_code) = observed_exit_code.as_deref_mut() {
                        *exit_code = Some(code);
                    }
                }
                event => {
                    if let Some(event) = provider_event(event, available_modes) {
                        push_sequenced_provider_event(
                            key,
                            source,
                            next_provider_sequence,
                            observations,
                            event,
                        );
                    }
                }
            }
            continue;
        }
        if let Some(event) = pending_provider_events.pop_front() {
            push_sequenced_provider_event(key, source, next_provider_sequence, observations, event);
            continue;
        }
        match events.try_recv() {
            Ok(AgentEvent::Exited { code }) => {
                if let Some(exit_code) = observed_exit_code.as_deref_mut() {
                    *exit_code = Some(code);
                }
            }
            Ok(event) => {
                if let Some(event) = provider_event(event, available_modes) {
                    push_sequenced_provider_event(
                        key,
                        source,
                        next_provider_sequence,
                        observations,
                        event,
                    );
                }
            }
            Err(broadcast::error::TryRecvError::Lagged(missed)) => {
                if let Some(source_sequence) =
                    reserve_provider_gap_sequence(next_provider_sequence, missed)
                {
                    observations.push(ObservationEnvelope {
                        operation_id: None,
                        instance_id: key.instance_id,
                        generation: key.generation,
                        observation: ControlObservation::ProviderGap {
                            source: source.clone(),
                            source_sequence,
                            missed,
                        },
                    });
                }
            }
            Err(broadcast::error::TryRecvError::Empty | broadcast::error::TryRecvError::Closed) => {
                break
            }
        }
    }
}

fn collect_provider_exits<S>(
    sessions: &mut BTreeMap<NativeSessionKey, OwnedProviderSession<S>>,
    observations: &mut Vec<ObservationEnvelope>,
    finished: impl Fn(&S) -> bool,
) {
    let completed: Vec<_> = sessions
        .iter()
        .filter_map(|(key, owned)| {
            (owned.observed_exit_code.is_some() || finished(&owned.session)).then_some(*key)
        })
        .collect();
    for key in completed {
        let owned = sessions
            .remove(&key)
            .expect("completed provider key came from the owned session map");
        observations.push(ObservationEnvelope {
            operation_id: None,
            instance_id: key.instance_id,
            generation: key.generation,
            observation: ControlObservation::ProcessExited {
                exit_code: owned.observed_exit_code,
                final_terminal: None,
            },
        });
    }
}

/// Prefix tags [`encode_rpc_request_id`] / [`decode_rpc_request_id`] use to
/// keep an `RpcId::Number` and an `RpcId::String` from colliding once both
/// are flattened into the bare `Option<String>` that
/// `ProviderEvent::InteractionRequested::request_id` and
/// `ProviderInteractionTarget::provider_request_id` carry.
const RPC_REQUEST_ID_NUMBER_PREFIX: &str = "number:";
const RPC_REQUEST_ID_STRING_PREFIX: &str = "string:";

/// Encode a JSON-RPC id as the `request_id` string carried on
/// `ProviderEvent::InteractionRequested` -- minted once, in `provider_event`'s
/// `AgentEvent::RpcIncomingRequest` arm, the moment a `session/request_
/// permission` call is first reported `HostRequestDecision::Deferred`. Read
/// back by [`decode_rpc_request_id`] when a later `ResolveInteraction`
/// effect needs to find this exact pending request again in
/// `AcpSession::resolve_pending_request` (`gate4agent::acp::session`).
///
/// Tagged rather than a bare `to_string()`: an agent-issued
/// `RpcId::Number(42)` and `RpcId::String("42".into())` are different ids on
/// the wire and must not collide into the same encoded string.
fn encode_rpc_request_id(id: &RpcId) -> String {
    match id {
        RpcId::Number(number) => format!("{RPC_REQUEST_ID_NUMBER_PREFIX}{number}"),
        RpcId::String(value) => format!("{RPC_REQUEST_ID_STRING_PREFIX}{value}"),
    }
}

/// Inverse of [`encode_rpc_request_id`]. `None` covers both an unrecognized
/// tag and a `number:` tag whose remainder does not parse as a `u64` --
/// either way, not an id this process ever minted, so there is nothing to
/// look up in `AcpSession`'s pending-request map.
fn decode_rpc_request_id(raw: &str) -> Option<RpcId> {
    if let Some(number) = raw.strip_prefix(RPC_REQUEST_ID_NUMBER_PREFIX) {
        return number.parse::<u64>().ok().map(RpcId::Number);
    }
    raw.strip_prefix(RPC_REQUEST_ID_STRING_PREFIX)
        .map(|value| RpcId::String(value.to_owned()))
}

/// Resolve a `ControlEffect::ResolveInteraction` naming exactly why it
/// could not be routed, when it could not be -- see
/// `docs/gate4agent/plans/gate4agent-acp-control-plane-on-the-wire-2026-09-02.md`
/// §4a-§5, where this is called "the deferral organ, not the plumbing" that
/// was still missing.
///
/// `session` is `None` for every transport this crate owns other than a
/// live ACP session for `key` -- PTY and pipe sessions never defer a
/// `session/request_permission` call in the first place (only
/// `AcpSessionOptions::defer_permission_requests` does, and that field only
/// exists on `AcpSessionOptions`), so there is never anything for them to
/// resolve here.
fn resolve_acp_interaction_observation(
    session: Option<&AcpSession>,
    target: ProviderInteractionTarget,
    response: ProviderInteractionResponse,
) -> ControlObservation {
    let interaction_id = target.interaction_id;
    let fail = |message: String| ControlObservation::InteractionResolutionFailed {
        interaction_id,
        message,
    };
    let Some(session) = session else {
        return fail("semantic interaction resolution requires an ACP session".to_owned());
    };
    let Some(provider_request_id) = target.provider_request_id.as_deref() else {
        return fail("ACP interaction resolution requires a provider request id".to_owned());
    };
    let Some(id) = decode_rpc_request_id(provider_request_id) else {
        return fail(format!(
            "ACP interaction resolution request id {provider_request_id:?} is not a valid JSON-RPC id"
        ));
    };
    match resolve_acp_permission_interaction(session, &id, response) {
        Ok(()) => ControlObservation::InteractionResolutionCompleted { interaction_id },
        Err(message) => fail(message),
    }
}

/// Route an operator's `ProviderInteractionResponse` for a deferred ACP
/// `session/request_permission` call into
/// `AcpSession::resolve_pending_request_as` (`gate4agent::acp::session`).
///
/// The operator states an intent, not an option id, and that is deliberate:
/// an ACP agent offers whatever subset of the four `PermissionOptionKind`
/// values it likes, and an `optionId` it never offered is ignored rather
/// than refused -- so a fabricated one would grant nothing while reporting
/// success. Selecting a REAL offered option is therefore
/// `AcpSession`'s job, since it is the side that holds the pending request's
/// own params; it walks the same preference order `HostPolicy` walks,
/// through one shared selector, so an approval means the same thing whether
/// policy or a human produced it. If the agent offered nothing in the
/// requested direction the answer is `Cancelled`, which every ACP agent
/// accepts as complete.
///
/// This is also why the wire verb carries a `ProviderInteractionResponse` --
/// the same approve/deny vocabulary a PTY interaction uses -- rather than an
/// ACP-specific option id: all three chains say the same thing to an
/// operator, and only the ACP path has to know what an option id is.
///
/// `Answer` never applies here: ACP `session/request_permission` only ever
/// offers allow/deny options, never a free-text one.
fn resolve_acp_permission_interaction(
    session: &AcpSession,
    id: &RpcId,
    response: ProviderInteractionResponse,
) -> Result<(), String> {
    let choice = match response {
        ProviderInteractionResponse::ApproveOnce => OperatorPermissionChoice::Approve,
        ProviderInteractionResponse::Deny => OperatorPermissionChoice::Reject,
        ProviderInteractionResponse::Answer { .. } => {
            return Err("ACP permission interactions do not accept free-text answers".to_owned())
        }
    };
    session.resolve_pending_request_as(id, choice).map_err(|error| error.to_string())
}

/// Resolve a `ControlEffect::SetSessionMode` against a live ACP session's
/// own advertised mode catalogue, naming exactly why it could not be
/// routed when it could not be -- same refusal-by-name discipline as
/// [`resolve_acp_interaction_observation`].
///
/// There is no `supports_*` probe for session modes (unlike
/// `AcpSession::supports_session_list` and its siblings): the ACP
/// `sessionCapabilities` flags block carries no `modes` key at all, so the
/// mode catalogue seeded at handshake (`AcpSession::available_modes`) IS
/// the capability signal -- empty means the agent never advertised any
/// modes, non-empty-but-missing-this-id means it advertised modes but not
/// this one.
async fn set_acp_session_mode_observation(
    session: Option<&AcpSession>,
    mode_id: String,
) -> ControlObservation {
    let Some(session) = session else {
        return ControlObservation::SessionModeSetFailed {
            message: "session mode switch requires an ACP session".to_owned(),
        };
    };
    let catalogue = session.available_modes();
    if catalogue.is_empty() {
        return ControlObservation::SessionModeSetFailed {
            message: "the provider announces no session-mode capability".to_owned(),
        };
    }
    if !catalogue.iter().any(|mode| mode.id == mode_id) {
        return ControlObservation::SessionModeSetFailed {
            message: format!("the provider never offered mode {mode_id:?}"),
        };
    }
    match session.set_mode(&mode_id).await {
        Ok(()) => ControlObservation::SessionModeSet { mode_id },
        Err(error) => ControlObservation::SessionModeSetFailed {
            message: error.to_string(),
        },
    }
}

/// Resolve a `ControlEffect::SetSessionConfigOption` against a live ACP
/// session's own advertised config-option catalogue -- same capability
/// reasoning as [`set_acp_session_mode_observation`] (no dedicated
/// `supports_*` probe; the catalogue seeded at handshake, `AcpSession::
/// config_options`, is the capability signal).
///
/// `value_json` arrives already validated as parseable JSON at the wire
/// boundary (`gate4agent-node-protocol`'s `deserialize_acp_config_value_
/// json`) and bounds-checked again at the engine
/// (`gate4agent_types::validate_session_config_value_json`), but is only
/// ever carried as text up to here -- `gate4agent-types` does not depend on
/// `serde_json`. Parsing it into the `serde_json::Value` `AcpSession::
/// set_config_option` actually takes is this function's job; the target
/// type is inferred from that call rather than named directly, so this
/// crate never needs its own `serde_json` dependency.
async fn set_acp_session_config_option_observation(
    session: Option<&AcpSession>,
    option_id: String,
    value_json: String,
) -> ControlObservation {
    let Some(session) = session else {
        return ControlObservation::SessionConfigOptionSetFailed {
            message: "session config-option switch requires an ACP session".to_owned(),
        };
    };
    let catalogue = session.config_options();
    if catalogue.is_empty() {
        return ControlObservation::SessionConfigOptionSetFailed {
            message: "the provider announces no session config-option capability".to_owned(),
        };
    }
    if !catalogue.iter().any(|option| option.id == option_id) {
        return ControlObservation::SessionConfigOptionSetFailed {
            message: format!("the provider never offered config option {option_id:?}"),
        };
    }
    let value = match value_json.parse() {
        Ok(value) => value,
        Err(error) => {
            return ControlObservation::SessionConfigOptionSetFailed {
                message: format!("session config option value is not valid JSON: {error}"),
            }
        }
    };
    match session.set_config_option(&option_id, value).await {
        Ok(()) => ControlObservation::SessionConfigOptionSet { option_id },
        Err(error) => ControlObservation::SessionConfigOptionSetFailed {
            message: error.to_string(),
        },
    }
}

/// Resolve a `ControlEffect::SetSessionModel`. Unlike session modes and
/// config options, `AcpSession` exposes no setter at all for this --
/// `available_models`/`current_model_id` observe Grok's vendor `_x.ai/
/// models/update` catalogue, but no live capture has ever shown a
/// host-invocable RPC to request a switch (ACP proper has no `session/
/// set_model`, and no vendor extension for one has been verified). Refuses
/// by name rather than fabricate a call the crate documented it would
/// never invent -- see `ControlCommand::SetSessionModel`'s doc comment.
fn set_acp_session_model_observation(
    session: Option<&AcpSession>,
    model_id: String,
) -> ControlObservation {
    if session.is_none() {
        return ControlObservation::SessionModelSetFailed {
            message: "session model switch requires an ACP session".to_owned(),
        };
    }
    ControlObservation::SessionModelSetFailed {
        message: format!(
            "this provider offers no host-invocable model-switch method (requested model {model_id:?})"
        ),
    }
}

/// Maps one `AgentEvent` onto the wire-typed `ProviderEvent`. `available_
/// modes` is used ONLY by the `AgentEvent::ModeChanged` arm -- it carries
/// the mode catalogue `AcpSession::available_modes()` read at handshake
/// (`session/new`), so a mode change reports the SAME catalogue the agent
/// actually offered, not just the id that changed. Every other arm ignores
/// it; passing `&[]` from a non-ACP transport (which never emits
/// `ModeChanged` in the first place -- see `update_to_event`'s
/// `CurrentModeUpdate` arm, `gate4agent`'s `src/acp/protocol.rs`) changes
/// nothing observable.
/// Maps `gate4agent`'s own `StopReason` onto the wire-typed
/// `ProviderStopReason` mirror -- see that type's own doc comment for why
/// this crate keeps a second copy rather than sharing one.
fn map_provider_stop_reason(reason: StopReason) -> ProviderStopReason {
    match reason {
        StopReason::EndTurn => ProviderStopReason::EndTurn,
        StopReason::MaxTokens => ProviderStopReason::MaxTokens,
        StopReason::MaxTurnRequests => ProviderStopReason::MaxTurnRequests,
        StopReason::Refusal => ProviderStopReason::Refusal,
        StopReason::Cancelled => ProviderStopReason::Cancelled,
        StopReason::Other(value) => ProviderStopReason::Other { value },
        StopReason::ProviderError { code, message, vendor_code } => {
            ProviderStopReason::ProviderError { code, message, vendor_code }
        }
    }
}

fn provider_event(event: AgentEvent, available_modes: &[SessionMode]) -> Option<ProviderEvent> {
    match event {
        AgentEvent::SessionStart {
            session_id,
            model,
            tools,
        } => Some(ProviderEvent::SessionStarted {
            session_id,
            model,
            tools,
        }),
        AgentEvent::Text { text, is_delta } => Some(ProviderEvent::Text { text, is_delta }),
        AgentEvent::Thinking { text } => Some(ProviderEvent::Thinking { text }),
        AgentEvent::ToolStart { id, name, input } => Some(ProviderEvent::ToolStarted {
            id,
            name,
            input_json: input.to_string(),
            agent_id: None,
        }),
        AgentEvent::ToolResult {
            id,
            output,
            is_error,
            duration_ms,
            non_execution_kind,
        } => Some(ProviderEvent::ToolCompleted {
            id,
            output,
            is_error,
            duration_ms,
            agent_id: None,
            non_execution_kind,
        }),
        AgentEvent::TurnComplete {
            input_tokens,
            output_tokens,
            cache_read_tokens,
            cache_write_tokens,
            reasoning_tokens,
            context_window,
            is_cumulative,
        } => Some(ProviderEvent::TurnCompleted {
            usage: TokenUsage {
                input_tokens,
                output_tokens,
                cache_read_tokens,
                cache_write_tokens,
                reasoning_tokens,
                context_window,
            },
            is_cumulative,
        }),
        AgentEvent::ContextWindowUsage { usage } => {
            Some(ProviderEvent::ContextWindowUsage {
                usage: ProviderContextWindowUsage {
                    uncached_input_tokens: usage.uncached_input_tokens,
                    cache_read_tokens: usage.cache_read_tokens,
                    cache_write_tokens: usage.cache_write_tokens,
                    output_tokens: usage.output_tokens,
                    unattributed_tokens: usage.unattributed_tokens,
                    used_tokens: usage.used_tokens,
                    capacity_tokens: usage.capacity_tokens,
                },
            })
        }
        AgentEvent::SessionEnd {
            result,
            cost_usd,
            is_error,
            stop_reason,
        } => Some(ProviderEvent::SessionEnded {
            result,
            cost_usd: cost_usd.map(|cost| cost.to_string()),
            is_error,
            stop_reason: stop_reason.map(map_provider_stop_reason),
        }),
        AgentEvent::Error { message } => Some(ProviderEvent::Error { message }),
        // ACP-only: `acp::session::AcpSession::start_prompt` synthesizes
        // this locally when a `session/prompt` call ends without a success
        // response (an agent RPC error, the session closing mid-call, or
        // `prompt_timeout` elapsing) -- see that event's own doc comment.
        // `ProviderEvent::TurnInterrupted` carries no `reason` field (it
        // predates this source and is also used by a PTY-side interrupt
        // with no text of its own to attach), so the reason is logged here
        // rather than silently dropped -- this is the one place downstream
        // of the ACP session that ever sees it.
        AgentEvent::TurnInterrupted { reason } => {
            tracing::warn!(reason = %reason, "acp turn interrupted");
            Some(ProviderEvent::TurnInterrupted)
        }
        AgentEvent::PtyParsed(message) => parsed_provider_event(message),
        AgentEvent::PtyReady => Some(ProviderEvent::Ready),
        AgentEvent::PtyToolApproval {
            tool_name,
            description,
        } => Some(ProviderEvent::InteractionRequested {
            request_id: None,
            interaction_kind: ProviderInteractionKind::Approval,
            tool_name,
            // A PTY screen has no structured title or option list to read
            // off it the way ACP's `session/request_permission` does --
            // this source has none, not a dropped one.
            title: None,
            prompt: description.unwrap_or_default(),
            options: Vec::new(),
            agent_id: None,
        }),
        AgentEvent::RateLimit(info) => Some(rate_limit_event(info)),
        // A `session/request_permission` call the host left `Deferred` (see
        // `AcpSessionOptions::defer_permission_requests`) is the one host
        // request an operator can actually act on -- so, ONLY for that
        // first, deferred sighting of a given id, this becomes an
        // `InteractionRequested` carrying the id (`encode_rpc_request_id`)
        // instead of the audit-only `HostRequestObserved` every other host
        // request becomes. The SAME id's eventual `Granted`/`Denied`
        // (`HostRequestDecision`'s doc comment on `Deferred`) still falls
        // through to `HostRequestObserved` below, exactly as before -- see
        // `docs/gate4agent/plans/gate4agent-acp-control-plane-on-the-wire-2026-09-02.md`
        // §4a.2, which is what this replaces (`id: _`, the id silently
        // dropped, so an ACP permission request never became an
        // `InteractionRequested` at all).
        AgentEvent::RpcIncomingRequest {
            id,
            method,
            params,
            decision,
            // A `Deferred` sighting never carries a reason -- nothing has
            // decided this request yet (see `AgentEvent::
            // RpcIncomingRequest`'s own doc comment).
            reason: _,
            // Nothing has run yet either -- always `Executed` for a
            // `Deferred` sighting (see `HostRequestOutcome`'s own doc
            // comment).
            outcome: _,
        } if method == "session/request_permission"
            && matches!(decision, HostRequestDecision::Deferred) =>
        {
            let tool_call = params.as_ref().and_then(|params| params.get("toolCall"));
            let field = |name: &str| {
                tool_call
                    .and_then(|tool_call| tool_call.get(name))
                    .and_then(|value| value.as_str())
                    .filter(|value| !value.is_empty())
                    .map(str::to_owned)
            };
            // `kind` is the tool's CLASS (`execute`, `edit`, `read`, ...) and
            // `title` is the human sentence describing this particular call.
            // They are two different things and the operator needs both: the
            // class is what the node hashes into `tool_class` for the
            // observation, and the title is the actual question. Putting the
            // title in `tool_name` and leaving `prompt` empty -- which is
            // what this did -- showed the operator a correlation id and a
            // sentence-shaped tool name, and never the question itself.
            let title = field("title");
            // The agent's own offered options -- read straight off the top-
            // level `options` array `PermissionRequestParams::options`
            // names in `src/acp/protocol.rs` (`option_id`/`name`/`kind`,
            // each `PermissionOption` field's own verified wire name:
            // `optionId`/`name`/`kind`), not `toolCall` -- `options` is a
            // sibling of `toolCall` on the request, not nested under it.
            // `kind` is carried verbatim as the ACP wire's own snake_case
            // string (`allow_once`, `reject_always`, ...); nothing here
            // reinterprets it. Without this the operator is choosing
            // approve/deny from a list they cannot see -- survivable for
            // two options, a guess for three or more.
            let options: Vec<ProviderInteractionOption> = params
                .as_ref()
                .and_then(|params| params.get("options"))
                .and_then(|options| options.as_array())
                .map(|options| {
                    options
                        .iter()
                        .filter_map(|option| {
                            let option_id = option.get("optionId")?.as_str()?.to_owned();
                            let name = option.get("name")?.as_str()?.to_owned();
                            let kind = option.get("kind")?.as_str()?.to_owned();
                            Some(ProviderInteractionOption { option_id, name, kind })
                        })
                        .collect()
                })
                .unwrap_or_default();
            Some(ProviderEvent::InteractionRequested {
                request_id: Some(encode_rpc_request_id(&id)),
                interaction_kind: ProviderInteractionKind::Approval,
                tool_name: field("kind").unwrap_or(method),
                title,
                prompt: field("title").unwrap_or_default(),
                options,
                agent_id: None,
            })
        }
        AgentEvent::RpcIncomingRequest {
            id: _,
            method,
            params,
            decision,
            // `outcome` distinguishes a `Granted` request that ran cleanly
            // from one that was authorized and then failed WHILE EXECUTING
            // (`HostRequestOutcome::Failed` -- e.g. a `terminal/create`
            // spawn error; see that type's own doc comment). Carried
            // through, never dropped: an execution failure must reach the
            // operator as `Granted` + `Failed { error }`, not an
            // undifferentiated `Granted` that silently swallows the
            // failure text.
            outcome,
            reason,
        } => Some(ProviderEvent::HostRequestObserved {
            method,
            params_json: params.map(|value| value.to_string()).unwrap_or_default(),
            decision: provider_host_request_decision(decision),
            outcome: provider_host_request_outcome(outcome),
            reason,
        }),
        AgentEvent::RpcNotification { method, params } => {
            Some(ProviderEvent::UnrecognizedNotification {
                method,
                payload_json: params.to_string(),
            })
        }
        AgentEvent::Started { .. } | AgentEvent::Exited { .. } | AgentEvent::PtyRaw { .. } => None,
        AgentEvent::UserMessage { text, is_delta } => {
            Some(ProviderEvent::UserMessage { text, is_delta })
        }
        AgentEvent::Plan { steps } => Some(ProviderEvent::Plan {
            steps: steps.into_iter().map(provider_plan_step).collect(),
        }),
        AgentEvent::AvailableCommandsUpdate { commands } => {
            Some(ProviderEvent::AvailableCommandsUpdated {
                commands: commands
                    .into_iter()
                    .map(|command| ProviderAvailableCommand {
                        name: command.name,
                        description: command.description,
                        input_hint: command.input_hint,
                    })
                    .collect(),
            })
        }
        AgentEvent::ModeChanged { mode_id } => Some(ProviderEvent::ModeChanged {
            mode_id,
            available: available_modes.iter().cloned().map(provider_mode_info).collect(),
        }),
        AgentEvent::SessionInfoUpdate { title } => {
            Some(ProviderEvent::SessionInfoUpdated { title })
        }
        AgentEvent::UsageUpdate {
            used_tokens,
            context_window,
            cost_amount,
            cost_currency,
        } => Some(ProviderEvent::UsageUpdated {
            used_tokens,
            context_window,
            cost_amount: cost_amount.map(|amount| amount.to_string()),
            cost_currency,
        }),
        AgentEvent::ConfigOptionsUpdate { options } => Some(ProviderEvent::ConfigOptionsUpdated {
            options: options.into_iter().map(provider_config_option).collect(),
        }),
        // Grok vendor `_x.ai/*` extensions (see `gate4agent::acp::protocol::
        // parse_vendor_notification`) -- not yet bridged to `ProviderEvent`.
        // No `ProviderEvent` variant exists for any of these today; adding
        // one is a separate, larger change across this crate's validation
        // (`ProviderEventValidationError`), the observation pipeline, and
        // the TUI, not part of parsing the ACP wire itself.
        AgentEvent::ModelsUpdate { .. }
        | AgentEvent::ProviderModelChanged { .. }
        | AgentEvent::SettingsUpdate { .. }
        | AgentEvent::HookExecutionUpdate { .. }
        | AgentEvent::McpServersUpdate { .. }
        | AgentEvent::McpInitProgress { .. }
        | AgentEvent::McpInitialized { .. }
        | AgentEvent::AnnouncementsUpdate { .. } => None,
    }
}

/// Map the ACP wire priority onto the typed `ProviderPlanPriority`. A
/// plain match, not `format!("{:?}", ..)` -- see `provider_rate_limit_kind`
/// for why: the wire carries the typed value itself.
fn provider_plan_priority(priority: gate4agent::core::types::PlanStepPriority) -> ProviderPlanPriority {
    use gate4agent::core::types::PlanStepPriority;
    match priority {
        PlanStepPriority::High => ProviderPlanPriority::High,
        PlanStepPriority::Medium => ProviderPlanPriority::Medium,
        PlanStepPriority::Low => ProviderPlanPriority::Low,
    }
}

/// Map the ACP wire status onto the typed `ProviderPlanStatus`.
fn provider_plan_status(status: gate4agent::core::types::PlanStepStatus) -> ProviderPlanStatus {
    use gate4agent::core::types::PlanStepStatus;
    match status {
        PlanStepStatus::Pending => ProviderPlanStatus::Pending,
        PlanStepStatus::InProgress => ProviderPlanStatus::InProgress,
        PlanStepStatus::Completed => ProviderPlanStatus::Completed,
    }
}

fn provider_plan_step(step: gate4agent::core::types::PlanStep) -> ProviderPlanStep {
    ProviderPlanStep {
        content: step.content,
        priority: provider_plan_priority(step.priority),
        status: provider_plan_status(step.status),
    }
}

/// Maps one ACP `SessionMode` (`gate4agent::acp::protocol::SessionMode`,
/// `session/new`'s `modes.availableModes`) onto the wire-typed
/// `ProviderModeInfo` carried on `ProviderEvent::ModeChanged::available`.
fn provider_mode_info(mode: SessionMode) -> ProviderModeInfo {
    ProviderModeInfo {
        id: mode.id,
        name: mode.name,
        description: mode.description,
    }
}

/// Map the ACP wire config-option kind onto the typed
/// `ProviderConfigOptionKind`.
fn provider_config_option_kind(
    kind: gate4agent::core::types::ConfigOptionKind,
) -> ProviderConfigOptionKind {
    use gate4agent::core::types::ConfigOptionKind;
    match kind {
        ConfigOptionKind::Select => ProviderConfigOptionKind::Select,
        ConfigOptionKind::Boolean => ProviderConfigOptionKind::Boolean,
        ConfigOptionKind::Unknown => ProviderConfigOptionKind::Unknown,
    }
}

/// `gate4agent-types` is a pure data contract and does not depend on
/// `serde_json`, so the option's current value and each choice's value --
/// both `serde_json::Value` in `gate4agent::core::types::ConfigOptionInfo`
/// -- cross the boundary pre-serialized to JSON text, same convention as
/// `ToolStarted::input_json` above.
fn provider_config_option(option: gate4agent::core::types::ConfigOptionInfo) -> ProviderConfigOption {
    ProviderConfigOption {
        id: option.id,
        name: option.name,
        description: option.description,
        category: option.category,
        kind: provider_config_option_kind(option.kind),
        value_json: option.value.to_string(),
        choices: option
            .choices
            .into_iter()
            .map(|choice| ProviderConfigChoice {
                value_json: choice.value.to_string(),
                label: choice.label,
            })
            .collect(),
    }
}

fn builtin_legacy_adapter_runtimes() -> AdapterRuntimeRegistry<CliTool> {
    // Each of the four fleet providers registers only the transport families
    // it actually declares in the built-in adapter registry -- Grok, for
    // instance, is ACP-only and has no `PtySemantic`/`Pipe` descriptor.
    // Absence of a family for a given provider is not an error; only a
    // duplicate registration is.
    let definitions = [
        ("claude-code", CliTool::ClaudeCode),
        ("codex", CliTool::Codex),
        ("kimi", CliTool::KimiCode),
        ("grok", CliTool::Grok),
    ];
    let mut runtimes = AdapterRuntimeRegistry::default();
    for (id, tool) in definitions {
        for family in [
            AdapterFamily::PtySemantic,
            AdapterFamily::Pipe,
            AdapterFamily::Acp,
        ] {
            let Some(binding) = builtin_adapter_registry().binding(family, id) else {
                continue;
            };
            runtimes
                .insert(family, binding.clone(), tool)
                .expect("built-in native adapter runtime must be unique");
        }
    }

    runtimes
}

fn terminal_frame(snapshot: PtyTerminalSnapshot, screen_state: PtyScreenState) -> TerminalFrame {
    TerminalFrame {
        sequence: snapshot.sequence,
        size: TerminalSize {
            rows: snapshot.size.rows,
            columns: snapshot.size.cols,
        },
        cursor_row: snapshot.cursor.0,
        cursor_column: snapshot.cursor.1,
        contents: snapshot.contents,
        formatted: snapshot.formatted,
        scrollback_formatted: snapshot.scrollback_formatted,
        alternate_screen: snapshot.alternate_screen,
        mouse_protocol_enabled: snapshot.mouse_protocol_enabled,
        mouse_protocol_encoding: match snapshot.mouse_protocol_encoding {
            PtyMouseProtocolEncoding::Default => TerminalMouseProtocolEncoding::Default,
            PtyMouseProtocolEncoding::Utf8 => TerminalMouseProtocolEncoding::Utf8,
            PtyMouseProtocolEncoding::Sgr => TerminalMouseProtocolEncoding::Sgr,
        },
        // Carried through unchanged from the PTY snapshot -- this crate does
        // not restamp it, see `TerminalFrame::produced_at_unix_ms`'s own doc.
        produced_at_unix_ms: snapshot.produced_at_unix_ms,
        screen_state,
        // Known at capture time: `PtyTerminalSnapshot::bracketed_paste` is
        // read off the same `vt100::Screen` as `contents`/`formatted`, so
        // `Some` here always means "sampled", never "unknown" -- see
        // `TerminalFrame::bracketed_paste`'s own doc for what `None` means.
        bracketed_paste: Some(snapshot.bracketed_paste),
    }
}

/// Whether the cheap `terminal_sequence()` gate should skip the expensive
/// `terminal_state()` call outright -- true exactly when the sequence read
/// is no newer than what this session already captured. An `Err` from the
/// cheap read does NOT skip: it falls through so the real call is attempted
/// (and reports its own failure through the normal `terminal_state()`
/// error path), matching the pre-instrumentation behaviour of the
/// `matches!` this replaces.
fn terminal_state_capture_should_skip<E>(sequence: Result<u64, E>, last_captured: u64) -> bool {
    matches!(sequence, Ok(sequence) if sequence <= last_captured)
}

/// Total wire-relevant byte size of one [`TerminalFrame`] -- `formatted`
/// plus every row of `scrollback_formatted` summed. This is exactly what
/// gets handed to the c2 relay/harness/operator wire per frame (`contents`
/// never leaves the node), which is why it is the number the frame-bytes
/// distribution reports.
fn terminal_frame_byte_len(frame: &TerminalFrame) -> u64 {
    let scrollback_bytes: usize = frame.scrollback_formatted.iter().map(Vec::len).sum();
    (frame.formatted.len() + scrollback_bytes) as u64
}

fn canonical_foreground(
    agent_id: AgentId,
    observation: &PtyForegroundObservation,
) -> ForegroundProcess {
    let kind = if observation.readiness.process_name.as_deref() == Some(agent_id.as_str()) {
        ForegroundProcessKind::Agent { agent_id }
    } else if observation.readiness.is_shell {
        ForegroundProcessKind::Shell
    } else {
        ForegroundProcessKind::Other
    };
    ForegroundProcess {
        root_process_id: observation.root_pid,
        process_id: observation.observed_pid,
        process_name: observation.observed_process.clone(),
        kind,
    }
}

fn completion_observation(
    operation_id: OperationId,
    instance_id: AgentInstanceId,
    generation: SessionGeneration,
    observation: ControlObservation,
) -> ObservationEnvelope {
    ObservationEnvelope {
        operation_id: Some(operation_id),
        instance_id,
        generation,
        observation,
    }
}

async fn wait_for_readiness(
    session: &PtySession,
    spec: &AgentSpec,
    intent: ReadinessIntent,
    detect_startup_gates: bool,
) -> Result<ReadinessPermit, String> {
    let started = Instant::now();
    let (terminal, attachment) = attach_readiness_boundary(session)?;
    let mut receiver = attachment.receiver;
    let mut tracker = ReadinessTracker::new(spec, RuntimePlatform::current(), intent);
    let mut diagnostics = ReadinessDiagnostics {
        draft_signal: Some(spec.readiness.draft_signal),
        ..ReadinessDiagnostics::default()
    };
    seed_readiness_from_terminal(
        &terminal,
        &mut tracker,
        &mut diagnostics,
        elapsed_ms(started),
    )?;
    let interval = Duration::from_millis(spec.readiness.poll_interval_ms.max(1));
    let mut next_probe = Instant::now();

    for event in attachment.replay {
        observe_readiness_event(
            &mut tracker,
            &mut diagnostics,
            event.event,
            elapsed_ms(started),
        )?;
        if detect_startup_gates {
            ensure_no_readiness_operator_gate(&diagnostics, spec)?;
            ensure_no_startup_operator_gate(session, spec)?;
        }
    }

    loop {
        if detect_startup_gates {
            ensure_no_startup_operator_gate(session, spec)?;
        }
        if Instant::now() >= next_probe {
            let foreground = session
                .observe_foreground()
                .await
                .map_err(|error| error.to_string())?;
            diagnostics.observe_foreground(&foreground.readiness);
            tracker.observe_foreground(&foreground.readiness, elapsed_ms(started));
            next_probe = Instant::now() + interval;
        }
        tracker.poll(elapsed_ms(started));
        if readiness_complete(tracker.status(), &diagnostics)? {
            if detect_startup_gates {
                ensure_no_startup_operator_gate(session, spec)?;
            }
            return tracker
                .into_permit()
                .ok_or_else(|| "ready tracker did not issue a permit".to_owned());
        }

        let wait = next_probe.saturating_duration_since(Instant::now());
        match tokio::time::timeout(wait, receiver.recv()).await {
            Ok(Ok(event)) => {
                if matches!(&event.event, PtyEvent::DataGap { .. }) {
                    let (terminal, attachment) = attach_readiness_boundary(session)?;
                    receiver = attachment.receiver;
                    tracker = ReadinessTracker::new(
                        spec,
                        RuntimePlatform::current(),
                        intent,
                    );
                    diagnostics = ReadinessDiagnostics {
                        draft_signal: Some(spec.readiness.draft_signal),
                        ..ReadinessDiagnostics::default()
                    };
                    seed_readiness_from_terminal(
                        &terminal,
                        &mut tracker,
                        &mut diagnostics,
                        elapsed_ms(started),
                    )?;
                    for retained in attachment.replay {
                        observe_readiness_event(
                            &mut tracker,
                            &mut diagnostics,
                            retained.event,
                            elapsed_ms(started),
                        )?;
                    }
                } else {
                    observe_readiness_event(
                        &mut tracker,
                        &mut diagnostics,
                        event.event,
                        elapsed_ms(started),
                    )?;
                }
                if detect_startup_gates {
                    ensure_no_readiness_operator_gate(&diagnostics, spec)?;
                    ensure_no_startup_operator_gate(session, spec)?;
                }
            }
            Ok(Err(error)) => return Err(error.to_string()),
            Err(_) => {
                tracker.poll(elapsed_ms(started));
            }
        }
        if readiness_complete(tracker.status(), &diagnostics)? {
            if detect_startup_gates {
                ensure_no_startup_operator_gate(session, spec)?;
            }
            return tracker
                .into_permit()
                .ok_or_else(|| "ready tracker did not issue a permit".to_owned());
        }
    }
}

fn attach_readiness_boundary(
    session: &PtySession,
) -> Result<(PtyTerminalSnapshot, PtyAttachment), String> {
    let terminal = session.terminal_state().map_err(|error| error.to_string())?;
    let cursor = PtyReplayCursor {
        provider_revision: terminal.provider_revision.clone(),
        generation: terminal.generation,
        next_sequence: terminal.sequence.saturating_add(1).max(1),
    };
    let attachment = session
        .attach_events(cursor)
        .map_err(|error| error.to_string())?;
    Ok((terminal, attachment))
}

fn seed_readiness_from_terminal(
    terminal: &PtyTerminalSnapshot,
    tracker: &mut ReadinessTracker<'_>,
    diagnostics: &mut ReadinessDiagnostics,
    elapsed_ms: u64,
) -> Result<(), String> {
    const ENABLE_BRACKETED_PASTE: &[u8] = b"\x1b[?2004h";
    if terminal.bracketed_paste {
        diagnostics.observe_output(ENABLE_BRACKETED_PASTE);
        tracker.observe_output(ENABLE_BRACKETED_PASTE, elapsed_ms);
    }
    if !terminal.formatted.is_empty() {
        diagnostics.observe_output(&terminal.formatted);
        tracker.observe_output(&terminal.formatted, elapsed_ms);
    }
    Ok(())
}

const STARTUP_GATE_SETTLE_MS: u64 = 350;
const STARTUP_GATE_POLL_MS: u64 = 25;
/// Steady-state cadence for `NativeEffectShell::reclassify_foreground`.
///
/// `wait_for_readiness` already polls the foreground far tighter than this
/// during startup (`spec.readiness.poll_interval_ms`, 150ms by default),
/// because a session takes at most a few seconds to come up and getting
/// that window right matters. This constant is not that -- it governs the
/// STEADY STATE: a session that has been sitting non-`Ready` for a long
/// time, which is exactly the incident this module fixes (an update
/// screen with nobody watching it). A session that reaches `Ready` stops
/// being probed at all (see `foreground_probe_schedule`), so the cost of
/// this interval is bounded by the count of sessions that are NOT
/// `Ready`, never by output rate and never by total session count. One
/// process-tree walk a second for a handful of stuck sessions is ample.
const FOREGROUND_RECLASSIFY_INTERVAL: Duration = Duration::from_secs(1);
// Codex rust-v0.144.0 keeps Enter in newline mode for 120 ms after
// Windows paste-burst activity. Wait beyond that window only after the TUI
// visibly incorporates the deferred initial prompt.
const CODEX_PASTE_ENTER_SUPPRESSION_MS: u64 = 120;
const CODEX_POST_RENDER_MARGIN_MS: u64 = 30;
const CODEX_SESSION_STATUS_PROBE_TIMEOUT_MS: u64 = 5_000;
const KIMI_SESSION_STATUS_PROBE_TIMEOUT_MS: u64 = 5_000;

async fn probe_fresh_codex_session_identity(
    session: &PtySession,
    spec: &AgentSpec,
) -> Result<Option<ProviderSessionIdentity>, String> {
    let permit = match wait_for_readiness(session, spec, ReadinessIntent::DraftPaste, true).await {
        Ok(permit) => permit,
        Err(_) => return Ok(None),
    };
    if wait_for_startup_operator_gate(session, spec).await.is_err() {
        return Ok(None);
    }
    let baseline = session
        .terminal_state()
        .map_err(|error| error.to_string())?;
    let mut extractor = CodexPtySessionIdentityExtractor::default();
    session
        .send_input_action(
            InputAction::AgentCommand(AgentCommand {
                agent_id: spec.id.clone(),
                name: "status".to_owned(),
                arguments: Vec::new(),
            }),
            permit,
        )
        .await
        .map_err(|error| format!("Codex /status identity probe failed: {error}"))?;

    let deadline = Instant::now()
        + Duration::from_millis(
            spec.readiness
                .timeout_ms
                .min(CODEX_SESSION_STATUS_PROBE_TIMEOUT_MS)
                .max(1),
        );
    loop {
        let snapshot = session
            .terminal_state()
            .map_err(|error| error.to_string())?;
        if snapshot.sequence > baseline.sequence {
            if let Some(identity) = extractor.observe_screen(&snapshot.contents) {
                return Ok(Some(identity));
            }
        }
        if Instant::now() >= deadline {
            return Ok(None);
        }
        tokio::time::sleep(Duration::from_millis(STARTUP_GATE_POLL_MS)).await;
    }
}

async fn probe_fresh_kimi_session_identity(
    session: &PtySession,
    spec: &AgentSpec,
) -> Result<Option<ProviderSessionIdentity>, String> {
    let permit = match wait_for_readiness(
        session,
        spec,
        ReadinessIntent::FollowupPrompt,
        true,
    )
    .await
    {
        Ok(permit) => permit,
        Err(_) => return Ok(None),
    };
    if wait_for_startup_operator_gate(session, spec).await.is_err() {
        return Ok(None);
    }
    let baseline = session
        .terminal_state()
        .map_err(|error| error.to_string())?;
    let mut extractor = KimiPtySessionIdentityExtractor::default();
    if let Some(identity) = extractor.observe_screen(&baseline.contents) {
        return Ok(Some(identity));
    }
    session
        .send_input_action(
            InputAction::SubmitPrompt(PromptPayload {
                text: "/status".to_owned(),
                framing: PromptFraming::BracketedPaste,
            }),
            permit,
        )
        .await
        .map_err(|error| format!("Kimi /status identity probe failed: {error}"))?;

    let deadline = Instant::now()
        + Duration::from_millis(
            spec.readiness
                .timeout_ms
                .min(KIMI_SESSION_STATUS_PROBE_TIMEOUT_MS)
                .max(1),
        );
    loop {
        let snapshot = session
            .terminal_state()
            .map_err(|error| error.to_string())?;
        if snapshot.sequence > baseline.sequence {
            if let Some(identity) = extractor.observe_screen(&snapshot.contents) {
                return Ok(Some(identity));
            }
        }
        if Instant::now() >= deadline {
            return Ok(None);
        }
        tokio::time::sleep(Duration::from_millis(STARTUP_GATE_POLL_MS)).await;
    }
}

async fn deliver_pending_initial_prompt(
    session: &mut PtySession,
    spec: &AgentSpec,
) -> Result<(), String> {
    if session.pending_followup_prompt().is_none() {
        return Ok(());
    }
    let mut permit =
        wait_for_readiness(session, spec, ReadinessIntent::FollowupPrompt, true).await?;
    wait_for_startup_operator_gate(session, spec).await?;
    let render_confirmed_submit = spec.id.as_str() == "claude"
        || (RuntimePlatform::current() == RuntimePlatform::Windows
            && spec.id.as_str() == "codex");
    if render_confirmed_submit {
        let prompt = session
            .pending_followup_prompt()
            .ok_or_else(|| "deferred initial prompt disappeared before paste".to_owned())?
            .to_owned();
        let baseline = session
            .terminal_state()
            .map_err(|error| error.to_string())?;
        let inserted = session
            .insert_pending_followup_prompt(PromptFraming::BracketedPaste, &permit)
            .await
            .map_err(|error| error.to_string())?;
        if !inserted {
            return Err("deferred initial prompt was not inserted".to_owned());
        }
        wait_for_prompt_render(
            session,
            spec,
            &prompt,
            &baseline,
            spec.readiness.timeout_ms,
        )
        .await?;
        if RuntimePlatform::current() == RuntimePlatform::Windows && spec.id.as_str() == "codex" {
            tokio::time::sleep(Duration::from_millis(
                CODEX_PASTE_ENTER_SUPPRESSION_MS + CODEX_POST_RENDER_MARGIN_MS,
            ))
            .await;
        }
        permit = wait_for_readiness(session, spec, ReadinessIntent::FollowupPrompt, true).await?;
        wait_for_startup_operator_gate(session, spec).await?;
    }
    ensure_no_startup_operator_gate(session, spec)?;
    let submitted = session
        .submit_pending_followup(PromptFraming::BracketedPaste, permit)
        .await
        .map_err(|error| error.to_string())?;
    if !submitted {
        return Err("deferred initial prompt disappeared before delivery".to_owned());
    }
    Ok(())
}

async fn wait_for_prompt_render(
    session: &PtySession,
    spec: &AgentSpec,
    prompt: &str,
    baseline: &PtyTerminalSnapshot,
    timeout_ms: u64,
) -> Result<(), String> {
    let probe = prompt_render_probe(&gate4agent_types::sanitize_prompt_text(prompt));
    let deadline = Instant::now() + Duration::from_millis(timeout_ms.max(1));
    loop {
        let snapshot = session.terminal_state().map_err(|error| error.to_string())?;
        if let Some(gate) = startup_operator_gate(&snapshot.contents) {
            return Err(startup_operator_error(spec, &gate));
        }
        if prompt_rendered(&snapshot, baseline, &probe) {
            return Ok(());
        }
        if Instant::now() >= deadline {
            let tail = terminal_tail(&snapshot.contents);
            let compact_tail = compact_alphanumeric(&tail);
            let baseline_tail = terminal_tail(&baseline.contents).to_ascii_lowercase();
            let normalized_tail = tail.to_ascii_lowercase();
            let retained = render_ack_event_summary(session, baseline.sequence);
            let foreground = session.observe_foreground().await.ok();
            let foreground_name = foreground
                .as_ref()
                .and_then(|observation| observation.readiness.process_name.as_deref())
                .map(safe_process_label)
                .unwrap_or_else(|| "none".to_owned());
            let child_live = retained.exit_code.is_none() && foreground.is_some();
            return Err(format!(
                "agent '{}' initial prompt paste was not rendered before submit; Enter was not sent (baseline_sequence={} current_sequence={} sequence_delta={} cursor_changed={} bracketed_baseline={} bracketed_current={} tail_chars={} probe_chars={} probe_match={} placeholder_baseline={} placeholder_current={} child_live={} foreground={} retained_output={} retained_foreground={} retained_snapshots={} retained_resized={} retained_gaps={} retained_reader_errors={} retained_operator_actions={} retained_exit_code={} output_flags={})",
                spec.id,
                baseline.sequence,
                snapshot.sequence,
                snapshot.sequence.saturating_sub(baseline.sequence),
                snapshot.cursor != baseline.cursor,
                baseline.bracketed_paste,
                snapshot.bracketed_paste,
                tail.chars().count(),
                probe.chars().count(),
                !probe.is_empty() && compact_tail.contains(&probe),
                paste_placeholder_visible(&baseline_tail),
                paste_placeholder_visible(&normalized_tail),
                child_live,
                foreground_name,
                retained.output,
                retained.foreground,
                retained.snapshots,
                retained.resized,
                retained.gaps,
                retained.reader_errors,
                retained.operator_actions,
                retained
                    .exit_code
                    .map_or_else(|| "none".to_owned(), |code| code.to_string()),
                if retained.output_flags.is_empty() {
                    "none".to_owned()
                } else {
                    retained.output_flags.join(",")
                },
            ));
        }
        tokio::time::sleep(Duration::from_millis(STARTUP_GATE_POLL_MS)).await;
    }
}

#[derive(Default)]
struct RenderAckEventSummary {
    output: usize,
    foreground: usize,
    snapshots: usize,
    resized: usize,
    gaps: usize,
    reader_errors: usize,
    operator_actions: usize,
    exit_code: Option<i32>,
    output_flags: Vec<&'static str>,
}

fn render_ack_event_summary(session: &PtySession, baseline_sequence: u64) -> RenderAckEventSummary {
    let mut summary = RenderAckEventSummary::default();
    let Ok(attachment) = session.attach_retained_events() else {
        return summary;
    };
    for envelope in attachment
        .replay
        .into_iter()
        .filter(|envelope| envelope.sequence > baseline_sequence)
    {
        match envelope.event {
            PtyEvent::Output(bytes) => {
                summary.output = summary.output.saturating_add(1);
                observe_render_ack_output_flags(&mut summary.output_flags, &bytes);
            }
            PtyEvent::ForegroundProcess(_) => {
                summary.foreground = summary.foreground.saturating_add(1);
            }
            PtyEvent::SnapshotAvailable { .. } => {
                summary.snapshots = summary.snapshots.saturating_add(1);
            }
            PtyEvent::Resized(_) => {
                summary.resized = summary.resized.saturating_add(1);
            }
            PtyEvent::DataGap { .. } => {
                summary.gaps = summary.gaps.saturating_add(1);
            }
            PtyEvent::ReaderError { .. } => {
                summary.reader_errors = summary.reader_errors.saturating_add(1);
            }
            PtyEvent::OperatorActionRequired { .. } => {
                summary.operator_actions = summary.operator_actions.saturating_add(1);
            }
            PtyEvent::Exited { code } => summary.exit_code = Some(code),
            PtyEvent::Started => {}
        }
    }
    summary
}

fn observe_render_ack_output_flags(flags: &mut Vec<&'static str>, bytes: &[u8]) {
    let normalized = String::from_utf8_lossy(bytes).to_ascii_lowercase();
    for (label, marker) in [
        ("error", "error"),
        ("panic", "panic"),
        ("fatal", "fatal"),
        ("login", "login"),
        ("auth", "auth"),
        ("permission", "permission"),
        ("rate-limit", "rate limit"),
        ("usage-limit", "usage limit"),
        ("update", "update"),
        ("working", "working"),
        ("thinking", "thinking"),
    ] {
        if normalized.contains(marker) && !flags.contains(&label) {
            flags.push(label);
        }
    }
}

fn safe_process_label(process_name: &str) -> String {
    process_name
        .chars()
        .take(64)
        .map(|character| {
            if character.is_ascii_alphanumeric() || matches!(character, '.' | '_' | '-') {
                character
            } else {
                '?'
            }
        })
        .collect()
}

fn prompt_rendered(
    snapshot: &PtyTerminalSnapshot,
    baseline: &PtyTerminalSnapshot,
    probe: &str,
) -> bool {
    if snapshot.sequence <= baseline.sequence {
        return false;
    }
    let tail = terminal_tail(&snapshot.contents);
    let compact = compact_alphanumeric(&tail);
    if !probe.is_empty() && compact.contains(probe) {
        return true;
    }
    let normalized_tail = tail.to_ascii_lowercase();
    let normalized_baseline = terminal_tail(&baseline.contents).to_ascii_lowercase();
    paste_placeholder_visible(&normalized_tail)
        && !paste_placeholder_visible(&normalized_baseline)
}

fn paste_placeholder_visible(normalized_tail: &str) -> bool {
    // Codex collapses larger pastes as `[Pasted Content ...]`; Claude 2.1.223
    // uses `[Pasted text #N ...]`. Treat only those vendor-owned render
    // markers as proof that the TUI consumed the bracketed paste.
    normalized_tail.contains("[pasted content")
        || normalized_tail.contains("[pasted text #")
}

fn terminal_tail(contents: &str) -> String {
    let mut lines = contents.lines().rev().take(12).collect::<Vec<_>>();
    lines.reverse();
    lines.join("\n")
}

fn prompt_render_probe(prompt: &str) -> String {
    let compact = compact_alphanumeric(prompt);
    let chars = compact.chars().collect::<Vec<_>>();
    chars[chars.len().saturating_sub(32)..].iter().collect()
}

fn compact_alphanumeric(value: &str) -> String {
    value
        .chars()
        .filter(|character| character.is_alphanumeric())
        .flat_map(char::to_lowercase)
        .collect()
}

async fn wait_for_startup_operator_gate(
    session: &PtySession,
    spec: &AgentSpec,
) -> Result<(), String> {
    let deadline = Instant::now() + Duration::from_millis(STARTUP_GATE_SETTLE_MS);
    loop {
        ensure_no_startup_operator_gate(session, spec)?;
        let now = Instant::now();
        if now >= deadline {
            return Ok(());
        }
        tokio::time::sleep(
            deadline
                .saturating_duration_since(now)
                .min(Duration::from_millis(STARTUP_GATE_POLL_MS)),
        )
        .await;
    }
}

/// Refuses a prompt submission while a known operator gate is on screen.
///
/// Deliberately checks gates ONLY, never `screen_failure`. A crash banner
/// means "the CLI fell over" solely before the agent has rendered its own
/// UI; afterwards the identical bytes mean "the agent is showing you a
/// crash" -- a test it ran, a traceback it was asked to explain. What
/// separates the two is not the text but WHEN it appeared, and this
/// function has no way to date its evidence: it holds a screen snapshot
/// and a spec, and is called from seven sites spanning both the startup
/// window and long-running follow-up delivery. A check that cannot tell
/// those apart would refuse work from a perfectly healthy session every
/// time its pane happened to show a failing subprocess.
///
/// The `Failing` classification is not lost by this -- it is computed
/// where the window IS known (`collect_terminal_frames`, gated on
/// `OwnedPtySession::ever_reached_ready`), published upstream, and enforced
/// by the callers that gate dispatch on `PtyScreenState`. Gates are
/// different in kind and stay here: a trust or update prompt is legitimate
/// at any point in a session's life, so it needs no window to be believed.
fn ensure_no_startup_operator_gate(session: &PtySession, spec: &AgentSpec) -> Result<(), String> {
    let snapshot = session.terminal_state().map_err(|error| error.to_string())?;
    match startup_operator_gate(&snapshot.contents) {
        Some(gate) => Err(startup_operator_error(spec, &gate)),
        None => Ok(()),
    }
}

fn startup_operator_error(spec: &AgentSpec, gate: &OperatorGateState) -> String {
    format!(
        "agent '{}' requires operator action at startup ({gate}); initial prompt was not submitted",
        spec.id
    )
}

fn ensure_no_readiness_operator_gate(
    diagnostics: &ReadinessDiagnostics,
    spec: &AgentSpec,
) -> Result<(), String> {
    match &diagnostics.operator_gate {
        Some(gate) => Err(startup_operator_error(spec, gate)),
        None => Ok(()),
    }
}

/// Whitespace-collapse and lowercase raw PTY screen text before pattern
/// matching. Shared by `startup_operator_gate` and `screen_failure` so the
/// two agree on what "the same phrase" means -- if they normalized
/// independently, a line-wrap difference or a run of extra spaces could
/// make one matcher see a phrase the other misses for no reason connected
/// to the actual screen content.
fn normalize_screen_text(contents: &str) -> String {
    contents
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
        .to_ascii_lowercase()
}

/// Phrases showing a package manager actively installing or updating a
/// package. Generic across npm/pip/yarn/pnpm rather than any one vendor's
/// package name, so a wrapper script fronting any provider CLI is
/// recognized the same way -- see the `PACKAGE_MANAGER_UPDATE_COMPLETION_MARKERS`
/// doc below for why a bare occurrence of one of these alone is not enough.
const PACKAGE_MANAGER_INSTALL_MARKERS: &[&str] = &[
    "npm install -g",
    "npm i -g",
    "npm update -g",
    "pip install --upgrade",
    "pip install -u",
    "yarn global add",
    "pnpm add -g",
];

/// Phrases showing the install/update above reached a terminal state and
/// wants the CLI relaunched. Required to co-occur with a marker from
/// `PACKAGE_MANAGER_INSTALL_MARKERS` so a screen that merely MENTIONS a
/// package-manager command (an agent explaining how to install something,
/// for instance) never matches on the install phrase alone.
const PACKAGE_MANAGER_UPDATE_COMPLETION_MARKERS: &[&str] = &[
    "update ran successfully",
    "please restart",
    "update complete",
    "updated successfully",
];

/// Builds the classified `OperatorGateState` for a matched `kind`/`subject`
/// pair, filling `input`/`options` from whatever `parse_operator_gate_options`
/// can read off the RAW (un-normalized, multi-line) screen text. Every
/// `startup_operator_gate` match arm goes through this one function so
/// option-list recognition is uniform across every gate kind rather than
/// hand-wired per branch -- a kind this module has not yet seen an option
/// layout for simply gets `OperatorGateInput::Unknown` and no options,
/// exactly like a kind whose options this parser fails to recognize on a
/// given screen; there is no special-casing between "not implemented yet"
/// and "not recognized this time".
fn operator_gate(kind: OperatorGateKind, subject: OperatorGateSubject, contents: &str) -> OperatorGateState {
    let (input, options) = parse_operator_gate_options(contents);
    OperatorGateState::new(kind)
        .with_subject(subject)
        .with_options(input, options)
}

fn startup_operator_gate(contents: &str) -> Option<OperatorGateState> {
    let normalized = normalize_screen_text(contents);
    if [
        "trust this folder",
        "trust the files in this folder",
        "trust the contents of this directory",
        "do you trust this directory",
    ]
    .iter()
    .any(|marker| normalized.contains(marker))
    {
        return Some(operator_gate(
            OperatorGateKind::WorkspaceTrust,
            OperatorGateSubject::Directory { path: None },
            contents,
        ));
    }
    if normalized.contains("quick safety check")
        && (normalized.contains("yes, i trust this folder")
            || normalized.contains("continue without these permissions"))
    {
        return Some(operator_gate(
            OperatorGateKind::WorkspaceTrust,
            OperatorGateSubject::Directory { path: None },
            contents,
        ));
    }
    // A CLI's own hook-trust prompt at startup (seen from Codex): a set of
    // shell hooks it discovered need to be reviewed/trusted before they are
    // allowed to run, distinct from `WorkspaceTrust` above -- that gate is
    // about trusting the PROJECT DIRECTORY, this one is about trusting
    // SHELL HOOKS the CLI found inside it, and an operator reading `kind`
    // should be able to tell which question is being asked. Required to
    // co-occur with the screen's own "decline" option rather than matching
    // on "hooks need review" alone, so an agent's ordinary narration that
    // merely uses the word "hooks" (explaining a git hook, a React hook, a
    // build hook) never matches: real narration essentially never also
    // contains the literal refusal phrasing "continue without trusting"
    // this same prompt renders. The number of hooks reported (which varies
    // run to run, and is not read into `subject`'s `count` -- no matcher
    // here parses it off the screen) plays no part in the match.
    if normalized.contains("hooks need review") && normalized.contains("continue without trusting")
    {
        return Some(operator_gate(
            OperatorGateKind::HookTrust,
            OperatorGateSubject::Hooks { count: None },
            contents,
        ));
    }
    if [
        "select authentication method",
        "choose how to authenticate",
        "no auth type is selected",
    ]
    .iter()
    .any(|marker| normalized.contains(marker))
    {
        return Some(operator_gate(
            OperatorGateKind::Authentication,
            OperatorGateSubject::Account,
            contents,
        ));
    }
    if normalized.contains("sign in")
        && (normalized.contains("openai")
            || normalized.contains("chatgpt")
            || normalized.contains("codex"))
    {
        return Some(operator_gate(
            OperatorGateKind::Authentication,
            OperatorGateSubject::Account,
            contents,
        ));
    }
    // Claude's own login-method chooser: a numbered list ("1. Claude ...",
    // "2. API usage billing", "3. 3rd-party platform ...") rendered under
    // "Select login method:". It shares neither "sign in" nor
    // "openai"/"chatgpt"/"codex" with the branch above, so that branch
    // never catches it. The phrase itself is specific enough (no ordinary
    // agent narration renders this exact prompt line) to stand alone,
    // matching the precedent set by "select authentication method" and
    // "choose how to authenticate" above.
    if normalized.contains("select login method") {
        return Some(operator_gate(
            OperatorGateKind::Authentication,
            OperatorGateSubject::Account,
            contents,
        ));
    }
    // Claude's OAuth wait screen: a URL to open in a browser plus a slot to
    // paste back the authorization code once that flow completes. Required
    // to co-occur with "paste code" (the screen's own field label) rather
    // than matching on "sign in" alone -- "sign in" by itself is common
    // enough in an agent's ordinary narration to be untrustworthy, the same
    // reasoning the branch above already applies via its own companion
    // words. No option list is rendered here -- it is one free-text slot,
    // not a choice from a list -- so `input` is set directly to
    // `TextEntry` rather than routed through `operator_gate`'s option-list
    // parser, which would find nothing on this screen shape and fall back
    // to `Unknown`.
    if normalized.contains("sign in") && normalized.contains("paste code") {
        return Some(
            OperatorGateState::new(OperatorGateKind::Authentication)
                .with_subject(OperatorGateSubject::Account)
                .with_options(OperatorGateInput::TextEntry, Vec::new()),
        );
    }
    if normalized.contains("kimi code update available")
        && normalized.contains("install update now")
    {
        return Some(operator_gate(
            OperatorGateKind::VendorUpdate,
            OperatorGateSubject::Unknown,
            contents,
        ));
    }
    // A wrapper script self-updating via a package manager before the real
    // CLI ever launches -- the case that produced the incident this module
    // fixes: an npm-driven wrapper ran an update to completion and printed
    // nothing that looked like the agent, while every consumer still saw a
    // live, `status: running` PTY. This shares `VendorUpdate` with the Kimi
    // in-app case just above on purpose, not by omission: both are "the CLI
    // is updating itself", the only difference is WHICH process drives it
    // (the agent's own composer vs. a wrapper script's package-manager
    // install), and an operator reading `kind` should see one meaning for
    // that fact regardless of which vendor's update mechanism produced it.
    if PACKAGE_MANAGER_INSTALL_MARKERS
        .iter()
        .any(|marker| normalized.contains(marker))
        && PACKAGE_MANAGER_UPDATE_COMPLETION_MARKERS
            .iter()
            .any(|marker| normalized.contains(marker))
    {
        return Some(operator_gate(
            OperatorGateKind::VendorUpdate,
            OperatorGateSubject::Unknown,
            contents,
        ));
    }
    if normalized.contains("choose the text style that looks best with your terminal") {
        return Some(operator_gate(
            OperatorGateKind::TerminalAppearance,
            OperatorGateSubject::Appearance,
            contents,
        ));
    }
    if normalized.contains("welcome to claude code for")
        && (normalized.contains("open files") || normalized.contains("selected lines"))
    {
        return Some(operator_gate(
            OperatorGateKind::Onboarding,
            OperatorGateSubject::Unknown,
            contents,
        ));
    }
    if normalized.contains("welcome to claude code")
        && (normalized.contains("press enter") || normalized.contains("enter to continue"))
    {
        return Some(operator_gate(
            OperatorGateKind::Onboarding,
            OperatorGateSubject::Unknown,
            contents,
        ));
    }
    if normalized.contains("migration") && normalized.contains("enter confirm") && normalized.contains("esc")
    {
        return Some(operator_gate(
            OperatorGateKind::ConfigurationMigration,
            OperatorGateSubject::Unknown,
            contents,
        ));
    }
    None
}

/// Reads the recognized on-screen choice list, if any, off the RAW
/// (multi-line, un-normalized) screen text -- called uniformly by every
/// `startup_operator_gate` match arm through `operator_gate`. Recognizes
/// exactly two rendered shapes, both observed verbatim on a live stand:
///
/// - a NUMBERED list (Codex's hook-trust prompt): each option line starts,
///   after an optional leading cursor glyph (`›`) and whitespace, with
///   `N.`; `Some` lines from `parse_numbered_gate_option_line` win outright
///   over the arrow shape below, so a screen that happens to also contain an
///   arrow glyph elsewhere (a Codex composer prompt sharing the pane, say)
///   is still read as the numbered list it actually is.
/// - an ARROW list (Kimi's workspace-trust prompt): the currently selected
///   option carries a leading `❯`; the other options carry no glyph at all,
///   so they are told apart from the description line rendered under each
///   one (`"Enable project MCP servers. Remembered for this folder."` under
///   `"Trust this folder"`, for instance) by `parse_arrow_gate_option_line`'s
///   own filter -- see that function's doc comment for the exact rule.
///
/// Neither line is stable across CLIs, and this parser recognizes nothing
/// else: a screen matching neither shape returns `(Unknown, vec![])`, never
/// a guess built from partial matches.
fn parse_operator_gate_options(contents: &str) -> (OperatorGateInput, Vec<OperatorGateOption>) {
    let numbered: Vec<OperatorGateOption> = contents
        .lines()
        .filter_map(parse_numbered_gate_option_line)
        .take(OPERATOR_GATE_OPTIONS_MAX)
        .collect();
    if !numbered.is_empty() {
        return (OperatorGateInput::NumberedList, numbered);
    }
    let arrow: Vec<OperatorGateOption> = contents
        .lines()
        .filter_map(parse_arrow_gate_option_line)
        .take(OPERATOR_GATE_OPTIONS_MAX)
        .collect();
    if !arrow.is_empty() {
        return (OperatorGateInput::ArrowList, arrow);
    }
    (OperatorGateInput::Unknown, Vec::new())
}

/// Parses one line of a numbered option list -- `"› 1. Review hooks"`,
/// `"  2. Trust all and continue"` -- into `(selected, text)`. `selected` is
/// true only when the line carries the leading `›` cursor glyph Codex draws
/// on the highlighted row; every other line in the same list has none.
/// Returns `None` for any line that, once a leading glyph is stripped, does
/// not start with `<digits>.` -- an instruction line like `"Press enter to
/// confirm or esc to go back"` is exactly this shape and is meant to fall
/// through untouched.
/// Cursor glyphs vendors draw ahead of the selected row of an option list.
/// Kept as one set shared by both list parsers: which glyph a vendor picks
/// says nothing about whether its list is numbered or marker-only, and
/// teaching one parser a glyph the other does not know is exactly how the
/// selected row went missing before.
const GATE_CURSOR_GLYPHS: [char; 2] = ['\u{203a}', '\u{276f}'];

fn parse_numbered_gate_option_line(line: &str) -> Option<OperatorGateOption> {
    let trimmed = line.trim_start();
    // Vendors mark the cursor row of a NUMBERED list with the marker BEFORE
    // the number (`> 2. Dark mode`), and they do not agree on the glyph:
    // Codex draws U+203A, Claude draws U+276F, and both appear ahead of the
    // digit rather than ahead of the text. Recognizing only one of them cost
    // the whole row -- the cursor line failed to parse as an option at all,
    // so the list came back one item short and with nothing marked selected,
    // observed live on Claude's theme chooser and Codex's login chooser.
    let (selected, rest) = match trimmed.strip_prefix(GATE_CURSOR_GLYPHS) {
        Some(stripped) => (true, stripped.trim_start()),
        None => (false, trimmed),
    };
    let digits_end = rest.find(|character: char| !character.is_ascii_digit()).unwrap_or(0);
    if digits_end == 0 {
        return None;
    }
    let text = rest[digits_end..].strip_prefix('.')?.trim();
    if text.is_empty() {
        return None;
    }
    Some(OperatorGateOption {
        semantics: classify_operator_gate_option_semantics(text),
        text: text.to_owned(),
        selected,
    })
}

/// Parses one line of an arrow-navigated option list -- `"❯ Don't trust"`,
/// `"  Trust this folder"` -- into `(selected, text)`. `selected` is true
/// only when the line carries the leading `❯` cursor glyph.
///
/// Distinguishing an option TITLE from the description/header/instruction
/// prose around it (`"Enable project MCP servers. Remembered for this
/// folder."` under `"Trust this folder"`; `"Do you trust the files in this
/// folder?"` above it; `"Press enter to confirm or esc to go back"` below a
/// DIFFERENT screen's numbered list entirely) cannot rely on the glyph
/// alone, since only the currently-selected title ever carries one. A
/// candidate line is accepted as an option only if EITHER it carries the
/// `❯` marker (the screen's own cursor is unambiguous proof this is a real,
/// currently-selected option, whatever its wording), OR it both looks like
/// a short menu label rather than a sentence (no `.`, `?`, `!`, or `:`
/// anywhere in it -- a description or instruction is a full sentence
/// carrying one of these; an option label like `"Trust this folder"` or
/// `"Don't trust"` never does) AND its own text uses one of the recognized
/// option verbs (`classify_operator_gate_option_semantics` returns
/// something other than `Unknown`) -- an unmarked line whose wording this
/// module does not recognize as a choice-verb is left as prose rather than
/// guessed into an option with `semantics: Unknown`. The arrow-key legend
/// itself (`"↑↓ navigate · Enter select · Esc exit"`) is excluded
/// explicitly rather than relying on either rule catching it.
fn parse_arrow_gate_option_line(line: &str) -> Option<OperatorGateOption> {
    let trimmed = line.trim();
    if trimmed.is_empty()
        || trimmed
            .chars()
            .any(|character| matches!(character, '.' | '?' | '!' | ':'))
    {
        return None;
    }
    let lower = trimmed.to_ascii_lowercase();
    if lower.contains('\u{2191}') || lower.contains('\u{2193}') || lower.contains("navigate") {
        return None;
    }
    let (selected, rest) = match trimmed.strip_prefix(GATE_CURSOR_GLYPHS) {
        Some(stripped) => (true, stripped.trim()),
        None => (false, trimmed),
    };
    if rest.is_empty() || !rest.chars().any(|character| character.is_alphabetic()) {
        return None;
    }
    let semantics = classify_operator_gate_option_semantics(rest);
    if !selected && semantics == OperatorGateOptionSemantics::Unknown {
        return None;
    }
    Some(OperatorGateOption {
        semantics,
        text: rest.to_owned(),
        selected,
    })
}

/// Infers what choosing a given on-screen option does from the verb in its
/// OWN text -- never from its position or number, since neither is stable
/// across CLIs or screen wraps. Decline phrasing is checked before accept
/// phrasing so `"Continue without trusting"` (contains both "continue" and
/// "without trusting") reads as `Decline`, matching what the option
/// actually does; an option whose text uses none of these verbs classifies
/// `Unknown` rather than a guessed default.
fn classify_operator_gate_option_semantics(text: &str) -> OperatorGateOptionSemantics {
    let lower = text.to_ascii_lowercase();
    if lower.contains("review") {
        OperatorGateOptionSemantics::Inspect
    } else if lower.contains("don't trust")
        || lower.contains("do not trust")
        || lower.contains("without trusting")
        || lower.contains("decline")
    {
        OperatorGateOptionSemantics::Decline
    } else if lower.contains("trust") || lower.contains("continue") || lower.contains("proceed") {
        OperatorGateOptionSemantics::Accept
    } else if lower.contains("exit") || lower.contains("quit") || lower.contains("cancel") {
        OperatorGateOptionSemantics::Exit
    } else {
        OperatorGateOptionSemantics::Unknown
    }
}

/// True if `line` ends in a bare shell-prompt character -- used only to
/// raise confidence on the one `screen_failure` marker
/// (`"no such file or directory"`) that is otherwise too generic to trust
/// alone; see that bucket's own comment.
fn looks_like_shell_prompt_line(line: &str) -> bool {
    matches!(line.trim_end().chars().last(), Some('$' | '%' | '#' | '>'))
}

/// Screens where the foreground process already matches the agent (this is
/// NOT the `NotAgent` process-mismatch case) but the screen itself shows
/// the process came up wrong or fell over. Nothing typed into THIS screen
/// fixes it, which is the line that separates `Failing` from
/// `OperatorGate`: a gate is resolved by typing an answer into the pane, a
/// failure is not.
///
/// Every marker here is a crash SHAPE -- a stack-trace banner, a shell's
/// own "command not found" line -- and as raw bytes a crash shape is
/// indistinguishable from an agent CHOOSING to render that same text while
/// explaining, or running, someone else's failure (`cargo test` hitting a
/// failing assertion, a script the agent ran that threw, a bug report it
/// was asked to read). Text alone cannot tell "the CLI crashed" from "the
/// CLI is showing you a crash" -- both put identical bytes on screen. The
/// one window where these markers ARE trustworthy is before this
/// generation's session has ever reached `Ready`: with no prior render of
/// the agent's own UI, there is nothing else on the screen that could have
/// produced a crash banner, so it genuinely means the launch failed. That
/// is why this function's caller in `collect_terminal_frames` stops
/// calling it at all once `Ready`, rather than trying to make the matching
/// itself tell healthy narration apart from a real crash -- no marker set
/// can do that from bytes alone.
fn screen_failure(contents: &str) -> Option<&'static str> {
    let normalized = normalize_screen_text(contents);

    // A language runtime's own uncaught-exception banner -- fixed strings
    // a runtime prints verbatim at the head of a crash dump, not phrasing
    // a chat transcript would casually reproduce in this exact shape.
    // `"fatal error:"` is deliberately NOT included: it is also what a
    // C/C++ compiler prints for an ordinary missing-header build error, and
    // a wrapper script's build step can emit that while the real CLI still
    // comes up fine afterwards -- untrustworthy even in the startup window
    // without a second signal this function does not have.
    if ["panicked at", "unhandled exception", "traceback (most recent call last)"]
        .iter()
        .any(|marker| normalized.contains(marker))
    {
        return Some("crash");
    }

    // A shell reporting that the launch command itself does not exist.
    // The first two are OS/shell-owned sentence shapes on their own. The
    // third, `"no such file or directory"`, is common enough in ordinary
    // ENOENT discussion that it needs a companion signal -- a line that
    // itself ends in a bare shell prompt -- before it counts.
    if normalized.contains("command not found")
        || normalized.contains("is not recognized as an internal or external command")
        || (normalized.contains("no such file or directory")
            && contents.lines().any(looks_like_shell_prompt_line))
    {
        return Some("missing command");
    }

    // A provider CLI's own missing-credential banner at launch -- Grok with
    // no key configured prints exactly this one line and never renders
    // anything else again, which makes it a crash SHAPE in the same sense
    // as the buckets above: nothing typed into this screen fixes it, only a
    // restart with a credential configured. Required to co-occur with the
    // literal `GROK_API_KEY` env var name rather than matching "api key
    // required" alone -- that phrase in the abstract is common enough in an
    // agent's own prose (explaining a DIFFERENT provider's setup, say) to be
    // untrustworthy alone; the exact env var name is specific to this one
    // banner.
    if normalized.contains("api key required") && normalized.contains("grok_api_key") {
        return Some("missing api key");
    }

    None
}

/// The window gate on `screen_failure`, factored into its own pure
/// function so the "stop trusting crash markers once this generation has
/// ever been `Ready`" rule is unit-testable without constructing a live
/// `OwnedPtySession` (which owns a real PTY and cannot be built in a unit
/// test). `collect_terminal_frames` calls this, not `screen_failure`
/// directly.
fn screen_failure_for_generation(contents: &str, ever_reached_ready: bool) -> Option<&'static str> {
    if ever_reached_ready {
        None
    } else {
        screen_failure(contents)
    }
}

/// The foreground half of the classification, resolved by the caller so
/// the merge itself stays a pure function.
#[derive(Clone, Debug, Eq, PartialEq)]
enum ForegroundVerdict {
    /// Foreground is the agent's own binary, or a tolerated wrapper.
    Agent,
    /// Foreground is something else. Carries what was actually seen.
    Foreign { process: String },
}

/// Merge the foreground and text signals into one screen classification.
///
/// The ORDER below, not the branches, is the part worth reading closely:
///
/// 1. A foreign foreground wins outright, even over a matching gate or
///    failure text pattern, because the process signal is structurally
///    exhaustive in the one way that matters -- it never needs to
///    recognize an updater's specific wording to say "this is not the
///    agent". A vendor wrapper whose text this module's matchers do not
///    yet know about still gets caught here.
/// 2. With no foreign foreground, `Failing` outranks `OperatorGate`: a
///    crashed screen can still have a leftover gate prompt sitting in
///    view above the crash dump, and "broken" is the more urgent of the
///    two truths for an operator to hear -- reporting "waiting for input"
///    about a session that has actually fallen over sends someone to type
///    into a pane that cannot use it.
/// 3. `OperatorGate` next, for the "resolvable by typing" reason
///    documented on `PtyScreenState` itself.
/// 4. With no foreground observation at all, the answer is `Unknown`, not
///    `Ready` -- a clean text read is NEVER, by itself, proof the screen
///    is the agent's. `Ready` requires the foreground to have been
///    checked AND to have matched, per the asymmetry documented on
///    `PtyScreenState::Ready`.
/// 5. Only once foreground is confirmed AND no gate/failure text matched
///    does the merge land on `Ready`.
fn classify_pty_screen_state(
    foreground: Option<&ForegroundVerdict>,
    gate: Option<&OperatorGateState>,
    failure: Option<&'static str>,
) -> PtyScreenState {
    if let Some(ForegroundVerdict::Foreign { process }) = foreground {
        return PtyScreenState::NotAgent {
            observed_process: process.clone(),
        };
    }
    if let Some(reason) = failure {
        return PtyScreenState::Failing {
            reason: reason.to_owned(),
        };
    }
    if let Some(gate) = gate {
        return PtyScreenState::OperatorGate { gate: gate.clone() };
    }
    if foreground.is_some() {
        PtyScreenState::Ready
    } else {
        PtyScreenState::Unknown
    }
}

/// Resolve what an OS process-tree observation means for classification,
/// reusing the exact matchers `ReadinessTracker::observe_foreground` trusts
/// at startup so this module's tolerance for a spawning wrapper
/// (`node`/`python`/`python3`) never drifts from readiness's own -- a false
/// `NotAgent` on a legitimate wrapper would be a regression on what
/// readiness already tolerates.
///
/// Deliberately looser than `ReadinessTracker::observe_foreground` in one
/// respect: it does not gate the wrapper tolerance behind
/// `has_child_processes`/a poll-count threshold. Those exist there to
/// decide "confident enough to flip session status to Running" from a
/// process signal ALONE. Here the text signal still has to independently
/// agree before the merge can reach `Ready` (see `classify_pty_screen_state`),
/// so being more permissive about which process counts as plausible never
/// lets a bad screen through on the process signal by itself.
fn resolve_foreground_verdict(
    spec: &AgentSpec,
    observation: &PtyForegroundObservation,
    platform: RuntimePlatform,
) -> ForegroundVerdict {
    let process_name = observation
        .readiness
        .process_name
        .as_deref()
        .unwrap_or(observation.observed_process.as_str());
    if is_expected_agent_process(spec, process_name, platform)
        || is_agent_foreground_wrapper(process_name, platform)
    {
        ForegroundVerdict::Agent
    } else {
        ForegroundVerdict::Foreign {
            process: observation.observed_process.clone(),
        }
    }
}

/// Whether `NativeEffectShell::reclassify_foreground` should schedule
/// another probe after a fresh classification, factored out as a small
/// pure function so the decision is testable without constructing a live
/// `OwnedPtySession` (which owns a real PTY and cannot be built in a unit
/// test).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ForegroundProbeSchedule {
    /// The session reached `Ready` -- stop probing until text disagrees.
    Disarmed,
    /// Still unresolved, or freshly non-ready -- probe again after the interval.
    Armed,
}

fn foreground_probe_schedule(state: &PtyScreenState) -> ForegroundProbeSchedule {
    if matches!(state, PtyScreenState::Ready) {
        ForegroundProbeSchedule::Disarmed
    } else {
        ForegroundProbeSchedule::Armed
    }
}

/// Whether a text-only reclassification that just changed the merged state
/// (inside `collect_terminal_frames`) should force the foreground probe due
/// immediately, rather than waiting for its normal cadence. Factored out
/// for the same testability reason as `foreground_probe_schedule`: a
/// session that was `Ready` and whose text just started matching a gate or
/// failure pattern needs its foreground re-checked promptly, since the
/// last thing anyone probed was clean and the screen no longer agrees.
fn foreground_probe_rearms_immediately(previous: &PtyScreenState, next: &PtyScreenState) -> bool {
    matches!(previous, PtyScreenState::Ready) && !matches!(next, PtyScreenState::Ready)
}

fn observe_readiness_event(
    tracker: &mut ReadinessTracker<'_>,
    diagnostics: &mut ReadinessDiagnostics,
    event: PtyEvent,
    elapsed_ms: u64,
) -> Result<(), String> {
    match event {
        PtyEvent::Output(data) => {
            diagnostics.observe_output(&data);
            tracker.observe_output(&data, elapsed_ms);
        }
        PtyEvent::ForegroundProcess(observation) => {
            diagnostics.observe_foreground(&observation.readiness);
            tracker.observe_foreground(&observation.readiness, elapsed_ms);
        }
        PtyEvent::DataGap { .. } => {
            return Err("PTY replay gap prevents positive readiness proof".to_owned());
        }
        PtyEvent::ReaderError { message } | PtyEvent::OperatorActionRequired { message } => {
            return Err(message);
        }
        PtyEvent::Exited { code } => {
            return Err(format!("PTY exited with code {code} before readiness"));
        }
        PtyEvent::Started | PtyEvent::Resized(_) | PtyEvent::SnapshotAvailable { .. } => {}
    }
    Ok(())
}

#[derive(Default)]
struct ReadinessDiagnostics {
    draft_signal: Option<gate4agent_types::DraftReadySignal>,
    output_bytes: usize,
    output_chunks: usize,
    tail: Vec<u8>,
    saw_bracketed_paste: bool,
    saw_cursor_show: bool,
    saw_cursor_hide: bool,
    saw_alternate_screen: bool,
    saw_clear_screen: bool,
    saw_claude_composer: bool,
    saw_codex_composer: bool,
    saw_named_foreground: bool,
    operator_gate: Option<OperatorGateState>,
}

impl ReadinessDiagnostics {
    fn observe_output(&mut self, data: &[u8]) {
        const SIGNAL_TAIL_BYTES: usize = 4_096;
        self.output_bytes = self.output_bytes.saturating_add(data.len());
        self.output_chunks = self.output_chunks.saturating_add(1);
        let mut combined = Vec::with_capacity(self.tail.len().saturating_add(data.len()));
        combined.extend_from_slice(&self.tail);
        combined.extend_from_slice(data);
        self.saw_bracketed_paste |= readiness_bytes_contain(&combined, b"\x1b[?2004h");
        self.saw_cursor_show |= readiness_bytes_contain(&combined, b"\x1b[?25h");
        self.saw_cursor_hide |= readiness_bytes_contain(&combined, b"\x1b[?25l");
        self.saw_alternate_screen |= readiness_bytes_contain(&combined, b"\x1b[?1049h");
        self.saw_clear_screen |= readiness_bytes_contain(&combined, b"\x1b[2J");
        self.saw_claude_composer |= readiness_bytes_contain(&combined, "❯".as_bytes());
        self.saw_codex_composer |= readiness_bytes_contain(&combined, "›".as_bytes());
        let text = String::from_utf8_lossy(&combined);
        self.operator_gate = self
            .operator_gate
            .take()
            .or_else(|| startup_operator_gate(&strip_ansi_codes(&text)));
        self.tail = combined[combined.len().saturating_sub(SIGNAL_TAIL_BYTES)..].to_vec();
    }

    fn observe_foreground(&mut self, foreground: &gate4agent::agent::ForegroundObservation) {
        self.saw_named_foreground |= foreground.process_name.is_some();
    }

    fn summary(&self) -> String {
        format!(
            "draft_signal={:?} output_bytes={} output_chunks={} named_foreground={} bracketed_paste={} cursor_show={} cursor_hide={} alternate_screen={} clear_screen={} claude_composer={} codex_composer={} csi={}",
            self.draft_signal,
            self.output_bytes,
            self.output_chunks,
            self.saw_named_foreground,
            self.saw_bracketed_paste,
            self.saw_cursor_show,
            self.saw_cursor_hide,
            self.saw_alternate_screen,
            self.saw_clear_screen,
            self.saw_claude_composer,
            self.saw_codex_composer,
            readiness_csi_signatures(&self.tail),
        )
    }
}

fn readiness_csi_signatures(bytes: &[u8]) -> String {
    let mut signatures = Vec::new();
    let mut index = 0;
    while index + 2 < bytes.len() && signatures.len() < 32 {
        if bytes[index] != 0x1b || bytes[index + 1] != b'[' {
            index += 1;
            continue;
        }
        let mut end = index + 2;
        while end < bytes.len() && end.saturating_sub(index) <= 24 {
            let byte = bytes[end];
            if (0x40..=0x7e).contains(&byte) {
                let signature = String::from_utf8_lossy(&bytes[index + 2..=end]).into_owned();
                if !signatures.iter().any(|existing| existing == &signature) {
                    signatures.push(signature);
                }
                index = end;
                break;
            }
            if !(0x20..=0x3f).contains(&byte) {
                break;
            }
            end += 1;
        }
        index += 1;
    }
    if signatures.is_empty() {
        "none".to_owned()
    } else {
        signatures.join("|")
    }
}

fn readiness_bytes_contain(haystack: &[u8], needle: &[u8]) -> bool {
    haystack
        .windows(needle.len())
        .any(|window| window == needle)
}

fn readiness_complete(
    status: ReadinessStatus,
    diagnostics: &ReadinessDiagnostics,
) -> Result<bool, String> {
    match status {
        ReadinessStatus::Waiting => Ok(false),
        ReadinessStatus::Ready(_) => Ok(true),
        ReadinessStatus::TimedOut => Err(format!(
            "PTY readiness timed out ({})",
            diagnostics.summary()
        )),
    }
}

fn elapsed_ms(started: Instant) -> u64 {
    u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX)
}

#[cfg(test)]
mod tests {
    use super::{
        acp_approval_level_args,
        approval_level_not_offered_message,
        classify_operator_gate_option_semantics,
        classify_pty_screen_state,
        defers_permission_requests,
        foreground_probe_rearms_immediately, foreground_probe_schedule,
        argument_looks_like_credential, host_policy_for_approval_level,
        mcp_server_acp_entry,
        parse_operator_gate_options, prepare_fresh_pty_provider_session,
        prompt_render_probe, prompt_rendered, required_acp_mode,
        reserve_provider_gap_sequence, resolve_foreground_verdict, screen_failure,
        screen_failure_for_generation, with_pty_terminal_capability_defaults,
        should_attach_pty_provider_stream, should_probe_pty_identity, startup_operator_gate,
        terminal_frame, terminal_frame_byte_len, terminal_state_capture_should_skip,
        validate_instance_launch_arguments, validate_spawn_runtime_policy,
        ForegroundProbeSchedule, ForegroundVerdict, ReadinessDiagnostics, RateLimitFeed,
        Utf8ChunkDecoder,
    };
    use gate4agent::acp::protocol::{McpServerConfig, SessionMode};
    use gate4agent::HostPolicy;
    use gate4agent_adapters::builtin_adapter_registry;
    use gate4agent_catalog::{EnvMutation, McpServerSpec, ModeId};
    use gate4agent::agent::ForegroundObservation;
    use gate4agent::core::types::{
        AgentEvent, ContextWindowUsage as AgentContextWindowUsage, HostDecisionAuthority,
        HostRequestDecision, HostRequestOutcome, RateLimitType,
    };
    use gate4agent::pty::event::PtyMouseProtocolEncoding;
    use gate4agent::pty::{PtyForegroundObservation, PtyForegroundSource, RateLimitDetector};
    use gate4agent::CliTool;
    use gate4agent_types::{
        AdapterFamily, AgentId, ApprovalLevel,
        HostDecisionAuthority as ProviderHostDecisionAuthority,
        HostRequestDecision as ProviderHostRequestDecision,
        HostRequestOutcome as ProviderHostRequestOutcome, OperatorGateInput,
        OperatorGateKind, OperatorGateOptionSemantics, OperatorGateState, OperatorGateSubject,
        ProviderEvent, ProviderInteractionKind, ProviderInteractionOption, ProviderRuntimePolicy,
        PtyScreenState, RuntimePlatform, TerminalMouseProtocolEncoding, TransportKind,
    };
    use std::ffi::{OsStr, OsString};

    fn snapshot(sequence: u64, contents: &str) -> super::PtyTerminalSnapshot {
        super::PtyTerminalSnapshot {
            pty_id: "fixture".to_owned(),
            provider_revision: "fixture-r1".to_owned(),
            generation: 1,
            sequence,
            size: gate4agent::pty::PtySize { rows: 24, cols: 80 },
            cursor: (0, 0),
            bracketed_paste: false,
            contents: contents.to_owned(),
            formatted: Vec::new(),
            scrollback_formatted: Vec::new(),
            alternate_screen: false,
            mouse_protocol_enabled: false,
            mouse_protocol_encoding: PtyMouseProtocolEncoding::Default,
            produced_at_unix_ms: 0,
        }
    }

    #[test]
    fn terminal_frame_preserves_scrollback_and_terminal_input_metadata() {
        let mut snapshot = snapshot(7, "visible");
        snapshot.scrollback_formatted = vec![b"older".to_vec()];
        snapshot.alternate_screen = true;
        snapshot.mouse_protocol_enabled = true;
        snapshot.mouse_protocol_encoding = PtyMouseProtocolEncoding::Sgr;
        snapshot.produced_at_unix_ms = 1_700_000_000_000;

        let frame = terminal_frame(snapshot, PtyScreenState::default());
        assert_eq!(frame.scrollback_formatted, vec![b"older".to_vec()]);
        assert!(frame.alternate_screen);
        assert!(frame.mouse_protocol_enabled);
        assert_eq!(frame.mouse_protocol_encoding, TerminalMouseProtocolEncoding::Sgr);
        // `terminal_frame` must carry the stamp through, never recompute it.
        assert_eq!(frame.produced_at_unix_ms, 1_700_000_000_000);
    }

    #[test]
    fn terminal_frame_byte_len_sums_formatted_and_every_scrollback_row() {
        let mut snapshot = snapshot(9, "visible");
        snapshot.formatted = b"\x1b[2Jvisible".to_vec();
        snapshot.scrollback_formatted =
            vec![b"row one".to_vec(), b"row two, longer".to_vec()];
        let expected = snapshot.formatted.len()
            + snapshot.scrollback_formatted[0].len()
            + snapshot.scrollback_formatted[1].len();

        let frame = terminal_frame(snapshot, PtyScreenState::default());
        assert_eq!(terminal_frame_byte_len(&frame), expected as u64);
    }

    #[test]
    fn the_sequence_gate_skips_only_when_the_sequence_did_not_advance() {
        assert!(terminal_state_capture_should_skip(Ok::<u64, ()>(5), 5));
        assert!(terminal_state_capture_should_skip(Ok::<u64, ()>(4), 5));
        assert!(!terminal_state_capture_should_skip(Ok::<u64, ()>(6), 5));
        // A failed cheap read never skips -- the real call is attempted so
        // its own error path (stale-published bookkeeping) still runs.
        assert!(!terminal_state_capture_should_skip(Err::<u64, ()>(()), 5));
    }

    #[test]
    fn structured_context_usage_maps_without_pty_inference() {
        let mapped = super::provider_event(
            AgentEvent::ContextWindowUsage {
                usage: AgentContextWindowUsage {
                    uncached_input_tokens: 70,
                    cache_read_tokens: 20,
                    cache_write_tokens: 0,
                    output_tokens: 10,
                    unattributed_tokens: 5,
                    used_tokens: 105,
                    capacity_tokens: 100,
                },
            },
            &[],
        );
        assert_eq!(
            mapped,
            Some(ProviderEvent::ContextWindowUsage {
                usage: gate4agent_types::ContextWindowUsage {
                    uncached_input_tokens: 70,
                    cache_read_tokens: 20,
                    cache_write_tokens: 0,
                    output_tokens: 10,
                    unattributed_tokens: 5,
                    used_tokens: 105,
                    capacity_tokens: 100,
                }
            })
        );
        assert_eq!(
            ProviderEvent::ContextWindowUsage {
                usage: gate4agent_types::ContextWindowUsage {
                    uncached_input_tokens: 70,
                    cache_read_tokens: 20,
                    cache_write_tokens: 0,
                    output_tokens: 10,
                    unattributed_tokens: 5,
                    used_tokens: 104,
                    capacity_tokens: 100,
                },
            }
            .validate_ingress(),
            Err(gate4agent_types::ProviderEventValidationError::ContextWindowSegmentsMismatch {
                segment_sum: 105,
                used_tokens: 104,
            })
        );
        assert!(
            super::provider_event(AgentEvent::PtyRaw { data: b"105/100".to_vec() }, &[]).is_none()
        );
    }

    /// `AgentEvent::TurnInterrupted` (synthesized by `acp::session::
    /// AcpSession::start_prompt` when a `session/prompt` call ends without a
    /// success response) must reach `ProviderEvent::TurnInterrupted` --
    /// `gate4agent-engine`'s snapshot reducer is the one place that resets
    /// `ProviderActivity` away from `Blocked` back to `Idle` for it, closing
    /// the stuck-forever "turn in flight" bug measured live against
    /// codex-acp 1.10.0 (a `session/prompt` RPC error left every subsequent
    /// prompt refused for the rest of the session).
    #[test]
    fn turn_interrupted_maps_to_the_provider_event_that_unblocks_the_next_prompt() {
        let mapped = super::provider_event(
            AgentEvent::TurnInterrupted {
                reason: "session/prompt timed out after 120s".to_owned(),
            },
            &[],
        );
        assert_eq!(mapped, Some(ProviderEvent::TurnInterrupted));
    }

    #[test]
    fn tool_result_non_execution_kind_carries_through_to_tool_completed() {
        let mapped = super::provider_event(
            AgentEvent::ToolResult {
                id: "t1".to_owned(),
                output: "denied".to_owned(),
                is_error: true,
                duration_ms: None,
                non_execution_kind: Some("permission-rule".to_owned()),
            },
            &[],
        );
        assert_eq!(
            mapped,
            Some(ProviderEvent::ToolCompleted {
                id: "t1".to_owned(),
                output: "denied".to_owned(),
                is_error: true,
                duration_ms: None,
                agent_id: None,
                non_execution_kind: Some("permission-rule".to_owned()),
            })
        );
    }

    #[test]
    fn session_end_stop_reason_carries_through_to_session_ended() {
        use gate4agent::StopReason;

        let refusal = super::provider_event(
            AgentEvent::SessionEnd {
                result: "refusal".to_owned(),
                cost_usd: None,
                is_error: true,
                stop_reason: Some(StopReason::Refusal),
            },
            &[],
        );
        assert_eq!(
            refusal,
            Some(ProviderEvent::SessionEnded {
                result: "refusal".to_owned(),
                cost_usd: None,
                is_error: true,
                stop_reason: Some(gate4agent_types::ProviderStopReason::Refusal),
            })
        );

        let quota = super::provider_event(
            AgentEvent::SessionEnd {
                result: "JSON-RPC error -32603: Internal error".to_owned(),
                cost_usd: None,
                is_error: true,
                stop_reason: Some(StopReason::ProviderError {
                    code: -32603,
                    message: "You've hit your usage limit.".to_owned(),
                    vendor_code: Some("usageLimitExceeded".to_owned()),
                }),
            },
            &[],
        );
        assert_eq!(
            quota,
            Some(ProviderEvent::SessionEnded {
                result: "JSON-RPC error -32603: Internal error".to_owned(),
                cost_usd: None,
                is_error: true,
                stop_reason: Some(gate4agent_types::ProviderStopReason::ProviderError {
                    code: -32603,
                    message: "You've hit your usage limit.".to_owned(),
                    vendor_code: Some("usageLimitExceeded".to_owned()),
                }),
            })
        );
    }

    #[test]
    fn host_request_reaches_the_operator_with_method_and_host_decision() {
        let denied = super::provider_event(
            AgentEvent::RpcIncomingRequest {
                id: gate4agent::rpc::message::RpcId::Number(1),
                method: "fs/read_text_file".to_owned(),
                params: None,
                decision: HostRequestDecision::Denied { by: HostDecisionAuthority::Policy },
                outcome: HostRequestOutcome::Executed,
                reason: None,
            },
            &[],
        );
        assert_eq!(
            denied,
            Some(ProviderEvent::HostRequestObserved {
                method: "fs/read_text_file".to_owned(),
                params_json: String::new(),
                decision: ProviderHostRequestDecision::Denied {
                    by: ProviderHostDecisionAuthority::Policy
                },
                outcome: ProviderHostRequestOutcome::Executed,
                reason: None,
            })
        );

        let granted = super::provider_event(
            AgentEvent::RpcIncomingRequest {
                id: gate4agent::rpc::message::RpcId::Number(2),
                method: "terminal/create".to_owned(),
                params: None,
                decision: HostRequestDecision::Granted { by: HostDecisionAuthority::Policy },
                outcome: HostRequestOutcome::Executed,
                reason: None,
            },
            &[],
        );
        assert_eq!(
            granted,
            Some(ProviderEvent::HostRequestObserved {
                method: "terminal/create".to_owned(),
                params_json: String::new(),
                decision: ProviderHostRequestDecision::Granted {
                    by: ProviderHostDecisionAuthority::Policy
                },
                outcome: ProviderHostRequestOutcome::Executed,
                reason: None,
            })
        );

        // Every authority carries through, not just the outcome -- a gate
        // block and an operator's answer must remain distinguishable on the
        // wire, and a deadline expiry must never be mistaken for one.
        let gate_denied = super::provider_event(
            AgentEvent::RpcIncomingRequest {
                id: gate4agent::rpc::message::RpcId::Number(3),
                method: "terminal/create".to_owned(),
                params: None,
                decision: HostRequestDecision::Denied { by: HostDecisionAuthority::Gate },
                outcome: HostRequestOutcome::Executed,
                reason: None,
            },
            &[],
        );
        assert_eq!(
            gate_denied,
            Some(ProviderEvent::HostRequestObserved {
                method: "terminal/create".to_owned(),
                params_json: String::new(),
                decision: ProviderHostRequestDecision::Denied {
                    by: ProviderHostDecisionAuthority::Gate
                },
                outcome: ProviderHostRequestOutcome::Executed,
                reason: None,
            })
        );

        let operator_granted = super::provider_event(
            AgentEvent::RpcIncomingRequest {
                id: gate4agent::rpc::message::RpcId::Number(4),
                method: "session/request_permission".to_owned(),
                params: None,
                decision: HostRequestDecision::Granted { by: HostDecisionAuthority::Operator },
                outcome: HostRequestOutcome::Executed,
                reason: None,
            },
            &[],
        );
        assert_eq!(
            operator_granted,
            Some(ProviderEvent::HostRequestObserved {
                method: "session/request_permission".to_owned(),
                params_json: String::new(),
                decision: ProviderHostRequestDecision::Granted {
                    by: ProviderHostDecisionAuthority::Operator
                },
                outcome: ProviderHostRequestOutcome::Executed,
                reason: None,
            })
        );

        let deadline_denied = super::provider_event(
            AgentEvent::RpcIncomingRequest {
                id: gate4agent::rpc::message::RpcId::Number(5),
                method: "session/request_permission".to_owned(),
                params: None,
                decision: HostRequestDecision::Denied { by: HostDecisionAuthority::DeadlinePolicy },
                outcome: HostRequestOutcome::Executed,
                reason: None,
            },
            &[],
        );
        assert_eq!(
            deadline_denied,
            Some(ProviderEvent::HostRequestObserved {
                method: "session/request_permission".to_owned(),
                params_json: String::new(),
                decision: ProviderHostRequestDecision::Denied {
                    by: ProviderHostDecisionAuthority::DeadlinePolicy
                },
                outcome: ProviderHostRequestOutcome::Executed,
                reason: None,
            })
        );

        // `session/request_permission` + `Deferred` is deliberately absent
        // here -- that combination becomes an `InteractionRequested`, not a
        // `HostRequestObserved`; see
        // `deferred_acp_permission_request_becomes_an_interaction_with_its_id`
        // below.
    }

    /// K1c's split: an authorized (`Granted`) host request that failed
    /// WHILE EXECUTING (e.g. a `terminal/create` spawn error) must carry
    /// `HostRequestOutcome::Failed` through to `ProviderEvent::
    /// HostRequestObserved` verbatim -- never dropped, and never collapsed
    /// into `Denied`: the request WAS authorized, only its execution
    /// failed.
    #[test]
    fn granted_host_request_execution_failure_carries_through_as_a_failed_outcome() {
        let spawn_error = "terminal/create spawn failed: os error 3";
        let mapped = super::provider_event(
            AgentEvent::RpcIncomingRequest {
                id: gate4agent::rpc::message::RpcId::Number(10),
                method: "terminal/create".to_owned(),
                params: None,
                decision: HostRequestDecision::Granted { by: HostDecisionAuthority::Policy },
                outcome: HostRequestOutcome::Failed { error: spawn_error.to_owned() },
                reason: None,
            },
            &[],
        );
        assert_eq!(
            mapped,
            Some(ProviderEvent::HostRequestObserved {
                method: "terminal/create".to_owned(),
                params_json: String::new(),
                decision: ProviderHostRequestDecision::Granted {
                    by: ProviderHostDecisionAuthority::Policy
                },
                outcome: ProviderHostRequestOutcome::Failed { error: spawn_error.to_owned() },
                reason: None,
            })
        );
        mapped.expect("mapped").validate_ingress().expect("bounded free-text error validates");
    }

    /// The bug this change fixes: the gate's own refusal text used to be
    /// computed, then thrown away -- an observer got the categorical
    /// `Denied { by: Gate }` and nothing naming WHY. `reason` now rides the
    /// SAME `AgentEvent::RpcIncomingRequest` → `ProviderEvent::
    /// HostRequestObserved` mapping every other field already used,
    /// verbatim, bounded by `validate_ingress`.
    #[test]
    fn host_request_reason_carries_through_to_the_operator() {
        let gate_text =
            "blocked by dangerous-command gate: rule=filesystem-wipe, argument=rm -rf /";
        let denied = super::provider_event(
            AgentEvent::RpcIncomingRequest {
                id: gate4agent::rpc::message::RpcId::Number(9),
                method: "terminal/create".to_owned(),
                params: None,
                decision: HostRequestDecision::Denied { by: HostDecisionAuthority::Gate },
                outcome: HostRequestOutcome::Executed,
                reason: Some(gate_text.to_owned()),
            },
            &[],
        );
        assert_eq!(
            denied,
            Some(ProviderEvent::HostRequestObserved {
                method: "terminal/create".to_owned(),
                params_json: String::new(),
                decision: ProviderHostRequestDecision::Denied {
                    by: ProviderHostDecisionAuthority::Gate
                },
                outcome: ProviderHostRequestOutcome::Executed,
                reason: Some(gate_text.to_owned()),
            })
        );

        // `validate_ingress` accepts the reason as ordinary bounded free
        // text -- the same bound `ToolCompleted::output` uses, proving this
        // is not smuggled through the categorical `Error::detail` field the
        // owner's incident named (that validator only accepts `a-z0-9-`).
        denied.expect("mapped").validate_ingress().expect("bounded free-text reason validates");
    }

    #[test]
    fn deferred_acp_permission_request_becomes_an_interaction_with_its_id() {
        let with_title = super::provider_event(
            AgentEvent::RpcIncomingRequest {
                id: gate4agent::rpc::message::RpcId::Number(6),
                method: "session/request_permission".to_owned(),
                params: Some(serde_json::json!({
                    "sessionId": "s1",
                    "toolCall": {"toolCallId": "t1", "kind": "edit", "title": "Edit src/main.rs"},
                    "options": [
                        {"optionId": "allow", "name": "Allow", "kind": "allow_once"},
                        {"optionId": "reject", "name": "Reject", "kind": "reject_once"},
                    ],
                })),
                decision: HostRequestDecision::Deferred,
                outcome: HostRequestOutcome::Executed,
                reason: None,
            },
            &[],
        );
        // `kind` is the tool CLASS and `title` is the question. They are two
        // different things and the operator needs both: putting the title in
        // `tool_name` and leaving `prompt` empty -- which this asserted
        // before -- showed a correlation id and a sentence-shaped tool name,
        // and never the question itself. `title`/`options` now carry the
        // agent's own values instead of arriving empty -- the operator's
        // approve/deny answer must resolve against an option list they can
        // actually see.
        assert_eq!(
            with_title,
            Some(ProviderEvent::InteractionRequested {
                request_id: Some("number:6".to_owned()),
                interaction_kind: ProviderInteractionKind::Approval,
                tool_name: "edit".to_owned(),
                title: Some("Edit src/main.rs".to_owned()),
                prompt: "Edit src/main.rs".to_owned(),
                options: vec![
                    ProviderInteractionOption {
                        option_id: "allow".to_owned(),
                        name: "Allow".to_owned(),
                        kind: "allow_once".to_owned(),
                    },
                    ProviderInteractionOption {
                        option_id: "reject".to_owned(),
                        name: "Reject".to_owned(),
                        kind: "reject_once".to_owned(),
                    },
                ],
                agent_id: None,
            })
        );

        // No `kind` on the wire (or no params at all) -- falls back to the
        // method name rather than an empty `tool_name`, which
        // `ProviderEvent::validate_ingress` rejects. An absent `title`
        // leaves `prompt` empty rather than inventing a question, and no
        // params at all means no option list to read, not a dropped one.
        let without_title = super::provider_event(
            AgentEvent::RpcIncomingRequest {
                id: gate4agent::rpc::message::RpcId::String("agent-7".to_owned()),
                method: "session/request_permission".to_owned(),
                params: None,
                decision: HostRequestDecision::Deferred,
                outcome: HostRequestOutcome::Executed,
                reason: None,
            },
            &[],
        );
        assert_eq!(
            without_title,
            Some(ProviderEvent::InteractionRequested {
                request_id: Some("string:agent-7".to_owned()),
                interaction_kind: ProviderInteractionKind::Approval,
                tool_name: "session/request_permission".to_owned(),
                title: None,
                prompt: String::new(),
                options: Vec::new(),
                agent_id: None,
            })
        );

        // The SAME id's eventual outcome (not itself `Deferred` anymore)
        // still reaches the operator as the ordinary audit trail, exactly
        // as every other host request does.
        let resolved = super::provider_event(
            AgentEvent::RpcIncomingRequest {
                id: gate4agent::rpc::message::RpcId::Number(6),
                method: "session/request_permission".to_owned(),
                params: None,
                decision: HostRequestDecision::Denied { by: HostDecisionAuthority::Operator },
                outcome: HostRequestOutcome::Executed,
                reason: None,
            },
            &[],
        );
        assert_eq!(
            resolved,
            Some(ProviderEvent::HostRequestObserved {
                method: "session/request_permission".to_owned(),
                params_json: String::new(),
                decision: ProviderHostRequestDecision::Denied {
                    by: ProviderHostDecisionAuthority::Operator
                },
                outcome: ProviderHostRequestOutcome::Executed,
                reason: None,
            })
        );
    }

    #[test]
    fn unrecognized_notification_reaches_the_operator_as_a_raw_event_instead_of_vanishing() {
        let mapped = super::provider_event(
            AgentEvent::RpcNotification {
                method: "session/update".to_owned(),
                params: Default::default(),
            },
            &[],
        );
        assert_eq!(
            mapped,
            Some(ProviderEvent::UnrecognizedNotification {
                method: "session/update".to_owned(),
                payload_json: "null".to_owned(),
            })
        );
    }

    #[test]
    fn pty_terminal_capability_defaults_never_override_a_caller_supplied_term() {
        let caller_supplied = vec![EnvMutation {
            key: OsString::from("TERM"),
            value: Some(OsString::from("dumb")),
        }];
        let filled = with_pty_terminal_capability_defaults(caller_supplied);

        let term_values: Vec<_> = filled
            .iter()
            .filter(|mutation| mutation.key.as_os_str() == OsStr::new("TERM"))
            .collect();
        assert_eq!(term_values.len(), 1, "TERM must not be duplicated");
        assert_eq!(term_values[0].value.as_deref(), Some(OsStr::new("dumb")));

        let colorterm = filled
            .iter()
            .find(|mutation| mutation.key.as_os_str() == OsStr::new("COLORTERM"))
            .expect("COLORTERM default is filled in when the caller left it unset");
        assert_eq!(colorterm.value.as_deref(), Some(OsStr::new("truecolor")));
    }

    // -----------------------------------------------------------------------
    // mcp_server_acp_entry — the ACP half of the door
    // (gate4agent-arc-mailbox-and-task-layer Slice A(ii))
    // -----------------------------------------------------------------------

    #[test]
    fn mcp_server_acp_entry_translates_a_spec_into_one_stdio_entry() {
        let spec = McpServerSpec::new(
            "test-mcp-server",
            OsString::from("C:\\example\\example-mcp-server.exe"),
            vec![OsString::from("--session-proxy")],
            vec![
                (
                    OsString::from("TEST_MCP_SESSION_ENDPOINT"),
                    OsString::from("\\\\.\\pipe\\example-mcp-server-s1"),
                ),
                (
                    OsString::from("TEST_MCP_SESSION_TOKEN"),
                    OsString::from("tok-abc"),
                ),
            ],
        )
        .unwrap();

        let server = mcp_server_acp_entry(&spec);
        match server {
            McpServerConfig::Stdio { name, command, args, env } => {
                assert_eq!(name, "test-mcp-server", "ACP v1 requires a name; the adapter registers by it");
                assert_eq!(command, "C:\\example\\example-mcp-server.exe");
                assert_eq!(args, vec!["--session-proxy".to_string()]);
                assert_eq!(env.len(), 2, "exactly the entries the spec was given, nothing else");
                assert_eq!(
                    env.iter().find(|pair| pair.name == "TEST_MCP_SESSION_ENDPOINT").map(|pair| pair.value.as_str()),
                    Some("\\\\.\\pipe\\example-mcp-server-s1")
                );
                assert_eq!(
                    env.iter().find(|pair| pair.name == "TEST_MCP_SESSION_TOKEN").map(|pair| pair.value.as_str()),
                    Some("tok-abc")
                );
            }
            McpServerConfig::Sse { .. } => panic!("expected Stdio variant"),
        }
    }

    #[test]
    fn mcp_server_acp_entry_carries_zero_env_pairs_when_the_spec_carries_none() {
        let spec = McpServerSpec::new(
            "test-mcp-server",
            OsString::from("C:\\example\\example-mcp-server.exe"),
            vec![OsString::from("--session-proxy")],
            Vec::new(),
        )
        .unwrap();

        let server = mcp_server_acp_entry(&spec);
        match server {
            McpServerConfig::Stdio { env, .. } => assert!(env.is_empty()),
            McpServerConfig::Sse { .. } => panic!("expected Stdio variant"),
        }
    }

    #[test]
    fn credential_shape_rule_matches_prefixed_hex64_not_bare_digest_or_uuid() {
        let hex64 = "a1b2c3d4e5f6".repeat(5) + "a1b2";
        assert_eq!(hex64.len(), 64);

        let prefixed_token = format!("g4aho_{hex64}");
        assert!(
            argument_looks_like_credential(&prefixed_token),
            "a short lowercase prefix plus '_' plus 64 lowercase hex chars is a credential"
        );

        assert!(
            !argument_looks_like_credential(&hex64),
            "a bare 64-hex digest with no prefix is a legitimate diagnostic, not a credential"
        );

        assert!(
            !argument_looks_like_credential("550e8400-e29b-41d4-a716-446655440000"),
            "a UUID must not be mistaken for a prefixed-hex64 credential"
        );
    }

    #[test]
    fn native_instance_launch_arguments_fail_closed_before_shell_spawn() {
        let claude = AgentId::new("claude").unwrap();
        assert_eq!(
            validate_instance_launch_arguments(
                &claude,
                TransportKind::Pipe,
                &[OsString::from("--bundle-mode")],
            )
            .unwrap_err(),
            "native instance launch arguments require PTY transport"
        );
        assert_eq!(
            validate_instance_launch_arguments(
                &claude,
                TransportKind::Pty,
                &[OsString::from("--resume=session-secret")],
            )
            .unwrap_err(),
            "native instance launch arguments conflict with Claude session, resume, or prompt authority"
        );
        assert!(validate_instance_launch_arguments(
            &claude,
            TransportKind::Pty,
            &[
                OsString::from("--permission-mode"),
                OsString::from("default"),
            ],
        )
        .is_ok());
    }

    /// Classifies `contents` and returns just the `kind` -- the same check
    /// every case below cares about, without repeating `.map(|gate|
    /// gate.kind)` at every call site.
    fn kind_of(contents: &str) -> Option<OperatorGateKind> {
        startup_operator_gate(contents).map(|gate| gate.kind)
    }

    #[test]
    fn startup_operator_gates_are_classified_without_returning_terminal_text() {
        assert_eq!(kind_of(" Trust this\nfolder? "), Some(OperatorGateKind::WorkspaceTrust));
        assert_eq!(
            kind_of("No auth type is selected"),
            Some(OperatorGateKind::Authentication)
        );
        assert_eq!(
            kind_of("Sign in with OpenAI to use Codex"),
            Some(OperatorGateKind::Authentication)
        );
        // Claude's login-method chooser and its OAuth code-paste wait
        // screen -- both previously misread as `Ready` because neither
        // contains "openai"/"chatgpt"/"codex", so the branch above never
        // caught them. Verbatim shape from `terminal-read` on a clean
        // macOS arm64 stand with no vendor login.
        assert_eq!(
            kind_of(
                "Claude Code can be used with your Claude subscription or billed based on \
                 API usage through your Console account.\n\
                 Select login method:\n\
                 \u{276f} 1. Claude ...\n\
                 2. API usage billing\n\
                 3. 3rd-party platform \u{b7} Amazon Bedrock ..."
            ),
            Some(OperatorGateKind::Authentication)
        );
        assert_eq!(
            kind_of(
                "Browser didn't open? Use the url below to sign in (c to copy)\n\
                 https://claude.com/oauth/authorize?client_id=abc&redirect_uri=https%3A%2F%2Fconsole.anthropic.com&code_challenge=xyz\n\
                 Paste code here"
            ),
            Some(OperatorGateKind::Authentication)
        );
        // Ordinary narration reusing "sign in" and "paste" separately, but
        // never as the screen's own "paste code" field label, must not
        // false-positive -- the same companion-word discipline the
        // OpenAI/Codex sign-in branch already applies above.
        assert_eq!(
            kind_of(
                "Once you sign in, copy the generated token and paste it into your .env file; \
                 no code entry happens on this screen."
            ),
            None
        );
        assert_eq!(
            kind_of("Kimi Code Update Available\nInstall update now (0.32.0)\nEnter confirm"),
            Some(OperatorGateKind::VendorUpdate)
        );
        assert_eq!(
            kind_of(
                "Welcome to Claude Code\nChoose the text style that looks best with your terminal"
            ),
            Some(OperatorGateKind::TerminalAppearance)
        );
        assert_eq!(
            kind_of(
                "Welcome to Claude Code for VS Code\nClaude has context of open files and selected lines"
            ),
            Some(OperatorGateKind::Onboarding)
        );
        assert_eq!(
            kind_of("Welcome to Claude Code\n❯ Press Enter to continue"),
            Some(OperatorGateKind::Onboarding)
        );
        assert_eq!(kind_of("Welcome to Claude Code\n❯ ready\nEnter to send"), None);
        assert_eq!(
            kind_of(
                "Quick safety check: Is this a project you trust?\nYes, I trust this folder\nNo, continue without these permissions"
            ),
            Some(OperatorGateKind::WorkspaceTrust)
        );
        assert_eq!(kind_of("ready for a prompt"), None);
        // Regression test for the incident this module fixes: a provider
        // CLI's wrapper self-updated via npm before the real agent ever
        // launched, and every consumer saw `status: running` on a live PTY
        // that was actually showing this text. Verbatim transcript.
        assert_eq!(
            kind_of(
                "Updating Codex via `npm install -g @openai/codex`...\n\
                 npm warn cleanup Failed to remove some directories\n\
                 Update ran successfully! Please restart Codex."
            ),
            Some(OperatorGateKind::VendorUpdate)
        );
        // Regression test for the live-stand incident this branch fixes:
        // Codex's startup hook-trust prompt was classified `Ready` because
        // no marker recognized it, so a prompt injected into the PTY landed
        // in this blocking select-list instead of the agent. Verbatim
        // transcript from `terminal-read`, 40x120 -- note this capture wraps
        // the `› 1. Review hooks` marker onto the end of the preceding
        // sentence, so it is deliberately NOT the clean list shape the
        // dedicated option-parsing tests below assert on; this test only
        // pins the `kind`, same as it always has.
        assert_eq!(
            kind_of(
                "  Hooks need review\n\
                   6 hooks are new or changed.\n\
                   Hooks can run outside the sandbox after you trust them.\u{203a} 1. Review hooks\n\
                   2. Trust all and continue\n\
                   3. Continue without trusting (hooks won't run)  Press enter to confirm or esc to go back"
            ),
            Some(OperatorGateKind::HookTrust)
        );
        // Same screen, different hook count -- the match must not depend on
        // the number.
        assert_eq!(
            kind_of(
                "  Hooks need review\n\
                   42 hooks are new or changed.\n\
                   Hooks can run outside the sandbox after you trust them.\u{203a} 1. Review hooks\n\
                   2. Trust all and continue\n\
                   3. Continue without trusting (hooks won't run)  Press enter to confirm or esc to go back"
            ),
            Some(OperatorGateKind::HookTrust)
        );
        // Ordinary agent narration that happens to mention hooks and trust
        // must NOT be classified as this gate -- it lacks the screen's own
        // "continue without trusting" refusal phrasing.
        assert_eq!(
            kind_of(
                "I reviewed the pre-commit hooks in this repo and they look safe to trust; \
                 I'll leave the hooks config as-is and continue with the refactor."
            ),
            None
        );
    }

    /// Codex's hook-trust prompt rendered as a clean numbered list (the
    /// shape actually described by the task this parser was written for,
    /// as opposed to the line-wrapped capture pinned by `kind` alone
    /// above): `parse_operator_gate_options` reads all three choices, marks
    /// the `›`-prefixed one selected, and infers accept/inspect/decline
    /// from each option's own verb -- never from its number or position.
    #[test]
    fn startup_operator_gate_parses_a_numbered_hook_trust_option_list() {
        let contents = "Hooks need review\n\
             \u{203a} 1. Review hooks\n  \
             2. Trust all and continue\n  \
             3. Continue without trusting (hooks won't run)\n\
             Press enter to confirm or esc to go back";
        let gate = startup_operator_gate(contents).expect("hook trust must classify");
        assert_eq!(gate.kind, OperatorGateKind::HookTrust);
        assert_eq!(gate.input, OperatorGateInput::NumberedList);
        assert_eq!(
            gate.options,
            vec![
                gate4agent_types::OperatorGateOption {
                    text: "Review hooks".to_owned(),
                    semantics: OperatorGateOptionSemantics::Inspect,
                    selected: true,
                },
                gate4agent_types::OperatorGateOption {
                    text: "Trust all and continue".to_owned(),
                    semantics: OperatorGateOptionSemantics::Accept,
                    selected: false,
                },
                gate4agent_types::OperatorGateOption {
                    text: "Continue without trusting (hooks won't run)".to_owned(),
                    semantics: OperatorGateOptionSemantics::Decline,
                    selected: false,
                },
            ],
        );
    }

    /// Kimi's workspace-trust prompt rendered as an arrow-navigated list
    /// with a description line under each title: `parse_operator_gate_options`
    /// reads the two TITLES ("Trust this folder", "Don't trust") as options,
    /// marks the `❯`-prefixed one selected, and does NOT mistake either
    /// description line (both full sentences, ending in `.`) for a third
    /// and fourth option.
    #[test]
    fn startup_operator_gate_parses_an_arrow_workspace_trust_option_list() {
        let contents = "Do you trust the files in this folder?\n  \
             Trust this folder\n  \
             Enable project MCP servers. Remembered for this folder.\n\u{276f} \
             Don't trust\n  \
             Exit Kimi Code. Asked again next launch.\n  \
             \u{2191}\u{2193} navigate \u{b7} Enter select \u{b7} Esc exit";
        let gate = startup_operator_gate(contents).expect("workspace trust must classify");
        assert_eq!(gate.kind, OperatorGateKind::WorkspaceTrust);
        assert_eq!(gate.input, OperatorGateInput::ArrowList);
        assert_eq!(
            gate.options,
            vec![
                gate4agent_types::OperatorGateOption {
                    text: "Trust this folder".to_owned(),
                    semantics: OperatorGateOptionSemantics::Accept,
                    selected: false,
                },
                gate4agent_types::OperatorGateOption {
                    text: "Don't trust".to_owned(),
                    semantics: OperatorGateOptionSemantics::Decline,
                    selected: true,
                },
            ],
        );
    }

    /// A matched gate whose screen carries no recognized option list (every
    /// other `kind` this module classifies today) must NOT invent one --
    /// `input` stays `Unknown` and `options` stays empty, never a guess.
    #[test]
    fn startup_operator_gate_without_a_recognized_option_list_reports_unknown_input() {
        let gate = startup_operator_gate("No auth type is selected")
            .expect("authentication must classify");
        assert_eq!(gate.kind, OperatorGateKind::Authentication);
        assert_eq!(gate.input, OperatorGateInput::Unknown);
        assert!(gate.options.is_empty());
    }

    /// Claude's login-method chooser renders its selected row with a `❯`
    /// cursor glyph where Codex draws `›`, and both sit AHEAD of the number rather
    /// than ahead of the text. `parse_numbered_gate_option_line` knew only
    /// Codex's glyph, so the cursor row failed to parse as an option at
    /// all: the list came back one item short AND with nothing marked
    /// selected -- observed live on this screen and on Codex's own login
    /// chooser. Both glyphs are read now, so all three options are present
    /// and the cursor row carries `selected`.
    #[test]
    fn startup_operator_gate_parses_claudes_login_method_chooser_including_its_cursor_row() {
        let contents = "Select login method:\n\
             \u{276f} 1. Claude ...\n\
             2. API usage billing\n\
             3. 3rd-party platform \u{b7} Amazon Bedrock ...";
        let gate = startup_operator_gate(contents).expect("authentication must classify");
        assert_eq!(gate.kind, OperatorGateKind::Authentication);
        assert_eq!(gate.subject, OperatorGateSubject::Account);
        assert_eq!(gate.input, OperatorGateInput::NumberedList);
        assert_eq!(
            gate.options,
            vec![
                gate4agent_types::OperatorGateOption {
                    text: "Claude ...".to_owned(),
                    semantics: OperatorGateOptionSemantics::Unknown,
                    selected: true,
                },
                gate4agent_types::OperatorGateOption {
                    text: "API usage billing".to_owned(),
                    semantics: OperatorGateOptionSemantics::Unknown,
                    selected: false,
                },
                gate4agent_types::OperatorGateOption {
                    text: "3rd-party platform \u{b7} Amazon Bedrock ...".to_owned(),
                    semantics: OperatorGateOptionSemantics::Unknown,
                    selected: false,
                },
            ],
        );
    }

    /// Claude's OAuth wait screen has no option list at all -- a URL to
    /// open and one free-text slot to paste the resulting code back into --
    /// so `input` is `TextEntry` with no options, never routed through the
    /// numbered/arrow option-list parser.
    #[test]
    fn startup_operator_gate_oauth_wait_screen_reports_text_entry_input() {
        let contents = "Browser didn't open? Use the url below to sign in (c to copy)\n\
             https://claude.com/oauth/authorize?client_id=abc&redirect_uri=https%3A%2F%2Fconsole.anthropic.com&code_challenge=xyz\n\
             Paste code here";
        let gate = startup_operator_gate(contents).expect("oauth wait screen must classify");
        assert_eq!(gate.kind, OperatorGateKind::Authentication);
        assert_eq!(gate.subject, OperatorGateSubject::Account);
        assert_eq!(gate.input, OperatorGateInput::TextEntry);
        assert!(gate.options.is_empty());
    }

    /// `parse_operator_gate_options` is the parser both dedicated tests
    /// above exercise indirectly through `startup_operator_gate`; this pins
    /// it directly against the same two shapes so a regression in the
    /// standalone parser is caught even if some future `kind` branch stops
    /// calling it through `operator_gate`.
    #[test]
    fn parse_operator_gate_options_recognizes_numbered_and_arrow_shapes_and_nothing_else() {
        assert_eq!(
            parse_operator_gate_options("Press enter to confirm or esc to go back"),
            (OperatorGateInput::Unknown, Vec::new()),
        );
        let (input, options) = parse_operator_gate_options(
            "\u{203a} 1. Review hooks\n  2. Trust all and continue",
        );
        assert_eq!(input, OperatorGateInput::NumberedList);
        assert_eq!(options.len(), 2);
        let (input, options) = parse_operator_gate_options(
            "  Trust this folder\n  Enable project MCP servers. Remembered for this folder.\n\u{276f} Don't trust",
        );
        assert_eq!(input, OperatorGateInput::ArrowList);
        assert_eq!(options.len(), 2);
    }

    #[test]
    fn classify_operator_gate_option_semantics_reads_the_verb_not_the_position() {
        assert_eq!(
            classify_operator_gate_option_semantics("Review hooks"),
            OperatorGateOptionSemantics::Inspect,
        );
        assert_eq!(
            classify_operator_gate_option_semantics("Trust all and continue"),
            OperatorGateOptionSemantics::Accept,
        );
        assert_eq!(
            classify_operator_gate_option_semantics("Continue without trusting (hooks won't run)"),
            OperatorGateOptionSemantics::Decline,
        );
        assert_eq!(
            classify_operator_gate_option_semantics("Don't trust"),
            OperatorGateOptionSemantics::Decline,
        );
        assert_eq!(
            classify_operator_gate_option_semantics("Exit Kimi Code"),
            OperatorGateOptionSemantics::Exit,
        );
        assert_eq!(
            classify_operator_gate_option_semantics("Something unrecognized"),
            OperatorGateOptionSemantics::Unknown,
        );
    }

    #[test]
    fn screen_failure_recognizes_crash_and_missing_command_banners() {
        assert_eq!(
            screen_failure("thread 'main' panicked at 'index out of bounds', src/main.rs:12:5"),
            Some("crash")
        );
        assert_eq!(
            screen_failure("Traceback (most recent call last):\n  File \"a.py\", line 1"),
            Some("crash")
        );
        assert_eq!(
            screen_failure("bash: fooagent: command not found"),
            Some("missing command")
        );
        assert_eq!(
            screen_failure("C:\\workspace> fooagent\n'fooagent' is not recognized as an internal or external command"),
            Some("missing command")
        );
        assert_eq!(
            screen_failure(
                "workspace/project $ fooagent: no such file or directory\nworkspace/project $"
            ),
            Some("missing command")
        );
        // Bare ENOENT prose with no trailing shell-prompt line is exactly
        // the generic case this bucket must NOT fire on alone.
        assert_eq!(
            screen_failure("The build log mentions no such file or directory near line 40."),
            None
        );
        // `"fatal error:"` was deliberately dropped: a build step inside a
        // wrapper script can print this while the real CLI still comes up
        // fine, so it is not a crash SHAPE this function trusts at all.
        assert_eq!(
            screen_failure("fooagent-installer: fatal error: missing header <stdio.h>"),
            None
        );
    }

    #[test]
    fn screen_failure_recognizes_grok_missing_api_key_banner() {
        // Verbatim transcript: Grok launched with no credential configured
        // prints exactly this one line and never renders anything else --
        // no gate to answer, no crash trace, just a dead PTY a blind
        // `Ready` write would silently swallow.
        assert_eq!(
            screen_failure(
                "\u{274c} Error: API key required. Set GROK_API_KEY environment variable, \
                 use --api-key flag, or set \"apiKey\" field in ~/.grok/user-settings.json"
            ),
            Some("missing api key")
        );
        // Generic prose about needing an API key, with no vendor-specific
        // env var name, must not false-positive -- an agent explaining a
        // DIFFERENT provider's setup routinely says exactly this.
        assert_eq!(
            screen_failure(
                "You'll need an API key for this provider before it works; check the docs \
                 for how to configure one."
            ),
            None
        );
    }

    #[test]
    fn screen_failure_no_longer_has_an_authentication_expired_bucket() {
        // Two common words matched anywhere on one 80x24 screen is not a
        // signal -- an agent's own prose explaining an auth bug ("the
        // token has expired") used to flip a healthy session to `Failing`.
        // The bucket is gone entirely, not narrowed.
        assert_eq!(
            screen_failure("Your session token has expired. Please re-authenticate."),
            None
        );
        assert_eq!(
            screen_failure("The stored credential was revoked by the workspace admin."),
            None
        );
    }

    #[test]
    fn screen_failure_does_not_false_positive_on_an_agent_narrating_an_error() {
        // The false-positive direction matters more than coverage here: an
        // agent CLI renders arbitrary text back at a human, including logs
        // and error messages it was asked to explain. None of the phrases
        // below are in the exact failure SHAPE this module matches on.
        let narration = "I looked at the traceback you pasted -- it's a Python \
             exception, a plain ValueError from a retry loop, not a real crash. \
             Our harness logs the word fatal in its own banner for visibility, \
             but nothing actually panicked. The command definitely exists; it \
             just needed different flags, and your token is still valid.";
        assert_eq!(screen_failure(narration), None);
    }

    #[test]
    fn screen_failure_for_generation_ignores_every_marker_once_the_session_was_ever_ready() {
        // Each of these is a screen from a HEALTHY, already-`Ready` session
        // whose own routine work happens to render a crash-shaped string.
        // This is the regression this whole gate exists to close: before
        // it, every one of these flipped a working session to `Failing`.
        let shell_command_not_found = "$ frobnicate --help\nbash: frobnicate: command not found\n$";
        assert_eq!(
            screen_failure_for_generation(shell_command_not_found, true),
            None
        );

        let python_traceback_from_a_ran_script = "$ python broken.py\n\
             Traceback (most recent call last):\n  File \"broken.py\", line 3, in <module>\n\
             ValueError: bad input\n$";
        assert_eq!(
            screen_failure_for_generation(python_traceback_from_a_ran_script, true),
            None
        );

        let cargo_test_panic = "running 1 test\n\
             error[E0308]: mismatched types\n\
             thread 'tests::it_fails' panicked at 'assertion failed', src/lib.rs:9:5\n\
             test result: FAILED. 0 passed; 1 failed";
        assert_eq!(screen_failure_for_generation(cargo_test_panic, true), None);

        let agent_narrating_an_expired_token = "The API token has expired; \
             I revoked the old credential and issued a new one for you.";
        assert_eq!(
            screen_failure_for_generation(agent_narrating_an_expired_token, true),
            None
        );

        // Pin the narrowing from the other side too: the exact same
        // screens are still real evidence of a broken LAUNCH inside the
        // startup window, before this generation has ever rendered its
        // own UI.
        assert_eq!(
            screen_failure_for_generation(shell_command_not_found, false),
            Some("missing command")
        );
        assert_eq!(
            screen_failure_for_generation(python_traceback_from_a_ran_script, false),
            Some("crash")
        );
        assert_eq!(screen_failure_for_generation(cargo_test_panic, false), Some("crash"));
    }

    #[test]
    fn classify_pty_screen_state_lets_a_foreign_process_win_over_a_matching_gate_text() {
        // The process signal outranks the text signal outright: it does not
        // need to recognize an updater's specific wording to know the
        // screen is not the agent's, so it wins even when the text ALSO
        // happens to match a known gate pattern.
        let foreign = ForegroundVerdict::Foreign {
            process: "npm".to_owned(),
        };
        assert_eq!(
            classify_pty_screen_state(Some(&foreign), None, None),
            PtyScreenState::NotAgent {
                observed_process: "npm".to_owned()
            }
        );
        let vendor_update_gate = OperatorGateState::new(OperatorGateKind::VendorUpdate);
        assert_eq!(
            classify_pty_screen_state(Some(&foreign), Some(&vendor_update_gate), None),
            PtyScreenState::NotAgent {
                observed_process: "npm".to_owned()
            }
        );
    }

    #[test]
    fn classify_pty_screen_state_reports_a_gate_only_when_foreground_matches() {
        let authentication_gate = OperatorGateState::new(OperatorGateKind::Authentication);
        assert_eq!(
            classify_pty_screen_state(Some(&ForegroundVerdict::Agent), Some(&authentication_gate), None),
            PtyScreenState::OperatorGate {
                gate: authentication_gate.clone()
            }
        );
    }

    #[test]
    fn classify_pty_screen_state_reports_failing_for_a_matched_foreground() {
        assert_eq!(
            classify_pty_screen_state(Some(&ForegroundVerdict::Agent), None, Some("crash")),
            PtyScreenState::Failing {
                reason: "crash".to_owned()
            }
        );
    }

    #[test]
    fn classify_pty_screen_state_prefers_failing_over_a_co_occurring_gate() {
        // Pins the precedence: a crashed screen can still carry a leftover
        // gate prompt above the crash dump, and `Failing` is the more
        // urgent of the two truths.
        let authentication_gate = OperatorGateState::new(OperatorGateKind::Authentication);
        assert_eq!(
            classify_pty_screen_state(
                Some(&ForegroundVerdict::Agent),
                Some(&authentication_gate),
                Some("crash")
            ),
            PtyScreenState::Failing {
                reason: "crash".to_owned()
            }
        );
    }

    #[test]
    fn classify_pty_screen_state_reaches_ready_only_with_matched_foreground_and_clean_text() {
        assert_eq!(
            classify_pty_screen_state(Some(&ForegroundVerdict::Agent), None, None),
            PtyScreenState::Ready
        );
    }

    #[test]
    fn classify_pty_screen_state_never_reaches_ready_without_a_foreground_observation() {
        // The one case that must never regress: a clean text read alone is
        // never proof of `Ready`.
        assert_eq!(classify_pty_screen_state(None, None, None), PtyScreenState::Unknown);
    }

    #[test]
    fn resolve_foreground_verdict_tolerates_a_spawning_wrapper_like_readiness_does() {
        // The fixture spec's `expected_processes` does not name "node", so
        // this only passes if the wrapper-tolerance branch (mirroring
        // `ReadinessTracker::observe_foreground`'s own `node`/`python`/
        // `python3` tolerance) is actually what resolves it -- proving the
        // existing wrapper tolerance is not regressed. Fed into
        // `classify_pty_screen_state` with clean text, this is what reaches
        // `Ready` rather than `NotAgent` for a legitimate spawning wrapper.
        let spec = gate4agent_testkit::interactive_agent_spec();
        let observation = PtyForegroundObservation {
            root_pid: 1,
            observed_pid: 2,
            observed_process: "node".to_owned(),
            readiness: ForegroundObservation {
                process_name: Some("node".to_owned()),
                has_child_processes: true,
                is_shell: false,
            },
            source: PtyForegroundSource::ProcessTree,
        };
        let verdict = resolve_foreground_verdict(&spec, &observation, RuntimePlatform::current());
        assert_eq!(verdict, ForegroundVerdict::Agent);
        assert_eq!(
            classify_pty_screen_state(Some(&verdict), None, None),
            PtyScreenState::Ready
        );
    }

    #[test]
    fn foreground_probe_disarms_only_once_ready_and_rearms_on_a_fresh_gate() {
        assert_eq!(
            foreground_probe_schedule(&PtyScreenState::Ready),
            ForegroundProbeSchedule::Disarmed
        );
        assert_eq!(
            foreground_probe_schedule(&PtyScreenState::Unknown),
            ForegroundProbeSchedule::Armed
        );
        assert_eq!(
            foreground_probe_schedule(&PtyScreenState::OperatorGate {
                gate: OperatorGateState::new(OperatorGateKind::VendorUpdate)
            }),
            ForegroundProbeSchedule::Armed
        );
    }

    #[test]
    fn text_only_gate_transition_rearms_the_probe_only_when_leaving_ready() {
        let gate = PtyScreenState::OperatorGate {
            gate: OperatorGateState::new(OperatorGateKind::VendorUpdate),
        };
        assert!(foreground_probe_rearms_immediately(
            &PtyScreenState::Ready,
            &gate
        ));
        // Was never `Ready` in the first place -- nothing to rearm early
        // for, the session's normal cadence already has it covered.
        assert!(!foreground_probe_rearms_immediately(
            &PtyScreenState::Unknown,
            &gate
        ));
    }

    #[test]
    fn readiness_diagnostics_detects_an_ansi_split_gate_without_exposing_text() {
        let mut diagnostics = ReadinessDiagnostics::default();
        diagnostics.observe_output(b"\x1b[31mNo auth ");
        diagnostics.observe_output(b"\x1b[0mtype is selected");
        assert_eq!(
            diagnostics.operator_gate.as_ref().map(|gate| gate.kind),
            Some(OperatorGateKind::Authentication)
        );
        assert!(!diagnostics.summary().contains("No auth"));
    }

    #[test]
    fn semantic_utf8_decoder_preserves_codepoints_split_across_pty_reads() {
        let mut decoder = Utf8ChunkDecoder::default();
        let bytes = "ready Привет".as_bytes();
        let split = bytes
            .windows(2)
            .position(|window| window[0] >= 0x80 && window[1] >= 0x80)
            .expect("Cyrillic text contains adjacent UTF-8 bytes")
            + 1;
        let first = decoder.push(&bytes[..split]);
        let second = decoder.push(&bytes[split..]);
        assert_eq!(format!("{first}{second}"), "ready Привет");
        assert!(!first.contains('\u{fffd}'));
        assert!(!second.contains('\u{fffd}'));
    }

    #[test]
    fn semantic_utf8_decoder_replaces_invalid_bytes_without_stalling() {
        let mut decoder = Utf8ChunkDecoder::default();
        assert_eq!(decoder.push(b"ok\xfftail"), "ok\u{fffd}tail");
        assert_eq!(decoder.push(" Привет".as_bytes()), " Привет");
    }

    #[test]
    fn fresh_claude_pty_preassigns_the_exact_vendor_session_id_argv() {
        let claude = builtin_adapter_registry()
            .binding(AdapterFamily::PtySemantic, "claude-code")
            .expect("Claude PTY binding");
        let mut args = Vec::new();
        let identity = prepare_fresh_pty_provider_session(Some(claude), false, true, &mut args)
            .expect("fresh Claude provider identity");
        let parsed = uuid::Uuid::parse_str(&identity.id).expect("valid Claude UUID");
        assert_eq!(parsed.get_version_num(), 4);
        assert_eq!(identity.key, gate4agent_types::ProviderSessionKey::SessionId);
        assert!(identity.transcript_path.is_none());
        assert_eq!(args, [OsString::from("--session-id"), OsString::from(identity.id)]);
    }

    #[test]
    fn fresh_codex_and_resumed_claude_do_not_preassign_a_second_identity() {
        let adapters = builtin_adapter_registry();
        let codex = adapters
            .binding(AdapterFamily::PtySemantic, "codex")
            .expect("Codex PTY binding");
        let claude = adapters
            .binding(AdapterFamily::PtySemantic, "claude-code")
            .expect("Claude PTY binding");
        let mut codex_args = Vec::new();
        assert!(prepare_fresh_pty_provider_session(Some(codex), false, true, &mut codex_args)
            .is_none());
        assert!(codex_args.is_empty());

        let mut resume_args = vec![OsString::from("--resume"), OsString::from("vendor-id")];
        assert!(prepare_fresh_pty_provider_session(Some(claude), true, true, &mut resume_args)
            .is_none());
        assert_eq!(
            resume_args,
            [OsString::from("--resume"), OsString::from("vendor-id")]
        );
    }

    #[test]
    fn raw_pty_policy_omits_all_identity_and_semantic_startup_paths() {
        let adapters = builtin_adapter_registry();
        let claude = adapters
            .binding(AdapterFamily::PtySemantic, "claude-code")
            .expect("Claude PTY binding");
        let codex = adapters
            .binding(AdapterFamily::PtySemantic, "codex")
            .expect("Codex PTY binding");
        let kimi = adapters
            .binding(AdapterFamily::PtySemantic, "kimi")
            .expect("Kimi PTY binding");
        let policy = ProviderRuntimePolicy::raw_pty();
        let mut args = Vec::new();

        assert!(prepare_fresh_pty_provider_session(Some(claude), false, false, &mut args)
            .is_none());
        assert!(args.is_empty());
        assert!(!should_probe_pty_identity(policy, Some(codex), false, "codex"));
        assert!(!should_probe_pty_identity(policy, Some(kimi), false, "kimi"));
        assert!(!should_attach_pty_provider_stream(policy));
    }

    #[test]
    fn identity_probe_requires_structured_prompt_for_codex_and_kimi() {
        let adapters = builtin_adapter_registry();
        let codex = adapters
            .binding(AdapterFamily::PtySemantic, "codex")
            .expect("Codex PTY binding");
        let kimi = adapters
            .binding(AdapterFamily::PtySemantic, "kimi")
            .expect("Kimi PTY binding");
        let without_structured_prompt =
            ProviderRuntimePolicy::new(true, true, false, true, false, false)
                .expect("identity observation policy without structured prompt");

        assert!(!should_probe_pty_identity(
            without_structured_prompt,
            Some(codex),
            false,
            "codex",
        ));
        assert!(!should_probe_pty_identity(
            without_structured_prompt,
            Some(kimi),
            false,
            "kimi",
        ));

        let with_structured_prompt =
            ProviderRuntimePolicy::new(true, true, true, true, false, false)
                .expect("identity probe policy");
        assert!(should_probe_pty_identity(
            with_structured_prompt,
            Some(codex),
            false,
            "codex",
        ));
        assert!(should_probe_pty_identity(
            with_structured_prompt,
            Some(kimi),
            false,
            "kimi",
        ));
    }

    #[test]
    fn runtime_policy_admits_raw_native_resume_but_denies_unverified_prompt_injection() {
        let raw = ProviderRuntimePolicy::raw_pty();
        assert!(validate_spawn_runtime_policy(raw, TransportKind::Pty, false, false).is_ok());
        assert!(validate_spawn_runtime_policy(raw, TransportKind::Pty, true, false)
            .unwrap_err()
            .contains("SemanticReadiness"));
        assert!(validate_spawn_runtime_policy(raw, TransportKind::Pty, false, true).is_ok());
        assert!(validate_spawn_runtime_policy(raw, TransportKind::Pty, true, true)
            .unwrap_err()
            .contains("SemanticReadiness"));

        let resume_without_prompt =
            ProviderRuntimePolicy::new(true, false, false, true, true, false)
                .expect("identity and resume policy");
        assert!(validate_spawn_runtime_policy(
            resume_without_prompt,
            TransportKind::Pty,
            false,
            true,
        )
        .is_ok());
        assert!(validate_spawn_runtime_policy(
            resume_without_prompt,
            TransportKind::Pty,
            true,
            true,
        )
        .unwrap_err()
        .contains("SemanticReadiness"));
    }

    #[test]
    fn acp_transport_bypasses_the_pty_semantic_policy_gate_pty_and_pipe_still_enforce_it() {
        // A provider that speaks ACP and nothing else (no raw PTY, no
        // verified terminal semantics) admits none of these capabilities --
        // exactly grok's real policy. `TransportKind::Acp` must not care:
        // ACP has no terminal to infer state from, so none of this policy
        // applies to it.
        let no_pty_capabilities_at_all = ProviderRuntimePolicy::new(
            false, false, false, false, false, false,
        )
        .expect("an all-false policy is internally valid");
        assert!(validate_spawn_runtime_policy(
            no_pty_capabilities_at_all,
            TransportKind::Acp,
            false,
            false,
        )
        .is_ok());
        // The same all-false policy is still correctly refused for Pty and
        // Pipe -- this fix narrows the gate to skip Acp specifically, it
        // does not weaken it for the transports that do need it.
        assert!(validate_spawn_runtime_policy(
            no_pty_capabilities_at_all,
            TransportKind::Pty,
            false,
            false,
        )
        .unwrap_err()
        .contains("RawPtyLifecycle"));
        assert!(validate_spawn_runtime_policy(
            no_pty_capabilities_at_all,
            TransportKind::Pipe,
            false,
            false,
        )
        .unwrap_err()
        .contains("RawPtyLifecycle"));
    }

    #[test]
    fn prompt_render_probe_ignores_terminal_wrapping_and_uses_the_tail() {
        let prompt = "prefix with spaces\nand punctuation: final-render-token-1234567890";
        let probe = prompt_render_probe(prompt);
        assert!("screen prefix with spaces and punctuation final render token 1234567890"
            .chars()
            .filter(|character| character.is_alphanumeric())
            .flat_map(char::to_lowercase)
            .collect::<String>()
            .contains(&probe));
        assert!(probe.chars().count() <= 32);
    }

    #[test]
    fn prompt_render_requires_new_sequence_and_visible_tail_evidence() {
        let probe = prompt_render_probe("final render token");
        let baseline = snapshot(7, "old composer");
        assert!(!prompt_rendered(
            &snapshot(7, "final\nrender\ntoken"),
            &baseline,
            &probe
        ));
        assert!(!prompt_rendered(
            &snapshot(8, "unrelated redraw"),
            &baseline,
            &probe
        ));
        assert!(prompt_rendered(
            &snapshot(8, "composer\nfinal\nrender\ntoken"),
            &baseline,
            &probe
        ));
        assert!(prompt_rendered(
            &snapshot(8, "composer [Pasted Content 4096 chars]"),
            &baseline,
            &probe
        ));
        assert!(prompt_rendered(
            &snapshot(8, "composer [Pasted text #1 +6 lines]"),
            &baseline,
            &probe
        ));
    }

    #[test]
    fn an_existing_paste_placeholder_cannot_pass_on_an_unrelated_redraw() {
        let probe = prompt_render_probe("a new long prompt");
        assert!(!prompt_rendered(
            &snapshot(8, "composer [Pasted Content 4096 chars]\nunrelated redraw"),
            &snapshot(7, "composer [Pasted Content 4096 chars]"),
            &probe
        ));
        assert!(!prompt_rendered(
            &snapshot(8, "composer [Pasted text #1 +6 lines]\nunrelated redraw"),
            &snapshot(7, "composer [Pasted text #1 +6 lines]"),
            &probe
        ));
    }

    #[test]
    fn punctuation_only_prompt_cannot_pass_on_an_unrelated_redraw() {
        let probe = prompt_render_probe("!?---");
        assert!(probe.is_empty());
        assert!(!prompt_rendered(
            &snapshot(2, "unrelated redraw"),
            &snapshot(1, "old composer"),
            &probe
        ));
    }

    #[test]
    fn prompt_probe_matches_the_sanitized_terminal_payload() {
        let prompt = "payload\u{1b}tail";
        let sanitized = gate4agent_types::sanitize_prompt_text(prompt);
        let probe = prompt_render_probe(&sanitized);
        assert!(prompt_rendered(
            &snapshot(2, "composer payload<ESC>tail"),
            &snapshot(1, "old composer"),
            &probe
        ));
    }

    #[test]
    fn lag_and_data_gap_reserve_missed_provider_source_positions() {
        let mut next = 7;
        assert_eq!(reserve_provider_gap_sequence(&mut next, 3), Some(9));
        assert_eq!(next, 10);
        assert_eq!(reserve_provider_gap_sequence(&mut next, 0), None);
        assert_eq!(next, 10);

        next = u64::MAX;
        assert_eq!(reserve_provider_gap_sequence(&mut next, 1), None);
        assert_eq!(next, u64::MAX);
    }

    // --- RateLimitFeed: ANSI-stripping and chunk reassembly ---
    //
    // Regression coverage for a live-stand defect: `provider.rate_limits`
    // used to be a bare `RateLimitDetector` fed the RAW PTY stream, escape
    // codes and all. codex's own `/status` render puts `\x1b[m` between
    // `limit:` and the progress bar, and `\x1b[2m` between `left` and
    // `(resets ...)` -- both inside gaps the quota-state regex's `\s*`
    // cannot see through -- so not one quota-state fact was ever observed
    // on a real run, despite the pattern being correct on clean text.

    /// The exact live bytes from the coordinator's capture (real `\x1b[m`
    /// and `\x1b[2m`, real `\r\n`), transcribed verbatim.
    const CODEX_STATUS_RAW_ANSI: &str = "│  5h limit:             \x1b[m[████████████████████] 100% left\x1b[2m (resets 00:08 on 31 Aug) │\r\n│  Weekly limit:         \x1b[m[████████████████████] 100% left\x1b[2m (resets 19:08 on 6 Sep)  │";

    #[test]
    fn bare_detector_misses_the_live_ansi_sample_that_rate_limit_feed_catches() {
        // This is the defect itself: matching the untouched raw stream
        // fails on real codex output, exactly as observed live.
        let bare = RateLimitDetector::new_for_tool(CliTool::Codex);
        assert!(bare.detect(CODEX_STATUS_RAW_ANSI).is_none());

        // `RateLimitFeed` strips ANSI (via `VteParser`) before matching,
        // so the same bytes must now be recognized.
        let mut feed = RateLimitFeed::new_for_tool(CliTool::Codex);
        let info = feed
            .detect(CODEX_STATUS_RAW_ANSI)
            .expect("quota-state line must be recognized once ANSI is stripped");
        assert_eq!(info.limit_type, RateLimitType::Session);
        assert_eq!(info.usage_percent, Some(0.0));
        assert_eq!(info.resets_at_text.as_deref(), Some("00:08 on 31 Aug"));
    }

    #[test]
    fn rate_limit_feed_reassembles_a_quota_state_line_split_mid_escape_and_mid_row() {
        // A live PTY chunk boundary has no reason to land anywhere
        // convenient -- here it falls INSIDE the `\x1b[2m` escape itself
        // (right after the ESC byte), on top of splitting the row.
        let first =
            "│  5h limit:             \x1b[m[████████████████████] 100% left\x1b";
        let second = "[2m (resets 00:08 on 31 Aug) │\r\n";

        let mut feed = RateLimitFeed::new_for_tool(CliTool::Codex);
        assert!(
            feed.detect(first).is_none(),
            "the row is not complete yet, so nothing should match on the first chunk"
        );
        let info = feed
            .detect(second)
            .expect("the row completes once the second chunk arrives");
        assert_eq!(info.limit_type, RateLimitType::Session);
        assert_eq!(info.resets_at_text.as_deref(), Some("00:08 on 31 Aug"));
    }

    #[test]
    fn rate_limit_feed_strips_ansi_before_matching_a_colored_failure_message() {
        // Failure patterns run through the same `RateLimitFeed::detect`
        // entry point as quota-state ones, so a vendor coloring its own
        // refusal text must not defeat detection either.
        let raw = "\x1b[31mError: rate limit exceeded\x1b[0m. Please wait.";
        let mut feed = RateLimitFeed::new_for_tool(CliTool::Codex);
        let info = feed
            .detect(raw)
            .expect("a colored refusal message must still be recognized");
        assert_eq!(info.limit_type, RateLimitType::Unknown);
    }

    #[test]
    fn rate_limit_feed_bounds_its_buffer_across_a_newline_free_redraw() {
        // A full-screen redraw with no `\n` at all (cursor-addressing
        // only) must not grow the pending-line buffer without bound for
        // as long as it runs -- and a real line must still be caught once
        // it finally arrives.
        let mut feed = RateLimitFeed::new_for_tool(CliTool::Codex);
        let noise = "x".repeat(super::RATE_LIMIT_FEED_BUFFER_MAX_BYTES * 3);
        assert!(feed.detect(&noise).is_none());
        assert!(feed.buffer.len() <= super::RATE_LIMIT_FEED_BUFFER_MAX_BYTES);

        let info = feed
            .detect(CODEX_STATUS_RAW_ANSI)
            .expect("a real quota-state line must still be recognized after the noise");
        assert_eq!(info.limit_type, RateLimitType::Session);
    }

    // -----------------------------------------------------------------------
    // host_policy_for_approval_level -- ApprovalLevel -> HostPolicy for ACP
    // -----------------------------------------------------------------------

    #[test]
    fn full_auto_maps_to_the_permissive_host_policy() {
        // The one combination that must never happen is `FullAuto` paired
        // with a refusing `HostPolicy` -- the process believes it has full
        // autonomy while the host silently refuses it.
        assert_eq!(host_policy_for_approval_level(ApprovalLevel::FullAuto), HostPolicy::Yolo);
    }

    #[test]
    fn read_only_maps_to_the_read_only_host_policy() {
        assert_eq!(
            host_policy_for_approval_level(ApprovalLevel::ReadOnly),
            HostPolicy::ReadOnly
        );
    }

    #[test]
    fn moderate_and_unmanaged_both_fall_back_to_the_default_host_policy() {
        assert_eq!(host_policy_for_approval_level(ApprovalLevel::Moderate), HostPolicy::Auto);
        assert_eq!(host_policy_for_approval_level(ApprovalLevel::Unmanaged), HostPolicy::Auto);
        assert_eq!(HostPolicy::default(), HostPolicy::Auto);
    }

    #[test]
    fn no_approval_level_ever_maps_to_a_refusing_policy_except_read_only_itself() {
        // Guards the "never full auto + refusing host" invariant generally:
        // `Deny` must never be reachable from this mapping at all -- it is
        // not one of the four `ApprovalLevel` outcomes, only `ReadOnly`'s
        // own deliberate restriction is.
        for level in [
            ApprovalLevel::FullAuto,
            ApprovalLevel::Moderate,
            ApprovalLevel::ReadOnly,
            ApprovalLevel::Unmanaged,
        ] {
            assert_ne!(
                host_policy_for_approval_level(level),
                HostPolicy::Deny,
                "{level:?} must never map to HostPolicy::Deny"
            );
        }
    }

    // -----------------------------------------------------------------------
    // defers_permission_requests -- reads `asks_for_permission` off the
    // catalog's per-(provider, level) vendor-mode table instead of matching
    // on the ApprovalLevel's own name (the bug this whole axis exists to
    // remove -- see the function's own doc comment).
    // -----------------------------------------------------------------------

    #[test]
    fn defers_permission_requests_matches_the_verified_provider_table() {
        // Source of truth: `gate4agent_catalog::launch::approval_level_resolution`
        // at HEAD (commit 7b6a8d2) and
        // `docs/gate4agent/audits/gate4agent-acp-slice1-proof-2026-09-02.md`
        // (session/new modes measured live, 2026-09-02).
        let claude = AgentId::new("claude").unwrap();
        assert!(!defers_permission_requests(&claude, ApprovalLevel::FullAuto));
        assert!(defers_permission_requests(&claude, ApprovalLevel::Moderate));
        // claude's `ReadOnly` now launches `default` (`plan` neither refuses
        // nor asks over ACP, measured twice) -- claude's own interactive
        // mode, which does ask about every write.
        assert!(defers_permission_requests(&claude, ApprovalLevel::ReadOnly));
        // `Unmanaged` never defers: it decides `session/request_permission`
        // immediately (auto-approve), since some providers' ACP clients
        // won't wait out a parked decision.
        assert!(!defers_permission_requests(&claude, ApprovalLevel::Unmanaged));

        let codex = AgentId::new("codex").unwrap();
        assert!(!defers_permission_requests(&codex, ApprovalLevel::FullAuto));
        // codex's `Moderate` ACP mode (`agent`, "Approve for me") wrote and
        // reported success with no `session/request_permission` at all --
        // measured live, unlike the PTY `on-request` flag it shares a row
        // with.
        assert!(!defers_permission_requests(&codex, ApprovalLevel::Moderate));
        assert!(defers_permission_requests(&codex, ApprovalLevel::ReadOnly));
        // `Unmanaged` never defers -- see the claude row's comment above.
        assert!(!defers_permission_requests(&codex, ApprovalLevel::Unmanaged));

        let grok = AgentId::new("grok").unwrap();
        assert!(!defers_permission_requests(&grok, ApprovalLevel::FullAuto));
        assert!(defers_permission_requests(&grok, ApprovalLevel::Moderate));
        // `ReadOnly` is `Unsupported` for grok -- the ACP spawn branch must
        // already have refused the session before this function would ever
        // see it live; the conservative fallback here still defers.
        assert!(defers_permission_requests(&grok, ApprovalLevel::ReadOnly));
        // `Unmanaged` never defers -- see the claude row's comment above.
        assert!(!defers_permission_requests(&grok, ApprovalLevel::Unmanaged));

        let kimi = AgentId::new("kimi").unwrap();
        assert!(!defers_permission_requests(&kimi, ApprovalLevel::FullAuto));
        // kimi's `Moderate` ACP mode is genuinely named `auto` and wrote
        // silently, measured live -- it does not ask.
        assert!(!defers_permission_requests(&kimi, ApprovalLevel::Moderate));
        // kimi's `ReadOnly` ACP mode (`plan`) refuses silently rather than
        // asking -- measured live, a write outside the working directory
        // produced no question at all.
        assert!(!defers_permission_requests(&kimi, ApprovalLevel::ReadOnly));
        // `Unmanaged` never defers -- see the claude row's comment above.
        assert!(!defers_permission_requests(&kimi, ApprovalLevel::Unmanaged));
    }

    // -----------------------------------------------------------------------
    // required_acp_mode / approval_level_not_offered_message -- Item 3's
    // table: one row per provider x level, plus the regression guard that
    // `auto` is unreachable without an explicit choice.
    // -----------------------------------------------------------------------

    fn session_mode(id: &str) -> SessionMode {
        SessionMode { id: id.to_owned(), name: id.to_owned(), description: None }
    }

    #[test]
    fn required_acp_mode_matches_the_sourced_table() {
        // Source of truth: `gate4agent_catalog::launch::approval_level_resolution`
        // at HEAD (commit 7b6a8d2) and
        // `docs/gate4agent/audits/gate4agent-acp-slice1-proof-2026-09-02.md`
        // (session/new modes measured live, 2026-09-02).
        let claude = AgentId::new("claude").unwrap();
        assert_eq!(
            required_acp_mode(&claude, ApprovalLevel::FullAuto),
            Ok(Some(ModeId::new("bypassPermissions")))
        );
        assert_eq!(
            required_acp_mode(&claude, ApprovalLevel::Moderate),
            Ok(Some(ModeId::new("acceptEdits")))
        );
        // measured live: `plan` neither refuses nor asks over ACP, so
        // `ReadOnly` moved to `default`, the one claude mode where both an
        // in-cwd and an out-of-cwd write raised `session/request_permission`.
        assert_eq!(
            required_acp_mode(&claude, ApprovalLevel::ReadOnly),
            Ok(Some(ModeId::new("default")))
        );
        assert_eq!(required_acp_mode(&claude, ApprovalLevel::Unmanaged), Ok(None));

        let codex = AgentId::new("codex").unwrap();
        assert_eq!(
            required_acp_mode(&codex, ApprovalLevel::FullAuto),
            Ok(Some(ModeId::new("agent-full-access")))
        );
        assert_eq!(
            required_acp_mode(&codex, ApprovalLevel::Moderate),
            Ok(Some(ModeId::new("agent")))
        );
        assert_eq!(
            required_acp_mode(&codex, ApprovalLevel::ReadOnly),
            Ok(Some(ModeId::new("read-only")))
        );
        assert_eq!(required_acp_mode(&codex, ApprovalLevel::Unmanaged), Ok(None));

        // kimi: `acp_mode_id` is `None` for every managed level -- measured
        // 2026-09-05, `kimi.exe` 0.29.0's `session/new` result carries
        // `configOptions` (a `model` select) and no `modes` field at all.
        // The 2026-09-02 `yolo`/`auto`/`plan` measurement this table used to
        // pin was a different build: the npm shell shim running under WSL
        // interop, not this native binary.
        // `FullAuto` is the one kimi level that carries vendor flags
        // (`--yolo`), so argv applies it and there is nothing left to refuse;
        // `Moderate`/`ReadOnly` carry none (their `--auto`/`--plan` remain
        // UNCONFIRMED under `kimi acp`) and still refuse, because for those
        // no mechanism exists at all.
        let kimi = AgentId::new("kimi").unwrap();
        assert_eq!(required_acp_mode(&kimi, ApprovalLevel::FullAuto), Ok(None));
        assert_eq!(
            acp_approval_level_args(&kimi, ApprovalLevel::FullAuto),
            vec!["--auto".to_owned()],
            "kimi's FullAuto must reach the process through argv, since it has no ACP mode"
        );
        for level in [ApprovalLevel::Moderate, ApprovalLevel::ReadOnly] {
            assert!(
                required_acp_mode(&kimi, level).is_err(),
                "kimi at {level:?} has neither a sourced ACP mode id nor vendor flags, so it must refuse"
            );
        }
        assert_eq!(required_acp_mode(&kimi, ApprovalLevel::Unmanaged), Ok(None));
        assert!(
            acp_approval_level_args(&kimi, ApprovalLevel::Unmanaged).is_empty(),
            "Unmanaged imposes nothing, so it must add no argv flags either"
        );

        // grok: `acp_mode_id` is `None` for every managed level (no live
        // mode catalogue sourced yet — slice-1 skipped grok). `FullAuto` and
        // `Moderate` are `Supported` with argv flags, so they resolve
        // `Ok(None)` and apply through argv; `ReadOnly` is outright
        // `Unsupported` and refuses. Flag spellings for FullAuto remain
        // UNCONFIRMED against Grok Build's own CLI surface (catalog docs).
        let grok = AgentId::new("grok").unwrap();
        assert_eq!(required_acp_mode(&grok, ApprovalLevel::FullAuto), Ok(None));
        assert_eq!(
            acp_approval_level_args(&grok, ApprovalLevel::FullAuto),
            vec!["--always-approve".to_owned()],
        );
        assert_eq!(required_acp_mode(&grok, ApprovalLevel::Moderate), Ok(None));
        assert_eq!(
            acp_approval_level_args(&grok, ApprovalLevel::Moderate),
            vec!["--permission-mode".to_owned(), "auto".to_owned()],
        );
        assert!(
            required_acp_mode(&grok, ApprovalLevel::ReadOnly).is_err(),
            "grok at ReadOnly is Unsupported outright, so it must refuse"
        );
        assert_eq!(required_acp_mode(&grok, ApprovalLevel::Unmanaged), Ok(None));
    }

    /// The regression guard for the whole change: no provider x level may
    /// silently resolve to nothing (which would leave the session running
    /// at the agent's own default, e.g. the live-measured `auto`) unless the
    /// level itself is `Unmanaged`. Every other level is either a concrete
    /// mode id or an outright refusal. kimi no longer has an exception here:
    /// measured 2026-09-05, `kimi.exe` 0.29.0 offers no ACP modes at all, so
    /// every one of its managed levels now refuses (`Err`) rather than
    /// sourcing a mode id -- the `Moderate` row's `auto` exception this
    /// guard used to carry was the 2026-09-02 npm-shim-under-WSL-interop
    /// measurement, a different build.
    #[test]
    fn required_acp_mode_never_silently_permits_auto_except_for_unmanaged() {
        for id in ["claude", "codex", "grok", "kimi"] {
            let agent = AgentId::new(id).unwrap();
            for level in [ApprovalLevel::FullAuto, ApprovalLevel::Moderate, ApprovalLevel::ReadOnly] {
                match required_acp_mode(&agent, level) {
                    Ok(Some(mode_id)) => assert_ne!(
                        mode_id.as_str(),
                        "auto",
                        "{id} at {level:?} must never silently resolve the vendor's own default 'auto'"
                    ),
                    Ok(None) => assert!(
                        !acp_approval_level_args(&agent, level).is_empty(),
                        "{id} at {level:?} resolved Ok(None) while carrying no vendor flags -- \
                         that leaves the session at the agent's own default. Only Unmanaged, or a \
                         level argv actually applies, may resolve to no mode"
                    ),
                    Err(_) => {} // refused outright -- also never reaches `auto`
                }
            }
            assert_eq!(
                required_acp_mode(&agent, ApprovalLevel::Unmanaged),
                Ok(None),
                "{id}: Unmanaged is the one level allowed to apply nothing"
            );
        }
    }

    #[test]
    fn approval_level_not_offered_message_refuses_by_name_and_lists_what_was_offered() {
        let offered = vec![session_mode("bypassPermissions"), session_mode("default")];
        let mode_id = ModeId::new("plan");
        let message = approval_level_not_offered_message(ApprovalLevel::ReadOnly, &mode_id, &offered)
            .expect("'plan' was not among the offered modes");
        assert!(message.contains("ApprovalLevelNotOfferedByAgent"));
        assert!(message.contains("bypassPermissions"));
        assert!(message.contains("default"));
        assert!(message.contains("ReadOnly"));
    }

    #[test]
    fn approval_level_not_offered_message_is_none_when_the_agent_announced_it() {
        let offered = vec![session_mode("plan")];
        let mode_id = ModeId::new("plan");
        assert_eq!(
            approval_level_not_offered_message(ApprovalLevel::ReadOnly, &mode_id, &offered),
            None
        );
    }

    #[test]
    fn approval_level_not_offered_message_handles_an_agent_that_announces_no_modes_at_all() {
        let mode_id = ModeId::new("bypassPermissions");
        let message = approval_level_not_offered_message(ApprovalLevel::FullAuto, &mode_id, &[])
            .expect("an empty mode catalog never offers anything");
        assert!(message.contains("ApprovalLevelNotOfferedByAgent"));
        assert!(message.contains("offered: []"));
    }

    // -----------------------------------------------------------------------
    // stop_native — pipe_sessions branch reads `force`.
    //
    // Regression coverage: this branch used to call
    // `owned.session.kill().await` unconditionally, so no headless Pipe run
    // could ever end any way other than a forced kill regardless of what the
    // caller asked for. `PipeSession::stop`'s own unit tests (`gate4agent`'s
    // `pipe::session::tests`) cover the graceful-wait/bound-elapse timing in
    // depth; these two only prove the NEW wiring in `stop_native` itself:
    // `force` reaches `PipeSession::stop`, and its `PipeStopOutcome` maps
    // onto `ControlObservation::StopCompleted` correctly. Built by inserting
    // directly into `pipe_sessions` (private field, visible to this child
    // module) rather than through `execute()`/`EffectEnvelope`, so this does
    // not depend on the catalog/spawn-plan machinery at all.
    // -----------------------------------------------------------------------

    use super::{NativeEffectShell, NativeSessionKey, OwnedProviderSession};
    use gate4agent_catalog::{AgentRegistry as FixtureAgentRegistry, AgentSpec as FixtureAgentSpec};
    use gate4agent_types::ControlObservation;
    use std::collections::VecDeque;

    fn fixture_pipe_key() -> NativeSessionKey {
        NativeSessionKey {
            instance_id: gate4agent_types::AgentInstanceId(9_001),
            generation: gate4agent_types::SessionGeneration(1),
        }
    }

    fn fixture_pipe_source() -> gate4agent_types::ProviderSource {
        gate4agent_types::ProviderSource {
            family: AdapterFamily::Pipe,
            binding: gate4agent_types::AdapterBinding::new(
                gate4agent_types::AdapterId::new("fixture").unwrap(),
                "1",
                gate4agent_types::AdapterVerification::SyntheticFixture,
            )
            .unwrap(),
        }
    }

    #[cfg(windows)]
    fn fixture_graceful_exit_launch() -> gate4agent_types::LaunchSpec {
        gate4agent_types::LaunchSpec {
            program: "powershell.exe".to_owned(),
            fixed_args: vec![
                "-NoProfile".to_owned(),
                "-NonInteractive".to_owned(),
                "-Command".to_owned(),
                "[Console]::In.ReadToEnd() | Out-Null; exit 0".to_owned(),
            ],
        }
    }

    #[cfg(not(windows))]
    fn fixture_graceful_exit_launch() -> gate4agent_types::LaunchSpec {
        gate4agent_types::LaunchSpec {
            program: "sh".to_owned(),
            fixed_args: vec!["-c".to_owned(), "cat >/dev/null; exit 0".to_owned()],
        }
    }

    #[cfg(windows)]
    fn fixture_ignore_stdin_launch() -> gate4agent_types::LaunchSpec {
        gate4agent_types::LaunchSpec {
            program: "powershell.exe".to_owned(),
            fixed_args: vec![
                "-NoProfile".to_owned(),
                "-NonInteractive".to_owned(),
                "-Command".to_owned(),
                "Start-Sleep -Seconds 30".to_owned(),
            ],
        }
    }

    #[cfg(not(windows))]
    fn fixture_ignore_stdin_launch() -> gate4agent_types::LaunchSpec {
        gate4agent_types::LaunchSpec {
            program: "sh".to_owned(),
            fixed_args: vec!["-c".to_owned(), "sleep 30".to_owned()],
        }
    }

    async fn spawn_fixture_pipe_shell(
        launch: gate4agent_types::LaunchSpec,
    ) -> (NativeEffectShell, NativeSessionKey) {
        let session = gate4agent::PipeSession::spawn_with_launch(
            gate4agent::core::types::SessionConfig::default(),
            "prompt",
            &launch,
            gate4agent_types::PipePromptDelivery::StdinClose,
        )
        .await
        .expect("fixture pipe process must spawn");
        let events = session.subscribe();
        let key = fixture_pipe_key();
        let mut shell = NativeEffectShell::new(
            FixtureAgentRegistry::new(std::iter::empty::<FixtureAgentSpec>())
                .expect("empty fixture catalog"),
        );
        shell.pipe_sessions.insert(
            key,
            OwnedProviderSession {
                source: fixture_pipe_source(),
                session,
                events,
                pending_events: VecDeque::new(),
                pending_provider_events: VecDeque::new(),
                next_provider_sequence: 1,
                observed_exit_code: None,
                runtime_policy: gate4agent_types::ProviderRuntimePolicy::none(),
            },
        );
        (shell, key)
    }

    #[tokio::test]
    async fn stop_native_pipe_session_reports_the_real_exit_code_when_not_forced() {
        let (mut shell, key) = spawn_fixture_pipe_shell(fixture_graceful_exit_launch()).await;

        match shell.stop_native(key, false).await {
            ControlObservation::StopCompleted {
                forced, exit_code, ..
            } => {
                assert!(!forced, "a process that exits on its own must not be forced");
                assert_eq!(exit_code, Some(0));
            }
            other => panic!("expected StopCompleted, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn stop_native_pipe_session_force_true_kills_immediately_without_waiting() {
        let (mut shell, key) = spawn_fixture_pipe_shell(fixture_ignore_stdin_launch()).await;

        let start = std::time::Instant::now();
        match shell.stop_native(key, true).await {
            ControlObservation::StopCompleted { forced, .. } => {
                assert!(forced, "force=true must always report forced");
            }
            other => panic!("expected StopCompleted, got {other:?}"),
        }
        assert!(
            start.elapsed()
                < std::time::Duration::from_secs(gate4agent::pipe::PIPE_GRACEFUL_STOP_BOUND_SECS),
            "force=true must not wait out the graceful bound"
        );
    }

    // -------------------------------------------------------------------
    // stop_native -- acp_sessions branch reads `force`.
    //
    // Regression coverage: this branch used to call
    // `owned.session.kill().await` unconditionally after an optional
    // `session/cancel`, so `forced` was always `true` regardless of what
    // the caller asked for. Fixture mirrors `gate4agent::acp::session`'s
    // own `AcpSession::stop` unit tests (which cover the graceful-wait/
    // bound-elapse timing in depth): a minimal handshake responder that
    // answers `initialize`/`session/new` and exits 0 on stdin EOF. This
    // test only proves the NEW wiring in `stop_native` itself: `force`
    // reaches `AcpSession::stop`, and its `AcpStopOutcome` maps onto
    // `ControlObservation::StopCompleted` correctly.
    // -------------------------------------------------------------------

    #[cfg(windows)]
    fn acp_fixture_launch() -> gate4agent_types::LaunchSpec {
        gate4agent_types::LaunchSpec {
            program: "powershell.exe".to_owned(),
            fixed_args: vec![
                "-NoLogo".to_owned(),
                "-NoProfile".to_owned(),
                "-NonInteractive".to_owned(),
                "-ExecutionPolicy".to_owned(),
                "Bypass".to_owned(),
                "-Command".to_owned(),
                ACP_HANDSHAKE_SCRIPT.to_owned(),
            ],
        }
    }

    #[cfg(not(windows))]
    fn acp_fixture_launch() -> gate4agent_types::LaunchSpec {
        gate4agent_types::LaunchSpec {
            program: "python3".to_owned(),
            fixed_args: vec!["-u".to_owned(), "-c".to_owned(), ACP_HANDSHAKE_SCRIPT.to_owned()],
        }
    }

    #[cfg(windows)]
    const ACP_HANDSHAKE_SCRIPT: &str = r#"[Console]::OutputEncoding=[Text.Encoding]::UTF8
function Write-JsonLine($value) { [Console]::WriteLine(($value | ConvertTo-Json -Compress -Depth 12)) }
$initialize = [Console]::ReadLine() | ConvertFrom-Json
Write-JsonLine @{jsonrpc='2.0';id=$initialize.id;result=@{}}
$newSession = [Console]::ReadLine() | ConvertFrom-Json
Write-JsonLine @{jsonrpc='2.0';id=$newSession.id;result=@{sessionId='fixture-acp-session'}}
while ($true) {
    $line = [Console]::ReadLine()
    if ($null -eq $line) { exit 0 }
}"#;
    #[cfg(not(windows))]
    const ACP_HANDSHAKE_SCRIPT: &str = r#"import json,sys
def read_message():
 line=sys.stdin.readline()
 if not line: return None
 return json.loads(line)
def write_message(message):
 print(json.dumps(message),flush=True)

initialize=read_message()
write_message({'jsonrpc':'2.0','id':initialize.get('id'),'result':{}})
new_session=read_message()
write_message({'jsonrpc':'2.0','id':new_session.get('id'),'result':{'sessionId':'fixture-acp-session'}})
while True:
 msg=read_message()
 if msg is None:
  sys.exit(0)"#;

    fn fixture_acp_key() -> NativeSessionKey {
        NativeSessionKey {
            instance_id: gate4agent_types::AgentInstanceId(9_002),
            generation: gate4agent_types::SessionGeneration(1),
        }
    }

    fn fixture_acp_source() -> gate4agent_types::ProviderSource {
        gate4agent_types::ProviderSource {
            family: AdapterFamily::Acp,
            binding: gate4agent_types::AdapterBinding::new(
                gate4agent_types::AdapterId::new("fixture").unwrap(),
                "1",
                gate4agent_types::AdapterVerification::SyntheticFixture,
            )
            .unwrap(),
        }
    }

    async fn spawn_fixture_acp_shell() -> (NativeEffectShell, NativeSessionKey) {
        let session = gate4agent::acp::AcpSession::spawn_with_launch(
            gate4agent::CliTool::ClaudeCode,
            &std::env::current_dir().expect("cwd"),
            gate4agent::acp::AcpSessionOptions::default(),
            &acp_fixture_launch(),
        )
        .await
        .expect("fixture ACP handshake must succeed");
        let events = session.subscribe();
        let key = fixture_acp_key();
        let mut shell = NativeEffectShell::new(
            FixtureAgentRegistry::new(std::iter::empty::<FixtureAgentSpec>())
                .expect("empty fixture catalog"),
        );
        shell.acp_sessions.insert(
            key,
            OwnedProviderSession {
                source: fixture_acp_source(),
                session,
                events,
                pending_events: VecDeque::new(),
                pending_provider_events: VecDeque::new(),
                next_provider_sequence: 1,
                observed_exit_code: None,
                runtime_policy: gate4agent_types::ProviderRuntimePolicy::none(),
            },
        );
        (shell, key)
    }

    #[tokio::test]
    async fn stop_native_acp_session_reports_the_real_exit_code_when_not_forced() {
        let (mut shell, key) = spawn_fixture_acp_shell().await;

        match shell.stop_native(key, false).await {
            ControlObservation::StopCompleted {
                forced, exit_code, ..
            } => {
                assert!(!forced, "a process that exits on its own must not be forced");
                assert_eq!(exit_code, Some(0));
            }
            other => panic!("expected StopCompleted, got {other:?}"),
        }
    }

    // -------------------------------------------------------------------
    // spawn_native -- ACP branch: `ProviderEvent::SessionIdentityObserved`.
    //
    // Regression coverage for the defect this carries fixed: nothing on the
    // ACP path ever emitted `SessionIdentityObserved`, so a managed session
    // record for an ACP-spawned agent could never leave
    // `ManagedSessionState::IdentityPending` (`gate4agent-node`'s
    // `reconcile_managed_record` binds the identity ONLY on that event).
    // Built through the full `execute()`/`EffectEnvelope` path (unlike
    // `spawn_fixture_acp_shell` above, which inserts an already-spawned
    // session directly into `acp_sessions`) so these tests exercise the
    // ACTUAL `TransportKind::Acp` arm of `spawn_native`, not a stand-in for
    // it -- the same synthetic stdio handshake fixture, extended with a
    // second script that omits `sessionId` to name the ACP-MUST violation
    // this whole feature exists to survive.
    // -------------------------------------------------------------------

    #[cfg(windows)]
    fn acp_fixture_launch_no_session_id() -> gate4agent_types::LaunchSpec {
        gate4agent_types::LaunchSpec {
            program: "powershell.exe".to_owned(),
            fixed_args: vec![
                "-NoLogo".to_owned(),
                "-NoProfile".to_owned(),
                "-NonInteractive".to_owned(),
                "-ExecutionPolicy".to_owned(),
                "Bypass".to_owned(),
                "-Command".to_owned(),
                ACP_HANDSHAKE_SCRIPT_NO_SESSION_ID.to_owned(),
            ],
        }
    }

    #[cfg(not(windows))]
    fn acp_fixture_launch_no_session_id() -> gate4agent_types::LaunchSpec {
        gate4agent_types::LaunchSpec {
            program: "python3".to_owned(),
            fixed_args: vec![
                "-u".to_owned(),
                "-c".to_owned(),
                ACP_HANDSHAKE_SCRIPT_NO_SESSION_ID.to_owned(),
            ],
        }
    }

    #[cfg(windows)]
    const ACP_HANDSHAKE_SCRIPT_NO_SESSION_ID: &str = r#"[Console]::OutputEncoding=[Text.Encoding]::UTF8
function Write-JsonLine($value) { [Console]::WriteLine(($value | ConvertTo-Json -Compress -Depth 12)) }
$initialize = [Console]::ReadLine() | ConvertFrom-Json
Write-JsonLine @{jsonrpc='2.0';id=$initialize.id;result=@{}}
$newSession = [Console]::ReadLine() | ConvertFrom-Json
Write-JsonLine @{jsonrpc='2.0';id=$newSession.id;result=@{}}
while ($true) {
    $line = [Console]::ReadLine()
    if ($null -eq $line) { exit 0 }
}"#;
    #[cfg(not(windows))]
    const ACP_HANDSHAKE_SCRIPT_NO_SESSION_ID: &str = r#"import json,sys
def read_message():
 line=sys.stdin.readline()
 if not line: return None
 return json.loads(line)
def write_message(message):
 print(json.dumps(message),flush=True)

initialize=read_message()
write_message({'jsonrpc':'2.0','id':initialize.get('id'),'result':{}})
new_session=read_message()
write_message({'jsonrpc':'2.0','id':new_session.get('id'),'result':{}})
while True:
 msg=read_message()
 if msg is None:
  sys.exit(0)"#;

    fn fixture_acp_spawn_agent_id() -> AgentId {
        AgentId::new("claude").expect("builtin catalog names 'claude'")
    }

    /// Clones the REAL built-in `claude` spec (so `capabilities.transports.acp`
    /// carries the same `AdapterBinding` the default `legacy_adapters`
    /// registry (`NativeEffectShell::new`) already resolves) and overrides
    /// only `launch_override`, so `spawn_native` execs the synthetic stdio
    /// fixture above instead of a real `claude` binary.
    fn fixture_acp_spawn_agent_spec(launch: gate4agent_types::LaunchSpec) -> FixtureAgentSpec {
        let mut spec = gate4agent_catalog::builtin_registry()
            .get(&fixture_acp_spawn_agent_id())
            .cloned()
            .expect("builtin catalog must declare claude");
        spec.capabilities
            .transports
            .acp
            .as_mut()
            .expect("claude must declare ACP capability")
            .launch_override = Some(launch);
        spec
    }

    fn fixture_acp_spawn_key() -> NativeSessionKey {
        NativeSessionKey {
            instance_id: gate4agent_types::AgentInstanceId(9_101),
            generation: gate4agent_types::SessionGeneration(1),
        }
    }

    /// Spawns through the full `execute()`/`EffectEnvelope` path with
    /// `ApprovalLevel::Unmanaged` -- the one level `required_acp_mode`
    /// resolves to `Ok(None)` for every agent, so the spawn never calls
    /// `session/set_mode` against a fixture that only answers `initialize`/
    /// `session/new`.
    async fn spawn_native_acp_fixture(
        launch: gate4agent_types::LaunchSpec,
        provider_session_identity: bool,
    ) -> (NativeEffectShell, NativeSessionKey, ControlObservation) {
        let mut policy = ProviderRuntimePolicy::none();
        policy.provider_session_identity = provider_session_identity;
        let key = fixture_acp_spawn_key();
        let mut shell = NativeEffectShell::new(
            FixtureAgentRegistry::new([fixture_acp_spawn_agent_spec(launch)])
                .expect("single-agent fixture catalog"),
        );
        let envelope = gate4agent_types::EffectEnvelope {
            operation_id: gate4agent_types::OperationId(1),
            instance_id: key.instance_id,
            generation: key.generation,
            effect: gate4agent_types::ControlEffect::Spawn {
                agent_id: fixture_acp_spawn_agent_id(),
                transport: TransportKind::Acp,
                runtime_policy: policy,
                request: gate4agent_types::StartRequest {
                    working_directory: std::env::current_dir()
                        .expect("cwd")
                        .to_string_lossy()
                        .into_owned(),
                    terminal_size: gate4agent_types::TerminalSize {
                        rows: 24,
                        columns: 80,
                    },
                    initial_prompt: None,
                    session_options: None,
                    approval_level: ApprovalLevel::Unmanaged,
                },
            },
        };
        let observation = shell.execute(envelope).await.observation;
        (shell, key, observation)
    }

    #[tokio::test]
    async fn acp_spawn_with_a_real_sessionid_emits_session_identity_observed_after_session_start() {
        let (mut shell, key, spawned) =
            spawn_native_acp_fixture(acp_fixture_launch(), true).await;
        match spawned {
            ControlObservation::Spawned { .. } => {}
            other => panic!("expected Spawned, got {other:?}"),
        }

        let mut provider_events = shell
            .collect_provider_events()
            .into_iter()
            .filter_map(|envelope| match envelope.observation {
                ControlObservation::ProviderEvent { event, .. } => Some(event),
                _ => None,
            });

        match provider_events.next() {
            Some(ProviderEvent::SessionStarted { .. }) => {}
            other => panic!("expected SessionStarted first, got {other:?}"),
        }
        match provider_events.next() {
            Some(ProviderEvent::SessionIdentityObserved { identity }) => {
                assert_eq!(identity.key, gate4agent_types::ProviderSessionKey::SessionId);
                assert_eq!(identity.id, "fixture-acp-session");
                assert!(identity.transcript_path.is_none());
            }
            other => panic!("expected SessionIdentityObserved second, got {other:?}"),
        }
        assert!(
            provider_events.next().is_none(),
            "expected exactly one SessionIdentityObserved and nothing after it"
        );

        let _ = shell.stop_native(key, true).await;
    }

    #[tokio::test]
    async fn acp_spawn_with_no_sessionid_emits_no_session_identity_observed() {
        let (mut shell, key, spawned) =
            spawn_native_acp_fixture(acp_fixture_launch_no_session_id(), true).await;
        match spawned {
            ControlObservation::Spawned { .. } => {}
            other => panic!("expected Spawned, got {other:?}"),
        }

        let provider_events: Vec<_> = shell
            .collect_provider_events()
            .into_iter()
            .filter_map(|envelope| match envelope.observation {
                ControlObservation::ProviderEvent { event, .. } => Some(event),
                _ => None,
            })
            .collect();

        assert!(
            provider_events
                .iter()
                .any(|event| matches!(event, ProviderEvent::SessionStarted { .. })),
            "expected SessionStarted even when the agent reported no sessionId, got {provider_events:?}"
        );
        assert!(
            !provider_events
                .iter()
                .any(|event| matches!(event, ProviderEvent::SessionIdentityObserved { .. })),
            "an agent that violates ACP's sessionId MUST must not be granted an identity: \
             got {provider_events:?}"
        );

        let _ = shell.stop_native(key, true).await;
    }
}