oxdock-ssh-plugin 0.37.0-alpha

Ephemeral user-space SSH server and client for OxDock scripts, bridged to stdio pipelines through the Engine facade.
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
//! End-to-end SSH plugin tests over loopback TCP.
//!
//! Every test here needs real sockets, threads, and a Tokio runtime, so
//! all of them skip under Miri with a reason.

use std::net::SocketAddr;
use std::sync::{
    Arc,
    atomic::{AtomicU64, Ordering},
};
use std::time::{Duration, Instant};

use indoc::indoc;
use oxdock_core::{Engine, EngineOutput, ExecIo};
use oxdock_fs::{GuardedPath, GuardedTempDir};

fn guard_root(temp: &GuardedTempDir) -> GuardedPath {
    temp.as_guarded_path().clone()
}

fn run_script(root: &GuardedPath, script: &str) -> anyhow::Result<EngineOutput> {
    let mut engine = Engine::new();
    engine.register_module(oxdock_ssh_plugin::module());
    engine.run_script(root, script)
}

fn run_script_with(
    registry: Arc<oxdock_net_plugin::EndpointRegistry>,
    root: &GuardedPath,
    script: &str,
) -> anyhow::Result<EngineOutput> {
    let mut engine = Engine::new();
    engine.register_module(oxdock_ssh_plugin::module_with_endpoints(registry));
    engine.run_script(root, script)
}

/// [`run_script_with`] with this run's worker telemetry staged: the
/// test owns the counter and polls it for zero, hermetic under
/// parallel harnesses with no process-global gauge involved.
fn run_script_with_workers(
    registry: Arc<oxdock_net_plugin::EndpointRegistry>,
    root: &GuardedPath,
    script: &str,
    workers: Arc<AtomicU64>,
) -> anyhow::Result<EngineOutput> {
    let mut io = ExecIo::new();
    io.set_worker_counter(workers);
    let mut engine = Engine::new().with_io(io);
    engine.register_module(oxdock_ssh_plugin::module_with_endpoints(registry));
    engine.run_script(root, script)
}

#[test]
#[cfg_attr(
    miri,
    ignore = "blind sampling drives SSH session paths outside Miri isolation"
)]
fn returns_gate_covers_ssh_functions() {
    // Same returns contract as STD builtins, over this module's own
    // registrations: sampled calls that reach `Ok` satisfy the slot,
    // and anything sampling cannot reach must carry examples. Examples
    // name `doc-ssh-*` services, so the harness pre-maps them the way a
    // CLI runner would: scripts declare, the runner binds.
    let registry = Arc::new(oxdock_net_plugin::EndpointRegistry::new(false));
    for service in [
        "doc-ssh-route",
        "doc-ssh-serve",
        "doc-ssh-accept",
        "doc-ssh-pump",
        "doc-ssh-close",
        "doc-ssh-connect",
        "doc-ssh-exec",
        "doc-ssh-pty",
        "doc-ssh-run",
        "doc-ssh-exit-status",
        "doc-ssh-gen-pass",
    ] {
        registry
            .add_cli_mapping(service, "127.0.0.1:0")
            .expect("map doc service");
    }
    registry.bind_all().expect("bind doc services");
    let module = oxdock_ssh_plugin::module_with_endpoints(registry);
    let proc = oxdock_process::default_process_manager();
    oxdock_core::assert_module_returns_conformance(
        "SSH",
        &module.funcs,
        vec![module.clone()],
        proc,
    );
}

fn read_trimmed(path: &GuardedPath) -> String {
    use oxdock_fs::PathResolver;
    let resolver = PathResolver::new(path.root(), path.root()).unwrap();
    resolver
        .read_to_string(path)
        .unwrap_or_default()
        .trim()
        .to_string()
}

/// Read the addr file a script writes after serving. Polls with a
/// deadline so a slow start fails loudly instead of racing the write.
fn read_addr(probe: &GuardedPath) -> String {
    let deadline = Instant::now() + Duration::from_secs(10);
    loop {
        let addr = read_trimmed(&probe.join("addr.txt").unwrap());
        if !addr.is_empty() {
            return addr;
        }
        if Instant::now() >= deadline {
            panic!("addr file never appeared");
        }
        std::thread::sleep(Duration::from_millis(50));
    }
}

/// Read a stage file a script writes mid-run. Same deadline discipline
/// as `read_addr`, for driver/script rendezvous points.
fn poll_file(probe: &GuardedPath, name: &str) -> String {
    let deadline = Instant::now() + Duration::from_secs(10);
    loop {
        let text = read_trimmed(&probe.join(name).unwrap());
        if !text.is_empty() {
            return text;
        }
        if Instant::now() >= deadline {
            panic!("{name} file never appeared");
        }
        std::thread::sleep(Duration::from_millis(50));
    }
}

/// Runner-mapped registry for one service: the harness binds ephemeral
/// loopback, the script only ever names the service. Mirrors a CLI
/// `-p 127.0.0.1:0:<service>` invocation.
fn mapped_registry(service: &str) -> Arc<oxdock_net_plugin::EndpointRegistry> {
    let registry = Arc::new(oxdock_net_plugin::EndpointRegistry::new(false));
    registry
        .add_cli_mapping(service, "127.0.0.1:0")
        .expect("map service");
    registry.bind_all().expect("bind service");
    registry
}

/// Runner-mapped memory registry for services: in-process rendezvous
/// by explicit runner designation. SSH rejects these pre-run; NET
/// rendezvous on them.
fn memory_registry(services: &[&str]) -> Arc<oxdock_net_plugin::EndpointRegistry> {
    let registry = Arc::new(oxdock_net_plugin::EndpointRegistry::new(false));
    for service in services {
        registry
            .add_mapping(
                &oxdock_net_plugin::EndpointKey::tcp(oxdock_net_plugin::VirtualEndpoint::Name(
                    service.to_string(),
                )),
                oxdock_net_plugin::BindingSpec::Memory,
            )
            .expect("map memory service");
    }
    registry
}

/// Script marker stamped with the test's runtime password (minted per
/// test with oxdock_ssh_plugin::generate_password, so the repo holds
/// no usable secret).
const PASSWORD_MARKER: &str = "__TEST_PASSWORD__";

/// Real bound address of a mapped service, for the `TestClient` driver.
fn service_addr(registry: &Arc<oxdock_net_plugin::EndpointRegistry>, service: &str) -> SocketAddr {
    registry
        .bound_addr(&oxdock_net_plugin::EndpointKey::tcp(
            oxdock_net_plugin::VirtualEndpoint::Name(service.to_string()),
        ))
        .expect("service bound")
}

/// Hold a numeric service name nobody else holds: bind ephemeral, read
/// the port back, and rebind it, retrying against parallel tests racing
/// for the same port. Used ONLY by the anti-binding proofs, where the
/// script must name a number the host never bound. A plugin that stole
/// the number fails every retry, so theft still fails deterministically.
fn hold_numeric_name() -> (std::net::TcpListener, String) {
    for _ in 0..50 {
        let port = std::net::TcpListener::bind("127.0.0.1:0")
            .expect("ephemeral bind")
            .local_addr()
            .expect("addr")
            .port();
        match std::net::TcpListener::bind(format!("127.0.0.1:{port}")) {
            Ok(held) => return (held, port.to_string()),
            Err(_) => continue,
        }
    }
    panic!("could not hold a numeric service name");
}

struct TestHandler;

impl russh::client::Handler for TestHandler {
    type Error = anyhow::Error;

    async fn check_server_key(
        &mut self,
        _server_public_key: &russh::keys::PublicKeyOrCertificate,
    ) -> anyhow::Result<bool> {
        Ok(true)
    }
}

/// Synchronous loopback SSH client for tests.
struct TestClient {
    runtime: tokio::runtime::Runtime,
    session: russh::client::Handle<TestHandler>,
    reader: russh::ChannelReadHalf,
    writer: russh::ChannelWriteHalf<russh::client::Msg>,
}

impl TestClient {
    fn connect(addr: SocketAddr, user: &str, password: &str) -> anyhow::Result<Self> {
        Self::connect_impl(addr, user, password, None, None)
    }

    /// Connect requesting the given `exec` command instead of a shell.
    /// The server announces the session with the command attached, so
    /// scripts can route before pumping.
    fn connect_exec(
        addr: SocketAddr,
        user: &str,
        password: &str,
        command: &str,
    ) -> anyhow::Result<Self> {
        Self::connect_impl(addr, user, password, None, Some(command))
    }

    /// Connect requesting a pseudo-terminal first, like interactive
    /// clients do. The server answers without allocating one.
    fn connect_with_pty(addr: SocketAddr, user: &str, password: &str) -> anyhow::Result<Self> {
        Self::connect_impl(addr, user, password, Some((80, 24)), None)
    }

    /// Connect with explicit pty dimensions (cols, rows).
    fn connect_with_pty_dims(
        addr: SocketAddr,
        user: &str,
        password: &str,
        cols: u16,
        rows: u16,
    ) -> anyhow::Result<Self> {
        Self::connect_impl(addr, user, password, Some((cols, rows)), None)
    }

    /// Send a live window-change for the open channel.
    fn window_change(&mut self, cols: u32, rows: u32) -> anyhow::Result<()> {
        self.runtime
            .block_on(self.writer.window_change(cols, rows, 0, 0))
            .map_err(|err| anyhow::anyhow!("window_change failed: {err}"))?;
        Ok(())
    }

    fn connect_impl(
        addr: SocketAddr,
        user: &str,
        password: &str,
        pty_dims: Option<(u16, u16)>,
        exec_command: Option<&str>,
    ) -> anyhow::Result<Self> {
        let runtime = tokio::runtime::Builder::new_multi_thread()
            .worker_threads(1)
            .enable_all()
            .build()?;
        let (session, reader, writer) = runtime.block_on(async {
            let config = Arc::new(russh::client::Config::default());
            let mut session = russh::client::connect(config, addr, TestHandler).await?;
            let auth = session.authenticate_password(user, password).await?;
            if !matches!(auth, russh::client::AuthResult::Success) {
                anyhow::bail!("test client authentication rejected");
            }
            let channel = session.channel_open_session().await?;
            if let Some((cols, rows)) = pty_dims {
                channel
                    .request_pty(
                        true,
                        "xterm-256color",
                        u32::from(cols),
                        u32::from(rows),
                        0,
                        0,
                        &[],
                    )
                    .await?;
            }
            if let Some(command) = exec_command {
                channel.exec(true, command).await?;
            } else {
                channel.request_shell(true).await?;
            }
            let (mut reader, writer) = channel.split();
            // Synchronize with the server: each want_reply request above
            // is answered with Success once processed (exec/shell requests
            // announce the session first). Returning before the acks lets
            // an immediate close win the race and strand the session
            // unannounced, hanging the dequeuer.
            let mut acks = 1 + usize::from(pty_dims.is_some());
            while acks > 0 {
                match tokio::time::timeout(Duration::from_secs(10), reader.wait())
                    .await
                    .map_err(|_| anyhow::anyhow!("no request acknowledgement from server"))?
                {
                    Some(russh::ChannelMsg::Success) => acks -= 1,
                    Some(_) => {}
                    None => anyhow::bail!("server closed the channel during handshake"),
                }
            }
            Ok::<_, anyhow::Error>((session, reader, writer))
        })?;
        Ok(Self {
            runtime,
            session,
            reader,
            writer,
        })
    }

    fn send(&mut self, bytes: &[u8]) -> anyhow::Result<()> {
        self.runtime
            .block_on(self.writer.data_bytes(bytes::Bytes::copy_from_slice(bytes)))
            .map_err(|err| anyhow::anyhow!("test client send failed: {err}"))?;
        Ok(())
    }

    /// Read until `needle` appears in the stream or `timeout` elapses.
    fn read_until(&mut self, needle: &[u8], timeout: Duration) -> anyhow::Result<Vec<u8>> {
        let deadline = Instant::now() + timeout;
        let mut collected = Vec::new();
        while !collected
            .windows(needle.len())
            .any(|window| window == needle)
        {
            let remaining = deadline
                .checked_duration_since(Instant::now())
                .unwrap_or_default();
            if remaining.is_zero() {
                anyhow::bail!("timed out waiting for echo");
            }
            let message = self
                .runtime
                .block_on(async { tokio::time::timeout(remaining, self.reader.wait()).await })
                .map_err(|_| anyhow::anyhow!("timed out waiting for echo"))?
                .ok_or_else(|| anyhow::anyhow!("server closed the channel"))?;
            if let russh::ChannelMsg::Data { data } = message {
                collected.extend_from_slice(&data);
            }
        }
        Ok(collected)
    }

    fn close(self) {
        let Self {
            runtime, session, ..
        } = self;
        let _ = runtime.block_on(session.disconnect(russh::Disconnect::ByApplication, "", ""));
    }

    /// Half-close our stdin: the server observes EOF while the channel
    /// stays open for the reply and the close.
    fn eof(&mut self) -> anyhow::Result<()> {
        self.runtime
            .block_on(self.writer.eof())
            .map_err(|err| anyhow::anyhow!("test client eof failed: {err}"))?;
        Ok(())
    }

    /// Wait for the server to close the channel, skipping any straggler
    /// messages. Times out loudly: a server that never closes a drained
    /// pump strands the client.
    fn wait_close(&mut self, timeout: Duration) -> anyhow::Result<()> {
        let deadline = Instant::now() + timeout;
        loop {
            let remaining = deadline
                .checked_duration_since(Instant::now())
                .unwrap_or_default();
            if remaining.is_zero() {
                anyhow::bail!("timed out waiting for server close");
            }
            let message = self
                .runtime
                .block_on(async { tokio::time::timeout(remaining, self.reader.wait()).await })
                .map_err(|_| anyhow::anyhow!("timed out waiting for server close"))?;
            if message.is_none() {
                return Ok(());
            }
        }
    }

