openjd-sessions 0.2.3

Open Job Description sessions — local job execution runtime
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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// Copyright by contributors to this project.
// SPDX-License-Identifier: (Apache-2.0 OR MIT)

//! Tests for Session — mirrors Python test_session.py

use openjd_expr::format_string::FormatString;
use openjd_model::job::{
    Action, Environment, EnvironmentActions, EnvironmentScript, StepActions, StepScript,
};
use openjd_sessions::action::ActionState;
use openjd_sessions::session::{Session, SessionConfig, SessionState};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use tempfile::TempDir;

fn fs(s: &str) -> FormatString {
    FormatString::new(s).unwrap()
}

fn action(cmd: &str, args: Vec<&str>) -> Action {
    Action {
        command: fs(cmd),
        args: Some(args.iter().map(|a| fs(a)).collect()),
        timeout: None,
        cancelation: None,
    }
}

fn step(cmd: &str, args: Vec<&str>) -> StepScript {
    StepScript {
        let_bindings: None,
        actions: StepActions {
            on_run: action(cmd, args),
        },
        embedded_files: None,
    }
}

fn env_with_enter(name: &str, cmd: &str, args: Vec<&str>) -> Environment {
    Environment {
        name: name.into(),
        description: None,
        script: Some(EnvironmentScript {
            let_bindings: None,
            actions: EnvironmentActions {
                on_enter: Some(action(cmd, args)),
                on_exit: None,
            },
            embedded_files: None,
        }),
        variables: None,
        resolved_symtab: None,
    }
}

fn env_with_vars(name: &str, vars: HashMap<String, FormatString>) -> Environment {
    Environment {
        name: name.into(),
        description: None,
        script: None,
        variables: Some(vars),
        resolved_symtab: None,
    }
}

// === TestSessionInitialization ===

#[tokio::test]
async fn test_initialize_basic() {
    let tmp = TempDir::new().unwrap();
    let session = Session::new_for_test(tmp.path().to_path_buf());
    assert_eq!(session.state(), SessionState::Ready);
    assert!(session.working_directory().exists());
}

#[tokio::test]
async fn test_initialize_with_root_dir() {
    let tmp = TempDir::new().unwrap();
    let session = Session::new_for_test(tmp.path().to_path_buf());
    assert_eq!(session.working_directory(), tmp.path());
}

/// Mirrors Python TestSession::test_root_dir_permissions — POSIX: owner rwx, group r/x, other r/x.
#[cfg(unix)]
#[tokio::test]
async fn test_root_dir_permissions_posix() {
    use std::os::unix::fs::PermissionsExt;
    let tmp = TempDir::new().unwrap();
    let config = SessionConfig {
        session_id: "test-perms".into(),
        job_parameter_values: Default::default(),
        session_root_directory: Some(tmp.path().to_path_buf()),
        path_mapping_rules: None,
        retain_working_dir: false,
        callback: None,
        os_env_vars: None,
        user: None,
        profile: None,
        cancel_token: None,
        debug_collect_stdout: true,
        echo_openjd_directives: true,
        sticky_bit_policy: openjd_sessions::StickyBitPolicy::Disabled,
    };
    let session = Session::with_config(config).unwrap();
    // The working dir is created by TempDir::new with mode 0o700 when no user is given.
    let working_mode = std::fs::metadata(session.working_directory())
        .unwrap()
        .permissions()
        .mode();
    assert_eq!(
        working_mode & 0o777,
        0o700,
        "working dir is 0o700 (no user)"
    );
}

// === StickyBitPolicy tests ===

/// Strict mode rejects a session root under a world-writable dir without sticky bit.
#[cfg(unix)]
#[tokio::test]
async fn test_sticky_bit_policy_strict_rejects_unsafe_dir() {
    use std::os::unix::fs::PermissionsExt;
    let tmp = TempDir::new().unwrap();
    let unsafe_dir = tmp.path().join("world_writable");
    std::fs::create_dir(&unsafe_dir).unwrap();
    std::fs::set_permissions(&unsafe_dir, std::fs::Permissions::from_mode(0o777)).unwrap();
    let root = unsafe_dir.join("root");
    std::fs::create_dir(&root).unwrap();

    let config = SessionConfig {
        session_id: "test-strict".into(),
        job_parameter_values: Default::default(),
        session_root_directory: Some(root),
        path_mapping_rules: None,
        retain_working_dir: false,
        callback: None,
        os_env_vars: None,
        user: None,
        profile: None,
        cancel_token: None,
        debug_collect_stdout: true,
        echo_openjd_directives: true,
        sticky_bit_policy: openjd_sessions::StickyBitPolicy::Strict,
    };
    let result = Session::with_config(config);
    assert!(result.is_err());
    let err = result.err().unwrap().to_string();
    assert!(err.contains("world-writable"), "error was: {err}");
}

/// Strict mode allows a session root when sticky bit is set.
#[cfg(unix)]
#[tokio::test]
async fn test_sticky_bit_policy_strict_allows_safe_dir() {
    use std::os::unix::fs::PermissionsExt;
    let tmp = TempDir::new().unwrap();
    let safe_dir = tmp.path().join("sticky");
    std::fs::create_dir(&safe_dir).unwrap();
    std::fs::set_permissions(&safe_dir, std::fs::Permissions::from_mode(0o1777)).unwrap();
    let root = safe_dir.join("root");
    std::fs::create_dir(&root).unwrap();

    let config = SessionConfig {
        session_id: "test-strict-ok".into(),
        job_parameter_values: Default::default(),
        session_root_directory: Some(root),
        path_mapping_rules: None,
        retain_working_dir: false,
        callback: None,
        os_env_vars: None,
        user: None,
        profile: None,
        cancel_token: None,
        debug_collect_stdout: true,
        echo_openjd_directives: true,
        sticky_bit_policy: openjd_sessions::StickyBitPolicy::Strict,
    };
    let session = Session::with_config(config).unwrap();
    assert_eq!(session.state(), SessionState::Ready);
}

/// Warn mode logs but does not reject an unsafe directory.
#[cfg(unix)]
#[tokio::test]
async fn test_sticky_bit_policy_warn_allows_unsafe_dir() {
    use std::os::unix::fs::PermissionsExt;
    testing_logger::setup();
    let tmp = TempDir::new().unwrap();
    let unsafe_dir = tmp.path().join("world_writable");
    std::fs::create_dir(&unsafe_dir).unwrap();
    std::fs::set_permissions(&unsafe_dir, std::fs::Permissions::from_mode(0o777)).unwrap();
    let root = unsafe_dir.join("root");
    std::fs::create_dir(&root).unwrap();

    let config = SessionConfig {
        session_id: "test-warn".into(),
        job_parameter_values: Default::default(),
        session_root_directory: Some(root),
        path_mapping_rules: None,
        retain_working_dir: false,
        callback: None,
        os_env_vars: None,
        user: None,
        profile: None,
        cancel_token: None,
        debug_collect_stdout: true,
        echo_openjd_directives: true,
        sticky_bit_policy: openjd_sessions::StickyBitPolicy::Warn,
    };
    let session = Session::with_config(config).unwrap();
    assert_eq!(session.state(), SessionState::Ready);

    testing_logger::validate(|captured_logs| {
        assert!(
            captured_logs
                .iter()
                .any(|log| log.level == log::Level::Warn
                    && log.body.contains("Sticky bit is not set")),
            "Expected a warning about missing sticky bit"
        );
    });
}

/// Disabled mode skips the check entirely — no error, no warning.
#[cfg(unix)]
#[tokio::test]
async fn test_sticky_bit_policy_disabled_skips_check() {
    use std::os::unix::fs::PermissionsExt;
    testing_logger::setup();
    let tmp = TempDir::new().unwrap();
    let unsafe_dir = tmp.path().join("world_writable");
    std::fs::create_dir(&unsafe_dir).unwrap();
    std::fs::set_permissions(&unsafe_dir, std::fs::Permissions::from_mode(0o777)).unwrap();
    let root = unsafe_dir.join("root");
    std::fs::create_dir(&root).unwrap();

    let config = SessionConfig {
        session_id: "test-disabled".into(),
        job_parameter_values: Default::default(),
        session_root_directory: Some(root),
        path_mapping_rules: None,
        retain_working_dir: false,
        callback: None,
        os_env_vars: None,
        user: None,
        profile: None,
        cancel_token: None,
        debug_collect_stdout: true,
        echo_openjd_directives: true,
        sticky_bit_policy: openjd_sessions::StickyBitPolicy::Disabled,
    };
    let session = Session::with_config(config).unwrap();
    assert_eq!(session.state(), SessionState::Ready);

    testing_logger::validate(|captured_logs| {
        assert!(
            !captured_logs
                .iter()
                .any(|log| log.body.contains("Sticky bit")),
            "Should not log anything about sticky bit when disabled"
        );
    });
}

/// Mirrors Python: Session dropped without cleanup() should log a warning.
#[tokio::test]
async fn test_session_drop_without_cleanup_warns() {
    testing_logger::setup();
    let tmp = TempDir::new().unwrap();
    {
        let _session = Session::new_for_test(tmp.path().to_path_buf());
        // drop without calling cleanup()
    }
    testing_logger::validate(|captured_logs| {
        assert!(
            captured_logs.iter().any(|log| {
                log.level == log::Level::Warn
                    && log.body.contains("dropped without calling cleanup()")
            }),
            "Expected a warning about session dropped without cleanup"
        );
    });
}

// === TestSessionRunTask_2023_09 ===

#[tokio::test]
async fn test_run_task() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let r = s
        .run_task(
            &step("sh", vec!["-c", "echo task_output"]),
            None,
            None,
            None,
        )
        .await
        .unwrap();
    assert_eq!(r.state, ActionState::Success);
    assert!(r.stdout.contains("task_output"));
}

#[tokio::test]
async fn test_run_task_with_env_vars() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let mut vars = HashMap::new();
    vars.insert("TASK_VAR".into(), fs("task_value"));
    let env = env_with_vars("env1", vars);
    s.enter_environment(&env, None, None, None).await.unwrap();

    let r = s
        .run_task(
            &step("sh", vec!["-c", "echo TASK_VAR=$TASK_VAR"]),
            None,
            None,
            None,
        )
        .await
        .unwrap();
    assert!(r.stdout.contains("TASK_VAR=task_value"));
}

#[tokio::test]
async fn test_run_task_fail_run() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let r = s
        .run_task(&step("sh", vec!["-c", "exit 42"]), None, None, None)
        .await
        .unwrap();
    assert_eq!(r.state, ActionState::Failed);
    assert_eq!(r.exit_code, Some(42));
}

#[tokio::test]
async fn test_no_task_run_after_fail() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    // First run fails — session becomes "brittle" (ReadyEnding), only exit_environment allowed
    s.run_task(&step("sh", vec!["-c", "exit 1"]), None, None, None)
        .await
        .unwrap();
    assert_eq!(s.state(), SessionState::ReadyEnding);
}

#[tokio::test]
async fn test_run_task_with_variables() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let mut task_params = openjd_model::types::TaskParameterSet::new();
    task_params.insert(
        "Greeting".into(),
        openjd_model::types::TaskParameterValue {
            param_type: openjd_model::types::TaskParameterType::String,
            value: openjd_expr::ExprValue::String("hello".into()),
        },
    );

    let script = StepScript {
        let_bindings: None,
        actions: StepActions {
            on_run: Action {
                command: fs("sh"),
                args: Some(vec![fs("-c"), fs("echo {{ Task.Param.Greeting }}")]),
                timeout: None,
                cancelation: None,
            },
        },
        embedded_files: None,
    };
    let r = s
        .run_task(&script, Some(&task_params), None, None)
        .await
        .unwrap();
    assert!(r.stdout.contains("hello"));
}

// === TestSessionEnterEnvironment_2023_09 ===

#[tokio::test]
async fn test_enter_environment_basic() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let env = env_with_enter("env1", "sh", vec!["-c", "echo entered"]);
    let id = s.enter_environment(&env, None, None, None).await.unwrap();
    assert!(!id.is_empty());
}