    /// Wait for the server's `exit-status` request. Data, acks, and a
    /// pre-status EOF are skipped like stock clients skip them; close or
    /// timeout bails.
    fn wait_exit_status(&mut self, timeout: Duration) -> anyhow::Result<u32> {
        let deadline = Instant::now() + timeout;
        loop {
            let remaining = deadline
                .checked_duration_since(Instant::now())
                .unwrap_or_default();
            if remaining.is_zero() {
                anyhow::bail!("timed out waiting for exit-status");
            }
            let message = self
                .runtime
                .block_on(async { tokio::time::timeout(remaining, self.reader.wait()).await })
                .map_err(|_| anyhow::anyhow!("timed out waiting for exit-status"))?
                .ok_or_else(|| anyhow::anyhow!("server closed the channel before exit-status"))?;
            match message {
                russh::ChannelMsg::ExitStatus { exit_status } => return Ok(exit_status),
                russh::ChannelMsg::Close => {
                    anyhow::bail!("channel ended before exit-status")
                }
                _ => {}
            }
        }
    }
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn serve_and_close_roundtrip() {
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-serve-close");
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-serve-close", {username: "guest", password: "close-pass"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $closed: BOOL = SSH_CLOSE($m.server)
        WRITE closed.txt "{{ $closed }}"
    "#};
    run_script_with(registry, &root, script).expect("serve and close runs");
    let addr = read_trimmed(&root.join("addr.txt").unwrap());
    assert!(
        addr.starts_with("127.0.0.1:") && !addr.ends_with(":0"),
        "mapped service reports its real bind: {addr}"
    );
    assert_eq!(read_trimmed(&root.join("closed.txt").unwrap()), "true");
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn wrong_password_rejected() {
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-auth");
    let right = oxdock_ssh_plugin::generate_password();
    let wrong = format!("{right}-wrong");
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-auth", {username: "guest", password: "__TEST_PASSWORD__"})
        SLEEP 8s
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &right);
    // Pre-bound by the harness: the driver addr is known before spawning.
    let addr = service_addr(&registry, "test-ssh-auth");
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    std::thread::sleep(Duration::from_secs(2));
    // Timed: russh pads every rejection to at least `auth_rejection_time`
    // (the client's opening `none` probe included), so a 1s padding
    // stalls each password prompt by a noticeable beat. The rejection
    // must land far under a second.
    let start = Instant::now();
    let wrong = TestClient::connect(addr, "guest", &wrong);
    let elapsed = start.elapsed();
    assert!(wrong.is_err(), "wrong password must be rejected");
    assert!(
        elapsed < Duration::from_millis(800),
        "wrong-password rejection took {elapsed:?}: auth padding regressed"
    );
    let wrong_user = TestClient::connect(addr, "intruder", &right);
    assert!(wrong_user.is_err(), "wrong username must be rejected");
    handle
        .join()
        .expect("script thread joins")
        .expect("run session completes");
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn accept_echo_roundtrip() {
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-echo");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-echo", {username: "guest", password: "__TEST_PASSWORD__"})
        LET $in: PIPE
        LET $out: PIPE
        LET $acc: HANDLE<VOID> = ASYNC { SSH_ACCEPT($m.server, $in, $out) }
        LET $echo: HANDLE<VOID> = ASYNC { SSH_PUMP($out, $in) }
        AWAIT $acc
        AWAIT $echo
        SSH_CLOSE($m.server)
"#}.replace(PASSWORD_MARKER, &pass);
    let addr = service_addr(&registry, "test-ssh-echo");
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    std::thread::sleep(Duration::from_secs(2));
    let mut client = TestClient::connect(addr, "guest", &pass).expect("client connects");
    client.send(b"hello-echo").expect("client sends");
    let echoed = client
        .read_until(b"hello-echo", Duration::from_secs(10))
        .expect("echo returns");
    assert!(
        echoed.windows(10).any(|window| window == b"hello-echo"),
        "echoed bytes must round-trip"
    );
    client.close();
    handle
        .join()
        .expect("script thread joins")
        .expect("script completes after disconnect");
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn pty_request_accepted_echo_roundtrip() {
    // Interactive shape: pty request, then shell, then bytes. The server
    // answers the pty request without allocating a terminal, and the
    // session must proceed to full duplex like a pty-less one.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-pty");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-pty", {username: "guest", password: "__TEST_PASSWORD__"})
        LET $in: PIPE
        LET $out: PIPE
        LET $acc: HANDLE<VOID> = ASYNC { SSH_ACCEPT($m.server, $in, $out) }
        LET $echo: HANDLE<VOID> = ASYNC { SSH_PUMP($out, $in) }
        AWAIT $acc
        AWAIT $echo
        SSH_CLOSE($m.server)
"#}.replace(PASSWORD_MARKER, &pass);
    let addr = service_addr(&registry, "test-ssh-pty");
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    std::thread::sleep(Duration::from_secs(2));
    let mut client =
        TestClient::connect_with_pty(addr, "guest", &pass).expect("pty client connects");
    client.send(b"hello-pty").expect("client sends");
    let echoed = client
        .read_until(b"hello-pty", Duration::from_secs(10))
        .expect("echo returns");
    assert!(
        echoed.windows(9).any(|window| window == b"hello-pty"),
        "echoed bytes must round-trip"
    );
    client.close();
    handle
        .join()
        .expect("script thread joins")
        .expect("script completes after disconnect");
}

/// Drive an outer session that resizes mid-stream, then give the
/// change time to flush through TCP and the poll loop before dropping:
/// `block_on` returns after queueing, not after delivery.
fn drive_outer_resize(addr: SocketAddr, pass: &str, cols: u16, rows: u16) {
    let mut client =
        TestClient::connect_with_pty_dims(addr, "u", pass, 90, 30).expect("client connects");
    std::thread::sleep(Duration::from_secs(1));
    client
        .window_change(u32::from(cols), u32::from(rows))
        .expect("resize sends");
    std::thread::sleep(Duration::from_secs(2));
}

#[test]
#[cfg_attr(
    miri,
    ignore = "needs loopback TCP plus threads plus a terminal plus subprocesses"
)]
fn pty_explicit_size() {
    // A pty sized explicitly must report exactly that size. The session
    // comes from DEQUEUE; explicit dims override whatever the client
    // requested. Unix reads `stty size` ("rows cols"); ConPTY answers
    // `mode con`.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-pty-size");
    let probe = root.clone();
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-pty-size", {username: "u", password: "__TEST_PASSWORD__"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $child: LIST<STRING> = ["sh", "-c", "stty size"]
        [family:windows] {
            $child = ["cmd", "/c", "mode con"]
        }
        LET $h: HANDLE<VOID> = ASYNC {
            LET $dq: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            LET $in: PIPE
            LET $out: PIPE
            LET $t: HANDLE<INT> = ASYNC { RETURN SSH_PTY_RUN($dq.session, $child, 40, 100, $in, $out) }
            AWAIT $t
            [family:unix] {
                ASSERT_CONTAINS $out "40 100"
            }
            [family:windows] {
                ASSERT_CONTAINS $out "Lines:"
                ASSERT_CONTAINS $out "40"
                ASSERT_CONTAINS $out "Columns:"
                ASSERT_CONTAINS $out "100"
            }
        }
        AWAIT $h
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    let addr = read_addr(&probe);
    let addr: SocketAddr = addr.parse().expect("addr parses");
    let client = TestClient::connect(addr, "u", &pass).expect("client connects");
    handle
        .join()
        .expect("script thread joins")
        .expect("explicit pty size runs");
    client.close();
}

#[test]
#[cfg(unix)]
#[cfg_attr(
    miri,
    ignore = "needs loopback TCP plus threads plus a terminal plus subprocesses"
)]
fn outer_window_change_reaches_pty_child_unix() {
    // End-to-end resize: the client opens 97x37, reads one `stty size`
    // line per newline sent, then a live window-change must move the
    // child's next report to 41x121. The child exits on stdin EOF, so
    // closing the client drains every task with no cancellation.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-resize-unix");
    let probe = root.clone();
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-resize-unix", {username: "u", password: "__TEST_PASSWORD__"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $h: HANDLE<VOID> = ASYNC {
            LET $dq: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            LET $c_in: PIPE
            LET $c_out: PIPE
            LET $t: HANDLE<INT> = ASYNC { RETURN SSH_PTY_RUN($dq.session, ["sh", "-c", "while IFS= read -r line; do stty size; done"], 0, 0, $c_out, $c_in) }
            LET $p: HANDLE<VOID> = ASYNC { SSH_PUMP_CHANNEL($dq.session, $c_in, $c_out) }
            AWAIT $t
            AWAIT $p
        }
        AWAIT $h
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    let addr = read_addr(&probe);
    let addr: SocketAddr = addr.parse().expect("addr parses");
    let mut client =
        TestClient::connect_with_pty_dims(addr, "u", &pass, 97, 37).expect("client connects");
    client.send(b"\n").expect("client prompts first report");
    client
        .read_until(b"37 97", Duration::from_secs(15))
        .expect("child reports opener size");
    client.window_change(121, 41).expect("window-change sends");
    client.send(b"\n").expect("client prompts resized report");
    let resized = client
        .read_until(b"41 121", Duration::from_secs(15))
        .expect("child reports resized window");
    assert!(
        resized.windows(6).any(|window| window == b"41 121"),
        "resized report must arrive, got: {resized:?}"
    );
    client.close();
    handle
        .join()
        .expect("script thread joins")
        .expect("resize script completes after disconnect");
}

#[test]
#[cfg(windows)]
#[cfg_attr(
    miri,
    ignore = "needs loopback TCP plus threads plus a terminal plus subprocesses"
)]
fn outer_window_change_reaches_pty_child_windows() {
    // Windows half of the resize proof: the client opens 97x37, reads
    // one console-size line per newline sent, then a live
    // window-change must move the child's next report to 41x121
    // through ConPTY. Tagged `W=`/`H=` lines keep the assertions
    // unambiguous under `mode`-style alignment. Console stdin has no
    // EOF (`ReadLine` blocks until a line arrives even after the
    // pipes close), so the child exits on an explicit `quit` line
    // the test sends before closing: disconnect alone can never
    // reap it. Unix proves the same path in
    // `outer_window_change_reaches_pty_child_unix`.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-resize-windows");
    let probe = root.clone();
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-resize-windows", {username: "u", password: "__TEST_PASSWORD__"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $h: HANDLE<VOID> = ASYNC {
            LET $dq: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            LET $c_in: PIPE
            LET $c_out: PIPE
            LET $t: HANDLE<INT> = ASYNC { RETURN SSH_PTY_RUN($dq.session, ["powershell", "-NoProfile", "-Command", "while (($l = [Console]::In.ReadLine()) -ne $null) { if ($l -eq 'quit') { Write-Output 'BYE'; break }; Write-Output \"W=$([Console]::WindowWidth) H=$([Console]::WindowHeight)\" }"], 0, 0, $c_out, $c_in) }
            LET $p: HANDLE<VOID> = ASYNC { SSH_PUMP_CHANNEL($dq.session, $c_in, $c_out) }
            AWAIT $t
            AWAIT $p
        }
        AWAIT $h
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    let addr = read_addr(&probe);
    let addr: SocketAddr = addr.parse().expect("addr parses");
    let mut client =
        TestClient::connect_with_pty_dims(addr, "u", &pass, 97, 37).expect("client connects");
    client.send(b"\n").expect("client prompts first report");
    // Same startup grace as the unit resize proof: PowerShell 5.1
    // cold-starts slowly on shared CI runners.
    client
        .read_until(b"W=97 H=37", Duration::from_secs(60))
        .expect("child reports opener size");
    client.window_change(121, 41).expect("window-change sends");
    client.send(b"\n").expect("client prompts resized report");
    let resized = client
        .read_until(b"W=121 H=41", Duration::from_secs(60))
        .expect("child reports resized window");
    assert!(
        resized.windows(10).any(|window| window == b"W=121 H=41"),
        "resized report must arrive, got: {resized:?}"
    );
    // Console stdin has no EOF: tell the child to exit and wait for
    // its goodbye before disconnecting, so the quit line cannot race
    // the teardown. The exit then completes the script join.
    client.send(b"quit\n").expect("client stops the child");
    let _goodbye = client
        .read_until(b"BYE", Duration::from_secs(15))
        .expect("child confirms exit");
    client.close();
    handle
        .join()
        .expect("script thread joins")
        .expect("resize script completes after disconnect");
}

#[test]
#[cfg_attr(
    miri,
    ignore = "needs loopback TCP plus threads plus a terminal plus subprocesses"
)]
fn pty_child_sees_session_env() {
    // Block-scoped ENV rides into the pty spawn: the child observes the
    // dequeued session's identity (user, client and server addresses,
    // requested command) through SSH_* vars. Unix expands `$VAR`;
    // ConPTY expands `%VAR%`.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-env");
    let probe = root.clone();
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-env", {username: "u", password: "__TEST_PASSWORD__"})
        WRITE addr.txt "{{ $m.addr }}"
        ENV PROBE_TOP="top"
        LET $child: LIST<STRING> = ["sh", "-c", "echo relay:$SSH_USER:$SSH_CLIENT:$SSH_SERVER:$SSH_COMMAND:$PROBE_TOP"]
        [family:windows] {
            $child = ["cmd", "/c", "echo relay:%SSH_USER%:%SSH_CLIENT%:%SSH_SERVER%:%SSH_COMMAND%:%PROBE_TOP%"]
        }
        LET $h: HANDLE<VOID> = ASYNC {
            LET $dq: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            ENV SSH_USER="{{ $dq.username }}"
            ENV SSH_CLIENT="{{ $dq.addr }}"
            ENV SSH_SERVER="{{ $m.addr }}"
            ENV SSH_COMMAND="{{ $dq.command }}"
            LET $in: PIPE
            LET $out: PIPE
            LET $t: HANDLE<VOID> = ASYNC { SSH_PTY_RUN($dq.session, $child, 0, 0, $in, $out) }
            AWAIT $t
            ASSERT_CONTAINS $out "relay:u:127.0.0.1:"
            ASSERT_CONTAINS $out "127.0.0.1:"
            ASSERT_CONTAINS $out "probe-command"
            ASSERT_CONTAINS $out ":top"
        }
        AWAIT $h
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    let addr = read_addr(&probe);
    let addr: SocketAddr = addr.parse().expect("addr parses");
    let client =
        TestClient::connect_exec(addr, "u", &pass, "probe-command").expect("client connects");
    handle
        .join()
        .expect("script thread joins")
        .expect("session env relay runs");
    client.close();
}

#[test]
#[cfg(unix)]
#[cfg_attr(
    miri,
    ignore = "needs loopback TCP plus threads plus forkpty plus subprocesses"
)]
fn argv_preserves_quote_backslash_unix() {
    // Unix-only by construction: asserts `execvp` delivers argv
    // byte-verbatim. Windows joins argv into one command line by
    // design, so the same assertion cannot hold there; the Windows
    // side pins its own contract in the `cmd_*` tests below.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-argv-unix");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-argv-unix", {username: "u", password: "__TEST_PASSWORD__"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $h: HANDLE<VOID> = ASYNC {
            LET $dq: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            LET $in: PIPE
            LET $out: PIPE
            LET $t: HANDLE<INT> = ASYNC { RETURN SSH_PTY_RUN($dq.session, ["printf", "%s", $dq.command], 0, 0, $in, $out) }
            LET $code: INT = AWAIT $t
            ASSERT_EQ $code 0
            ASSERT_CONTAINS $out "a\"b\\c"
        }
        AWAIT $h
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let probe = root.clone();
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    let addr = read_addr(&probe);
    let addr: SocketAddr = addr.parse().expect("addr parses");
    let client = TestClient::connect_exec(addr, "u", &pass, "a\"b\\c").expect("client connects");
    client.close();
    handle
        .join()
        .expect("script thread joins")
        .expect("run session completes");
}

/// Poll this run's worker count to zero. The run is finite and the
/// counter attributes only its own workers, so zero is reachable
/// exactly when nothing leaked; expiry fails loudly, never hangs.
fn poll_workers_zero(workers: &Arc<AtomicU64>, timeout: Duration) -> bool {
    let start = Instant::now();
    while workers.load(Ordering::SeqCst) != 0 {
        if start.elapsed() >= timeout {
            return false;
        }
        std::thread::sleep(Duration::from_millis(50));
    }
    true
}