#[tokio::test]
async fn test_enter_environment_with_env_vars() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let mut vars = HashMap::new();
    vars.insert("ENV_VAR".into(), fs("env_value"));
    let env = Environment {
        name: "env1".into(),
        description: None,
        script: Some(EnvironmentScript {
            let_bindings: None,
            actions: EnvironmentActions {
                on_enter: Some(action("sh", vec!["-c", "echo ENV_VAR=$ENV_VAR"])),
                on_exit: None,
            },
            embedded_files: None,
        }),
        variables: Some(vars),
        resolved_symtab: None,
    };
    let id = s.enter_environment(&env, None, None, None).await.unwrap();
    assert!(!id.is_empty());
}

#[tokio::test]
async fn test_enter_two_environments() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let env1 = env_with_enter(
        "env1",
        "sh",
        vec!["-c", "echo 'openjd_env: FROM_ENV1=val1'"],
    );
    let env2 = env_with_enter("env2", "sh", vec!["-c", "echo FROM_ENV1=$FROM_ENV1"]);
    s.enter_environment(&env1, None, None, None).await.unwrap();
    let id2 = s.enter_environment(&env2, None, None, None).await.unwrap();
    assert!(!id2.is_empty());
}

#[tokio::test]
async fn test_enter_environment_fail_run() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let env = env_with_enter("env1", "sh", vec!["-c", "exit 1"]);
    assert!(s.enter_environment(&env, None, None, None).await.is_err());
}

#[tokio::test]
async fn test_enter_environment_command_not_found() {
    // Regression: when the subprocess command doesn't exist, the session must
    // transition to ReadyEnding with action_state=Failed, not stay stuck in Running.
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let env = env_with_enter("env1", "nonexistent-command-xyz", vec![]);
    let result = s.enter_environment(&env, None, None, None).await;
    assert!(result.is_err());
    assert_eq!(s.state(), SessionState::ReadyEnding);
    let status = s
        .action_status()
        .expect("action_status should be set after failure");
    assert_eq!(status.state, ActionState::Failed);
}

#[tokio::test]
async fn test_run_task_command_not_found() {
    // Same regression test for run_task: command not found must set Failed state.
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let script = step("nonexistent-command-xyz", vec![]);
    let result = s.run_task(&script, None, None, None).await;
    assert!(result.is_err());
    assert_eq!(s.state(), SessionState::ReadyEnding);
    let status = s
        .action_status()
        .expect("action_status should be set after failure");
    assert_eq!(status.state, ActionState::Failed);
}

#[tokio::test]
async fn test_enter_no_action() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let env = Environment {
        name: "env1".into(),
        description: None,
        script: Some(EnvironmentScript {
            let_bindings: None,
            actions: EnvironmentActions {
                on_enter: None,
                on_exit: None,
            },
            embedded_files: None,
        }),
        variables: None,
        resolved_symtab: None,
    };
    assert!(s.enter_environment(&env, None, None, None).await.is_ok());
}

#[tokio::test]
async fn test_enter_environment_with_resolved_variables() {
    let tmp = TempDir::new().unwrap();
    use openjd_model::types::JobParameterValue;
    let mut job_params = HashMap::new();
    job_params.insert(
        "Val".to_string(),
        JobParameterValue {
            param_type: openjd_model::types::JobParameterType::String,
            value: openjd_expr::ExprValue::String("resolved".into()),
        },
    );
    let session_config = openjd_sessions::session::SessionConfig {
        session_id: "test".into(),
        job_parameter_values: job_params,
        path_mapping_rules: None,
        retain_working_dir: false,
        callback: None,
        os_env_vars: None,
        session_root_directory: Some(tmp.path().to_path_buf()),
        user: None,
        profile: None,
        cancel_token: None,
        debug_collect_stdout: true,
        echo_openjd_directives: true,
        sticky_bit_policy: openjd_sessions::StickyBitPolicy::Disabled,
    };
    let mut s = Session::with_config(session_config).unwrap();
    let mut vars = HashMap::new();
    vars.insert("RESOLVED".into(), fs("{{ Param.Val }}"));
    let env = Environment {
        name: "env1".into(),
        description: None,
        script: Some(EnvironmentScript {
            let_bindings: None,
            actions: EnvironmentActions {
                on_enter: Some(action("sh", vec!["-c", "echo RESOLVED=$RESOLVED"])),
                on_exit: None,
            },
            embedded_files: None,
        }),
        variables: Some(vars),
        resolved_symtab: None,
    };
    let id = s.enter_environment(&env, None, None, None).await.unwrap();
    assert!(!id.is_empty());
}

// === TestSessionExitEnvironment_2023_09 ===

#[tokio::test]
async fn test_exit_environment_basic() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let env = Environment {
        name: "env1".into(),
        description: None,
        script: Some(EnvironmentScript {
            let_bindings: None,
            actions: EnvironmentActions {
                on_enter: None,
                on_exit: Some(action("sh", vec!["-c", "echo exited"])),
            },
            embedded_files: None,
        }),
        variables: None,
        resolved_symtab: None,
    };
    let id = s.enter_environment(&env, None, None, None).await.unwrap();
    let out = s.exit_environment(&id, None, true, None).await.unwrap();
    assert!(out.contains("exited"));
}

#[tokio::test]
async fn test_exit_environment_with_env_vars() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let mut vars = HashMap::new();
    vars.insert("EXIT_VAR".into(), fs("exit_value"));
    let env = Environment {
        name: "env1".into(),
        description: None,
        script: Some(EnvironmentScript {
            let_bindings: None,
            actions: EnvironmentActions {
                on_enter: None,
                on_exit: Some(action("sh", vec!["-c", "echo EXIT_VAR=$EXIT_VAR"])),
            },
            embedded_files: None,
        }),
        variables: Some(vars.clone()),
        resolved_symtab: None,
    };
    // Enter first to set vars
    let id = s.enter_environment(&env, None, None, None).await.unwrap();
    let out = s.exit_environment(&id, None, true, None).await.unwrap();
    assert!(out.contains("EXIT_VAR=exit_value"));
}

#[tokio::test]
async fn test_exit_environment_removes_variables() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let mut vars = HashMap::new();
    vars.insert("REMOVED_VAR".into(), fs("value"));
    let env = env_with_vars("env1", vars);
    let id = s.enter_environment(&env, None, None, None).await.unwrap();
    s.exit_environment(&id, None, true, None).await.unwrap();

    let r = s
        .run_task(
            &step("sh", vec!["-c", "echo REMOVED_VAR=${REMOVED_VAR:-gone}"]),
            None,
            None,
            None,
        )
        .await
        .unwrap();
    assert!(r.stdout.contains("REMOVED_VAR=gone"));
}

#[tokio::test]
async fn test_exit_environment_fail_run() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let env = Environment {
        name: "env1".into(),
        description: None,
        script: Some(EnvironmentScript {
            let_bindings: None,
            actions: EnvironmentActions {
                on_enter: None,
                on_exit: Some(action("sh", vec!["-c", "exit 1"])),
            },
            embedded_files: None,
        }),
        variables: None,
        resolved_symtab: None,
    };
    let id = s.enter_environment(&env, None, None, None).await.unwrap();
    assert!(s.exit_environment(&id, None, true, None).await.is_err());
}

#[tokio::test]
async fn test_run_task_after_env_exit() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let env = env_with_enter("env1", "sh", vec!["-c", "echo 'openjd_env: PERSIST=yes'"]);
    let id = s.enter_environment(&env, None, None, None).await.unwrap();
    s.exit_environment(&id, None, true, None).await.unwrap();

    // After exit, env vars set via openjd_env are removed along with the environment.
    // Only process_env vars persist across environment exits.
    let r = s
        .run_task(
            &step("sh", vec!["-c", "echo PERSIST=${PERSIST:-no}"]),
            None,
            None,
            None,
        )
        .await
        .unwrap();
    assert!(r.stdout.contains("PERSIST=no"));
}

// === TestEnvironmentVariablesInTasks_2023_09 ===

#[tokio::test]
async fn test_direct_definition() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let mut vars = HashMap::new();
    vars.insert("DIRECT".into(), fs("direct_val"));
    let env = env_with_vars("env1", vars);
    s.enter_environment(&env, None, None, None).await.unwrap();

    let r = s
        .run_task(
            &step("sh", vec!["-c", "echo DIRECT=$DIRECT"]),
            None,
            None,
            None,
        )
        .await
        .unwrap();
    assert!(r.stdout.contains("DIRECT=direct_val"));
}

#[tokio::test]
async fn test_redefinition_nested() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let mut vars1 = HashMap::new();
    vars1.insert("VAR".into(), fs("outer"));
    let env1 = env_with_vars("env1", vars1);
    s.enter_environment(&env1, None, None, None).await.unwrap();

    let mut vars2 = HashMap::new();
    vars2.insert("VAR".into(), fs("inner"));
    let env2 = env_with_vars("env2", vars2);
    s.enter_environment(&env2, None, None, None).await.unwrap();

    let r = s
        .run_task(&step("sh", vec!["-c", "echo VAR=$VAR"]), None, None, None)
        .await
        .unwrap();
    assert!(r.stdout.contains("VAR=inner"));
}

#[tokio::test]
async fn test_def_via_stdout() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let env = env_with_enter(
        "env1",
        "sh",
        vec!["-c", "echo 'openjd_env: STDOUT_VAR=stdout_val'"],
    );
    s.enter_environment(&env, None, None, None).await.unwrap();

    let r = s
        .run_task(
            &step("sh", vec!["-c", "echo STDOUT_VAR=$STDOUT_VAR"]),
            None,
            None,
            None,
        )
        .await
        .unwrap();
    assert!(r.stdout.contains("STDOUT_VAR=stdout_val"));
}

#[tokio::test]
async fn test_def_via_stdout_overrides_direct() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let mut vars = HashMap::new();
    vars.insert("OVERRIDE".into(), fs("direct"));
    let env = Environment {
        name: "env1".into(),
        description: None,
        script: Some(EnvironmentScript {
            let_bindings: None,
            actions: EnvironmentActions {
                on_enter: Some(action(
                    "sh",
                    vec!["-c", "echo 'openjd_env: OVERRIDE=from_stdout'"],
                )),
                on_exit: None,
            },
            embedded_files: None,
        }),
        variables: Some(vars),
        resolved_symtab: None,
    };
    s.enter_environment(&env, None, None, None).await.unwrap();

    let r = s
        .run_task(
            &step("sh", vec!["-c", "echo OVERRIDE=$OVERRIDE"]),
            None,
            None,
            None,
        )
        .await
        .unwrap();
    assert!(r.stdout.contains("OVERRIDE=from_stdout"));
}

#[tokio::test]
async fn test_undef_via_stdout() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let env1 = env_with_enter("env1", "sh", vec!["-c", "echo 'openjd_env: TO_UNDEF=val'"]);
    s.enter_environment(&env1, None, None, None).await.unwrap();

    let env2 = env_with_enter(
        "env2",
        "sh",
        vec!["-c", "echo 'openjd_unset_env: TO_UNDEF'"],
    );
    s.enter_environment(&env2, None, None, None).await.unwrap();

    let r = s
        .run_task(
            &step("sh", vec!["-c", "echo TO_UNDEF=${TO_UNDEF:-gone}"]),
            None,
            None,
            None,
        )
        .await
        .unwrap();
    assert!(r.stdout.contains("TO_UNDEF=gone"));
}

#[tokio::test]
async fn test_def_via_redacted_env_stdout() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf()).with_profile(
        openjd_model::ModelProfile::new(openjd_model::types::SpecificationRevision::V2023_09)
            .with_extensions(
                [openjd_model::types::ModelExtension::RedactedEnvVars]
                    .into_iter()
                    .collect(),
            ),
    );
    let env = env_with_enter(
        "env1",
        "sh",
        vec!["-c", "echo 'openjd_redacted_env: SECRET_KEY=secret_val'"],
    );
    s.enter_environment(&env, None, None, None).await.unwrap();

    let r = s
        .run_task(
            &step("sh", vec!["-c", "echo SECRET_KEY=$SECRET_KEY"]),
            None,
            None,
            None,
        )
        .await
        .unwrap();
    assert!(r.stdout.contains("SECRET_KEY=********"));

    // Redaction should work
    let redacted = s.redact("The key is secret_val");
    assert!(!redacted.contains("secret_val"));
}

// === TestSimplifiedEnvironmentVariableChanges ===
// These test the env var tracking. In Rust, this is handled by the Session's env_vars HashMap.

#[tokio::test]
async fn test_env_var_changes_init() {
    let tmp = TempDir::new().unwrap();
    let s = Session::new_for_test(tmp.path().to_path_buf());
    assert_eq!(s.state(), SessionState::Ready);
}

// === TestEnvironmentVariablesInTasks_2023_09 — additional tests ===

#[tokio::test]
async fn test_def_via_multi_line_stdout() {
    // Test that JSON-encoded multi-line env vars are set correctly
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let env = env_with_enter(
        "env1",
        "sh",
        vec!["-c", r#"printf '%s\n' 'openjd_env: "FOO=12\n34"'"#],
    );
    s.enter_environment(&env, None, None, None).await.unwrap();

    let r = s
        .run_task(
            &step("sh", vec!["-c", "printf 'FOO=%s\n' \"$FOO\""]),
            None,
            None,
            None,
        )
        .await
        .unwrap();
    assert!(r.stdout.contains("FOO=12\n34") || r.stdout.contains("FOO=12"));
}

#[tokio::test]
async fn test_def_via_stdout_set_empty() {
    // Test that setting an env var to empty string works
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let env = env_with_enter("env1", "sh", vec!["-c", "echo 'openjd_env: FOO='"]);
    s.enter_environment(&env, None, None, None).await.unwrap();

    let r = s
        .run_task(&step("sh", vec!["-c", "echo FOO=$FOO"]), None, None, None)
        .await
        .unwrap();
    assert!(r.stdout.contains("FOO="));
}

#[tokio::test]
async fn test_def_via_stdout_set_empty_json() {
    // Test that setting an env var to empty string via JSON works
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let env = env_with_enter("env1", "sh", vec!["-c", r#"echo 'openjd_env: "FOO="'"#]);
    s.enter_environment(&env, None, None, None).await.unwrap();

    let r = s
        .run_task(&step("sh", vec!["-c", "echo FOO=$FOO"]), None, None, None)
        .await
        .unwrap();
    assert!(r.stdout.contains("FOO="));
}

#[tokio::test]
async fn test_def_via_redacted_env_json_stdout() {
    // Test that redacted env vars are redacted in logs but not set without extension
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let env = env_with_enter(
        "env1",
        "sh",
        vec!["-c", "echo 'openjd_redacted_env: API_KEY=abc123def456'"],
    );
    s.enter_environment(&env, None, None, None).await.unwrap();

    // Without extension, the env var should NOT be set
    let r = s
        .run_task(
            &step("sh", vec!["-c", "echo API_KEY=${API_KEY:-not_set}"]),
            None,
            None,
            None,
        )
        .await
        .unwrap();
    assert!(r.stdout.contains("API_KEY=not_set"));

    // But the value should still be tracked for redaction
    let redacted = s.redact("The key is abc123def456");
    assert!(!redacted.contains("abc123def456"));
}

#[tokio::test]
async fn test_def_via_redacted_env_with_extension() {
    // Test that redacted env vars ARE set when extension is enabled
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf()).with_profile(
        openjd_model::ModelProfile::new(openjd_model::types::SpecificationRevision::V2023_09)
            .with_extensions(
                [openjd_model::types::ModelExtension::RedactedEnvVars]
                    .into_iter()
                    .collect(),
            ),
    );
    let env = env_with_enter(
        "env1",
        "sh",
        vec!["-c", "echo 'openjd_redacted_env: PASSWORD=secret123'"],
    );
    s.enter_environment(&env, None, None, None).await.unwrap();

    let r = s
        .run_task(
            &step("sh", vec!["-c", "echo PASSWORD=$PASSWORD"]),
            None,
            None,
            None,
        )
        .await
        .unwrap();
    assert!(r.stdout.contains("PASSWORD=********"));

    let redacted = s.redact("PASSWORD=secret123");
    assert!(!redacted.contains("secret123"));
}

#[tokio::test]
async fn test_def_via_redacted_env_with_variables() {
    // Test that redacted env vars override directly defined variables when extension is NOT enabled
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let mut vars = HashMap::new();
    vars.insert("TOKEN".into(), fs("public-token"));
    let env = Environment {
        name: "env1".into(),
        description: None,
        script: Some(openjd_model::job::EnvironmentScript {
            let_bindings: None,
            actions: openjd_model::job::EnvironmentActions {
                on_enter: Some(action(
                    "sh",
                    vec!["-c", "echo 'openjd_redacted_env: TOKEN=secret-token'"],
                )),
                on_exit: None,
            },
            embedded_files: None,
        }),
        variables: Some(vars),
        resolved_symtab: None,
    };
    s.enter_environment(&env, None, None, None).await.unwrap();

    // Without extension, the redacted env should NOT override the direct variable
    let r = s
        .run_task(
            &step("sh", vec!["-c", "echo TOKEN=$TOKEN"]),
            None,
            None,
            None,
        )
        .await
        .unwrap();
    assert!(r.stdout.contains("TOKEN=public-token"));

    // But the secret value should still be tracked for redaction
    let redacted = s.redact("secret-token");
    assert!(!redacted.contains("secret-token"));
}

#[tokio::test]
async fn test_multiple_different_redacted_env_vars() {
    // Test that multiple redacted env vars with different values are handled correctly
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf()).with_profile(
        openjd_model::ModelProfile::new(openjd_model::types::SpecificationRevision::V2023_09)
            .with_extensions(
                [openjd_model::types::ModelExtension::RedactedEnvVars]
                    .into_iter()
                    .collect(),
            ),
    );
    let env = env_with_enter("env1", "sh", vec!["-c",
        "echo 'openjd_redacted_env: PASSWORD=secret123'; echo 'openjd_redacted_env: PASSWORD2=mysecret123'"
    ]);
    s.enter_environment(&env, None, None, None).await.unwrap();

    let r = s
        .run_task(
            &step(
                "sh",
                vec!["-c", "echo PASSWORD=$PASSWORD; echo PASSWORD2=$PASSWORD2"],
            ),
            None,
            None,
            None,
        )
        .await
        .unwrap();
    assert!(r.stdout.contains("PASSWORD=********"));
    assert!(r.stdout.contains("PASSWORD2=********"));

    let redacted = s.redact("secret123 and mysecret123");
    assert!(!redacted.contains("secret123"));
    assert!(!redacted.contains("mysecret123"));
}

// === TestSessionRunTaskWithoutSessionEnv_2023_09 ===
// Tests for run_subprocess with use_session_env_vars=false

#[tokio::test]
async fn test_run_subprocess_basic() {
    let tmp = TempDir::new().unwrap();
    let config = openjd_sessions::session::SessionConfig {
        session_id: "test".into(),
        job_parameter_values: HashMap::new(),
        path_mapping_rules: None,
        retain_working_dir: false,
        callback: None,
        os_env_vars: None,
        session_root_directory: Some(tmp.path().to_path_buf()),
        user: None,
        profile: None,
        cancel_token: None,
        debug_collect_stdout: true,
        echo_openjd_directives: true,
        sticky_bit_policy: openjd_sessions::StickyBitPolicy::Disabled,
    };
    let mut s = Session::with_config(config).unwrap();
    let r = s
        .run_subprocess(
            "echo",
            Some(&["hello_subprocess".into()]),
            None,
            None,
            true,
            None,
        )
        .await
        .unwrap();
    assert_eq!(r.state, openjd_sessions::action::ActionState::Success);
    assert!(r.stdout.contains("hello_subprocess"));
}

#[tokio::test]
async fn test_run_subprocess_ignores_entered_environments() {
    // Test that run_subprocess with use_session_env_vars=false ignores entered environment variables
    let tmp = TempDir::new().unwrap();
    let config = openjd_sessions::session::SessionConfig {
        session_id: "test".into(),
        job_parameter_values: HashMap::new(),
        path_mapping_rules: None,
        retain_working_dir: false,
        callback: None,
        os_env_vars: None,
        session_root_directory: Some(tmp.path().to_path_buf()),
        user: None,
        profile: None,
        cancel_token: None,
        debug_collect_stdout: true,
        echo_openjd_directives: true,
        sticky_bit_policy: openjd_sessions::StickyBitPolicy::Disabled,
    };
    let mut s = Session::with_config(config).unwrap();

    // Enter an environment that sets FOO=bar
    let mut vars = HashMap::new();
    vars.insert("FOO".into(), fs("bar"));
    let env = env_with_vars("env1", vars);
    s.enter_environment(&env, None, None, None).await.unwrap();

    // run_subprocess with use_session_env_vars=false should NOT see FOO
    let r = s
        .run_subprocess(
            "sh",
            Some(&["-c".into(), "echo FOO=${FOO:-NOT_SET}".into()]),
            None,
            None,
            false,
            None,
        )
        .await
        .unwrap();
    assert!(r.stdout.contains("FOO=NOT_SET"));
}

#[tokio::test]
async fn test_run_subprocess_with_os_env_vars() {
    let tmp = TempDir::new().unwrap();
    let config = openjd_sessions::session::SessionConfig {
        session_id: "test".into(),
        job_parameter_values: HashMap::new(),
        path_mapping_rules: None,
        retain_working_dir: false,
        callback: None,
        os_env_vars: None,
        session_root_directory: Some(tmp.path().to_path_buf()),
        user: None,
        profile: None,
        cancel_token: None,
        debug_collect_stdout: true,
        echo_openjd_directives: true,
        sticky_bit_policy: openjd_sessions::StickyBitPolicy::Disabled,
    };
    let mut s = Session::with_config(config).unwrap();
    let mut extra = HashMap::new();
    extra.insert("CUSTOM_VAR".into(), "custom_value".into());
    let r = s
        .run_subprocess(
            "sh",
            Some(&["-c".into(), "echo CUSTOM_VAR=$CUSTOM_VAR".into()]),
            None,
            Some(&extra),
            false,
            None,
        )
        .await
        .unwrap();
    assert!(r.stdout.contains("CUSTOM_VAR=custom_value"));
}

#[tokio::test]
async fn test_run_subprocess_includes_constructor_env_vars() {
    // Test that session constructor env vars are always included
    let tmp = TempDir::new().unwrap();
    let mut ctor_env = HashMap::new();
    ctor_env.insert("CTOR_VAR".into(), "ctor_value".into());
    let config = openjd_sessions::session::SessionConfig {
        session_id: "test".into(),
        job_parameter_values: HashMap::new(),
        path_mapping_rules: None,
        retain_working_dir: false,
        callback: None,
        os_env_vars: Some(ctor_env),
        session_root_directory: Some(tmp.path().to_path_buf()),
        user: None,
        profile: None,
        cancel_token: None,
        debug_collect_stdout: true,
        echo_openjd_directives: true,
        sticky_bit_policy: openjd_sessions::StickyBitPolicy::Disabled,
    };
    let mut s = Session::with_config(config).unwrap();
    let r = s
        .run_subprocess(
            "sh",
            Some(&["-c".into(), "echo CTOR_VAR=$CTOR_VAR".into()]),
            None,
            None,
            false,
            None,
        )
        .await
        .unwrap();
    assert!(r.stdout.contains("CTOR_VAR=ctor_value"));
}

#[tokio::test]
async fn test_run_subprocess_empty_command_fails() {
    let tmp = TempDir::new().unwrap();
    let config = openjd_sessions::session::SessionConfig {
        session_id: "test".into(),
        job_parameter_values: HashMap::new(),
        path_mapping_rules: None,
        retain_working_dir: false,
        callback: None,
        os_env_vars: None,
        session_root_directory: Some(tmp.path().to_path_buf()),
        user: None,
        profile: None,
        cancel_token: None,
        debug_collect_stdout: true,
        echo_openjd_directives: true,
        sticky_bit_policy: openjd_sessions::StickyBitPolicy::Disabled,
    };
    let mut s = Session::with_config(config).unwrap();
    assert!(s
        .run_subprocess("", None, None, None, true, None)
        .await
        .is_err());
}

#[tokio::test]
async fn test_run_subprocess_whitespace_command_fails() {
    let tmp = TempDir::new().unwrap();
    let config = openjd_sessions::session::SessionConfig {
        session_id: "test".into(),
        job_parameter_values: HashMap::new(),
        path_mapping_rules: None,
        retain_working_dir: false,
        callback: None,
        os_env_vars: None,
        session_root_directory: Some(tmp.path().to_path_buf()),
        user: None,
        profile: None,
        cancel_token: None,
        debug_collect_stdout: true,
        echo_openjd_directives: true,
        sticky_bit_policy: openjd_sessions::StickyBitPolicy::Disabled,
    };
    let mut s = Session::with_config(config).unwrap();
    assert!(s
        .run_subprocess("   ", None, None, None, true, None)
        .await
        .is_err());
}

// === TestSessionExitEnvironment — additional: exit LIFO order ===

#[tokio::test]
async fn test_exit_environment_lifo_order() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let env1 = env_with_vars("env1", HashMap::new());
    let env2 = env_with_vars("env2", HashMap::new());
    let id1 = s.enter_environment(&env1, None, None, None).await.unwrap();
    let id2 = s.enter_environment(&env2, None, None, None).await.unwrap();

    // Must exit env2 first (LIFO)
    let err = s
        .exit_environment(&id1, None, true, None)
        .await
        .unwrap_err();
    assert!(matches!(
        err,
        openjd_sessions::SessionError::LifoViolation { .. }
    ));
    assert!(s.exit_environment(&id2, None, true, None).await.is_ok());
    assert!(s.exit_environment(&id1, None, true, None).await.is_ok());
}