#[test]
#[cfg(unix)]
#[cfg_attr(
    miri,
    ignore = "needs loopback TCP plus threads plus a real subprocess plus a daemonized grandchild"
)]
fn run_cancel_with_orphan_stdout_returns_promptly() {
    // A daemonized grandchild holds the child's stdout open past every
    // kill: `sh` backgrounds `sleep` and exits at once, and the reaper
    // zeroes the pid on wait, so the cancel-time kill is a no-op and
    // nothing ever signals the orphan. The output worker parks in its
    // read forever. The supervisor must still return promptly on
    // cancellation; only the parked worker is left behind (it drains
    // when the orphan dies, asserted below). Under a joining scope
    // this test hangs instead of failing it.
    // Own telemetry: the run stages this counter and every forked
    // task hub shares it, so the poll below observes exactly this
    // script's workers under any parallel load.
    let workers = Arc::new(AtomicU64::new(0));
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-run-orphan");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-run-orphan", {username: "u", password: "__TEST_PASSWORD__"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $h: HANDLE<VOID> = ASYNC {
            LET $dq: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            LET $to_child: PIPE
            LET $from_child: PIPE
            LET $err: PIPE
            LET $run: HANDLE<INT> = ASYNC { LET $c: INT = TIMEOUT 8s SSH_RUN($dq.session, ["sh", "-c", "sleep 20 >&1 &"], $to_child, $from_child, $err); RETURN $c }
            LET $code: INT = AWAIT $run
            ASSERT_EQ $code 0
        }
        AWAIT $h
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let probe = root.clone();
    let session_workers = Arc::clone(&workers);
    let handle = std::thread::spawn(move || {
        run_script_with_workers(registry, &root, &script, session_workers)
    });
    let addr = read_addr(&probe);
    let addr: SocketAddr = addr.parse().expect("addr parses");
    let _client = TestClient::connect(addr, "u", &pass).expect("client connects");
    let start = Instant::now();
    let err = handle
        .join()
        .expect("script thread joins")
        .expect_err("cancelling past an orphan-held pipe must fail the TIMEOUT, fast");
    let elapsed = start.elapsed();
    assert!(
        format!("{err:#}").contains("TIMEOUT"),
        "TIMEOUT owns the failure, not the hang: {err:#}",
    );
    assert!(
        elapsed >= Duration::from_secs(7),
        "the timeout ran its course first: {elapsed:?}",
    );
    assert!(
        elapsed < Duration::from_secs(20),
        "cancellation returned promptly past the orphan: {elapsed:?}",
    );
    // The orphan outlives the assertion by design; its death drains
    // the parked worker. Malfunction would leave this run's count
    // elevated forever, so zero proves the leak is bounded by the
    // orphan's life, not the session's.
    assert!(
        poll_workers_zero(&workers, Duration::from_secs(90)),
        "parked workers drain when the orphan dies",
    );
}

#[test]
#[cfg_attr(
    miri,
    ignore = "needs loopback TCP plus threads plus real subprocesses"
)]
fn pump_workers_drain_after_completion_and_cancel() {
    // Hygiene for the common case: workers of finished sessions must
    // drain back to zero, on the clean path and on cancellation
    // (non-orphan: every wake fires, so nothing parks). Own
    // telemetry, so concurrent tests cannot pollute the observation.
    let workers = Arc::new(AtomicU64::new(0));
    // Clean echo session first.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-drain-clean");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-drain-clean", {username: "guest", password: "__TEST_PASSWORD__"})
        LET $in: PIPE
        LET $out: PIPE
        LET $acc: HANDLE<VOID> = ASYNC { SSH_ACCEPT($m.server, $in, $out) }
        LET $echo: HANDLE<VOID> = ASYNC { SSH_PUMP($out, $in) }
        AWAIT $acc
        AWAIT $echo
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let addr = service_addr(&registry, "test-ssh-drain-clean");
    let clean_workers = Arc::clone(&workers);
    let handle = std::thread::spawn(move || {
        run_script_with_workers(registry, &root, &script, clean_workers)
    });
    std::thread::sleep(Duration::from_secs(2));
    let mut client = TestClient::connect(addr, "guest", &pass).expect("client connects");
    client.send(b"drain-me").expect("client sends");
    client
        .read_until(b"drain-me", Duration::from_secs(10))
        .expect("echo returns");
    client.close();
    handle
        .join()
        .expect("script thread joins")
        .expect("clean session completes");
    assert!(
        poll_workers_zero(&workers, Duration::from_secs(90)),
        "workers drain after a clean session",
    );
    // Cancelled session second: connect, then cancel the client leg.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-drain-cancel");
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-drain-cancel", {username: "guest", password: "__TEST_PASSWORD__"})
        LET $in: PIPE
        LET $out: PIPE
        LET $acc: HANDLE<VOID> = ASYNC { SSH_ACCEPT($m.server, $in, $out) }
        LET $cin: PIPE
        LET $cout: PIPE
        LET $c: HANDLE<VOID> = ASYNC { SSH_CONNECT("test-ssh-drain-cancel", "guest", "__TEST_PASSWORD__", $cin, $cout) }
        WITH_IO [stdout=$in] ECHO "server-greeting"
        AWAIT $acc
        CANCEL $c
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let cancel_workers = Arc::clone(&workers);
    let handle = std::thread::spawn(move || {
        run_script_with_workers(registry, &root, &script, cancel_workers)
    });
    handle
        .join()
        .expect("script thread joins")
        .expect("cancelled session completes end to end");
    assert!(
        poll_workers_zero(&workers, Duration::from_secs(90)),
        "workers drain after cancellation",
    );
}

#[test]
#[cfg(windows)]
#[cfg_attr(
    miri,
    ignore = "needs loopback TCP plus threads plus ConPTY plus subprocesses"
)]
fn cmd_argv_preserves_backslashes_windows() {
    // Issue 223 claim, `cmd`-specific: backslashes without quotes must
    // survive the argv to command-line join literally. No Unix twin:
    // Unix never joins, proven by `argv_preserves_quote_backslash_unix`.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-argv-bs-win");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-argv-bs-win", {username: "u", password: "__TEST_PASSWORD__"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $h: HANDLE<VOID> = ASYNC {
            LET $dq: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            LET $in: PIPE
            LET $out: PIPE
            LET $t: HANDLE<INT> = ASYNC { RETURN SSH_PTY_RUN($dq.session, ["cmd", "/c", $dq.command], 0, 0, $in, $out) }
            LET $code: INT = AWAIT $t
            ASSERT_EQ $code 0
            ASSERT_CONTAINS $out "AB\\CD"
        }
        AWAIT $h
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let probe = root.clone();
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    let addr = read_addr(&probe);
    let addr: SocketAddr = addr.parse().expect("addr parses");
    let client =
        TestClient::connect_exec(addr, "u", &pass, "echo AB\\CD").expect("client connects");
    client.close();
    handle
        .join()
        .expect("script thread joins")
        .expect("backslashes survive argv");
}

#[test]
#[cfg(windows)]
#[cfg_attr(
    miri,
    ignore = "needs loopback TCP plus threads plus ConPTY plus subprocesses"
)]
fn cmd_env_quote_behavior_windows() {
    // Quoted segments travel through the environment relay instead of
    // `cmd /c` argv: the join quotes for CRT programs, which `cmd`
    // does not parse back, so command text rides `%SSH_COMMAND%`
    // verbatim (see issue 223).
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-env-q-win");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-env-q-win", {username: "u", password: "__TEST_PASSWORD__"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $h: HANDLE<VOID> = ASYNC {
            LET $dq: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            ENV SSH_COMMAND="{{ $dq.command }}"
            LET $in: PIPE
            LET $out: PIPE
            LET $t: HANDLE<INT> = ASYNC { RETURN SSH_PTY_RUN($dq.session, ["cmd", "/c", "%SSH_COMMAND%"], 0, 0, $in, $out) }
            LET $code: INT = AWAIT $t
            ASSERT_EQ $code 0
            ASSERT_CONTAINS $out "\"foo bar\""
        }
        AWAIT $h
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let probe = root.clone();
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    let addr = read_addr(&probe);
    let addr: SocketAddr = addr.parse().expect("addr parses");
    let client =
        TestClient::connect_exec(addr, "u", &pass, "echo \"foo bar\"").expect("client connects");
    client.close();
    handle
        .join()
        .expect("script thread joins")
        .expect("quotes survive env relay");
}

#[test]
#[cfg(windows)]
#[cfg_attr(
    miri,
    ignore = "needs loopback TCP plus threads plus ConPTY plus subprocesses"
)]
fn cmd_argv_percent_verbatim_windows() {
    // Issue 223 claim, `cmd`-specific: percent signs travel verbatim
    // through the spawn with no doubling. No Unix twin: `%` is
    // ordinary data outside `cmd`.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-argv-pct-win");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-argv-pct-win", {username: "u", password: "__TEST_PASSWORD__"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $h: HANDLE<VOID> = ASYNC {
            LET $dq: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            LET $in: PIPE
            LET $out: PIPE
            LET $t: HANDLE<INT> = ASYNC { RETURN SSH_PTY_RUN($dq.session, ["cmd", "/c", $dq.command], 0, 0, $in, $out) }
            LET $code: INT = AWAIT $t
            ASSERT_EQ $code 0
            ASSERT_CONTAINS $out "100%%done"
        }
        AWAIT $h
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let probe = root.clone();
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    let addr = read_addr(&probe);
    let addr: SocketAddr = addr.parse().expect("addr parses");
    let client =
        TestClient::connect_exec(addr, "u", &pass, "echo 100%%done").expect("client connects");
    client.close();
    handle
        .join()
        .expect("script thread joins")
        .expect("percent signs survive argv");
}

#[test]
#[cfg(windows)]
#[cfg_attr(
    miri,
    ignore = "needs loopback TCP plus threads plus ConPTY plus subprocesses"
)]
fn env_relay_preserves_backslashes_windows() {
    // Environment relay is byte-verbatim: backslash runs in the
    // dequeued command must reach `cmd` untouched. Windows-only
    // because the corruption claim (issue 223 bug 2) is about `cmd`
    // observing the relay; the shared verbatim path is proven on both
    // platforms by `pty_child_sees_session_env`.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-env-bs-win");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-env-bs-win", {username: "u", password: "__TEST_PASSWORD__"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $h: HANDLE<VOID> = ASYNC {
            LET $dq: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            ENV SSH_COMMAND="{{ $dq.command }}"
            LET $in: PIPE
            LET $out: PIPE
            LET $t: HANDLE<INT> = ASYNC { RETURN SSH_PTY_RUN($dq.session, ["cmd", "/c", "%SSH_COMMAND%"], 0, 0, $in, $out) }
            LET $code: INT = AWAIT $t
            ASSERT_EQ $code 0
            ASSERT_CONTAINS $out "AB\\CD\\\\EF"
        }
        AWAIT $h
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let probe = root.clone();
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    let addr = read_addr(&probe);
    let addr: SocketAddr = addr.parse().expect("addr parses");
    let client =
        TestClient::connect_exec(addr, "u", &pass, "echo AB\\CD\\\\EF").expect("client connects");
    client.close();
    handle
        .join()
        .expect("script thread joins")
        .expect("backslashes survive env relay");
}

#[test]
#[cfg(windows)]
#[cfg_attr(
    miri,
    ignore = "needs loopback TCP plus threads plus ConPTY plus subprocesses"
)]
fn cmd_env_relay_quoted_reg_query_windows() {
    // The windows-headless TODO, verbatim: plain quoted `reg query`
    // paths must work once the transport is faithful. They do through
    // the environment relay: quotes reach `cmd` untouched, so the key
    // resolves instead of looking up a `\"...`-prefixed name.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-env-reg-win");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-env-reg-win", {username: "u", password: "__TEST_PASSWORD__"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $h: HANDLE<VOID> = ASYNC {
            LET $dq: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            ENV SSH_COMMAND="{{ $dq.command }}"
            LET $in: PIPE
            LET $out: PIPE
            LET $t: HANDLE<INT> = ASYNC { RETURN SSH_PTY_RUN($dq.session, ["cmd", "/c", "%SSH_COMMAND%"], 0, 0, $in, $out) }
            LET $code: INT = AWAIT $t
            ASSERT_EQ $code 0
            ASSERT_CONTAINS $out "SetupType"
            ASSERT_CONTAINS $out "REG_DWORD"
        }
        AWAIT $h
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let probe = root.clone();
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    let addr = read_addr(&probe);
    let addr: SocketAddr = addr.parse().expect("addr parses");
    let client = TestClient::connect_exec(
        addr,
        "u",
        &pass,
        "reg query \"HKLM\\SYSTEM\\Setup\" /v SetupType",
    )
    .expect("client connects");
    client.close();
    handle
        .join()
        .expect("script thread joins")
        .expect("quoted reg query resolves");
}

#[test]
#[cfg(windows)]
#[cfg_attr(
    miri,
    ignore = "needs loopback TCP plus threads plus ConPTY plus subprocesses"
)]
fn cmd_env_relay_full_probe_windows() {
    // The windows-headless readiness probe, verbatim
    // (`src/ssh.rs::reg_probe_command` on feat/oxdock-ssh): `&`-chained
    // queries with `2>nul` redirects, `set` + `call` deferred expansion
    // with single `%`, and `&&`/`||` verdicts. All five markers must
    // arrive through the environment relay, proving the quote-free
    // contortions are unnecessary: this exact shape runs unmodified.
    // The single `%` also proves interpolation never touches `%`.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-env-probe-win");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-env-probe-win", {username: "u", password: "__TEST_PASSWORD__"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $h: HANDLE<VOID> = ASYNC {
            LET $dq: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            ENV SSH_COMMAND="{{ $dq.command }}"
            LET $in: PIPE
            LET $out: PIPE
            LET $t: HANDLE<INT> = ASYNC { RETURN SSH_PTY_RUN($dq.session, ["cmd", "/c", "%SSH_COMMAND%"], 0, 0, $in, $out) }
            LET $code: INT = AWAIT $t
            ASSERT_EQ $code 0
            ASSERT_CONTAINS $out "[SETUP]"
            ASSERT_CONTAINS $out "[OOBE]"
            ASSERT_CONTAINS $out "[CBS]"
            ASSERT_CONTAINS $out "[WU]"
            ASSERT_CONTAINS $out "[END]"
            ASSERT_CONTAINS $out "SetupType"
        }
        AWAIT $h
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let probe = root.clone();
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    let addr = read_addr(&probe);
    let addr: SocketAddr = addr.parse().expect("addr parses");
    let command = [
        "echo [SETUP]",
        "reg query HKLM\\SYSTEM\\Setup /v SetupType 2>nul",
        "echo [OOBE]",
        "reg query HKLM\\SYSTEM\\Setup /v OOBEInProgress 2>nul",
        "echo [CBS]",
        "set WHCBSK=HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Component Based Servicing\\RebootPending& call reg query %WHCBSK% 2>nul && echo YES || echo NO",
        "echo [WU]",
        "set WHWUK=HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update\\RebootRequired& call reg query %WHWUK% 2>nul && echo YES || echo NO",
        "echo [END]",
    ]
    .join(" & ");
    let client = TestClient::connect_exec(addr, "u", &pass, &command).expect("client connects");
    client.close();
    handle
        .join()
        .expect("script thread joins")
        .expect("full probe runs unmodified");
}