// === TestSessionExitEnvironment — exit unknown identifier ===

#[tokio::test]
async fn test_exit_unknown_environment() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    assert!(s
        .exit_environment(&"nonexistent".to_string(), None, true, None)
        .await
        .is_err());
}

// === Redefinition exit restores outer value ===

#[tokio::test]
async fn test_redefinition_exit() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let mut vars1 = HashMap::new();
    vars1.insert("VAR".into(), fs("outer"));
    let env1 = env_with_vars("env1", vars1);
    let _id1 = s.enter_environment(&env1, None, None, None).await.unwrap();

    let mut vars2 = HashMap::new();
    vars2.insert("VAR".into(), fs("inner"));
    let env2 = env_with_vars("env2", vars2);
    let id2 = s.enter_environment(&env2, None, None, None).await.unwrap();

    // Exit inner env — outer value should be restored
    s.exit_environment(&id2, None, true, None).await.unwrap();
    let r = s
        .run_task(&step("sh", vec!["-c", "echo VAR=$VAR"]), None, None, None)
        .await
        .unwrap();
    assert!(r.stdout.contains("VAR=outer"));
}

// === Real-time message processing tests ===

type TimestampLog = std::sync::Arc<
    std::sync::Mutex<
        Vec<(
            std::time::Duration,
            ActionState,
            Option<f64>,
            Option<String>,
        )>,
    >,
>;

/// Helper: warm up OS caches (shell binary, DLLs, filesystem metadata) before a
/// real-time timing test runs. Without this, the first `sh` spawn on a CI
/// machine — especially Windows — can dwarf the task's actual sleep duration,
/// making the "callback arrived before completion" assertion racy.
///
/// Uses its own TempDir so cleanup-on-drop doesn't touch the caller's tmp.
async fn warmup_shell() {
    let warmup_tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(warmup_tmp.path().to_path_buf());
    let _ = s
        .run_task(
            &step("sh", vec!["-c", "echo warmup; sleep 0.05"]),
            None,
            None,
            None,
        )
        .await;
}

/// Helper: create a SessionConfig with a callback that records (elapsed, state, progress).
fn realtime_test_config(
    tmp: &TempDir,
    session_id: &str,
    timestamps: TimestampLog,
) -> openjd_sessions::session::SessionConfig {
    let start = std::time::Instant::now();
    let ts = timestamps.clone();
    openjd_sessions::session::SessionConfig {
        session_id: session_id.into(),
        job_parameter_values: HashMap::new(),
        path_mapping_rules: None,
        retain_working_dir: false,
        callback: Some(Box::new(move |_sid, status| {
            ts.lock().unwrap().push((
                start.elapsed(),
                status.state,
                status.progress,
                status.status_message.clone(),
            ));
        })),
        os_env_vars: None,
        session_root_directory: Some(tmp.path().to_path_buf()),
        user: None,
        profile: None,
        cancel_token: None,
        debug_collect_stdout: true,
        echo_openjd_directives: true,
        sticky_bit_policy: openjd_sessions::StickyBitPolicy::Disabled,
    }
}

#[tokio::test]
async fn test_callback_receives_progress_before_completion() {
    let tmp = TempDir::new().unwrap();
    // Warm up OS caches so shell startup doesn't dominate the 200ms sleep.
    warmup_shell().await;
    let ts = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
    let mut s = Session::with_config(realtime_test_config(&tmp, "rt-prog", ts.clone())).unwrap();

    // Emit progress immediately, then sleep long enough that shell startup
    // overhead (which can be 500ms+ on Windows CI under parallel load) is
    // negligible relative to the total runtime.
    let script = step("sh", vec!["-c", "echo 'openjd_progress: 50.0'; sleep 2"]);
    let t0 = std::time::Instant::now();
    s.run_task(&script, None, None, None).await.unwrap();
    let total = t0.elapsed();

    let ts = ts.lock().unwrap();
    let first = ts
        .iter()
        .find(|(_, st, p, _)| *st == ActionState::Running && p.is_some());
    let first = first.expect("Expected progress callback during RUNNING");
    assert!(
        first.0 < total / 2,
        "Progress callback at {:?} but task took {:?} — not real-time",
        first.0,
        total
    );
}

#[tokio::test]
async fn test_callback_receives_status_before_completion() {
    let tmp = TempDir::new().unwrap();
    // Warm up OS caches so shell startup doesn't dominate the 200ms sleep.
    warmup_shell().await;
    let ts = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
    let mut s = Session::with_config(realtime_test_config(&tmp, "rt-stat", ts.clone())).unwrap();

    let script = step(
        "sh",
        vec!["-c", "echo 'openjd_status: Rendering frame 1'; sleep 2"],
    );
    let t0 = std::time::Instant::now();
    s.run_task(&script, None, None, None).await.unwrap();
    let total = t0.elapsed();

    let ts = ts.lock().unwrap();
    let first = ts
        .iter()
        .find(|(_, st, _, msg)| *st == ActionState::Running && msg.is_some());
    let first = first.expect("Expected status callback during RUNNING");
    assert!(
        first.0 < total / 2,
        "Status callback at {:?} but task took {:?} — not real-time",
        first.0,
        total
    );
}

#[tokio::test]
async fn test_env_enter_callback_receives_progress_before_completion() {
    let tmp = TempDir::new().unwrap();
    // Warm up OS caches so shell startup doesn't dominate the 200ms sleep.
    warmup_shell().await;
    let ts = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
    let mut s = Session::with_config(realtime_test_config(&tmp, "rt-env", ts.clone())).unwrap();

    let env = env_with_enter(
        "env1",
        "sh",
        vec!["-c", "echo 'openjd_progress: 50.0'; sleep 2"],
    );
    let t0 = std::time::Instant::now();
    s.enter_environment(&env, None, None, None).await.unwrap();
    let total = t0.elapsed();

    let ts = ts.lock().unwrap();
    let first = ts
        .iter()
        .find(|(_, st, p, _)| *st == ActionState::Running && p.is_some());
    let first = first.expect("Expected progress callback during env enter RUNNING");
    assert!(
        first.0 < total / 2,
        "Progress callback at {:?} but enter took {:?} — not real-time",
        first.0,
        total
    );
}

// === Tests for per-action os_env_vars ===

#[tokio::test]
async fn test_run_task_with_per_action_os_env_vars() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let extra = HashMap::from([("EXTRA_VAR".to_string(), "extra_value".to_string())]);
    let r = s
        .run_task(
            &step("sh", vec!["-c", "echo EXTRA_VAR=$EXTRA_VAR"]),
            None,
            None,
            Some(&extra),
        )
        .await
        .unwrap();
    assert_eq!(r.state, ActionState::Success);
    assert!(r.stdout.contains("EXTRA_VAR=extra_value"));
}

#[tokio::test]
async fn test_enter_environment_with_per_action_os_env_vars() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let env = env_with_enter("env1", "sh", vec!["-c", "echo ACTION_VAR=$ACTION_VAR"]);
    let extra = HashMap::from([("ACTION_VAR".to_string(), "from_action".to_string())]);
    let (_, stdout) = s
        .enter_environment_with_output(&env, None, None, Some(&extra))
        .await
        .unwrap();
    assert!(stdout.contains("ACTION_VAR=from_action"));
}

#[tokio::test]
async fn test_exit_environment_with_per_action_os_env_vars() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let env = Environment {
        name: "env1".into(),
        description: None,
        script: Some(EnvironmentScript {
            let_bindings: None,
            actions: EnvironmentActions {
                on_enter: None,
                on_exit: Some(action("sh", vec!["-c", "echo EXIT_VAR=$EXIT_VAR"])),
            },
            embedded_files: None,
        }),
        variables: None,
        resolved_symtab: None,
    };
    let id = s.enter_environment(&env, None, None, None).await.unwrap();
    let extra = HashMap::from([("EXIT_VAR".to_string(), "from_exit".to_string())]);
    let stdout = s
        .exit_environment(&id, None, true, Some(&extra))
        .await
        .unwrap();
    assert!(stdout.contains("EXIT_VAR=from_exit"));
}

#[tokio::test]
async fn test_per_action_os_env_vars_override_session_env() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    // Set a session-level env var via an environment's variables block
    let mut vars = HashMap::new();
    vars.insert("MY_VAR".into(), fs("session_value"));
    let env = env_with_vars("env1", vars);
    s.enter_environment(&env, None, None, None).await.unwrap();

    // Per-action os_env_vars should be overridden by environment-defined vars
    // (matching Python's layering: process_env < per-action < environment-defined)
    let extra = HashMap::from([("MY_VAR".to_string(), "action_value".to_string())]);
    let r = s
        .run_task(
            &step("sh", vec!["-c", "echo MY_VAR=$MY_VAR"]),
            None,
            None,
            Some(&extra),
        )
        .await
        .unwrap();
    // Environment-defined vars take precedence over per-action vars
    assert!(r.stdout.contains("MY_VAR=session_value"));
}

#[tokio::test]
async fn test_per_action_os_env_vars_do_not_persist() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let extra = HashMap::from([("EPHEMERAL".to_string(), "yes".to_string())]);
    let r = s
        .run_task(
            &step("sh", vec!["-c", "echo EPHEMERAL=$EPHEMERAL"]),
            None,
            None,
            Some(&extra),
        )
        .await
        .unwrap();
    assert!(r.stdout.contains("EPHEMERAL=yes"));

    // Next action without extra env vars should NOT see the variable
    let r = s
        .run_task(
            &step("sh", vec!["-c", "echo EPHEMERAL=${EPHEMERAL:-gone}"]),
            None,
            None,
            None,
        )
        .await
        .unwrap();
    assert!(r.stdout.contains("EPHEMERAL=gone"));
}

// === TestCancelAction ===

#[tokio::test]
async fn test_cancel_action_not_running() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    // Session is in READY state, cancel should fail
    let result = s.cancel_action(None, false);
    assert!(result.is_err());
}

#[tokio::test]
async fn test_cancel_action_mark_failed() {
    let tmp = TempDir::new().unwrap();
    let config = openjd_sessions::session::SessionConfig {
        session_id: "cancel-test".into(),
        job_parameter_values: HashMap::new(),
        path_mapping_rules: None,
        retain_working_dir: false,
        callback: None,
        os_env_vars: None,
        session_root_directory: Some(tmp.path().to_path_buf()),
        user: None,
        profile: None,
        cancel_token: None,
        debug_collect_stdout: true,
        echo_openjd_directives: true,
        sticky_bit_policy: openjd_sessions::StickyBitPolicy::Disabled,
    };
    let mut s = Session::with_config(config).unwrap();

    // Test via malformed env command which triggers CancelMarkFailed internally.
    // openjd_env:bad=value (no space after colon) is detected as malformed,
    // causing cancel with mark_action_failed=true.
    let script = step("sh", vec!["-c", "echo 'openjd_env:bad=value'; sleep 10"]);
    let r = s.run_task(&script, None, None, None).await.unwrap();
    assert_eq!(
        r.state,
        ActionState::Failed,
        "Malformed env command should cause Failed state, got {:?}",
        r.state
    );
    assert_eq!(s.state(), SessionState::ReadyEnding);
}

#[tokio::test]
async fn test_malformed_env_cancels_and_marks_failed() {
    // Test that a malformed openjd_env command (missing space after colon) causes
    // the action to be canceled and marked as failed
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());

    let script = step("sh", vec!["-c", "echo 'openjd_env:FOO=bar'; sleep 10"]);
    let r = s.run_task(&script, None, None, None).await.unwrap();
    assert_eq!(r.state, ActionState::Failed);
    assert_eq!(s.state(), SessionState::ReadyEnding);

    // Check that the fail message was set
    let status = s.action_status().unwrap();
    assert!(status.fail_message.is_some());
}

#[tokio::test]
async fn test_malformed_unset_env_cancels_and_marks_failed() {
    // Test that a malformed openjd_unset_env command causes cancel+fail
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());

    let script = step("sh", vec!["-c", "echo 'openjd_unset_env:FOO'; sleep 10"]);
    let r = s.run_task(&script, None, None, None).await.unwrap();
    assert_eq!(r.state, ActionState::Failed);
}

#[tokio::test]
async fn test_invalid_env_var_name_cancels_and_marks_failed() {
    // Test that an invalid env var name (starts with digit) causes cancel+fail
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());

    let script = step("sh", vec!["-c", "echo 'openjd_env: 1BAD=value'; sleep 10"]);
    let r = s.run_task(&script, None, None, None).await.unwrap();
    assert_eq!(r.state, ActionState::Failed);
}

// === TestGetEnabledExtensions ===

#[tokio::test]
async fn test_get_enabled_extensions_with_extensions() {
    let tmp = TempDir::new().unwrap();
    let s = Session::new_for_test(tmp.path().to_path_buf()).with_profile(
        openjd_model::ModelProfile::new(openjd_model::types::SpecificationRevision::V2023_09)
            .with_extensions(
                [
                    openjd_model::types::ModelExtension::Expr,
                    openjd_model::types::ModelExtension::RedactedEnvVars,
                ]
                .into_iter()
                .collect(),
            ),
    );
    let mut exts = s.get_enabled_extensions();
    exts.sort();
    assert_eq!(exts, vec!["EXPR", "REDACTED_ENV_VARS"]);
}

#[tokio::test]
async fn test_get_enabled_extensions_empty() {
    let tmp = TempDir::new().unwrap();
    let s = Session::new_for_test(tmp.path().to_path_buf());
    assert!(s.get_enabled_extensions().is_empty());
}

// === InvalidState error carries SessionState enum values ===

#[tokio::test]
async fn invalid_state_error_carries_enum_values() {
    // After cleanup (Ended), enter_environment should give InvalidState
    // with expected=[Ready], current=Ended as SessionState values.
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    s.cleanup();
    let env = env_with_enter("env1", "echo", vec!["hi"]);
    let err = s
        .enter_environment(&env, None, None, None)
        .await
        .unwrap_err();
    match err {
        openjd_sessions::error::SessionError::InvalidState { expected, current } => {
            assert_eq!(expected, &[SessionState::Ready]);
            assert_eq!(current, SessionState::Ended);
        }
        other => panic!("expected InvalidState, got: {other}"),
    }
}

#[tokio::test]
async fn invalid_state_error_multiple_expected_states() {
    // exit_environment when in Ended state should give expected=[Ready, ReadyEnding]
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    s.cleanup();
    let id = "env1".to_string();
    let err = s
        .exit_environment(&id, None, false, None)
        .await
        .unwrap_err();
    match err {
        openjd_sessions::error::SessionError::InvalidState { expected, current } => {
            assert!(
                expected.contains(&SessionState::Ready),
                "expected should contain Ready"
            );
            assert!(
                expected.contains(&SessionState::ReadyEnding),
                "expected should contain ReadyEnding"
            );
            assert_eq!(current, SessionState::Ended);
        }
        other => panic!("expected InvalidState, got: {other}"),
    }
}

#[tokio::test]
async fn invalid_state_error_display_format() {
    // Verify the Display output is human-readable
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    s.cleanup();
    let env = env_with_enter("env1", "echo", vec!["hi"]);
    let err = s
        .enter_environment(&env, None, None, None)
        .await
        .unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("READY"),
        "should mention expected state: {msg}"
    );
    assert!(msg.contains("ENDED"), "should mention current state: {msg}");
}

// === Action-level timeout enforcement ===

fn action_with_timeout(cmd: &str, args: Vec<&str>, timeout_secs: &str) -> Action {
    Action {
        command: fs(cmd),
        args: Some(args.iter().map(|a| fs(a)).collect()),
        timeout: Some(fs(timeout_secs)),
        cancelation: None,
    }
}

/// Step script onRun action with a timeout should kill the process when the
/// timeout expires and report ActionState::Timeout.
#[tokio::test]
async fn test_run_task_action_timeout_enforced() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let script = StepScript {
        let_bindings: None,
        actions: StepActions {
            on_run: action_with_timeout("sh", vec!["-c", "echo start; sleep 30; echo done"], "1"),
        },
        embedded_files: None,
    };
    let start = std::time::Instant::now();
    let r = s.run_task(&script, None, None, None).await.unwrap();
    let elapsed = start.elapsed();
    assert_eq!(
        r.state,
        ActionState::Timeout,
        "Expected Timeout but got {:?} (exit_code={:?})",
        r.state,
        r.exit_code
    );
    assert!(
        elapsed < std::time::Duration::from_secs(10),
        "Timeout should have fired quickly, but took {elapsed:?}"
    );
    assert!(
        r.stdout.contains("start"),
        "Should see output before timeout"
    );
    assert!(
        !r.stdout.contains("done"),
        "Should not see output after timeout"
    );
}

/// Environment onEnter action with a timeout should be enforced.
#[tokio::test]
async fn test_enter_environment_action_timeout_enforced() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let env = Environment {
        name: "timeout_env".into(),
        description: None,
        script: Some(EnvironmentScript {
            let_bindings: None,
            actions: EnvironmentActions {
                on_enter: Some(action_with_timeout(
                    "sh",
                    vec!["-c", "echo entering; sleep 30"],
                    "1",
                )),
                on_exit: None,
            },
            embedded_files: None,
        }),
        variables: None,
        resolved_symtab: None,
    };
    let start = std::time::Instant::now();
    let result = s.enter_environment(&env, None, None, None).await;
    let elapsed = start.elapsed();
    // onEnter failure returns an error
    assert!(
        result.is_err(),
        "Expected error from timed-out onEnter, got Ok"
    );
    assert!(
        elapsed < std::time::Duration::from_secs(10),
        "Timeout should have fired quickly, but took {elapsed:?}"
    );
}

/// Environment onExit action with an explicit timeout should use that timeout,
/// not the 5-minute default.
#[tokio::test]
async fn test_exit_environment_action_timeout_enforced() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    // Enter with a simple env first
    let env = Environment {
        name: "exit_timeout_env".into(),
        description: None,
        script: Some(EnvironmentScript {
            let_bindings: None,
            actions: EnvironmentActions {
                on_enter: Some(action("echo", vec!["entered"])),
                on_exit: Some(action_with_timeout(
                    "sh",
                    vec!["-c", "echo exiting; sleep 30"],
                    "1",
                )),
            },
            embedded_files: None,
        }),
        variables: None,
        resolved_symtab: None,
    };
    let id = s.enter_environment(&env, None, None, None).await.unwrap();
    let start = std::time::Instant::now();
    let result = s.exit_environment(&id, None, true, None).await;
    let elapsed = start.elapsed();
    // onExit failure returns an error
    assert!(
        result.is_err(),
        "Expected error from timed-out onExit, got Ok"
    );
    assert!(
        elapsed < std::time::Duration::from_secs(10),
        "Timeout should have fired in ~1s, not the 5-minute default ({elapsed:?})"
    );
}

/// Action with no timeout should still work (no regression).
#[tokio::test]
async fn test_run_task_no_timeout_still_works() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let r = s
        .run_task(&step("sh", vec!["-c", "echo hello"]), None, None, None)
        .await
        .unwrap();
    assert_eq!(r.state, ActionState::Success);
    assert!(r.stdout.contains("hello"));
}

// === Callback coverage tests ===
// Verify the callback fires in every code path: with-script, no-script,
// success, failure, command-not-found, for enter/exit/task/subprocess.

type CbLog = Vec<(ActionState, Option<f64>)>;

fn cb_test_config(tmp: &TempDir, id: &str, log: Arc<Mutex<CbLog>>) -> SessionConfig {
    SessionConfig {
        session_id: id.into(),
        job_parameter_values: HashMap::new(),
        path_mapping_rules: None,
        retain_working_dir: false,
        callback: Some(Box::new(move |_sid, status| {
            log.lock().unwrap().push((status.state, status.progress));
        })),
        os_env_vars: None,
        session_root_directory: Some(tmp.path().to_path_buf()),
        user: None,
        profile: None,
        cancel_token: None,
        debug_collect_stdout: true,
        echo_openjd_directives: true,
        sticky_bit_policy: openjd_sessions::StickyBitPolicy::Disabled,
    }
}

#[tokio::test]
async fn test_callback_enter_env_with_script() {
    let tmp = TempDir::new().unwrap();
    let log: Arc<Mutex<CbLog>> = Arc::new(Mutex::new(Vec::new()));
    let mut s = Session::with_config(cb_test_config(&tmp, "cb-enter-script", log.clone())).unwrap();
    let env = env_with_enter("e", "sh", vec!["-c", "echo hello"]);
    s.enter_environment(&env, None, None, None).await.unwrap();
    let log = log.lock().unwrap();
    assert!(
        !log.is_empty(),
        "Callback must fire for enter_environment with script"
    );
    assert!(
        log.iter().any(|(st, _)| *st == ActionState::Success),
        "Must have Success callback"
    );
}

#[tokio::test]
async fn test_callback_enter_env_no_script_with_vars() {
    let tmp = TempDir::new().unwrap();
    let log: Arc<Mutex<CbLog>> = Arc::new(Mutex::new(Vec::new()));
    let mut s = Session::with_config(cb_test_config(&tmp, "cb-enter-vars", log.clone())).unwrap();
    let mut vars = HashMap::new();
    vars.insert("FOO".into(), FormatString::new("bar").unwrap());
    let env = env_with_vars("e", vars);
    s.enter_environment(&env, None, None, None).await.unwrap();
    let log = log.lock().unwrap();
    assert!(
        !log.is_empty(),
        "Callback must fire for enter_environment with variables only"
    );
    assert_eq!(log.last().unwrap().0, ActionState::Success);
}

#[tokio::test]
async fn test_callback_enter_env_no_script_no_vars() {
    let tmp = TempDir::new().unwrap();
    let log: Arc<Mutex<CbLog>> = Arc::new(Mutex::new(Vec::new()));
    let mut s = Session::with_config(cb_test_config(&tmp, "cb-enter-empty", log.clone())).unwrap();
    let env = Environment {
        name: "empty".into(),
        description: None,
        script: None,
        variables: None,
        resolved_symtab: None,
    };
    s.enter_environment(&env, None, None, None).await.unwrap();
    let log = log.lock().unwrap();
    assert!(
        !log.is_empty(),
        "Callback must fire for enter_environment with no script and no vars"
    );
    assert_eq!(log.last().unwrap().0, ActionState::Success);
}