#[test]
#[cfg(windows)]
#[cfg_attr(
    miri,
    ignore = "needs loopback TCP plus threads plus ConPTY plus subprocesses"
)]
fn cmd_env_relay_quoted_powershell_windows() {
    // The windows-headless diet TODO: a plain quoted `-Command` string
    // carrying a pipeline must survive. The relay hands `cmd` the text
    // verbatim; `cmd` keeps the quoted pipe inside the argument, and
    // PowerShell parses the pipeline itself.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-env-ps-win");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-env-ps-win", {username: "u", password: "__TEST_PASSWORD__"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $h: HANDLE<VOID> = ASYNC {
            LET $dq: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            ENV SSH_COMMAND="{{ $dq.command }}"
            LET $in: PIPE
            LET $out: PIPE
            LET $t: HANDLE<INT> = ASYNC { RETURN SSH_PTY_RUN($dq.session, ["cmd", "/c", "%SSH_COMMAND%"], 0, 0, $in, $out) }
            LET $code: INT = AWAIT $t
            ASSERT_EQ $code 0
            ASSERT_CONTAINS $out "QP-ALPHA"
            ASSERT_CONTAINS $out "QP-BETA"
        }
        AWAIT $h
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let probe = root.clone();
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    let addr = read_addr(&probe);
    let addr: SocketAddr = addr.parse().expect("addr parses");
    let client = TestClient::connect_exec(
        addr,
        "u",
        &pass,
        "powershell -NoProfile -Command \"'qp-alpha','qp-beta' | ForEach-Object { $_.ToUpper() }\"",
    )
    .expect("client connects");
    client.close();
    handle
        .join()
        .expect("script thread joins")
        .expect("quoted powershell pipeline runs");
}