#[tokio::test]
async fn test_callback_exit_env_with_script() {
    let tmp = TempDir::new().unwrap();
    let log: Arc<Mutex<CbLog>> = Arc::new(Mutex::new(Vec::new()));
    let mut s = Session::with_config(cb_test_config(&tmp, "cb-exit-script", log.clone())).unwrap();
    let env = Environment {
        name: "e".into(),
        description: None,
        script: Some(EnvironmentScript {
            let_bindings: None,
            actions: EnvironmentActions {
                on_enter: None,
                on_exit: Some(action("sh", vec!["-c", "echo bye"])),
            },
            embedded_files: None,
        }),
        variables: None,
        resolved_symtab: None,
    };
    s.enter_environment(&env, None, Some("eid"), None)
        .await
        .unwrap();
    log.lock().unwrap().clear(); // clear enter callbacks
    s.exit_environment(&"eid".to_string(), None, true, None)
        .await
        .unwrap();
    let log = log.lock().unwrap();
    assert!(
        !log.is_empty(),
        "Callback must fire for exit_environment with script"
    );
    assert!(log.iter().any(|(st, _)| *st == ActionState::Success));
}

#[tokio::test]
async fn test_callback_exit_env_no_script() {
    let tmp = TempDir::new().unwrap();
    let log: Arc<Mutex<CbLog>> = Arc::new(Mutex::new(Vec::new()));
    let mut s =
        Session::with_config(cb_test_config(&tmp, "cb-exit-noscript", log.clone())).unwrap();
    let env = Environment {
        name: "e".into(),
        description: None,
        script: None,
        variables: None,
        resolved_symtab: None,
    };
    s.enter_environment(&env, None, Some("eid"), None)
        .await
        .unwrap();
    log.lock().unwrap().clear();
    s.exit_environment(&"eid".to_string(), None, true, None)
        .await
        .unwrap();
    let log = log.lock().unwrap();
    assert!(
        !log.is_empty(),
        "Callback must fire for exit_environment with no script"
    );
    assert_eq!(log.last().unwrap().0, ActionState::Success);
}

#[tokio::test]
async fn test_callback_run_task_success() {
    let tmp = TempDir::new().unwrap();
    let log: Arc<Mutex<CbLog>> = Arc::new(Mutex::new(Vec::new()));
    let mut s = Session::with_config(cb_test_config(&tmp, "cb-task-ok", log.clone())).unwrap();
    s.run_task(&step("sh", vec!["-c", "echo ok"]), None, None, None)
        .await
        .unwrap();
    let log = log.lock().unwrap();
    assert!(!log.is_empty(), "Callback must fire for run_task success");
    assert!(log.iter().any(|(st, _)| *st == ActionState::Success));
}

#[tokio::test]
async fn test_callback_run_task_failure() {
    let tmp = TempDir::new().unwrap();
    let log: Arc<Mutex<CbLog>> = Arc::new(Mutex::new(Vec::new()));
    let mut s = Session::with_config(cb_test_config(&tmp, "cb-task-fail", log.clone())).unwrap();
    let r = s
        .run_task(&step("sh", vec!["-c", "exit 1"]), None, None, None)
        .await
        .unwrap();
    assert_eq!(r.state, ActionState::Failed);
    let log = log.lock().unwrap();
    assert!(!log.is_empty(), "Callback must fire for run_task failure");
    assert!(log.iter().any(|(st, _)| *st == ActionState::Failed));
}

#[tokio::test]
async fn test_callback_run_task_command_not_found() {
    let tmp = TempDir::new().unwrap();
    let log: Arc<Mutex<CbLog>> = Arc::new(Mutex::new(Vec::new()));
    let mut s =
        Session::with_config(cb_test_config(&tmp, "cb-task-notfound", log.clone())).unwrap();
    let r = s
        .run_task(&step("nonexistent-cmd-xyz", vec![]), None, None, None)
        .await;
    assert!(r.is_err());
    let log = log.lock().unwrap();
    assert!(
        !log.is_empty(),
        "Callback must fire for run_task command not found"
    );
    assert!(log.iter().any(|(st, _)| *st == ActionState::Failed));
}

#[tokio::test]
async fn test_callback_enter_env_command_not_found() {
    let tmp = TempDir::new().unwrap();
    let log: Arc<Mutex<CbLog>> = Arc::new(Mutex::new(Vec::new()));
    let mut s = Session::with_config(cb_test_config(&tmp, "cb-env-notfound", log.clone())).unwrap();
    let env = env_with_enter("e", "nonexistent-cmd-xyz", vec![]);
    let r = s.enter_environment(&env, None, None, None).await;
    assert!(r.is_err());
    let log = log.lock().unwrap();
    assert!(
        !log.is_empty(),
        "Callback must fire for enter_environment command not found"
    );
    assert!(log.iter().any(|(st, _)| *st == ActionState::Failed));
}

#[tokio::test]
async fn test_callback_run_subprocess_success() {
    let tmp = TempDir::new().unwrap();
    let log: Arc<Mutex<CbLog>> = Arc::new(Mutex::new(Vec::new()));
    let mut s = Session::with_config(cb_test_config(&tmp, "cb-subproc", log.clone())).unwrap();
    s.run_subprocess("echo", Some(&["hello".into()]), None, None, true, None)
        .await
        .unwrap();
    let log = log.lock().unwrap();
    assert!(!log.is_empty(), "Callback must fire for run_subprocess");
    assert!(log.iter().any(|(st, _)| *st == ActionState::Success));
}

#[tokio::test]
async fn test_callback_run_subprocess_command_not_found() {
    let tmp = TempDir::new().unwrap();
    let log: Arc<Mutex<CbLog>> = Arc::new(Mutex::new(Vec::new()));
    let mut s =
        Session::with_config(cb_test_config(&tmp, "cb-subproc-notfound", log.clone())).unwrap();
    let r = s
        .run_subprocess("nonexistent-cmd-xyz", None, None, None, true, None)
        .await;
    assert!(r.is_err());
    let log = log.lock().unwrap();
    assert!(
        !log.is_empty(),
        "Callback must fire for run_subprocess command not found"
    );
    assert!(log.iter().any(|(st, _)| *st == ActionState::Failed));
}

#[tokio::test]
async fn test_callback_progress_not_leaked_between_actions() {
    // Regression: progress from one action must not leak into the next.
    let tmp = TempDir::new().unwrap();
    let log: Arc<Mutex<CbLog>> = Arc::new(Mutex::new(Vec::new()));
    let mut s = Session::with_config(cb_test_config(&tmp, "cb-no-leak", log.clone())).unwrap();

    // First action sets progress to 50%
    let env = env_with_enter("e", "sh", vec!["-c", "echo 'openjd_progress: 50.0'"]);
    s.enter_environment(&env, None, Some("eid"), None)
        .await
        .unwrap();

    // Check that progress was set
    let has_progress = log.lock().unwrap().iter().any(|(_, p)| *p == Some(50.0));
    assert!(has_progress, "First action should have 50% progress");

    log.lock().unwrap().clear();

    // Second action: exit with no script — should NOT have 50% progress
    s.exit_environment(&"eid".to_string(), None, true, None)
        .await
        .unwrap();
    let log = log.lock().unwrap();
    assert!(!log.is_empty(), "Exit callback must fire");
    for (state, progress) in log.iter() {
        assert_eq!(*state, ActionState::Success);
        assert_eq!(
            *progress, None,
            "Progress from previous action must not leak: got {:?}",
            progress
        );
    }
}

// === run_task state validation ===

#[tokio::test]
async fn test_run_task_rejects_ended_state() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    s.cleanup();
    assert_eq!(s.state(), SessionState::Ended);

    let result = s
        .run_task(&step("echo", vec!["hello"]), None, None, None)
        .await;
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("READY"),
        "Expected InvalidState error, got: {err}"
    );
}

#[tokio::test]
async fn test_exit_environment_failure_still_pops_for_lifo() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());

    // Enter two environments
    let env1 = env_with_enter("env1", "sh", vec!["-c", "echo enter1"]);
    let id1 = s.enter_environment(&env1, None, None, None).await.unwrap();

    let env2 = Environment {
        name: "env2".into(),
        description: None,
        script: Some(EnvironmentScript {
            let_bindings: None,
            actions: EnvironmentActions {
                on_enter: Some(action("sh", vec!["-c", "echo enter2"])),
                on_exit: Some(action("sh", vec!["-c", "exit 1"])),
            },
            embedded_files: None,
        }),
        variables: None,
        resolved_symtab: None,
    };
    let id2 = s.enter_environment(&env2, None, None, None).await.unwrap();

    // Exit env2 — the onExit script fails
    let result = s.exit_environment(&id2, None, true, None).await;
    assert!(
        result.is_err(),
        "exit_environment should fail when onExit script fails"
    );
    assert_eq!(s.state(), SessionState::ReadyEnding);

    // Exit env1 — this should succeed because env2 was popped despite its failure
    let result = s.exit_environment(&id1, None, true, None).await;
    assert!(
        result.is_ok(),
        "Should be able to exit env1 after env2 failed: {:?}",
        result.err()
    );
}

// ══════════════════════════════════════════════════════════════
// extend_path_mapping_rules
// ══════════════════════════════════════════════════════════════

#[tokio::test]
async fn test_extend_path_mapping_rules_appends_and_sorts() {
    use openjd_expr::path_mapping::{PathFormat, PathMappingRule};

    let tmp = TempDir::new().unwrap();
    let mut s =
        Session::new_for_test(tmp.path().to_path_buf()).with_path_mapping(vec![PathMappingRule {
            source_path_format: PathFormat::Posix,
            source_path: "/short".into(),
            destination_path: "/s".into(),
        }]);

    assert_eq!(s.path_mapping_rules().len(), 1);

    s.extend_path_mapping_rules(vec![
        PathMappingRule {
            source_path_format: PathFormat::Posix,
            source_path: "/much/longer/path".into(),
            destination_path: "/m".into(),
        },
        PathMappingRule {
            source_path_format: PathFormat::Posix,
            source_path: "/med".into(),
            destination_path: "/d".into(),
        },
    ]);

    let rules = s.path_mapping_rules();
    assert_eq!(rules.len(), 3);
    // Sorted by source_path length descending (longest first)
    assert_eq!(rules[0].source_path, "/much/longer/path");
    assert_eq!(rules[1].source_path, "/short");
    assert_eq!(rules[2].source_path, "/med");
}

// ══════════════════════════════════════════════════════════════
// cancel_action via Session API
// ══════════════════════════════════════════════════════════════

#[tokio::test]
async fn test_cancel_action_requires_running_state() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    assert_eq!(s.state(), SessionState::Ready);
    let err = s.cancel_action(None, false).unwrap_err();
    assert!(matches!(
        err,
        openjd_sessions::SessionError::InvalidState { .. }
    ));
}

// ══════════════════════════════════════════════════════════════
// parent_cancel_token cascading + mark_action_failed
// ══════════════════════════════════════════════════════════════

#[tokio::test]
async fn test_parent_cancel_token_cancels_running_action() {
    use tokio_util::sync::CancellationToken;

    let tmp = TempDir::new().unwrap();
    let parent_token = CancellationToken::new();

    let statuses: Arc<Mutex<Vec<ActionState>>> = Arc::new(Mutex::new(Vec::new()));
    let statuses_clone = statuses.clone();

    let config = SessionConfig {
        session_id: "cancel-test".into(),
        job_parameter_values: HashMap::new(),
        path_mapping_rules: None,
        retain_working_dir: false,
        callback: Some(Box::new(move |_sid, status| {
            statuses_clone.lock().unwrap().push(status.state);
        })),
        os_env_vars: None,
        session_root_directory: Some(tmp.path().to_path_buf()),
        user: None,
        profile: None,
        cancel_token: Some(parent_token.clone()),
        debug_collect_stdout: true,
        echo_openjd_directives: true,
        sticky_bit_policy: openjd_sessions::StickyBitPolicy::Disabled,
    };
    let mut s = Session::with_config(config).unwrap();

    let token_clone = parent_token.clone();
    tokio::spawn(async move {
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        token_clone.cancel();
    });

    let _result = s
        .run_task(&step("sh", vec!["-c", "sleep 30"]), None, None, None)
        .await;

    assert_eq!(s.state(), SessionState::ReadyEnding);
    let final_statuses = statuses.lock().unwrap();
    assert!(
        final_statuses.contains(&ActionState::Canceled),
        "Expected Canceled in statuses: {:?}",
        *final_statuses
    );
}