#[test]
#[cfg(windows)]
#[cfg_attr(
    miri,
    ignore = "needs loopback TCP plus threads plus ConPTY plus subprocesses"
)]
fn interactive_shell_first_bytes_survive_windows() {
    // Windows-only stress probe for the issue 223 first-keystroke loss:
    // the suspected race site is the ConPTY console-setup handshake,
    // which has no Unix counterpart. Each of several fresh pty+shell
    // connections sends a marker immediately after the handshake, and
    // every marker must round-trip through the echo pump.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-shell-stress");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-shell-stress", {username: "guest", password: "__TEST_PASSWORD__"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $i: INT = 0
        WHILE $i < 10 {
            LET $in: PIPE
            LET $out: PIPE
            LET $acc: HANDLE<VOID> = ASYNC { SSH_ACCEPT($m.server, $in, $out) }
            LET $echo: HANDLE<VOID> = ASYNC { SSH_PUMP($out, $in) }
            AWAIT $acc
            AWAIT $echo
            $i = $i + 1
        }
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let probe = root.clone();
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    let addr = read_addr(&probe);
    let addr: SocketAddr = addr.parse().expect("addr parses");
    for i in 0..10 {
        let marker = format!("first-byte-{i}");
        let mut client =
            TestClient::connect_with_pty(addr, "guest", &pass).expect("client connects");
        client.send(marker.as_bytes()).expect("client sends");
        let echoed = client
            .read_until(marker.as_bytes(), Duration::from_secs(10))
            .expect("marker round-trips");
        assert!(
            echoed
                .windows(marker.len())
                .any(|window| window == marker.as_bytes()),
            "session {i} must deliver its first bytes"
        );
        client.close();
    }
    handle
        .join()
        .expect("script thread joins")
        .expect("stress script completes");
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn semaphore_guards_the_accept_loop() {
    // End to end of the proxy admission shape: cap 1 admits the first
    // session into a worker, rejects the second while the permit is
    // held, and admits a third after the worker returns (release on
    // task return, no decrement code anywhere).
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-sem");
    let probe = root.clone();
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-sem", {username: "guest", password: "__TEST_PASSWORD__"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
        LET $w: HANDLE<BOOL> = ASYNC {
            LET $s1: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            LET $a1: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
            LET $held1: BOOL = $a1.held
            ASSERT_EQ $held1 true
            LET $permit: PERMIT = $a1.permit
            WRITE stage1.txt "admitted"
            LET $hold: HANDLE<BOOL> = ASYNC {
                LET $s2: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
                LET $a2: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
                WRITE rejected.txt "{{ $a2.held }}"
                RETURN $a2.held
            }
            LET $r: BOOL = AWAIT $hold
            ASSERT_EQ $r false
            RETURN $r
        }
        LET $res: BOOL = AWAIT $w
        ASSERT_EQ $res false
        LET $t3: HANDLE<MAP<ANY>> = ASYNC { RETURN SSH_DEQUEUE($m.server) }
        LET $s3: MAP<ANY> = AWAIT $t3
        LET $a3: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
        WRITE admitted.txt "{{ $a3.held }}"
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    let addr = read_addr(&probe);
    let addr: SocketAddr = addr.parse().expect("addr parses");
    let client_a = TestClient::connect(addr, "guest", &pass).expect("first client connects");
    poll_file(&probe, "stage1.txt");
    let client_b = TestClient::connect(addr, "guest", &pass).expect("second client connects");
    assert_eq!(poll_file(&probe, "rejected.txt"), "false");
    let client_c = TestClient::connect(addr, "guest", &pass).expect("third client connects");
    handle
        .join()
        .expect("script thread joins")
        .expect("guarded accept loop runs");
    assert_eq!(
        read_trimmed(&probe.join("admitted.txt").unwrap()),
        "true",
        "cap frees after worker return"
    );
    client_a.close();
    client_b.close();
    client_c.close();
}

#[test]
#[cfg_attr(
    miri,
    ignore = "needs loopback TCP plus threads plus a terminal plus subprocesses"
)]
fn pty_live_resize() {
    // An outer window-change mid-session must resize the local terminal.
    // The session's own cell carries the resize; other sessions never
    // see it. Unix reads `stty size` after a delay; ConPTY answers
    // `mode con` (`ping` is the delay hack: `timeout` can interact
    // with stdin).
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-resize");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-resize", {username: "u", password: "__TEST_PASSWORD__"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $child: LIST<STRING> = ["sh", "-c", "sleep 4; stty size"]
        [family:windows] {
            $child = ["cmd", "/c", "ping -n 5 127.0.0.1 >nul & mode con"]
        }
        LET $h: HANDLE<VOID> = ASYNC {
            LET $dq: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            LET $in: PIPE
            LET $out: PIPE
            LET $t: HANDLE<VOID> = ASYNC { SSH_PTY_RUN($dq.session, $child, 0, 0, $in, $out) }
            AWAIT $t
            [family:unix] {
                ASSERT_CONTAINS $out "50 120"
            }
            [family:windows] {
                ASSERT_CONTAINS $out "Lines:"
                ASSERT_CONTAINS $out "50"
                ASSERT_CONTAINS $out "Columns:"
                ASSERT_CONTAINS $out "120"
            }
        }
        AWAIT $h
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    let addr_path = temp.as_guarded_path().join("addr.txt").unwrap();
    let addr: SocketAddr = loop {
        std::thread::sleep(Duration::from_millis(100));
        let text = read_trimmed(&addr_path);
        if !text.is_empty() {
            break text.parse().expect("addr parses");
        }
    };
    drive_outer_resize(addr, &pass, 120, 50);
    handle
        .join()
        .expect("script thread joins")
        .expect("resize script completes");
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn main_thread_accept_bails() {
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-main-accept");
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-main-accept", {username: "guest", password: "pass"})
        LET $in: PIPE
        LET $out: PIPE
        SSH_ACCEPT($m.server, $in, $out)
    "#};
    let err = run_script_with(registry, &root, script).expect_err("main-thread ACCEPT must bail");
    assert!(format!("{err:#}").contains("requires ASYNC"), "{err:#}");
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn teardown_wakes_blocked_accept() {
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-teardown");
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-teardown", {username: "guest", password: "pass"})
        LET $in: PIPE
        LET $out: PIPE
        LET $t: HANDLE<VOID> = ASYNC { SSH_ACCEPT($m.server, $in, $out) }
        SLEEP 2s
        SSH_CLOSE($m.server)
        AWAIT $t
    "#};
    let start = Instant::now();
    let err = run_script_with(registry, &root, script).expect_err("ACCEPT must fail after close");
    // ASYNC task errors now carry the full causal chain across the task
    // boundary, so the inner close reason is visible end to end.
    assert!(format!("{err:#}").contains("closed"), "{err:#}");
    assert!(
        start.elapsed() < Duration::from_secs(15),
        "close must wake the waiter promptly"
    );
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn cancel_mid_pump_terminates() {
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $a: PIPE
        LET $b: PIPE
        LET $t: HANDLE<VOID> = ASYNC SSH_PUMP($a, $b)
        TIMEOUT 2s AWAIT $t
    "#};
    let start = Instant::now();
    let err = run_script(&root, script).expect_err("silent pump must time out");
    assert!(format!("{err:#}").contains("TIMEOUT"), "{err}");
    assert!(
        start.elapsed() < Duration::from_secs(10),
        "pump must not outlive its timeout"
    );
}

#[test]
#[cfg(unix)]
#[cfg_attr(
    miri,
    ignore = "needs loopback TCP plus threads plus a Tokio runtime plus subprocesses"
)]
fn inner_exit_closes_outer_session() {
    // Nano analog: the RUN leg produces output and exits while the outer
    // client stays connected. The inner death must propagate outer-ward
    // (response flushes, then the channel closes) instead of stranding
    // ACCEPT in its pump with the client hanging.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-inner-exit");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-inner-exit", {username: "test", password: "__TEST_PASSWORD__"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $c_in: PIPE
        LET $c_out: PIPE
        LET $acc: HANDLE<VOID> = ASYNC { SSH_ACCEPT($m.server, $c_in, $c_out) }
        WITH_IO [stdin=$c_out, stdout=$c_in] RUN ["sh", "-c", "echo canned-response"]
        AWAIT $acc
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let (done_tx, done_rx) = std::sync::mpsc::channel();
    let handle = std::thread::spawn(move || {
        let result = run_script_with(registry, &root, &script);
        let _ = done_tx.send(());
        result
    });
    let addr_path = temp.as_guarded_path().join("addr.txt").unwrap();
    let addr: SocketAddr = loop {
        std::thread::sleep(Duration::from_millis(100));
        let text = read_trimmed(&addr_path);
        if !text.is_empty() {
            break text.parse().expect("addr parses");
        }
    };
    let start = Instant::now();
    let mut client = TestClient::connect(addr, "test", &pass).expect("client connects");
    client
        .read_until(b"canned-response", Duration::from_secs(10))
        .expect("inner output arrives");
    // Stay connected: the script must still finish on its own once the
    // inner leg is gone, and the client must observe the close.
    let closed = done_rx.recv_timeout(Duration::from_secs(15)).is_ok();
    assert!(closed, "script must complete after inner exit");
    assert!(
        start.elapsed() < Duration::from_secs(25),
        "teardown must not stall"
    );
    drop(client);
    handle
        .join()
        .expect("script thread joins")
        .expect("script completes");
}

#[test]
#[cfg(unix)]
#[cfg_attr(
    miri,
    ignore = "needs loopback TCP plus threads plus a Tokio runtime plus subprocesses"
)]
fn real_openssh_client_echo_roundtrip() {
    // The real `ssh` binary (password via SSH_ASKPASS, no tty anywhere)
    // through ACCEPT plus an echo PUMP: pins the diagnosis that an
    // interactive password prompt on a synthetic pty is the only
    // openssh configuration that stalls, client-side and pre-auth.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-real-client");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r##"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        WRITE askpass.sh "#!/bin/sh\necho __TEST_PASSWORD__\n"
        RUN ["chmod", "+x", "askpass.sh"]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-real-client", {username: "test", password: "__TEST_PASSWORD__"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $in: PIPE
        LET $out: PIPE
        LET $acc: HANDLE<VOID> = ASYNC { SSH_ACCEPT($m.server, $in, $out) }
        LET $echo: HANDLE<VOID> = ASYNC { SSH_PUMP($out, $in) }
        AWAIT $acc
        AWAIT $echo
        SSH_CLOSE($m.server)
    "##}.replace(PASSWORD_MARKER, &pass);
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    let addr_path = temp.as_guarded_path().join("addr.txt").unwrap();
    let addr = loop {
        std::thread::sleep(Duration::from_millis(100));
        let text = read_trimmed(&addr_path);
        if !text.is_empty() {
            break text;
        }
    };
    let askpass = temp
        .as_guarded_path()
        .join("askpass.sh")
        .unwrap()
        .as_path()
        .display()
        .to_string();
    let shell_command = format!(
        "printf 'hello-openssh' | SSH_ASKPASS=\"{askpass}\" SSH_ASKPASS_REQUIRE=force ssh -T -p {} -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o PreferredAuthentications=password -o PubkeyAuthentication=no -o LogLevel=ERROR test@{}",
        addr.trim()
            .rsplit_once(':')
            .map(|(_, port)| port)
            .unwrap_or("0"),
        addr.trim()
            .rsplit_once(':')
            .map(|(host, _)| host)
            .unwrap_or("127.0.0.1"),
    );
    let mut cmd = oxdock_process::CommandBuilder::new("sh");
    cmd.args(["-c".to_string(), shell_command]);
    cmd.current_dir(temp.as_guarded_path().as_path());
    let output = cmd.output().expect("run outer ssh");
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("hello-openssh"),
        "real ssh must round-trip through cat, got: {stdout:?} stderr: {:?}",
        String::from_utf8_lossy(&output.stderr)
    );
    handle
        .join()
        .expect("script thread joins")
        .expect("script completes after disconnect");
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn proxy_outer_to_inner_roundtrip() {
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let outer = oxdock_ssh_plugin::generate_password();
    let inner = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $o: SSH_SERVE_INFO = SSH_SERVE("test-ssh-proxy-outer", {username: "outer", password: "__OUTER_PASSWORD__"})
        LET $i: SSH_SERVE_INFO = SSH_SERVE("test-ssh-proxy-inner", {username: "inner", password: "__INNER_PASSWORD__"})
        LET $j_in: PIPE
        LET $j_out: PIPE
        LET $h_inner: HANDLE<VOID> = ASYNC { SSH_ACCEPT($i.server, $j_in, $j_out) }
        LET $h_iecho: HANDLE<VOID> = ASYNC { SSH_PUMP($j_out, $j_in) }
        LET $c_in: PIPE
        LET $c_out: PIPE
        LET $i_in: PIPE
        LET $i_out: PIPE
        LET $h_conn: HANDLE<VOID> = ASYNC { SSH_CONNECT("test-ssh-proxy-inner", "inner", "__INNER_PASSWORD__", $i_in, $i_out) }
        LET $h_p1: HANDLE<VOID> = ASYNC { SSH_PUMP($c_out, $i_in) }
        LET $h_p2: HANDLE<VOID> = ASYNC { SSH_PUMP($i_out, $c_in) }
        LET $h_acc: HANDLE<VOID> = ASYNC { SSH_ACCEPT($o.server, $c_in, $c_out) }
        AWAIT $h_acc
        AWAIT $h_conn
        AWAIT $h_p1
        AWAIT $h_p2
        AWAIT $h_inner
        AWAIT $h_iecho
        SSH_CLOSE($o.server)
        SSH_CLOSE($i.server)
    "#}.replace("__OUTER_PASSWORD__", &outer).replace("__INNER_PASSWORD__", &inner);
    // One registry maps both legs; the inner CONNECT goes through the
    // mapped name, never a physical dial.
    let registry = mapped_registry("test-ssh-proxy-outer");
    registry
        .add_cli_mapping("test-ssh-proxy-inner", "127.0.0.1:0")
        .expect("map inner");
    registry.bind_all().expect("bind inner");
    let addr = service_addr(&registry, "test-ssh-proxy-outer");
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    std::thread::sleep(Duration::from_secs(3));
    let mut client = TestClient::connect(addr, "outer", &outer).expect("outer client connects");
    client.send(b"proxy-ping").expect("client sends");
    let echoed = client
        .read_until(b"proxy-ping", Duration::from_secs(15))
        .expect("proxied echo returns");
    assert!(
        echoed.windows(10).any(|window| window == b"proxy-ping"),
        "bytes must traverse both SSH legs"
    );
    client.close();
    handle
        .join()
        .expect("script thread joins")
        .expect("proxy script completes after disconnect");
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn unknown_serve_option_bails() {
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-bad-option");
    let err = run_script_with(
        registry,
        &root,
        indoc! {r#"
            IMPORT [STD, SSH]
            INHERIT_ENV [PATH]
            LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-bad-option", {username: "guest", password: "pass", frobnicate: 1})
            SSH_CLOSE($m.server)
        "#},
    )
    .expect_err("unknown option must fail");
    assert!(
        format!("{err:#}").contains("unknown option 'frobnicate'"),
        "{err:#}"
    );
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn non_map_serve_options_bails() {
    // MAP-typed options enforce at the pre-pass: a non-map fails
    // statically with TypeMismatch before any socket opens.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-bad-options");
    let err = run_script_with(
        registry,
        &root,
        indoc! {r#"
            IMPORT [STD, SSH]
            INHERIT_ENV [PATH]
            LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-bad-options", "nope")
            SSH_CLOSE($m.server)
        "#},
    )
    .expect_err("non-map options must fail");
    assert!(err.to_string().contains("TypeMismatch"), "{err:#}");
    assert!(err.to_string().contains("expected MAP"), "{err:#}");
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn missing_username_bails() {
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-no-user");
    let err = run_script_with(
        registry,
        &root,
        indoc! {r#"
            IMPORT [STD, SSH]
            INHERIT_ENV [PATH]
            LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-no-user", {password: "pass"})
            SSH_CLOSE($m.server)
        "#},
    )
    .expect_err("missing username must fail");
    assert!(
        format!("{err:#}").contains("option 'username' is required"),
        "{err:#}"
    );
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn empty_password_bails() {
    // A server without credentials is meaningless: no silent ephemeral
    // password is generated.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-empty-pass");
    let err = run_script_with(
        registry,
        &root,
        indoc! {r#"
            IMPORT [STD, SSH]
            INHERIT_ENV [PATH]
            LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-empty-pass", {username: "guest", password: ""})
            SSH_CLOSE($m.server)
        "#},
    )
    .expect_err("empty password must fail");
    assert!(
        format!("{err:#}").contains("option 'password' must not be empty"),
        "{err:#}"
    );
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn missing_password_bails() {
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-no-pass");
    let err = run_script_with(
        registry,
        &root,
        indoc! {r#"
            IMPORT [STD, SSH]
            INHERIT_ENV [PATH]
            LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-no-pass", {username: "guest"})
            SSH_CLOSE($m.server)
        "#},
    )
    .expect_err("missing password must fail");
    assert!(
        format!("{err:#}").contains("option 'password' is required"),
        "{err:#}"
    );
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn non_string_username_bails() {
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-bad-user-type");
    let err = run_script_with(
        registry,
        &root,
        indoc! {r#"
            IMPORT [STD, SSH]
            INHERIT_ENV [PATH]
            LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-bad-user-type", {username: 1, password: "pass"})
            SSH_CLOSE($m.server)
        "#},
    )
    .expect_err("non-string username must fail");
    assert!(
        format!("{err:#}").contains("option 'username': expected STRING, got INT"),
        "{err:#}"
    );
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn unknown_option_names_all_valid_keys() {
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-frobnicate");
    let err = run_script_with(
        registry,
        &root,
        indoc! {r#"
            IMPORT [STD, SSH]
            INHERIT_ENV [PATH]
            LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-frobnicate", {username: "guest", password: "pass", frobnicate: 1})
            SSH_CLOSE($m.server)
        "#},
    )
    .expect_err("unknown option must fail");
    assert!(
        format!("{err:#}").contains("(expected: username, password, key_path, idle_timeout)"),
        "{err:#}"
    );
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn non_string_key_path_bails() {
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-bad-keypath-type");
    let err = run_script_with(
        registry,
        &root,
        indoc! {r#"
            IMPORT [STD, SSH]
            INHERIT_ENV [PATH]
            LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-bad-keypath-type", {username: "guest", password: "pass", key_path: 1})
            SSH_CLOSE($m.server)
        "#},
    )
    .expect_err("non-string key_path must fail");
    assert!(
        format!("{err:#}").contains("expected STRING, got INT"),
        "{err:#}"
    );
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn stable_host_key_reused_across_restarts() {
    use oxdock_fs::PathResolver;
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-key-stable");
    let serve_first = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-key-stable", {username: "guest", password: "key-pass", key_path: "ssh_host_key"})
        SSH_CLOSE($m.server)
    "#};
    let serve_second = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-key-stable", {username: "guest", password: "key-pass", key_path: "ssh_host_key"})
        SSH_CLOSE($m.server)
    "#};
    run_script_with(registry.clone(), &root, serve_first).expect("first boot creates the key");
    let resolver = PathResolver::new(root.root(), root.root()).unwrap();
    let key_path = root.join("ssh_host_key").unwrap();
    let first = resolver.read_file(&key_path).expect("key file exists");
    assert!(
        first.starts_with(b"-----BEGIN OPENSSH PRIVATE KEY-----"),
        "key file is OpenSSH PEM"
    );
    run_script_with(registry.clone(), &root, serve_second).expect("second boot loads the key");
    let second = resolver.read_file(&key_path).expect("key file still there");
    assert_eq!(first, second, "restart must reuse the key, not regenerate");
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn loaded_host_key_serves_clients() {
    // Behavioral proof the loaded key is a working host key: create it on
    // one boot, then run a full echo roundtrip on the next. Both boots
    // serve mapped names: key loading happens past acquisition.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-key-first");
    let pass = oxdock_ssh_plugin::generate_password();
    registry
        .add_cli_mapping("test-ssh-key-client", "127.0.0.1:0")
        .expect("map client service");
    registry.bind_all().expect("bind client service");
    let first_boot = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-key-first", {username: "guest", password: "__TEST_PASSWORD__", key_path: "ssh_host_key"})
        SSH_CLOSE($m.server)
    "#}
    .replace(PASSWORD_MARKER, &pass);
    run_script_with(registry.clone(), &root, &first_boot).expect("first boot creates the key");
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-key-client", {username: "guest", password: "__TEST_PASSWORD__", key_path: "ssh_host_key"})
        LET $in: PIPE
        LET $out: PIPE
        LET $acc: HANDLE<VOID> = ASYNC { SSH_ACCEPT($m.server, $in, $out) }
        LET $echo: HANDLE<VOID> = ASYNC { SSH_PUMP($out, $in) }
        AWAIT $acc
        AWAIT $echo
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let addr = service_addr(&registry, "test-ssh-key-client");
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    std::thread::sleep(Duration::from_secs(2));
    let mut client = TestClient::connect(addr, "guest", &pass).expect("client connects");
    client.send(b"stable-key-echo").expect("client sends");
    let echoed = client
        .read_until(b"stable-key-echo", Duration::from_secs(10))
        .expect("echo returns");
    assert!(
        echoed
            .windows(15)
            .any(|window| window == b"stable-key-echo"),
        "echoed bytes must round-trip on the loaded key"
    );
    client.close();
    handle
        .join()
        .expect("script thread joins")
        .expect("script completes after disconnect");
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
#[cfg(unix)]
fn created_host_key_has_owner_only_permissions() {
    use oxdock_fs::PathResolver;
    use std::os::unix::fs::PermissionsExt;
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-key-perms");
    run_script_with(registry,
        &root,
        indoc! {r#"
            IMPORT [STD, SSH]
            INHERIT_ENV [PATH]
            LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-key-perms", {username: "guest", password: "key-pass", key_path: "ssh_host_key"})
            SSH_CLOSE($m.server)
        "#},
    )
    .expect("boot creates the key");
    let resolver = PathResolver::new(root.root(), root.root()).unwrap();
    let key_path = root.join("ssh_host_key").unwrap();
    let mode = resolver
        .metadata(&key_path)
        .expect("key stat")
        .permissions()
        .mode()
        & 0o777;
    assert_eq!(mode, 0o600, "created key must be owner-only, got 0{mode:o}");
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn invalid_host_key_file_bails() {
    use oxdock_fs::PathResolver;
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-key-invalid");
    let resolver = PathResolver::new(root.root(), root.root()).unwrap();
    let key_path = root.join("ssh_host_key").unwrap();
    resolver.write_file(&key_path, b"not-a-key").unwrap();
    // Owner-only permissions so the test reaches the parse stage (the
    // permission gate runs first on Unix).
    resolver
        .set_permissions_mode_unix(&key_path, 0o600)
        .unwrap();
    let err = run_script_with(registry,
        &root,
        indoc! {r#"
            IMPORT [STD, SSH]
            INHERIT_ENV [PATH]
            LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-key-invalid", {username: "guest", password: "key-pass", key_path: "ssh_host_key"})
            SSH_CLOSE($m.server)
        "#},
    )
    .expect_err("invalid key must fail");
    assert!(
        format!("{err:#}").contains("cannot parse host key"),
        "{err:#}"
    );
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
#[cfg(unix)]
fn world_readable_host_key_bails() {
    use oxdock_fs::PathResolver;
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-key-world");
    let resolver = PathResolver::new(root.root(), root.root()).unwrap();
    let key_path = root.join("ssh_host_key").unwrap();
    run_script_with(registry.clone(),
        &root,
        indoc! {r#"
            IMPORT [STD, SSH]
            INHERIT_ENV [PATH]
            LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-key-world", {username: "guest", password: "key-pass", key_path: "ssh_host_key"})
            SSH_CLOSE($m.server)
        "#},
    )
    .expect("first boot creates the key");
    resolver
        .set_permissions_mode_unix(&key_path, 0o644)
        .unwrap();
    let err = run_script_with(registry.clone(),
        &root,
        indoc! {r#"
            IMPORT [STD, SSH]
            INHERIT_ENV [PATH]
            LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-key-world", {username: "guest", password: "key-pass", key_path: "ssh_host_key"})
            SSH_CLOSE($m.server)
        "#},
    )
    .expect_err("world-readable key must fail");
    let text = format!("{err:#}");
    assert!(
        text.contains("insecure permissions on host key file"),
        "{text}"
    );
    assert!(text.contains("expected 0600"), "{text}");
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn blank_key_path_keeps_ephemeral_key() {
    use oxdock_fs::PathResolver;
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-key-blank");
    run_script_with(registry,
        &root,
        indoc! {r#"
            IMPORT [STD, SSH]
            INHERIT_ENV [PATH]
            LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-key-blank", {username: "guest", password: "key-pass", key_path: ""})
            SSH_CLOSE($m.server)
        "#},
    )
    .expect("blank key_path serves");
    let resolver = PathResolver::new(root.root(), root.root()).unwrap();
    assert!(
        !resolver.exists(&root.join("ssh_host_key").unwrap()),
        "blank key_path must leave no trace"
    );
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn escaping_key_path_bails() {
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-key-escape");
    let err = run_script_with(registry,
        &root,
        indoc! {r#"
            IMPORT [STD, SSH]
            INHERIT_ENV [PATH]
            LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-key-escape", {username: "guest", password: "key-pass", key_path: "../escape_key"})
            SSH_CLOSE($m.server)
        "#},
    )
    .expect_err("escaping key_path must fail");
    assert!(
        format!("{err:#}").contains("escapes the workspace"),
        "{err:#}"
    );
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn leading_slash_key_path_anchors_to_workspace_root() {
    // A leading `/` means the workspace root (like WRITE), not the
    // filesystem root: both boots share `<root>/slash_key`.
    use oxdock_fs::PathResolver;
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-key-slash");
    let serve_first = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-key-slash", {username: "guest", password: "key-pass", key_path: "/slash_key"})
        SSH_CLOSE($m.server)
    "#};
    let serve_second = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-key-slash", {username: "guest", password: "key-pass", key_path: "/slash_key"})
        SSH_CLOSE($m.server)
    "#};
    run_script_with(registry.clone(), &root, serve_first).expect("first boot creates the key");
    let resolver = PathResolver::new(root.root(), root.root()).unwrap();
    let key_path = root.join("slash_key").unwrap();
    let first = resolver.read_file(&key_path).expect("key file exists");
    run_script_with(registry.clone(), &root, serve_second).expect("second boot loads the key");
    let second = resolver.read_file(&key_path).expect("key file still there");
    assert_eq!(first, second, "restart must reuse the key, not regenerate");
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn dequeue_exposes_metadata_before_pump() {
    // Control plane before byte plane: the exec command, username, and
    // peer address are visible the moment the request arrives, with no
    // pump started.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-dequeue");
    let addr = service_addr(&registry, "test-ssh-dequeue");
    let pass = oxdock_ssh_plugin::generate_password();
    let probe = root.clone();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-dequeue", {username: "guest", password: "__TEST_PASSWORD__"})
        LET $t: HANDLE<VOID> = ASYNC {
            LET $sess: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            WRITE meta.txt "{{ $sess.command }}|{{ $sess.username }}|{{ $sess.addr }}"
        }
        AWAIT $t
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    std::thread::sleep(Duration::from_secs(2));
    let client = TestClient::connect_exec(addr, "guest", &pass, "health-check")
        .expect("client exec connects");
    client.close();
    handle
        .join()
        .expect("script thread joins")
        .expect("script completes after dequeue");
    let meta = read_trimmed(&probe.join("meta.txt").unwrap());
    let mut parts = meta.split('|');
    assert_eq!(
        parts.next(),
        Some("health-check"),
        "exec command routed: {meta}"
    );
    assert_eq!(parts.next(), Some("guest"), "username visible: {meta}");
    let addr = parts.next().unwrap_or_default();
    assert!(
        addr.starts_with("127.0.0.1:"),
        "peer addr is loopback with client port: {meta}"
    );
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn virtual_command_router() {
    // The router shape: route on the dequeued command, serve a synthetic
    // reply from pure DSL logic (no OS binaries), pump it.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-router");
    let addr = service_addr(&registry, "test-ssh-router");
    let pass = oxdock_ssh_plugin::generate_password();
    let probe = root.clone();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-router", {username: "guest", password: "__TEST_PASSWORD__"})
        LET $t: HANDLE<VOID> = ASYNC {
            LET $sess: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            IF $sess.command == "health-check" {
                LET $in: PIPE
                LET $out: PIPE
                LET $p: HANDLE<VOID> = ASYNC { WITH_IO [stdout=$in] ECHO "System Status: OK" }
                SSH_PUMP_CHANNEL($sess.session, $in, $out)
                AWAIT $p
                WRITE routed.txt "health-check"
            } ELSE {
                WRITE routed.txt "rejected:{{ $sess.command }}"
            }
        }
        AWAIT $t
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    std::thread::sleep(Duration::from_secs(2));
    let mut client = TestClient::connect_exec(addr, "guest", &pass, "health-check")
        .expect("client exec connects");
    let reply = client
        .read_until(b"System Status: OK", Duration::from_secs(10))
        .expect("virtual command replies");
    assert!(
        reply
            .windows(17)
            .any(|window| window == b"System Status: OK"),
        "synthetic reply must stream"
    );
    client.close();
    handle
        .join()
        .expect("script thread joins")
        .expect("script completes after disconnect");
    assert_eq!(
        read_trimmed(&probe.join("routed.txt").unwrap()),
        "health-check",
        "router took the command branch"
    );
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn unknown_virtual_command_rejected_cleanly() {
    // No pump starts for unknown commands: the ELSE branch records the
    // rejection and the script completes without streaming anything.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-reject");
    let addr = service_addr(&registry, "test-ssh-reject");
    let pass = oxdock_ssh_plugin::generate_password();
    let probe = root.clone();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-reject", {username: "guest", password: "__TEST_PASSWORD__"})
        LET $t: HANDLE<VOID> = ASYNC {
            LET $sess: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            IF $sess.command == "health-check" {
                WRITE routed.txt "health-check"
            } ELSE {
                WRITE rejected.txt "rejected:{{ $sess.command }}"
            }
        }
        AWAIT $t
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    std::thread::sleep(Duration::from_secs(2));
    let client =
        TestClient::connect_exec(addr, "guest", &pass, "frobnicate").expect("client exec connects");
    client.close();
    handle
        .join()
        .expect("script thread joins")
        .expect("script completes without pumping");
    assert_eq!(
        read_trimmed(&probe.join("rejected.txt").unwrap()),
        "rejected:frobnicate",
        "unknown command took the ELSE branch"
    );
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn session_value_crosses_await_boundary() {
    // Probe: a dequeued session travels through task RETURN + AWAIT
    // binding without hanging or losing its ends.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-session");
    let addr = service_addr(&registry, "test-ssh-session");
    let pass = oxdock_ssh_plugin::generate_password();
    let probe = root.clone();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-session", {username: "guest", password: "__TEST_PASSWORD__"})
        LET $t: HANDLE<SSH_SESSION> = ASYNC {
            LET $sess: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            RETURN $sess.session
        }
        LET $s: SSH_SESSION = AWAIT $t
        WRITE stage.txt "bound"
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    std::thread::sleep(Duration::from_secs(2));
    let client = TestClient::connect_exec(addr, "guest", &pass, "x").expect("client exec connects");
    client.close();
    handle
        .join()
        .expect("script thread joins")
        .expect("session crosses await");
    assert_eq!(
        read_trimmed(&probe.join("stage.txt").unwrap()),
        "bound",
        "session value bound after await"
    );
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn pump_channel_second_pump_bails() {
    // Session ends are take-once: a second pump on the same session
    // bails instead of splitting bytes across pumps.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-pump-twice");
    let addr = service_addr(&registry, "test-ssh-pump-twice");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-pump-twice", {username: "guest", password: "__TEST_PASSWORD__"})
        LET $t: HANDLE<SSH_SESSION> = ASYNC {
            LET $sess: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            RETURN $sess.session
        }
        LET $s: SSH_SESSION = AWAIT $t
        LET $in: PIPE
        LET $out: PIPE
        LET $prod: HANDLE<VOID> = ASYNC { WITH_IO [stdout=$in] ECHO "in-bytes" }
        LET $p1: HANDLE<VOID> = ASYNC { SSH_PUMP_CHANNEL($s, $in, $out) }
        AWAIT $prod
        AWAIT $p1
        LET $p2: HANDLE<VOID> = ASYNC { SSH_PUMP_CHANNEL($s, $in, $out) }
        AWAIT $p2
    "#}.replace(PASSWORD_MARKER, &pass);
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    std::thread::sleep(Duration::from_secs(2));
    let client = TestClient::connect_exec(addr, "guest", &pass, "x").expect("client exec connects");
    client.close();
    let err = handle
        .join()
        .expect("script thread joins")
        .expect_err("second pump must fail");
    assert!(format!("{err:#}").contains("already pumped"), "{err:#}");
}

#[test]
fn worker_pool_script_parses() {
    // The multi-connection proto shape (LIST_APPEND handles in a WHILE loop, one
    // group AWAIT) must parse with the SSH module registered. Parse-only:
    // the script itself runs forever by design.
    let mut engine = Engine::new();
    engine.register_module(oxdock_ssh_plugin::module());
    let table = engine.module_table();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        WORKSPACE LOCAL

        LET $server: SSH_SERVE_INFO = SSH_SERVE(
            "test-ssh-pool-parse", {
                username: "test",
                password: "test123",
                key_path: "test_key"
            }
        )

        ECHO "ssh proxy listening on {{ $server.addr }} (login test)"

        LET $workers: LIST<ANY> = []
        LET $w: INT = 0
        WHILE $w < 4 {
            LET $h: HANDLE<VOID> = ASYNC {
                LET $run: BOOL = true
                WHILE $run {
                    LET $c_in: PIPE
                    LET $c_out: PIPE
                    LET $acc: HANDLE<VOID> = ASYNC { SSH_ACCEPT($server.server, $c_in, $c_out) }

                    LET $proc: HANDLE<VOID> = ASYNC {
                        WITH_IO [stdin=$c_out, stdout=$c_in] RUN ["ssh", "-o", "BatchMode=yes", "orb"]
                    }

                    AWAIT $acc
                    AWAIT $proc
                }
            }
            LIST_APPEND $workers $h
            $w = $w + 1
        }

        # Block main thread so background workers run indefinitely
        AWAIT $workers
    "#};
    let steps = oxdock_core::parse_script_with_modules(script, table).expect("pool parses");
    // IMPORT is a directive, not a step: INHERIT_ENV, WORKSPACE, LET,
    // ECHO, LET, LET, WHILE, AWAIT.
    assert_eq!(steps.len(), 8, "all pool steps lower");
    assert!(
        matches!(&steps[7].kind, oxdock_core::StepKind::Await { var } if var == "workers"),
        "pool ends with the group await, got {:?}",
        steps[7].kind
    );
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn finite_worker_pool_runs_to_completion() {
    // Same constructs as the infinite proto pool, but workers exit so the
    // group AWAIT terminates: proves LIST_APPEND-in-loop plus LIST AWAIT with the
    // SSH module registered.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    run_script(
        &root,
        indoc! {r#"
            IMPORT [STD, SSH]
            INHERIT_ENV [PATH]
            LET $workers: LIST<ANY> = []
            LET $w: INT = 0
            WHILE $w < 4 {
                LET $h: HANDLE<VOID> = ASYNC { ECHO "w{{ $w }}" }
                LIST_APPEND $workers $h
                $w = $w + 1
            }
            AWAIT $workers
            WRITE done.txt "ok"
        "#},
    )
    .expect("finite pool runs");
    assert_eq!(read_trimmed(&root.join("done.txt").unwrap()), "ok");
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn pool_accept_round_robins_across_workers() {
    // Multi-connection shape: 4 workers ACCEPTing on one server, joined by
    // one group AWAIT. Four sequential clients must all round-trip; every
    // leg here is a DSL pump (script pipes), so teardown propagates EOF.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-pool");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-pool", {username: "test", password: "__TEST_PASSWORD__"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $workers: LIST<ANY> = []
        LET $w: INT = 0
        WHILE $w < 4 {
            LET $h: HANDLE<VOID> = ASYNC {
                LET $in: PIPE
                LET $out: PIPE
                LET $acc: HANDLE<VOID> = ASYNC { SSH_ACCEPT($m.server, $in, $out) }
                LET $echo: HANDLE<VOID> = ASYNC { SSH_PUMP($out, $in) }
                AWAIT $acc
                AWAIT $echo
            }
            LIST_APPEND $workers $h
            $w = $w + 1
        }
        AWAIT $workers
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    let addr_path = temp.as_guarded_path().join("addr.txt").unwrap();
    let addr_str = {
        use oxdock_fs::PathResolver;
        let resolver = PathResolver::new(addr_path.root(), addr_path.root()).unwrap();
        let deadline = Instant::now() + Duration::from_secs(15);
        loop {
            if let Ok(s) = resolver.read_to_string(&addr_path) {
                let s = s.trim().to_string();
                if !s.is_empty() {
                    break s;
                }
            }
            assert!(
                Instant::now() < deadline,
                "server never wrote its addr (script hung before serving?)"
            );
            std::thread::sleep(Duration::from_millis(50));
        }
    };
    let addr: SocketAddr = addr_str.parse().expect("addr parses");
    for i in 0..4 {
        let needle = format!("echo4-ping-{i}");
        let mut client = TestClient::connect(addr, "test", &pass).expect("pool client connects");
        client.send(needle.as_bytes()).expect("client sends");
        let echoed = client
            .read_until(needle.as_bytes(), Duration::from_secs(15))
            .expect("pool echo returns");
        assert!(
            echoed.windows(needle.len()).any(|w| w == needle.as_bytes()),
            "session {i} must round-trip"
        );
        client.close();
    }
    handle
        .join()
        .expect("script thread joins")
        .expect("pool script completes after 4 sessions");
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
#[cfg(unix)]
fn pool_pty_run_companions_terminate() {
    // The supported multi-connection companion shape: each worker dequeues
    // its own session, pumps its bytes, and runs its companion command
    // against that session's size cell. Per-session work goes through the
    // native PTY runner, never WITH_IO RUN. Every leg stays a
    // script-backed DSL pump, so session teardown propagates EOF and the
    // group AWAIT joins. (Pairing ACCEPT with WITH_IO RUN over the same
    // pipes OS-promotes them: force-close stops working and teardown
    // hangs. That engine trap is tracked separately.)
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-pty-pool");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-pty-pool", {username: "test", password: "__TEST_PASSWORD__"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $workers: LIST<ANY> = []
        LET $w: INT = 0
        WHILE $w < 2 {
            LET $h: HANDLE<VOID> = ASYNC {
                LET $dq: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
                LET $c_in: PIPE
                LET $c_out: PIPE
                LET $acc: HANDLE<VOID> = ASYNC { SSH_PUMP_CHANNEL($dq.session, $c_in, $c_out) }
                LET $pty: HANDLE<VOID> = ASYNC { SSH_PTY_RUN($dq.session, ["cat"], 0, 0, $c_out, $c_in) }
                AWAIT $acc
                AWAIT $pty
            }
            LIST_APPEND $workers $h
            $w = $w + 1
        }
        AWAIT $workers
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    let addr_path = temp.as_guarded_path().join("addr.txt").unwrap();
    let addr_str = {
        use oxdock_fs::PathResolver;
        let resolver = PathResolver::new(addr_path.root(), addr_path.root()).unwrap();
        let deadline = Instant::now() + Duration::from_secs(15);
        loop {
            if let Ok(s) = resolver.read_to_string(&addr_path) {
                let s = s.trim().to_string();
                if !s.is_empty() {
                    break s;
                }
            }
            assert!(
                Instant::now() < deadline,
                "server never wrote its addr (script hung before serving?)"
            );
            std::thread::sleep(Duration::from_millis(50));
        }
    };
    let addr: SocketAddr = addr_str.parse().expect("addr parses");
    for i in 0..2 {
        let needle = format!("pty-ping-{i}");
        let mut client = TestClient::connect(addr, "test", &pass).expect("pool client connects");
        client.send(needle.as_bytes()).expect("client sends");
        let echoed = client
            .read_until(needle.as_bytes(), Duration::from_secs(15))
            .expect("pool echo returns");
        assert!(
            echoed.windows(needle.len()).any(|w| w == needle.as_bytes()),
            "session {i} must round-trip"
        );
        client.close();
    }
    handle
        .join()
        .expect("script thread joins")
        .expect("pty pool script completes after 2 sessions");
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn serve_reports_virtual_echo() {
    // Mapped services: the result MAP echoes the service name alongside
    // the runner-assigned bind.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-virtual-echo");
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-virtual-echo", {username: "guest", password: "pass"})
        WRITE addr.txt "{{ $m.addr }}"
        WRITE virt.txt "{{ $m.virtual }}"
        SSH_CLOSE($m.server)
    "#};
    run_script_with(registry, &root, script).expect("serve runs");
    let addr = read_trimmed(&root.join("addr.txt").unwrap());
    assert!(
        addr.starts_with("127.0.0.1:") && !addr.ends_with(":0"),
        "mapped service reports its real bind: {addr}"
    );
    assert_eq!(
        read_trimmed(&root.join("virt.txt").unwrap()),
        "test-ssh-virtual-echo"
    );
}

#[test]
#[cfg_attr(miri, ignore = "needs a Tokio runtime for the SSH module")]
fn physical_serve_binds_rejected_in_script() {
    // Scripts carry zero bind authority: physical shapes bail before any
    // key, socket, or thread work.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("127.0.0.1:23348", {username: "guest", password: "pass"})
    "#};
    let err = run_script(&root, script).expect_err("physical bind must fail");
    assert!(err.to_string().contains("logical endpoints"), "{err:#}");
}

/// The isolation mandate for SSH, proved end to end: a service named
/// like a port number never binds the host network. SERVE bails with
/// the CLI mapping hint, and the harness binds the number afterwards
/// to prove nothing took it.
#[test]
#[cfg_attr(miri, ignore = "needs a Tokio runtime for the SSH module")]
fn numeric_serve_never_binds() {
    let (held, number) = hold_numeric_name();
    drop(held);
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let script = format!(
        indoc! {r#"
            IMPORT [STD, SSH]
            INHERIT_ENV [PATH]
            LET $m: SSH_SERVE_INFO = SSH_SERVE("{number}", {{username: "guest", password: "pass"}})
        "#},
        number = number,
    );
    let err = run_script(&root, &script).expect_err("numeric serve must fail");
    assert!(
        err.to_string().contains(&format!(
            "SSH_SERVE service '{number}' has no CLI port mapping; pass -p <host_port>:{number} at invocation"
        )),
        "{err:#}"
    );
    // Nothing bound it: the harness retakes the number. Retry against
    // parallel tests; a plugin theft fails every attempt.
    let mut retaken = false;
    for _ in 0..50 {
        if std::net::TcpListener::bind(format!("127.0.0.1:{number}")).is_ok() {
            retaken = true;
            break;
        }
    }
    assert!(retaken, "number stayed free");
}

/// The dial half: a numeric service never dials either. The harness
/// holds the number open (bound, never accepting) while the script
/// CONNECTs; resolution bails before any socket work, and the harness
/// saw zero inbound connections.
#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn numeric_connect_never_dials() {
    let (held, number) = hold_numeric_name();
    held.set_nonblocking(true).expect("nonblocking");
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let script = format!(
        indoc! {r#"
            IMPORT [STD, SSH]
            INHERIT_ENV [PATH]
            LET $in: PIPE
            LET $out: PIPE
            LET $c: HANDLE<VOID> = ASYNC {{
                SSH_CONNECT("{number}", "guest", "pass", $in, $out)
            }}
            AWAIT $c
        "#},
        number = number,
    );
    let err = run_script(&root, &script).expect_err("numeric connect must fail");
    assert!(
        err.to_string().contains(&format!(
            "SSH_CONNECT service '{number}' has no CLI port mapping"
        )),
        "{err:#}"
    );
    // The script finished: any dial it made would sit in the backlog.
    // WouldBlock proves zero inbound connections were ever attempted.
    match held.accept() {
        Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {}
        accepted => panic!("numeric service touched the host network: {accepted:?}"),
    }
}

#[test]
#[cfg_attr(miri, ignore = "needs a Tokio runtime for the SSH module")]
fn memory_service_serve_rejected() {
    // SSH needs a TCP socket: serving a memory rendezvous bails loudly
    // instead of hanging a socketless server.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("ssh-mem-svc", {username: "guest", password: "pass"})
    "#};
    let err = run_script(&root, script).expect_err("memory serve must fail");
    assert!(
        err.to_string().contains("has no CLI port mapping"),
        "{err:#}"
    );
}

/// A memory-mapped service fails SSH before execution, not at the
/// serve step: the pre-run check enforces the socket requirement, so
/// even the preceding WRITE never happens.
#[test]
#[cfg_attr(miri, ignore = "needs a Tokio runtime for the SSH module")]
fn memory_mapped_serve_fails_before_execution() {
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = memory_registry(&["test-ssh-mem-mapped"]);
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        WRITE early.txt "must-not-exist"
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-mem-mapped", {username: "guest", password: "pass"})
        SSH_CLOSE($m.server)
    "#};
    let err = run_script_with(registry, &root, script).expect_err("memory serve must fail pre-run");
    assert!(
        err.to_string()
            .contains("SSH_SERVE service 'test-ssh-mem-mapped' has no CLI port mapping"),
        "{err:#}"
    );
    assert!(
        read_trimmed(&root.join("early.txt").unwrap()).is_empty(),
        "no step executed"
    );
}

#[test]
#[cfg_attr(miri, ignore = "needs a Tokio runtime for the SSH module")]
fn serve_reclaim_after_close_rebinds() {
    // Close-and-reclaim loops work: release frees the claim, so the next
    // SERVE on the same service re-claims the runner's socket.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-reclaim");
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $a: SSH_SERVE_INFO = SSH_SERVE("test-ssh-reclaim", {username: "guest", password: "pass"})
        SSH_CLOSE($a.server)
        LET $b: SSH_SERVE_INFO = SSH_SERVE("test-ssh-reclaim", {username: "guest", password: "pass"})
        ASSERT_EQ $a.addr $b.addr
        SSH_CLOSE($b.server)
    "#};
    run_script_with(registry, &root, script).expect("re-serve after close runs");
}

#[test]
#[cfg_attr(miri, ignore = "needs a Tokio runtime for the SSH module")]
fn offline_serve_and_close_opens_no_socket() {
    // `--offline` runs: SERVE returns a live handle echoing the virtual
    // endpoint with no thread and no socket; CLOSE tears it down.
    let registry = Arc::new(oxdock_net_plugin::EndpointRegistry::new(true));
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-offline-serve", {username: "guest", password: "pass"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $closed: BOOL = SSH_CLOSE($m.server)
        WRITE closed.txt "{{ $closed }}"
    "#};
    run_script_with(registry, &root, script).expect("offline serve runs");
    assert_eq!(
        read_trimmed(&root.join("addr.txt").unwrap()),
        "test-ssh-offline-serve"
    );
    assert_eq!(read_trimmed(&root.join("closed.txt").unwrap()), "true");
}

#[test]
#[cfg_attr(miri, ignore = "needs a Tokio runtime for the SSH module")]
fn offline_connect_bails_before_sockets() {
    // The sandbox gate fires before DNS or dial: a literal loopback dial
    // bails under `--offline`.
    let registry = Arc::new(oxdock_net_plugin::EndpointRegistry::new(true));
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $in: PIPE
        LET $out: PIPE
        LET $c: HANDLE<VOID> = ASYNC {
            SSH_CONNECT("test-ssh-offline-connect", "guest", "pass", $in, $out)
        }
        AWAIT $c
    "#};
    let err = run_script_with(registry, &root, script).expect_err("offline dial must fail");
    assert!(format!("{err:#}").contains("--offline mode"), "{err:#}");
}

#[test]
#[cfg(unix)]
#[cfg_attr(
    miri,
    ignore = "needs loopback TCP plus threads plus forkpty plus subprocesses"
)]
fn concurrent_guests_keep_their_own_pty_size() {
    // The reported bug: two guests with different terminal sizes must
    // each see their own dimensions. Sizes ride per-session cells from
    // pty-request to pump; a shared cell would let the second guest's
    // request clobber the first (last-writer-wins).
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-two-guests");
    let probe = root.clone();
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-two-guests", {username: "u", password: "__TEST_PASSWORD__"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $h: HANDLE<VOID> = ASYNC {
            LET $a: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            LET $b: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            LET $a_in: PIPE
            LET $a_out: PIPE
            LET $b_in: PIPE
            LET $b_out: PIPE
            LET $ta: HANDLE<VOID> = ASYNC { SSH_PTY_RUN($a.session, ["sh", "-c", "sleep 3; stty size"], 0, 0, $a_in, $a_out) }
            LET $tb: HANDLE<VOID> = ASYNC { SSH_PTY_RUN($b.session, ["sh", "-c", "sleep 3; stty size"], 0, 0, $b_in, $b_out) }
            AWAIT $ta
            AWAIT $tb
            ASSERT_CONTAINS $a_out "40 100"
            ASSERT_CONTAINS $b_out "50 120"
        }
        AWAIT $h
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    let addr = read_addr(&probe);
    let addr: SocketAddr = addr.parse().expect("addr parses");
    let client_a =
        TestClient::connect_with_pty_dims(addr, "u", &pass, 100, 40).expect("guest A connects");
    std::thread::sleep(Duration::from_secs(1));
    let client_b =
        TestClient::connect_with_pty_dims(addr, "u", &pass, 120, 50).expect("guest B connects");
    handle
        .join()
        .expect("script thread joins")
        .expect("isolated sizes report per guest");
    client_a.close();
    client_b.close();
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn logical_port_connect_roundtrip() {
    // The client dials a service name, never a physical address: the
    // runner mapped it to loopback before the run. The server sends
    // first: the client side never EOFs its input, so the reply cannot
    // race teardown.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-mapped-roundtrip");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-mapped-roundtrip", {username: "guest", password: "__TEST_PASSWORD__"})
        LET $in: PIPE
        LET $out: PIPE
        LET $acc: HANDLE<VOID> = ASYNC { SSH_ACCEPT($m.server, $in, $out) }
        LET $cin: PIPE
        LET $cout: PIPE
        LET $c: HANDLE<VOID> = ASYNC { SSH_CONNECT("test-ssh-mapped-roundtrip", "guest", "__TEST_PASSWORD__", $cin, $cout) }
        WITH_IO [stdout=$in] ECHO "server-greeting"
        LET $info: MAP<ANY> = INSPECT($cout)
        LET $empty: BOOL = $info.buffer_bytes == 0
        LET $tries: INT = 0
        WHILE $empty {
            SLEEP 100ms
            $info = INSPECT($cout)
            $empty = $info.buffer_bytes == 0
            $tries = $tries + 1
            IF $tries > 100 {
                EXIT 1
            }
        }
        ASSERT_CONTAINS $cout "server-greeting"
        AWAIT $acc
        CANCEL $c
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    handle
        .join()
        .expect("script thread joins")
        .expect("logical connect script completes end to end");
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn mapped_name_connect_roundtrip() {
    // Pattern 1 with a CLI-style mapping: the service name resolves to
    // a pre-bound ephemeral socket, so neither side names a physical
    // address or port. The connect side proves the TcpBound arm.
    let registry = Arc::new(oxdock_net_plugin::EndpointRegistry::new(false));
    registry
        .add_mapping(
            &oxdock_net_plugin::EndpointKey::tcp(oxdock_net_plugin::VirtualEndpoint::Name(
                "doc-demo".to_string(),
            )),
            oxdock_net_plugin::BindingSpec::Exposed {
                addr: "127.0.0.1:0".parse().expect("loopback ephemeral"),
            },
        )
        .expect("mapping");
    registry.bind_all().expect("bind_all resolves ephemeral");
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-demo", {username: "guest", password: "__TEST_PASSWORD__"})
        LET $in: PIPE
        LET $out: PIPE
        LET $acc: HANDLE<VOID> = ASYNC { SSH_ACCEPT($m.server, $in, $out) }
        LET $cin: PIPE
        LET $cout: PIPE
        LET $c: HANDLE<VOID> = ASYNC { SSH_CONNECT("doc-demo", "guest", "__TEST_PASSWORD__", $cin, $cout) }
        WITH_IO [stdout=$in] ECHO "server-greeting"
        LET $info: MAP<ANY> = INSPECT($cout)
        LET $empty: BOOL = $info.buffer_bytes == 0
        LET $tries: INT = 0
        WHILE $empty {
            SLEEP 100ms
            $info = INSPECT($cout)
            $empty = $info.buffer_bytes == 0
            $tries = $tries + 1
            IF $tries > 100 {
                EXIT 1
            }
        }
        ASSERT_CONTAINS $cout "server-greeting"
        AWAIT $acc
        CANCEL $c
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let probe = root.clone();
    let handle = std::thread::spawn(move || run_script_with(registry, &probe, &script));
    handle
        .join()
        .expect("script thread joins")
        .expect("mapped connect script completes end to end");
}

#[test]
#[cfg_attr(
    miri,
    ignore = "needs loopback TCP plus threads plus a terminal plus subprocesses"
)]
fn proxy_client_lingers_for_reply_and_status() {
    // Client-side pumps must not end with their own stdin EOF: the
    // echo reply and the exit-status arrive after it. Ending early
    // returns first and disconnects, killing the server mid-reply.
    // Same shape as the README proxy fence: each child reads a stdin
    // line and exits by itself (`cat` on Unix; a console line read on
    // Windows, where children never observe stdin EOF). Plain lines
    // submit everywhere: the pump expands them for console input.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-proxy-linger");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-proxy-linger", {username: "guest", password: "__TEST_PASSWORD__"})
        LET $child: LIST<STRING> = ["cat"]
        [family:windows] {
            $child = ["cmd", "/v:on", "/c", "(set /p line= && echo got:!line!)"]
        }
        LET $srv: HANDLE<VOID> = ASYNC {
            LET $sess: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            LET $c_in: PIPE
            LET $c_out: PIPE
            LET $pty: HANDLE<INT> = ASYNC { RETURN SSH_PTY_RUN($sess.session, $child, 0, 0, $c_out, $c_in) }
            LET $pump: HANDLE<VOID> = ASYNC { SSH_PUMP_CHANNEL($sess.session, $c_in, $c_out) }
            LET $code: INT = AWAIT $pty
            ASSERT_EQ $code 0
            AWAIT $pump
        }
        LET $cin: PIPE
        LET $cout: PIPE
        LET $c: HANDLE<MAP<closed: BOOL, exit_status: INT>> = ASYNC { RETURN SSH_CONNECT("test-ssh-proxy-linger", "guest", "__TEST_PASSWORD__", $cin, $cout) }
        WITH_IO [stdout=$cin] ECHO "linger-ping"
        LET $cDone: MAP<closed: BOOL, exit_status: INT> = AWAIT $c
        ASSERT_EQ $cDone.closed true
        ASSERT_EQ $cDone.exit_status 0
        ASSERT_CONTAINS $cout "linger-ping"
        AWAIT $srv
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    handle
        .join()
        .expect("script thread joins")
        .expect("proxy linger completes");
}

#[test]
#[cfg_attr(
    miri,
    ignore = "needs loopback TCP plus threads plus a terminal plus subprocesses"
)]
fn pty_session_opens_cleared() {
    // Win32-OpenSSH parity: every console session opens cleared and
    // homed, so the child renders onto a known blank screen. The clear
    // leads the stream (written synchronously before the pump starts);
    // `[2J` is plain ASCII, so a contains-assert pins it without an
    // ESC-capable matcher.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-pty-clear");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-pty-clear", {username: "u", password: "__TEST_PASSWORD__"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $child: LIST<STRING> = ["sh", "-c", "exit 0"]
        [family:windows] {
            $child = ["cmd", "/c", "exit 0"]
        }
        LET $h: HANDLE<VOID> = ASYNC {
            LET $dq: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            LET $in: PIPE
            LET $out: PIPE
            LET $t: HANDLE<INT> = ASYNC { RETURN SSH_PTY_RUN($dq.session, $child, 0, 0, $in, $out) }
            LET $code: INT = AWAIT $t
            ASSERT_EQ $code 0
            ASSERT_CONTAINS $out "[2J"
        }
        AWAIT $h
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let probe = root.clone();
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    let addr = read_addr(&probe);
    let addr: SocketAddr = addr.parse().expect("addr parses");
    let client = TestClient::connect(addr, "u", &pass).expect("client connects");
    handle
        .join()
        .expect("script thread joins")
        .expect("cleared session opens");
    client.close();
}

#[test]
#[cfg(windows)]
#[cfg_attr(
    miri,
    ignore = "needs loopback TCP plus threads plus ConPTY plus subprocesses"
)]
fn conhost_setup_query_never_reaches_client_windows() {
    // A real terminal answers `ESC[6n` itself, and that answer lands in
    // the shell as stray input eating the first keystroke. The pump
    // answers conhost locally, so the query must never reach the wire:
    // read through the prompt and assert the whole stream is clean.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-no-dsr-leak");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-no-dsr-leak", {username: "u", password: "__TEST_PASSWORD__"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $h: HANDLE<VOID> = ASYNC {
            LET $dq: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            LET $to_child: PIPE
            LET $from_child: PIPE
            LET $pty: HANDLE<INT> = ASYNC { RETURN SSH_PTY_RUN($dq.session, ["powershell.exe", "-NoProfile"], 0, 0, $to_child, $from_child) }
            LET $pump: HANDLE<VOID> = ASYNC { SSH_PUMP_CHANNEL($dq.session, $from_child, $to_child) }
            LET $code: INT = AWAIT $pty
            AWAIT $pump
        }
        AWAIT $h
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let probe = root.clone();
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    let addr = read_addr(&probe);
    let addr: SocketAddr = addr.parse().expect("addr parses");
    let mut client = TestClient::connect_with_pty(addr, "u", &pass).expect("client connects");
    let out = client
        .read_until(b"> ", Duration::from_secs(20))
        .expect("prompt renders");
    assert!(
        !out.windows(3).any(|window| window == b"[6n"),
        "conhost setup query must not reach the client"
    );
    client.send(b"exit\r").expect("client exits shell");
    client
        .wait_close(Duration::from_secs(20))
        .expect("server closes");
    handle
        .join()
        .expect("script thread joins")
        .expect("shell session completes");
}

#[test]
#[cfg_attr(
    miri,
    ignore = "needs loopback TCP plus threads plus a real subprocess"
)]
fn run_exec_binary_roundtrip() {
    // SSH_RUN is the binary-safe leg: bytes travel untouched (no init
    // sequence, no newline translation), stdout and stderr stay split,
    // and stdin EOF closes the child stdin so a stdin-driven child
    // exits on its own (the zero exit-status below proves it).
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-run-bin");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-run-bin", {username: "u", password: "__TEST_PASSWORD__"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $child: LIST<STRING> = ["sh", "-c", "cat"]
        [family:windows] {
            $child = ["powershell.exe", "-NoProfile", "-Command", "$i=[Console]::OpenStandardInput(); $o=[Console]::OpenStandardOutput(); $i.CopyTo($o)"]
        }
        LET $h: HANDLE<VOID> = ASYNC {
            LET $dq: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            LET $to_child: PIPE
            LET $from_child: PIPE
            LET $err: PIPE
            LET $run: HANDLE<INT> = ASYNC { RETURN SSH_RUN($dq.session, $child, $to_child, $from_child, $err) }
            LET $pump: HANDLE<VOID> = ASYNC { SSH_PUMP_CHANNEL($dq.session, $from_child, $to_child) }
            LET $code: INT = AWAIT $run
            AWAIT $pump
            ASSERT_EQ $code 0
        }
        AWAIT $h
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let probe = root.clone();
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    let addr = read_addr(&probe);
    let addr: SocketAddr = addr.parse().expect("addr parses");
    let mut client = TestClient::connect(addr, "u", &pass).expect("client connects");
    // NUL, high bytes, and a bare LF: any translation layer mangles one
    // of these, and the trailing marker bounds the read.
    let blob: Vec<u8> = b"bin\x00\xffary\nbare-lf\r\ncrlf\r\nEND\r\n".to_vec();
    client.send(&blob).expect("client sends blob");
    let echoed = client
        .read_until(b"END\r\n", Duration::from_secs(15))
        .expect("blob round-trips");
    assert_eq!(echoed, blob, "bytes must travel untouched");
    client.eof().expect("client half-closes");
    assert_eq!(
        client
            .wait_exit_status(Duration::from_secs(15))
            .expect("exit-status arrives"),
        0,
        "stdin EOF must close the child stdin so cat exits 0"
    );
    client
        .wait_close(Duration::from_secs(15))
        .expect("server closes");
    handle
        .join()
        .expect("script thread joins")
        .expect("run session completes");
}

#[test]
#[cfg_attr(
    miri,
    ignore = "needs loopback TCP plus threads plus a real subprocess"
)]
fn run_exec_reports_exit_code() {
    // A fast child must not lose its status to the close: the wire
    // report queues the instant the exit is observed, ahead of the EOF
    // pipe closes.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-run-code");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-run-code", {username: "u", password: "__TEST_PASSWORD__"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $child: LIST<STRING> = ["sh", "-c", "exit 3"]
        [family:windows] {
            $child = ["cmd", "/c", "exit 3"]
        }
        LET $h: HANDLE<VOID> = ASYNC {
            LET $dq: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            LET $to_child: PIPE
            LET $from_child: PIPE
            LET $err: PIPE
            LET $run: HANDLE<INT> = ASYNC { RETURN SSH_RUN($dq.session, $child, $to_child, $from_child, $err) }
            LET $pump: HANDLE<VOID> = ASYNC { SSH_PUMP_CHANNEL($dq.session, $from_child, $to_child) }
            LET $code: INT = AWAIT $run
            AWAIT $pump
            ASSERT_EQ $code 3
        }
        AWAIT $h
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let probe = root.clone();
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    let addr = read_addr(&probe);
    let addr: SocketAddr = addr.parse().expect("addr parses");
    let mut client = TestClient::connect(addr, "u", &pass).expect("client connects");
    assert_eq!(
        client
            .wait_exit_status(Duration::from_secs(15))
            .expect("exit-status arrives"),
        3,
        "fast child must report its real code, not 255"
    );
    client
        .wait_close(Duration::from_secs(15))
        .expect("server closes");
    handle
        .join()
        .expect("script thread joins")
        .expect("run session completes");
}

#[test]
#[cfg_attr(
    miri,
    ignore = "needs loopback TCP plus threads plus a real subprocess"
)]
fn run_exec_splits_stderr() {
    // Diagnostics ride their own pipe: stderr bytes must never appear
    // in the stdout stream the client observes.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-run-err");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-run-err", {username: "u", password: "__TEST_PASSWORD__"})
        WRITE addr.txt "{{ $m.addr }}"
        LET $child: LIST<STRING> = ["sh", "-c", "echo out; echo oops >&2"]
        [family:windows] {
            $child = ["cmd", "/c", "echo out & echo oops 1>&2"]
        }
        LET $h: HANDLE<VOID> = ASYNC {
            LET $dq: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            LET $to_child: PIPE
            LET $from_child: PIPE
            LET $err: PIPE
            LET $run: HANDLE<INT> = ASYNC { RETURN SSH_RUN($dq.session, $child, $to_child, $from_child, $err) }
            LET $pump: HANDLE<VOID> = ASYNC { SSH_PUMP_CHANNEL($dq.session, $from_child, $to_child) }
            LET $code: INT = AWAIT $run
            AWAIT $pump
            ASSERT_EQ $code 0
            ASSERT_CONTAINS $err "oops"
        }
        AWAIT $h
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let probe = root.clone();
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    let addr = read_addr(&probe);
    let addr: SocketAddr = addr.parse().expect("addr parses");
    let mut client = TestClient::connect(addr, "u", &pass).expect("client connects");
    let out = client
        .read_until(b"out", Duration::from_secs(15))
        .expect("stdout arrives");
    assert!(
        !out.windows(4).any(|window| window == b"oops"),
        "stderr must never pollute the stdout stream"
    );
    // Half-close races server teardown for immediately-exiting
    // children: if the server already closed the channel, the close
    // wait below observes it at once instead of failing on the lost
    // race. A genuinely wedged channel still fails loudly there, and
    // the script join below still catches server-side failures.
    let _ = client.eof();
    client
        .wait_close(Duration::from_secs(15))
        .expect("server closes");
    handle
        .join()
        .expect("script thread joins")
        .expect("run session completes");
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn serve_accepts_idle_timeout_option() {
    // Plumbing, not timing: waiting out a real timeout would stall the
    // suite. The option must parse, reach the server, and leave a
    // working session behind; garbage must bail naming the option.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-idle-opt");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-idle-opt", {username: "u", password: "__TEST_PASSWORD__", idle_timeout: "5s"})
        WRITE addr.txt "{{ $m.addr }}"
        SLEEP 5s
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let probe = root.clone();
    let thread_root = root.clone();
    let handle = std::thread::spawn(move || run_script_with(registry, &thread_root, &script));
    let addr = read_addr(&probe);
    let addr: SocketAddr = addr.parse().expect("addr parses");
    let client = TestClient::connect(addr, "u", &pass).expect("client connects");
    client.close();
    handle
        .join()
        .expect("script thread joins")
        .expect("serve with idle_timeout runs");

    let registry = mapped_registry("test-ssh-idle-bad");
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-idle-bad", {username: "u", password: "p", idle_timeout: "soon"})
        SSH_CLOSE($m.server)
    "#};
    let err = run_script_with(registry, &root, script).expect_err("bad duration must fail");
    assert!(
        format!("{err:#}").contains("idle_timeout"),
        "failure names the option: {err:#}"
    );
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn pump_channel_close_reaches_client_while_session_held() {
    // Regression: the exit-status control sender must not outlive the
    // pump. The client half-closes, the pump drains, and the server
    // must close the channel while the script still holds the session
    // (parked in SLEEP, long past the drain): a close that waits for
    // the last session clone strands the client.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-pump-close");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-pump-close", {username: "guest", password: "__TEST_PASSWORD__"})
        LET $t: HANDLE<SSH_SESSION> = ASYNC {
            LET $sess: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            RETURN $sess.session
        }
        LET $s: SSH_SESSION = AWAIT $t
        LET $in: PIPE
        LET $out: PIPE
        LET $p: HANDLE<VOID> = ASYNC { SSH_PUMP_CHANNEL($s, $in, $out) }
        LET $e: HANDLE<VOID> = ASYNC { SSH_PUMP($out, $in) }
        SLEEP 12s
        AWAIT $p
        AWAIT $e
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let addr = service_addr(&registry, "test-ssh-pump-close");
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    std::thread::sleep(Duration::from_secs(2));
    let mut client = TestClient::connect(addr, "guest", &pass).expect("client connects");
    client.send(b"close-me").expect("client sends");
    let echoed = client
        .read_until(b"close-me", Duration::from_secs(10))
        .expect("echo returns");
    assert!(
        echoed.windows(8).any(|window| window == b"close-me"),
        "echoed bytes must round-trip"
    );
    client.eof().expect("client half-closes");
    client
        .wait_close(Duration::from_secs(10))
        .expect("server closes the drained channel");
    client.close();
    handle
        .join()
        .expect("script thread joins")
        .expect("close script completes");
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn send_exit_status_reaches_exec_client() {
    // No byte pump involved: the status queues on the control sender and
    // the wire writer delivers it, so a client learns the code even when
    // the session never pumps.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-exit-status-raw");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-exit-status-raw", {username: "guest", password: "__TEST_PASSWORD__"})
        LET $h: HANDLE<VOID> = ASYNC {
            LET $sess: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            SSH_SEND_EXIT_STATUS($sess.session, 42)
        }
        AWAIT $h
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let addr = service_addr(&registry, "test-ssh-exit-status-raw");
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    std::thread::sleep(Duration::from_secs(2));
    let mut client =
        TestClient::connect_exec(addr, "guest", &pass, "probe").expect("client exec connects");
    let code = client
        .wait_exit_status(Duration::from_secs(10))
        .expect("exit-status arrives");
    assert_eq!(code, 42, "client must observe the sent status");
    client.close();
    handle
        .join()
        .expect("script thread joins")
        .expect("status script completes");
}

#[test]
#[cfg_attr(
    miri,
    ignore = "needs loopback TCP plus threads plus a terminal plus subprocesses"
)]
fn pty_child_code_reaches_exec_client() {
    // The proxy shape from the issue: the `SSH_PTY_RUN` exit code is
    // reported on the wire at child exit (ahead of the pump drain), so
    // stock clients report the real code instead of 255. No explicit
    // send: the terminal run reports by itself.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-exit-status-pty");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-exit-status-pty", {username: "guest", password: "__TEST_PASSWORD__"})
        LET $child: LIST<STRING> = ["sh", "-c", "exit 7"]
        [family:windows] {
            $child = ["cmd", "/c", "exit 7"]
        }
        LET $h: HANDLE<VOID> = ASYNC {
            LET $dq: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            LET $c_in: PIPE
            LET $c_out: PIPE
            LET $t: HANDLE<INT> = ASYNC { RETURN SSH_PTY_RUN($dq.session, $child, 0, 0, $c_out, $c_in) }
            LET $p: HANDLE<VOID> = ASYNC { SSH_PUMP_CHANNEL($dq.session, $c_in, $c_out) }
            LET $code: INT = AWAIT $t
            ASSERT_EQ $code 7
            AWAIT $p
        }
        AWAIT $h
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let addr = service_addr(&registry, "test-ssh-exit-status-pty");
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    std::thread::sleep(Duration::from_secs(2));
    let mut client =
        TestClient::connect_exec(addr, "guest", &pass, "probe").expect("client exec connects");
    let code = client
        .wait_exit_status(Duration::from_secs(10))
        .expect("exit-status arrives");
    assert_eq!(code, 7, "client must observe the child exit code");
    client.close();
    handle
        .join()
        .expect("script thread joins")
        .expect("proxy status script completes");
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn send_exit_status_rejects_negative_code() {
    // Exit codes are unsigned on the wire: a negative code bails
    // instead of wrapping.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-exit-status-neg");
    let addr = service_addr(&registry, "test-ssh-exit-status-neg");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-exit-status-neg", {username: "guest", password: "__TEST_PASSWORD__"})
        LET $h: HANDLE<VOID> = ASYNC {
            LET $sess: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
            SSH_SEND_EXIT_STATUS($sess.session, -1)
        }
        AWAIT $h
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    let handle = std::thread::spawn(move || run_script_with(registry, &root, &script));
    std::thread::sleep(Duration::from_secs(2));
    let client =
        TestClient::connect_exec(addr, "guest", &pass, "probe").expect("client exec connects");
    client.close();
    let err = handle
        .join()
        .expect("script thread joins")
        .expect_err("negative code must fail");
    assert!(
        format!("{err:#}").contains("must not be negative"),
        "{err:#}"
    );
}

#[test]
#[cfg(unix)]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus subprocesses")]
fn exec_argv_round_trip_preserves_hostile_words() {
    // Unix-only by construction: the responder runs `echo` with one
    // hostile argument, so the test asserts the wire join and the
    // responder split preserved every byte. Quoting, `$vars`, and
    // backticks cross as literal argument bytes because argv never
    // becomes a shell string in script hands: the single join lives in
    // the plugin behind `shell_words::join`.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-exec-quote");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        INHERIT_ENV [PATH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-exec-quote", {username: "u", password: "__TEST_PASSWORD__"})
        LET $d: HANDLE<SSH_DEQUEUE_INFO> = ASYNC { RETURN SSH_DEQUEUE($m.server) }
        LET $runner: HANDLE<VOID> = ASYNC {
            LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
            LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS($sess.command)
            LET $wire: PIPE
            LET $drain: PIPE
            LET $pump: HANDLE<MAP<ANY>> = ASYNC { RETURN SSH_PUMP_CHANNEL($sess.session, $wire, $drain) }
            LET $pin: PIPE
            LET $pout: PIPE
            LET $perr: PIPE
            LET $run: HANDLE<INT> = ASYNC { RETURN SSH_RUN($sess.session, $argv, $pin, $pout, $perr) }
            LET $n: INT = SSH_PUMP($pout, $wire)
            LET $code: INT = AWAIT $run
            LET $pDone: MAP<ANY> = AWAIT $pump
            ASSERT_EQ $code 0
        }
        LET $nasty: STRING = "it's $HOME \"quoted\" `ticked`"
        LET $res: MAP<ANY> = SSH_EXEC("test-ssh-exec-quote", "u", "__TEST_PASSWORD__", ["echo", $nasty], {})
        ASSERT_EQ $res.timed_out false
        ASSERT_EQ $res.truncated false
        ASSERT_EQ $res.exit 0
        ASSERT_CONTAINS $res.stdout $nasty
        AWAIT $runner
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    run_script_with(registry, &root, &script).expect("hostile argv round-trips byte-identical");
}

#[test]
#[cfg_attr(miri, ignore = "needs loopback TCP plus threads plus a Tokio runtime")]
fn exec_timeout_returns_partials() {
    // Nobody dequeues, so the exec never runs: the client kills the
    // wait at the option timeout and returns what arrived (nothing)
    // with `timed_out` set instead of hanging or erroring.
    let temp = GuardedPath::tempdir().unwrap();
    let root = guard_root(&temp);
    let registry = mapped_registry("test-ssh-exec-timeout");
    let pass = oxdock_ssh_plugin::generate_password();
    let script = indoc! {r#"
        IMPORT [STD, SSH]
        LET $m: SSH_SERVE_INFO = SSH_SERVE("test-ssh-exec-timeout", {username: "u", password: "__TEST_PASSWORD__"})
        LET $res: MAP<ANY> = SSH_EXEC("test-ssh-exec-timeout", "u", "__TEST_PASSWORD__", ["echo", "hi"], {timeout: "1s"})
        ASSERT_EQ $res.timed_out true
        LET $unknown: INT = 0 - 1
        ASSERT_EQ $res.exit $unknown
        SSH_CLOSE($m.server)
    "#}.replace(PASSWORD_MARKER, &pass);
    run_script_with(registry, &root, &script).expect("exec timeout returns partials");
}