#[tokio::test]
async fn test_cancel_action_with_mark_failed() {
    use tokio_util::sync::CancellationToken;

    let tmp = TempDir::new().unwrap();
    let parent_token = CancellationToken::new();

    let statuses: Arc<Mutex<Vec<ActionState>>> = Arc::new(Mutex::new(Vec::new()));
    let statuses_clone = statuses.clone();

    // Signal when the Failed callback fires so we know the malformed command was processed.
    let failed_notify = Arc::new(tokio::sync::Notify::new());
    let failed_notify_clone = failed_notify.clone();

    let config = SessionConfig {
        session_id: "mark-failed-test".into(),
        job_parameter_values: HashMap::new(),
        path_mapping_rules: None,
        retain_working_dir: false,
        callback: Some(Box::new(move |_sid, status| {
            statuses_clone.lock().unwrap().push(status.state);
            if status.state == ActionState::Failed {
                failed_notify_clone.notify_one();
            }
        })),
        os_env_vars: None,
        session_root_directory: Some(tmp.path().to_path_buf()),
        user: None,
        profile: None,
        cancel_token: Some(parent_token.clone()),
        debug_collect_stdout: true,
        echo_openjd_directives: true,
        sticky_bit_policy: openjd_sessions::StickyBitPolicy::Disabled,
    };
    let mut s = Session::with_config(config).unwrap();

    // The malformed openjd_env command triggers CancelMarkFailed which cancels
    // the action and marks it as Failed. The parent token cancel is only a
    // safety net to kill the `sleep 30` if something goes wrong.
    let token_clone = parent_token.clone();
    tokio::spawn(async move {
        // Wait for the Failed callback (malformed command processed), or
        // fall back to a generous timeout so the test doesn't hang.
        tokio::select! {
            _ = failed_notify.notified() => {}
            _ = tokio::time::sleep(std::time::Duration::from_secs(30)) => {}
        }
        token_clone.cancel();
    });

    let _result = s
        .run_task(
            &step("sh", vec!["-c", "echo 'openjd_env:badformat'; sleep 30"]),
            None,
            None,
            None,
        )
        .await;

    assert_eq!(s.state(), SessionState::ReadyEnding);
    let final_statuses = statuses.lock().unwrap();
    // CancelMarkFailed converts the action to Failed
    assert!(
        final_statuses.contains(&ActionState::Failed),
        "Expected Failed in statuses: {:?}",
        *final_statuses
    );
}

// ══════════════════════════════════════════════════════════════
// run_subprocess validation
// ══════════════════════════════════════════════════════════════

#[tokio::test]
async fn test_run_subprocess_rejects_empty_command() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let err = s
        .run_subprocess("", None, None, None, false, None)
        .await
        .unwrap_err();
    assert!(
        err.to_string().contains("non-empty"),
        "Expected non-empty error, got: {err}"
    );
}

#[tokio::test]
async fn test_run_subprocess_rejects_whitespace_only_command() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let err = s
        .run_subprocess("   ", None, None, None, false, None)
        .await
        .unwrap_err();
    assert!(
        err.to_string().contains("non-empty"),
        "Expected non-empty error, got: {err}"
    );
}

#[tokio::test]
async fn test_run_subprocess_rejects_zero_timeout() {
    let tmp = TempDir::new().unwrap();
    let mut s = Session::new_for_test(tmp.path().to_path_buf());
    let err = s
        .run_subprocess(
            "echo",
            None,
            Some(std::time::Duration::from_secs(0)),
            None,
            false,
            None,
        )
        .await
        .unwrap_err();
    assert!(
        err.to_string().contains("positive"),
        "Expected positive timeout error, got: {err}"
    );
}

// ══════════════════════════════════════════════════════════════
// redactions_enabled interaction with profile
// ══════════════════════════════════════════════════════════════

#[tokio::test]
async fn test_redacted_env_sets_var_with_extension() {
    use openjd_model::types::{ModelExtension, SpecificationRevision};
    use openjd_model::ModelProfile;

    let tmp = TempDir::new().unwrap();
    let mut exts = std::collections::HashSet::new();
    exts.insert(ModelExtension::RedactedEnvVars);
    let profile = ModelProfile::new(SpecificationRevision::V2023_09).with_extensions(exts);

    let mut s = Session::new_for_test(tmp.path().to_path_buf()).with_profile(profile);

    // With REDACTED_ENV_VARS extension, openjd_redacted_env should set env vars.
    let env = Environment {
        name: "env1".into(),
        description: None,
        script: Some(EnvironmentScript {
            let_bindings: None,
            actions: EnvironmentActions {
                on_enter: Some(action(
                    "sh",
                    vec!["-c", "echo 'openjd_redacted_env: SECRET=hunter2'"],
                )),
                on_exit: Some(action("sh", vec!["-c", "echo SECRET=${SECRET:-unset}"])),
            },
            embedded_files: None,
        }),
        variables: None,
        resolved_symtab: None,
    };
    let id = s.enter_environment(&env, None, None, None).await.unwrap();
    let out = s.exit_environment(&id, None, true, None).await.unwrap();
    // SECRET should be set because REDACTED_ENV_VARS extension is enabled
    assert!(
        out.contains("SECRET=********"),
        "SECRET should be redacted in collected stdout, got: {out}"
    );
}

#[tokio::test]
async fn test_redacted_env_does_not_set_var_without_extension() {
    use openjd_model::types::SpecificationRevision;
    use openjd_model::ModelProfile;

    let tmp = TempDir::new().unwrap();
    let profile = ModelProfile::new(SpecificationRevision::V2023_09);

    let mut s = Session::new_for_test(tmp.path().to_path_buf()).with_profile(profile);

    // Without REDACTED_ENV_VARS extension, openjd_redacted_env should NOT set env vars.
    let env = Environment {
        name: "env1".into(),
        description: None,
        script: Some(EnvironmentScript {
            let_bindings: None,
            actions: EnvironmentActions {
                on_enter: Some(action(
                    "sh",
                    vec!["-c", "echo 'openjd_redacted_env: SECRET=hunter2'"],
                )),
                on_exit: Some(action("sh", vec!["-c", "echo SECRET=${SECRET:-unset}"])),
            },
            embedded_files: None,
        }),
        variables: None,
        resolved_symtab: None,
    };
    let id = s.enter_environment(&env, None, None, None).await.unwrap();
    let out = s.exit_environment(&id, None, true, None).await.unwrap();
    assert!(
        out.contains("SECRET=unset"),
        "SECRET should not be set without REDACTED_ENV_VARS extension, got: {out}"
    );
}

#[tokio::test]
async fn test_redactions_disabled_with_no_profile() {
    let tmp = TempDir::new().unwrap();
    // No profile at all (default Session::new)
    let mut s = Session::new_for_test(tmp.path().to_path_buf());

    let env = Environment {
        name: "env1".into(),
        description: None,
        script: Some(EnvironmentScript {
            let_bindings: None,
            actions: EnvironmentActions {
                on_enter: Some(action(
                    "sh",
                    vec!["-c", "echo 'openjd_redacted_env: SECRET=hunter2'"],
                )),
                on_exit: Some(action("sh", vec!["-c", "echo SECRET=${SECRET:-unset}"])),
            },
            embedded_files: None,
        }),
        variables: None,
        resolved_symtab: None,
    };
    let id = s.enter_environment(&env, None, None, None).await.unwrap();
    let out = s.exit_environment(&id, None, true, None).await.unwrap();
    assert!(
        out.contains("SECRET=unset"),
        "SECRET should not be set with no profile, got: {out}"
    );
}

// ══════════════════════════════════════════════════════════════
// cancel_action escalation: soft signal followed by a hard TERMINATE
// after the grace period. Exercised without a real cross-user helper
// by injecting a file as the cancel_writer and inspecting what was
// written over time.
// ══════════════════════════════════════════════════════════════

mod cancel_escalation {
    use super::*;
    use std::fs::OpenOptions;
    use std::io::Read;
    use std::time::Duration;

    fn read_cancel_messages(path: &std::path::Path) -> Vec<serde_json::Value> {
        let mut buf = String::new();
        let mut f = OpenOptions::new().read(true).open(path).unwrap();
        f.read_to_string(&mut buf).unwrap();
        buf.lines()
            .filter_map(|line| serde_json::from_str(line).ok())
            .collect()
    }

    fn session_with_observable_writer(tmp: &TempDir) -> (Session, std::path::PathBuf) {
        let mut s = Session::new_for_test(tmp.path().to_path_buf());
        s.set_state_for_test(SessionState::Running);
        let writer_path = tmp.path().join("cancel_writer.log");
        let writer = OpenOptions::new()
            .create(true)
            .append(true)
            .open(&writer_path)
            .unwrap();
        s.set_cancel_writer_for_test(writer);
        (s, writer_path)
    }

    /// With no time_limit, the default notify period is 5s.
    #[tokio::test(flavor = "multi_thread")]
    async fn default_grace_sends_notify_then_terminate() {
        let tmp = TempDir::new().unwrap();
        let (mut s, path) = session_with_observable_writer(&tmp);

        s.cancel_action(None, false).expect("cancel_action ok");

        std::thread::sleep(Duration::from_millis(200));
        let msgs = read_cancel_messages(&path);
        assert_eq!(
            msgs.len(),
            1,
            "session should send exactly one cancel message"
        );
        assert_eq!(msgs[0]["cancel"].as_str().unwrap(), "NOTIFY_THEN_TERMINATE");
        assert_eq!(msgs[0]["notifyPeriodInSeconds"].as_u64().unwrap(), 5);

        // No escalation thread — wait past the grace to confirm nothing else is written.
        std::thread::sleep(Duration::from_secs(6));
        let late = read_cancel_messages(&path);
        assert_eq!(
            late.len(),
            1,
            "session should not send a second message; escalation is in the helper"
        );
    }

    /// Custom grace (8s) — e.g. set via a job template's cancelation timeout.
    #[tokio::test(flavor = "multi_thread")]
    async fn custom_grace_8s_sends_correct_notify_period() {
        let tmp = TempDir::new().unwrap();
        let (mut s, path) = session_with_observable_writer(&tmp);

        s.cancel_action(Some(Duration::from_secs(8)), false)
            .expect("cancel_action ok");

        std::thread::sleep(Duration::from_millis(200));
        let msgs = read_cancel_messages(&path);
        assert_eq!(msgs.len(), 1);
        assert_eq!(msgs[0]["cancel"].as_str().unwrap(), "NOTIFY_THEN_TERMINATE");
        assert_eq!(msgs[0]["notifyPeriodInSeconds"].as_u64().unwrap(), 8);
    }

    /// A zero-duration time_limit means "kill now" — TERMINATE is sent directly.
    #[tokio::test(flavor = "multi_thread")]
    async fn zero_time_limit_sends_terminate() {
        let tmp = TempDir::new().unwrap();
        let (mut s, path) = session_with_observable_writer(&tmp);

        s.cancel_action(Some(Duration::from_secs(0)), false)
            .expect("cancel_action ok");

        std::thread::sleep(Duration::from_millis(200));
        let msgs = read_cancel_messages(&path);
        assert_eq!(msgs.len(), 1, "should send exactly one message");
        assert_eq!(msgs[0]["cancel"].as_str().unwrap(), "TERMINATE");
        assert!(
            msgs[0].get("notifyPeriodInSeconds").is_none(),
            "TERMINATE should not include notifyPeriodInSeconds"
        );
    }

    /// When a helper auth token is configured, every cancel command written
    /// through the cancel_writer must include it as a `"token"` field. This
    /// is what `set_helper_auth_token_for_test` is for.
    #[tokio::test(flavor = "multi_thread")]
    async fn cancel_includes_auth_token_when_configured() {
        let tmp = TempDir::new().unwrap();
        let (mut s, path) = session_with_observable_writer(&tmp);
        s.set_helper_auth_token_for_test("AbCdEfGhIjKlMnOpQrStUv".into());

        // Soft cancel
        s.cancel_action(None, false).expect("cancel_action ok");
        std::thread::sleep(Duration::from_millis(200));
        let msgs = read_cancel_messages(&path);
        assert_eq!(msgs.len(), 1);
        assert_eq!(
            msgs[0]["token"].as_str().unwrap(),
            "AbCdEfGhIjKlMnOpQrStUv",
            "NOTIFY_THEN_TERMINATE cancel must carry the token",
        );
        assert_eq!(msgs[0]["cancel"].as_str().unwrap(), "NOTIFY_THEN_TERMINATE");
    }

    /// TERMINATE (zero grace) must also carry the token.
    #[tokio::test(flavor = "multi_thread")]
    async fn terminate_cancel_includes_auth_token_when_configured() {
        let tmp = TempDir::new().unwrap();
        let (mut s, path) = session_with_observable_writer(&tmp);
        s.set_helper_auth_token_for_test("AbCdEfGhIjKlMnOpQrStUv".into());

        s.cancel_action(Some(Duration::from_secs(0)), false)
            .expect("cancel_action ok");
        std::thread::sleep(Duration::from_millis(200));
        let msgs = read_cancel_messages(&path);
        assert_eq!(msgs.len(), 1);
        assert_eq!(msgs[0]["token"].as_str().unwrap(), "AbCdEfGhIjKlMnOpQrStUv",);
        assert_eq!(msgs[0]["cancel"].as_str().unwrap(), "TERMINATE");
    }
}

/// Test Option 1: Session-level test for the cancel race condition.
///
/// Simulates the pyo3 binding's cancel path: the parent cancel token is
/// cancelled AND the process is killed externally (via the cancel_writer /
/// helper pipe) simultaneously. This mirrors what happens when the pyo3
/// `cancel_action` `None` branch fires — it cancels the token and writes
/// to the helper, but doesn't call `session.cancel_action()`.
///
/// The process dies from the external kill before the tokio select loop
/// processes the token cancellation. Without the fix, the callback reports
/// `Failed`; with the fix it reports `Canceled`.
#[cfg(unix)]
#[tokio::test]
async fn test_parent_token_cancel_with_external_kill_reports_canceled() {
    use tokio_util::sync::CancellationToken;

    let tmp = TempDir::new().unwrap();
    let parent_token = CancellationToken::new();

    let statuses: Arc<Mutex<Vec<ActionState>>> = Arc::new(Mutex::new(Vec::new()));
    let statuses_clone = statuses.clone();

    let config = SessionConfig {
        session_id: "cancel-race-test".into(),
        job_parameter_values: HashMap::new(),
        path_mapping_rules: None,
        retain_working_dir: false,
        callback: Some(Box::new(move |_sid, status| {
            statuses_clone.lock().unwrap().push(status.state);
        })),
        os_env_vars: None,
        session_root_directory: Some(tmp.path().to_path_buf()),
        user: None,
        profile: None,
        cancel_token: Some(parent_token.clone()),
        debug_collect_stdout: false,
        echo_openjd_directives: true,
        sticky_bit_policy: openjd_sessions::StickyBitPolicy::Disabled,
    };
    let mut s = Session::with_config(config).unwrap();

    // The script writes its PID to a file then sleeps.
    // The spawned task cancels the token and kills the process externally.
    // Pre-cancel the token, then run a task that exits non-zero.
    // The session should report Canceled because the token was cancelled.
    parent_token.cancel();

    let _result = s
        .run_task(&step("sh", vec!["-c", "exit 42"]), None, None, None)
        .await;

    assert_eq!(s.state(), SessionState::ReadyEnding);
    let final_statuses = statuses.lock().unwrap();
    assert!(
        final_statuses.contains(&ActionState::Canceled),
        "Expected Canceled when token is cancelled and process killed externally, got: {:?}",
        *final_statuses
    );
}

/// Verify that the session callback fires with intermediate progress values
/// as `openjd_progress:` messages are printed to stdout, not just on completion.
#[tokio::test]
async fn test_callback_reports_intermediate_progress() {
    let tmp = TempDir::new().unwrap();

    // Collect all (state, progress) pairs from callbacks
    #[allow(clippy::type_complexity)]
    let updates: Arc<Mutex<Vec<(ActionState, Option<f64>)>>> = Arc::new(Mutex::new(Vec::new()));
    let updates_clone = updates.clone();

    let config = SessionConfig {
        session_id: "progress-test".into(),
        job_parameter_values: HashMap::new(),
        path_mapping_rules: None,
        retain_working_dir: false,
        callback: Some(Box::new(move |_sid, status| {
            updates_clone
                .lock()
                .unwrap()
                .push((status.state, status.progress));
        })),
        os_env_vars: None,
        session_root_directory: Some(tmp.path().to_path_buf()),
        user: None,
        profile: None,
        cancel_token: None,
        debug_collect_stdout: false,
        echo_openjd_directives: true,
        sticky_bit_policy: openjd_sessions::StickyBitPolicy::Disabled,
    };
    let mut s = Session::with_config(config).unwrap();

    // Script prints progress 25 and 75, with a status message
    let result = s
        .run_task(
            &step(
                "sh",
                vec![
                    "-c",
                    "echo 'openjd_progress: 25'; echo 'openjd_status: working'; echo 'openjd_progress: 75'; echo 'openjd_status: almost done'",
                ],
            ),
            None,
            None,
            None,
        )
        .await
        .unwrap();

    assert_eq!(result.state, ActionState::Success);

    let all_updates = updates.lock().unwrap();

    // There should be intermediate Running callbacks with progress values
    let running_with_progress: Vec<_> = all_updates
        .iter()
        .filter(|(state, progress)| {
            *state == ActionState::Running && progress.is_some() && *progress != Some(0.0)
        })
        .collect();

    assert!(
        !running_with_progress.is_empty(),
        "Expected intermediate progress callbacks while Running, got: {:?}",
        *all_updates
    );

    // Specifically, we should see progress 25 and 75
    let progress_values: Vec<f64> = all_updates.iter().filter_map(|(_, p)| *p).collect();

    assert!(
        progress_values.contains(&25.0),
        "Expected progress 25.0 in callbacks, got: {:?}",
        progress_values
    );
    assert!(
        progress_values.contains(&75.0),
        "Expected progress 75.0 in callbacks, got: {:?}",
        progress_values
    );
}

// === Tests for SessionConfig::echo_openjd_directives ===
//
// Mirrors the Python reference implementation, where the equivalent
// ActionMonitoringFilter `suppress_filtered` parameter defaults to False
// (i.e. directives are echoed to the log). These tests verify that:
//   * `echo_openjd_directives = true` (the default) lets directive lines
//     reach the session log, and
//   * `echo_openjd_directives = false` filters them out.
// `openjd_redacted_env` follows the same rule, with the secret value
// replaced by `********` before the line reaches the log.

#[cfg(unix)]
fn echo_directives_test_config(
    tmp: &TempDir,
    session_id: &str,
    echo: bool,
) -> openjd_sessions::session::SessionConfig {
    openjd_sessions::session::SessionConfig {
        session_id: session_id.into(),
        job_parameter_values: HashMap::new(),
        path_mapping_rules: None,
        retain_working_dir: false,
        callback: None,
        os_env_vars: None,
        session_root_directory: Some(tmp.path().to_path_buf()),
        user: None,
        profile: None,
        cancel_token: None,
        debug_collect_stdout: true,
        echo_openjd_directives: echo,
        sticky_bit_policy: openjd_sessions::StickyBitPolicy::Disabled,
    }
}

#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_echo_openjd_directives_true_passes_directive_lines_to_log() {
    testing_logger::setup();
    let tmp = TempDir::new().unwrap();
    let mut s = Session::with_config(echo_directives_test_config(&tmp, "echo-on", true)).unwrap();

    // Construct the directive at runtime from environment variables so the
    // literal text `openjd_progress: 42.0` does not appear in the script
    // command (the command itself is logged via `format_command_for_log`,
    // and we want to assert specifically that the *output* line was echoed).
    let script = step(
        "sh",
        vec![
            "-c",
            r#"K=op; J=enjd; printf '%s%s_progress: %s\n' "$K" "$J" 42.0; echo 'echo-on-plain-output'"#,
        ],
    );
    let r = s.run_task(&script, None, None, None).await.unwrap();
    assert_eq!(r.state, ActionState::Success);

    testing_logger::validate(|captured| {
        let directive_logged = captured
            .iter()
            .any(|log| log.body.contains("openjd_progress: 42.0"));
        assert!(
            directive_logged,
            "expected the openjd_progress directive to appear in the log when echo=true"
        );
        let plain_logged = captured
            .iter()
            .any(|log| log.body.contains("echo-on-plain-output"));
        assert!(
            plain_logged,
            "non-directive output must always reach the log"
        );
    });
}

#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_echo_openjd_directives_false_suppresses_directive_lines_from_log() {
    testing_logger::setup();
    let tmp = TempDir::new().unwrap();
    let mut s = Session::with_config(echo_directives_test_config(&tmp, "echo-off", false)).unwrap();

    // See the sister `..._true_..._to_log` test — the literal directive
    // string must not appear in the script command itself, so we synthesize
    // it at runtime. Use a different progress value (43.0) so this test's
    // assertion is robust against testing_logger's process-global state.
    let script = step(
        "sh",
        vec![
            "-c",
            r#"K=op; J=enjd; printf '%s%s_progress: %s\n' "$K" "$J" 43.0; echo 'echo-off-plain-output'"#,
        ],
    );
    let r = s.run_task(&script, None, None, None).await.unwrap();
    assert_eq!(r.state, ActionState::Success);

    testing_logger::validate(|captured| {
        let directive_logged = captured
            .iter()
            .any(|log| log.body.contains("openjd_progress: 43.0"));
        assert!(
            !directive_logged,
            "expected the openjd_progress directive to be suppressed from the log when echo=false"
        );
        let plain_logged = captured
            .iter()
            .any(|log| log.body.contains("echo-off-plain-output"));
        assert!(
            plain_logged,
            "non-directive output must still reach the log even when directives are suppressed"
        );
    });
}

#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_echo_openjd_directives_true_redacts_redacted_env_in_log() {
    use openjd_model::types::{ModelExtension, SpecificationRevision};
    use openjd_model::ModelProfile;

    testing_logger::setup();
    let tmp = TempDir::new().unwrap();
    // REDACTED_ENV_VARS extension must be enabled for redaction semantics to
    // engage; the directive is parsed regardless, but redactions_enabled() drives
    // whether the value is added to the redaction set with full effect.
    let profile = ModelProfile::new(SpecificationRevision::V2023_09)
        .with_extensions([ModelExtension::RedactedEnvVars].into_iter().collect());

    let config = openjd_sessions::session::SessionConfig {
        session_id: "redacted-echo".into(),
        job_parameter_values: HashMap::new(),
        path_mapping_rules: None,
        retain_working_dir: false,
        callback: None,
        os_env_vars: None,
        session_root_directory: Some(tmp.path().to_path_buf()),
        user: None,
        profile: Some(profile),
        cancel_token: None,
        debug_collect_stdout: true,
        echo_openjd_directives: true,
        sticky_bit_policy: openjd_sessions::StickyBitPolicy::Disabled,
    };
    let mut s = Session::with_config(config).unwrap();

    // Synthesize the directive AND the secret value at runtime so neither
    // the literal `openjd_redacted_env:` token nor the secret bytes appear
    // verbatim in the script command (the command is logged via
    // `format_command_for_log`, which would otherwise leak both into the
    // log before the action filter has a chance to redact them).
    let script = step(
        "sh",
        vec![
            "-c",
            r#"K=op; J=enjd; A=tops; B=ecret; C=123; printf '%s%s_redacted_env: TOKEN=%s%s%s\n' "$K" "$J" "$A" "$B" "$C""#,
        ],
    );
    let r = s.run_task(&script, None, None, None).await.unwrap();
    assert_eq!(r.state, ActionState::Success);

    testing_logger::validate(|captured| {
        // The directive line itself must be present (echo=true)…
        let directive_logged = captured
            .iter()
            .any(|log| log.body.contains("openjd_redacted_env: TOKEN="));
        assert!(
            directive_logged,
            "expected the redacted_env directive to appear in the log when echo=true"
        );
        // …but the secret value must NOT appear in any log record.
        let secret_leaked = captured.iter().any(|log| log.body.contains("topsecret123"));
        assert!(
            !secret_leaked,
            "secret value must never reach the log; expected redaction to fixed-length asterisks"
        );
        let redacted_form = captured
            .iter()
            .any(|log| log.body.contains("TOKEN=********"));
        assert!(
            redacted_form,
            "expected the redacted_env line to show NAME=******** in the log"
        );
    });
}