nono-cli 0.47.0

CLI for nono capability-based sandbox
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
//! Execution strategy for sandboxed commands.
//!
//! This module defines how nono executes commands within the sandbox.
//! The strategy determines the process model and what features are available.
//!
//! # Async-Signal-Safety
//!
//! The Supervised strategy uses `fork()` to create a child process. After fork in a
//! multi-threaded program, the child can only safely call async-signal-safe functions
//! until `exec()`. This module carefully prepares all data in the parent (where
//! allocation is safe) and uses only raw libc calls in the child.

mod env_sanitization;
#[cfg(target_os = "linux")]
mod supervisor_linux;

use crate::startup_prompt::{print_terminal_safe_stderr, prompt_startup_termination_for_child};
use crate::{DETACHED_CWD_PROMPT_RESPONSE_ENV, DETACHED_LAUNCH_ENV, DETACHED_SESSION_ID_ENV};
use nix::libc;
use nix::sys::signal::{self, Signal};
use nix::sys::wait::{waitpid, WaitPidFlag, WaitStatus};
use nix::unistd::{fork, ForkResult, Pid};
use nono::supervisor::{ApprovalDecision, AuditEntry, SupervisorMessage, SupervisorResponse};
use nono::{
    ApprovalBackend, CapabilitySet, DenialReason, DenialRecord, DiagnosticFormatter,
    DiagnosticMode, NonoError, Result, Sandbox, SupervisorSocket,
};
use std::collections::HashSet;
use std::ffi::{CString, OsStr};
use std::os::fd::FromRawFd;
use std::os::fd::{AsRawFd, OwnedFd};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::process::CommandExt;
use std::path::{Component, Path, PathBuf};
use std::process::Command;
use std::sync::Mutex;
use std::time::{Duration, Instant};
use tracing::{debug, info, warn};

pub(crate) use env_sanitization::is_dangerous_env_var;
use env_sanitization::should_skip_env_var;
pub(crate) use env_sanitization::validate_allow_vars_pattern;

/// Resolve a program name to its absolute path.
///
/// This should be called BEFORE the sandbox is applied to ensure the program
/// can be found even if its directory is not in the sandbox's allowed paths.
///
/// # Errors
/// Returns an error if the program cannot be found in PATH or as a valid path.
pub fn resolve_program(program: &str) -> Result<PathBuf> {
    which::which(program).map_err(|e| {
        NonoError::CommandExecution(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            format!("{}: {}", program, e),
        ))
    })
}

/// Maximum threads allowed when keyring backend is active.
/// Main thread (1) + up to 3 keyring threads for D-Bus/Security.framework.
const MAX_KEYRING_THREADS: usize = 4;
/// Maximum threads allowed when crypto library thread pool is active.
/// Main thread (1) + tokio proxy workers (2) + aws-lc-rs ECDSA pool (4).
/// When --network-profile is used with trust scanning, both the proxy runtime
/// and crypto verification threads may be active simultaneously.
const MAX_CRYPTO_THREADS: usize = 7;
/// Hard cap on retained denial records to prevent memory exhaustion.
const MAX_DENIAL_RECORDS: usize = 1000;
/// Hard cap on request IDs tracked for replay detection.
const MAX_TRACKED_REQUEST_IDS: usize = 4096;

fn offer_profile_save_for_child(
    pty: Option<&mut crate::pty_proxy::PtyProxy>,
    policy_explanations: &[nono::diagnostic::PolicyExplanation],
    error_observation: &nono::diagnostic::ErrorObservation,
    caps: &CapabilitySet,
    command: &[String],
    compared_profile: Option<&str>,
) -> Result<()> {
    if let Some(proxy) = pty {
        let _released_terminal = proxy.release_terminal_for_prompt();
        return crate::profile_save_runtime::offer_save_run_profile(
            policy_explanations,
            error_observation,
            caps,
            command,
            compared_profile,
        );
    }

    crate::profile_save_runtime::offer_save_run_profile(
        policy_explanations,
        error_observation,
        caps,
        command,
        compared_profile,
    )
}

/// Linux procfs context for resolving child-relative procfs paths in the supervisor.
///
/// `/proc/self/...` must refer to the sandboxed child process, not the unsandboxed
/// supervisor. For seccomp interceptions we may also know the calling TID, which
/// lets us resolve `/proc/thread-self/...` accurately.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct ProcfsAccessContext {
    process_pid: u32,
    thread_pid: Option<u32>,
}

impl ProcfsAccessContext {
    fn new(process_pid: u32, thread_pid: Option<u32>) -> Self {
        Self {
            process_pid,
            thread_pid,
        }
    }
}

/// Threading context for fork safety validation.
///
/// After loading secrets from the system keystore, the keyring crate may leave
/// background threads running (for D-Bus/Security.framework communication).
/// Similarly, cryptographic verification (aws-lc-rs ECDSA) spawns idle thread
/// pool workers. These threads are benign for our fork+exec pattern because:
/// - They don't hold locks that the main thread or child process needs
/// - The child immediately calls exec(), clearing all thread state
/// - The parent's threads continue independently
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ThreadingContext {
    /// Enforce single-threaded execution (default).
    /// Fork will fail if thread count > 1.
    #[default]
    Strict,

    /// Allow elevated thread count for known-safe keyring backends.
    /// Fork proceeds if thread count <= MAX_KEYRING_THREADS.
    /// Keyring threads are idle XPC dispatch workers (macOS) or D-Bus workers
    /// (Linux) after the synchronous keyring call completes — parked, not
    /// holding allocator locks. Safe for Supervised mode's post-fork
    /// Sandbox::apply() allocation.
    KeyringExpected,

    /// Allow elevated thread count for crypto library thread pools.
    /// Spawned by trust scan's ECDSA verification (aws-lc-rs) and keystore
    /// public key lookup. These are idle pool workers parked on condvars,
    /// NOT holding allocator locks — safe for supervised mode's post-fork
    /// Sandbox::apply() allocation.
    CryptoExpected,
}

/// Execution strategy for running sandboxed commands.
///
/// Each strategy provides different trade-offs between security,
/// functionality, and complexity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ExecStrategy {
    /// Direct exec: apply sandbox, then exec into command.
    /// nono ceases to exist after exec.
    ///
    /// - Minimal attack surface (no persistent parent)
    /// - No diagnostic footer on error
    /// - No rollback support
    /// - Used by `nono wrap` for scripts and embedding
    Direct,

    /// Supervised mode: fork first, sandbox only child.
    /// Parent is unsandboxed.
    ///
    /// - Larger attack surface (requires hardening)
    /// - Diagnostic footer on non-zero exit
    /// - Undo support (parent can write snapshots)
    /// - IPC for capability expansion
    /// - Default for `nono shell`
    /// - Used by `nono run` when a parent process is required
    #[default]
    Supervised,
}

/// Configuration for command execution.
pub struct ExecConfig<'a> {
    /// The command to execute (program + args).
    pub command: &'a [String],
    /// Pre-resolved absolute path to the program.
    /// This is resolved BEFORE the sandbox is applied to ensure the program
    /// can be found even if its directory is not in the sandbox's allowed paths.
    pub resolved_program: &'a std::path::Path,
    /// Capabilities for the sandbox.
    pub caps: &'a CapabilitySet,
    /// Environment variables to set.
    pub env_vars: Vec<(&'a str, &'a str)>,
    /// Path to the capability state file.
    pub cap_file: &'a std::path::Path,
    /// Directory the child process should start in.
    pub current_dir: &'a std::path::Path,
    /// Whether to suppress diagnostic output.
    pub no_diagnostics: bool,
    /// Threading context for fork safety validation.
    pub threading: ThreadingContext,
    /// Paths that are write-protected (signed instruction files).
    pub protected_paths: &'a [std::path::PathBuf],
    /// Base profile name to derive a saved user patch from after run-time denials.
    pub profile_save_base: Option<&'a str>,
    /// Optional startup timeout for known interactive CLIs that were launched
    /// without their recommended built-in profile.
    pub startup_timeout: Option<StartupTimeoutConfig<'a>>,
    /// Whether runtime capability elevation is enabled.
    /// When true, the child installs seccomp-notify and the parent can grant
    /// capabilities at runtime. On macOS this is currently unused.
    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
    pub capability_elevation: bool,
    /// Whether the seccomp proxy-only network fallback is needed.
    /// Set by the parent before fork when Landlock ABI lacks AccessNet
    /// and ProxyOnly network mode is requested. Both child and parent
    /// use this flag to coordinate: child installs the proxy filter and
    /// sends the notify fd; parent expects to receive it.
    #[cfg(target_os = "linux")]
    pub seccomp_proxy_fallback: bool,
    /// Allow-list of environment variable names. When set, only variables
    /// matching an exact name or prefix pattern (e.g. `"AWS_*"`) are
    /// passed to the child. Nono-injected credentials always bypass this.
    pub allowed_env_vars: Option<Vec<String>>,
}

#[derive(Clone, Copy)]
pub struct StartupTimeoutConfig<'a> {
    pub timeout: Duration,
    pub program: &'a str,
    pub profile: &'a str,
}

/// Configuration for supervisor IPC in supervised execution mode.
///
/// When provided to [`execute_supervised()`], the supervisor creates a Unix
/// socket pair before fork, passes the child end to the child process via
/// the `NONO_SUPERVISOR_FD` environment variable, and runs an IPC event loop
/// in the parent that handles capability expansion requests from the
/// sandboxed child.
pub struct SupervisorConfig<'a> {
    /// Protected nono state roots that must never be granted dynamically.
    pub protected_roots: &'a [std::path::PathBuf],
    /// Backend for approval decisions (terminal prompt, webhook, policy engine)
    pub approval_backend: &'a dyn ApprovalBackend,
    /// Session identifier used for audit correlation.
    pub session_id: &'a str,
    /// Whether the launching terminal should be attached immediately.
    pub attach_initial_client: bool,
    /// Configured in-band PTY detach sequence.
    pub detach_sequence: Option<&'a [u8]>,
    /// Allowed URL origins for supervisor-delegated browser opens (from profile).
    /// Empty means no URLs are allowed.
    pub open_url_origins: &'a [String],
    /// Whether to allow http://localhost and http://127.0.0.1 URLs.
    pub open_url_allow_localhost: bool,
    /// Optional append-only audit recorder for supervisor events.
    pub audit_recorder: Option<&'a Mutex<crate::audit_integrity::AuditRecorder>>,
    /// Whether direct LaunchServices opening is enabled for this session.
    #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
    pub allow_launch_services_active: bool,
    /// Proxy port allowed for seccomp proxy-only fallback (0 = not active).
    #[cfg(target_os = "linux")]
    pub proxy_port: u16,
    /// Bind ports allowed for seccomp proxy-only fallback.
    #[cfg(target_os = "linux")]
    pub proxy_bind_ports: Vec<u16>,
}

#[cfg(target_os = "macos")]
fn should_install_macos_open_shim(supervisor: Option<&SupervisorConfig<'_>>) -> bool {
    supervisor.is_some_and(|cfg| !cfg.allow_launch_services_active)
}

#[cfg(target_os = "linux")]
const fn linux_child_requires_dumpable(
    capability_elevation: bool,
    seccomp_proxy_fallback: bool,
) -> bool {
    capability_elevation || seccomp_proxy_fallback
}

/// Execute a command using the Direct strategy (exec, nono disappears).
///
/// This is the original behavior: apply sandbox, then exec into the command.
/// nono ceases to exist after exec() succeeds.
pub fn execute_direct(config: &ExecConfig<'_>) -> Result<()> {
    let cmd_args = &config.command[1..];

    info!(
        "Executing (direct): {} {:?}",
        config.resolved_program.display(),
        cmd_args
    );

    let mut cmd = Command::new(config.resolved_program);
    cmd.env_clear();
    cmd.current_dir(config.current_dir);

    for (key, value) in std::env::vars() {
        if should_skip_env_var(
            &key,
            &config.env_vars,
            &[
                "NONO_CAP_FILE",
                DETACHED_LAUNCH_ENV,
                DETACHED_SESSION_ID_ENV,
                DETACHED_CWD_PROMPT_RESPONSE_ENV,
            ],
        ) {
            continue;
        }
        if let Some(ref allowed) = config.allowed_env_vars {
            if !env_sanitization::is_env_var_allowed(&key, allowed) {
                continue;
            }
        }
        cmd.env(&key, &value);
    }

    cmd.args(cmd_args).env("NONO_CAP_FILE", config.cap_file);

    for (key, value) in &config.env_vars {
        cmd.env(key, value);
    }

    let err = cmd.exec();

    // exec() only returns if there's an error
    Err(NonoError::CommandExecution(err))
}

/// Execute a command using the Supervised strategy (fork first, sandbox only child).
///
/// Forks first and applies the sandbox only in the child. The parent remains
/// unsandboxed, enabling rollback snapshots and IPC capability expansion.
///
/// # Security Properties
///
/// - Child is sandboxed with full restrictions
/// - Parent is NOT sandboxed - requires additional hardening:
///   - Linux: parent is made non-dumpable immediately after fork. The child is
///     made non-dumpable unless seccomp-driven runtime inspection needs
///     `/proc/PID/mem` access. Failure is fatal.
///   - macOS: PT_DENY_ATTACH applied in parent immediately after fork (not inherited
///     across fork on macOS). Failure is fatal - child is killed and error returned.
///
/// # Sandbox Application in Child
///
/// The child calls `Sandbox::apply()` after fork, which allocates memory (generating
/// Seatbelt profile strings on macOS, opening Landlock PathFds on Linux). This is safe
/// because we validate threading context before fork — known-safe thread contexts
/// (keyring workers, crypto pool) are idle and not holding allocator locks.
///
/// # Process Flow
///
/// 1. Prepare all data for exec in parent (CString conversion)
/// 2. Verify threading context allows fork
/// 3. Fork into parent and child
/// 4. Child: apply Landlock, install seccomp-notify, close inherited FDs, exec
/// 5. Parent: apply PR_SET_DUMPABLE(0) + PT_DENY_ATTACH, receive seccomp fd, run supervisor loop
///
/// Does NOT pipe stdout/stderr. The child inherits the parent's terminal directly,
/// preserving TTY semantics for interactive programs (e.g., Claude Code, vim).
/// The parent prints diagnostics and rollback UI after the child exits.
pub fn execute_supervised(
    config: &ExecConfig<'_>,
    supervisor: Option<&SupervisorConfig<'_>>,
    trust_interceptor: Option<crate::trust_intercept::TrustInterceptor>,
    on_fork: Option<&mut dyn FnMut(u32)>,
    pty_pair: Option<crate::pty_proxy::PtyPair>,
    pty_session_id: Option<&str>,
) -> Result<i32> {
    let program = &config.command[0];
    let cmd_args = &config.command[1..];

    info!("Executing (supervised): {} {:?}", program, cmd_args);

    // Use pre-resolved program path (resolved before fork)
    let program_path = config.resolved_program;

    // Convert program path to CString for execve
    let program_c = CString::new(program_path.to_string_lossy().as_bytes())
        .map_err(|_| NonoError::SandboxInit("Program path contains null byte".to_string()))?;
    let current_dir_c = CString::new(config.current_dir.as_os_str().as_bytes())
        .map_err(|_| NonoError::SandboxInit("Working directory contains null byte".to_string()))?;

    // Build argv: [program, args..., NULL]
    let mut argv_c: Vec<CString> = Vec::with_capacity(1 + cmd_args.len());
    argv_c.push(program_c.clone());
    for arg in cmd_args {
        argv_c.push(CString::new(arg.as_bytes()).map_err(|_| {
            NonoError::SandboxInit(format!("Argument contains null byte: {}", arg))
        })?);
    }

    // Create supervisor socket pair only when the exec'd child actually needs
    // to talk back to the unsandboxed parent. The supervised parent/session
    // model still works without this socket: attach/detach uses the PTY proxy
    // and diagnostics come from the parent wait path. On Linux, avoiding a raw
    // inherited supervisor socket for the common "plain supervised run" path
    // improves compatibility with CLIs that abort on unexpected inherited fds.
    #[cfg(target_os = "linux")]
    let needs_child_ipc = supervisor.is_some()
        && (config.capability_elevation
            || config.seccomp_proxy_fallback
            || trust_interceptor.is_some());

    #[cfg(not(target_os = "linux"))]
    let needs_child_ipc = supervisor.is_some();

    let socket_pair = if needs_child_ipc {
        Some(SupervisorSocket::pair()?)
    } else {
        None
    };
    let child_sock_fd: Option<i32> = socket_pair.as_ref().map(|(_, c)| c.as_raw_fd());

    // Build environment: inherit current env + add our vars
    let mut env_c: Vec<CString> = Vec::new();

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    let mut browser_shim: Option<BrowserShim> = None;

    // Copy current environment, filtering dangerous and overridden vars
    for (key, value) in std::env::vars_os() {
        if let (Some(k), Some(v)) = (key.to_str(), value.to_str()) {
            if should_skip_env_var(
                k,
                &config.env_vars,
                &[
                    "NONO_CAP_FILE",
                    "NONO_SUPERVISOR_FD",
                    DETACHED_LAUNCH_ENV,
                    DETACHED_SESSION_ID_ENV,
                    DETACHED_CWD_PROMPT_RESPONSE_ENV,
                ],
            ) {
                continue;
            }
            if let Some(ref allowed) = config.allowed_env_vars {
                if !env_sanitization::is_env_var_allowed(k, allowed) {
                    continue;
                }
            }
            if let Ok(cstr) = CString::new(format!("{}={}", k, v)) {
                env_c.push(cstr);
            }
        }
    }

    // Add NONO_CAP_FILE
    if let Some(cap_file_str) = config.cap_file.to_str() {
        if let Ok(cstr) = CString::new(format!("NONO_CAP_FILE={}", cap_file_str)) {
            env_c.push(cstr);
        }
    }

    // Add user-specified environment variables (secrets, etc.)
    for (key, value) in &config.env_vars {
        let mut kv = Vec::with_capacity(key.len() + 1 + value.len() + 1);
        kv.extend_from_slice(key.as_bytes());
        kv.push(b'=');
        kv.extend_from_slice(value.as_bytes());
        if let Ok(cstr) = CString::new(kv) {
            env_c.push(cstr);
        }
    }

    // Delegate URL opens to the unsandboxed supervisor.
    //
    // On Linux, child processes inherit Landlock restrictions so the browser
    // can't access its own config directories. xdg-open and the Node.js `open`
    // package respect the BROWSER env var, so we set it to our helper.
    //
    // On macOS, the Node.js `open` package ignores BROWSER and always spawns
    // `/usr/bin/open`. Seatbelt blocks that from launching URLs. Instead, we
    // create a shim script named `open` in a temp directory and prepend it to
    // PATH so the npm `open` package hits our shim first.
    if supervisor.is_some() {
        if let Ok(nono_exe) = std::env::current_exe() {
            #[cfg(target_os = "linux")]
            {
                if let Some(fd) = child_sock_fd {
                    if let Some(shim) = create_linux_browser_shim(&nono_exe, fd) {
                        let browser_cmd = format!("BROWSER={}", shim.launcher.display());
                        if let Ok(cstr) = CString::new(browser_cmd) {
                            env_c.push(cstr);
                        }
                        browser_shim = Some(shim);
                    }
                }
            }

            #[cfg(target_os = "macos")]
            {
                if should_install_macos_open_shim(supervisor) {
                    // Create a shim `open` script that delegates to nono open-url-helper.
                    // The npm `open` package spawns `open <url>` on macOS; by placing our
                    // shim earlier in PATH, we intercept the call.
                    if let Some(fd) = child_sock_fd {
                        if let Some(shim) = create_open_shim(&nono_exe, fd) {
                            // Prepend shim dir to PATH and also set BROWSER for any tool
                            // that does respect it.
                            let current_path = std::env::var("PATH").unwrap_or_default();
                            let new_path =
                                format!("PATH={}:{current_path}", shim.dir.path().display());
                            if let Ok(cstr) = CString::new(new_path) {
                                // Remove existing PATH from env_c, then add our modified one
                                env_c.retain(|c| !c.as_bytes().starts_with(b"PATH="));
                                env_c.push(cstr);
                            }
                            let browser_cmd = format!("BROWSER={}", shim.launcher.display());
                            if let Ok(cstr) = CString::new(browser_cmd) {
                                env_c.push(cstr);
                            }
                            browser_shim = Some(shim);
                        }
                    }
                }
            }
        }
    }

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    let _keep_browser_shim_alive = browser_shim;

    // Create null-terminated pointer arrays for execve
    let argv_ptrs: Vec<*const libc::c_char> = argv_c
        .iter()
        .map(|s| s.as_ptr())
        .chain(std::iter::once(std::ptr::null()))
        .collect();

    let envp_ptrs: Vec<*const libc::c_char> = env_c
        .iter()
        .map(|s| s.as_ptr())
        .chain(std::iter::once(std::ptr::null()))
        .collect();

    // Validate threading before fork.
    // Supervised mode applies sandbox in child (allocates), so threads holding
    // allocator locks would cause deadlock. Both KeyringExpected and CryptoExpected
    // threads are safe: keyring threads are idle XPC dispatch workers (macOS) or
    // D-Bus workers (Linux) parked after the synchronous call completes; crypto
    // threads are idle aws-lc-rs pool workers parked on condvars. Neither holds
    // allocator locks.
    let thread_count = get_thread_count()?;
    match (config.threading, thread_count) {
        (_, 1) => {}
        (ThreadingContext::KeyringExpected, n) if n <= MAX_KEYRING_THREADS => {
            debug!(
                "Supervised fork with {} threads (keyring workers, idle after sync call)",
                n
            );
        }
        (ThreadingContext::CryptoExpected, n) if n <= MAX_CRYPTO_THREADS => {
            debug!(
                "Supervised fork with {} threads (crypto pool workers, idle on condvar)",
                n
            );
        }
        (ThreadingContext::Strict, n) => {
            return Err(NonoError::SandboxInit(format!(
                "Cannot fork in supervised mode: process has {} threads (expected 1). \
                 This is a bug - fork() requires single-threaded execution.",
                n
            )));
        }
        (ThreadingContext::KeyringExpected, n) => {
            return Err(NonoError::SandboxInit(format!(
                "Cannot fork: process has {} threads (max {} with keyring). \
                 Unexpected threading detected.",
                n, MAX_KEYRING_THREADS
            )));
        }
        (ThreadingContext::CryptoExpected, n) => {
            return Err(NonoError::SandboxInit(format!(
                "Cannot fork: process has {} threads (max {} with crypto pool). \
                 Unexpected threading detected.",
                n, MAX_CRYPTO_THREADS
            )));
        }
    }

    // NOTE: We do not set PR_SET_DUMPABLE(0) before fork because the parent may
    // need to inspect the child's memory for seccomp-notify requests. Instead,
    // the parent hardens itself immediately after fork and the child hardens
    // itself after sandbox/filter setup whenever procfs inspection is not
    // required.

    // PTY pair is prepared by the caller so sessions can be detached and
    // reattached independently of capability elevation.
    let pty_slave_fd = pty_pair.as_ref().map(|p| p.slave.as_raw_fd());

    // Compute child's FD keep list: PTY slave (if elevation) + supervisor socket fd
    let mut child_keep_fds: Vec<i32> = Vec::new();
    if let Some(fd) = pty_slave_fd {
        child_keep_fds.push(fd);
    }
    if let Some(fd) = child_sock_fd {
        child_keep_fds.push(fd);
    }

    // Compute max FD in parent (get_max_fd may allocate on Linux)
    let max_fd = get_max_fd();

    // Clear any stale forwarding target before forking.
    clear_signal_forwarding_target();

    // SAFETY: fork() is safe here because we validated threading context.
    // Child will call Sandbox::apply() which allocates, but this is safe
    // because the child is single-threaded (validated above).
    let fork_result = unsafe { fork() };

    match fork_result {
        Ok(ForkResult::Child) => {
            #[cfg(target_os = "linux")]
            let mut child_caps = config.caps.clone();
            #[cfg(target_os = "linux")]
            child_caps.remap_procfs_self_references(std::process::id(), None);
            #[cfg(target_os = "linux")]
            child_caps.widen_procfs_self_to_proc();
            #[cfg(target_os = "linux")]
            let effective_caps: &CapabilitySet = &child_caps;

            #[cfg(target_os = "macos")]
            let mut child_caps = config.caps.clone();
            #[cfg(target_os = "macos")]
            if supervisor.is_some() {
                child_caps.set_seatbelt_debug_deny(true);
            }
            #[cfg(target_os = "macos")]
            let effective_caps: &CapabilitySet = &child_caps;

            #[cfg(all(not(target_os = "linux"), not(target_os = "macos")))]
            let effective_caps: &CapabilitySet = config.caps;

            // CHILD: Set up PTY, apply sandbox, then exec.
            //
            // The child applies the sandbox itself before exec.
            // Sandbox::apply() allocates (Seatbelt profile generation, Landlock
            // PathFd opens) but this is safe because we validated single-threaded
            // execution before fork, giving us a clean heap.

            // The supervisor socket must survive exec into the sandboxed command,
            // and later into any helper (`open-url-helper`) that needs to speak
            // IPC back to the unsandboxed parent. `UnixStream::pair()` creates
            // fds with close-on-exec set, so clear it on the child end here.
            if let Some(fd) = child_sock_fd {
                if let Err(e) = clear_close_on_exec(fd) {
                    let detail = format!(
                        "nono: failed to clear close-on-exec on supervisor socket: {}\n",
                        e
                    );
                    let msg = detail.as_bytes();
                    unsafe {
                        libc::write(
                            libc::STDERR_FILENO,
                            msg.as_ptr().cast::<libc::c_void>(),
                            msg.len(),
                        );
                        libc::_exit(126);
                    }
                }
            }

            // Set up PTY slave as the child's controlling terminal (elevation only).
            // This gives the child its own terminal so TUI apps can freely
            // change terminal modes without affecting the supervisor.
            // SAFETY: We are in the child after fork, slave_fd is valid.
            if let Some(slave_fd) = pty_slave_fd {
                unsafe { crate::pty_proxy::setup_child_pty(slave_fd) };
            }

            // Apply Landlock FIRST. Landlock's restrict_self() opens path fds
            // for rule creation, so it must run before seccomp-notify is installed.
            // (seccomp-notify traps ALL openat/openat2 syscalls, which would
            // intercept Landlock's own path opens and deadlock.)
            #[cfg(target_os = "linux")]
            {
                match Sandbox::apply(effective_caps) {
                    Ok(_fallback) => {}
                    Err(e) => {
                        let detail =
                            format!("nono: failed to apply sandbox in supervised child: {}\n", e);
                        let msg = detail.as_bytes();
                        unsafe {
                            libc::write(
                                libc::STDERR_FILENO,
                                msg.as_ptr().cast::<libc::c_void>(),
                                msg.len(),
                            );
                            libc::_exit(126);
                        }
                    }
                }
            }

            #[cfg(not(target_os = "linux"))]
            {
                if let Err(e) = Sandbox::apply(effective_caps) {
                    let detail =
                        format!("nono: failed to apply sandbox in supervised child: {}\n", e);
                    let msg = detail.as_bytes();
                    unsafe {
                        libc::write(
                            libc::STDERR_FILENO,
                            msg.as_ptr().cast::<libc::c_void>(),
                            msg.len(),
                        );
                        libc::_exit(126);
                    }
                }
            }

            // On Linux with capability elevation: install seccomp-notify filter
            // AFTER Landlock. The kernel evaluates seccomp before LSM hooks
            // regardless of installation order, so the security properties are
            // identical. All openat/openat2 from exec'd child are routed to
            // the supervisor, which can inject fds for approved paths.
            // Without elevation, seccomp is not installed — the child runs
            // with static Landlock capabilities only.
            //
            // On WSL2, seccomp user notification returns EBUSY because WSL2's
            // init already claims the notify listener. The main.rs guards should
            // have disabled these flags, but we check again as defense in depth.
            #[cfg(target_os = "linux")]
            {
                if config.capability_elevation && nono::sandbox::is_wsl2() {
                    let msg = b"nono: WSL2 detected, skipping seccomp-notify (capability elevation unavailable)\n";
                    unsafe {
                        libc::write(
                            libc::STDERR_FILENO,
                            msg.as_ptr().cast::<libc::c_void>(),
                            msg.len(),
                        );
                    }
                } else if config.capability_elevation {
                    if let Some(fd) = child_sock_fd {
                        match nono::sandbox::install_seccomp_notify() {
                            Ok(notify_fd) => {
                                if let Err(e) = nono::supervisor::socket::send_fd_via_socket(
                                    fd,
                                    notify_fd.as_raw_fd(),
                                ) {
                                    let detail = format!(
                                        "nono: failed to send seccomp notify fd to supervisor: {}\n",
                                        e
                                    );
                                    let msg = detail.as_bytes();
                                    unsafe {
                                        libc::write(
                                            libc::STDERR_FILENO,
                                            msg.as_ptr().cast::<libc::c_void>(),
                                            msg.len(),
                                        );
                                        libc::_exit(126);
                                    }
                                }
                            }
                            Err(e) => {
                                // seccomp not available -- proceed without transparent expansion
                                let detail = format!(
                                    "nono: seccomp-notify not available, expansion disabled: {}\n",
                                    e
                                );
                                let msg = detail.as_bytes();
                                unsafe {
                                    libc::write(
                                        libc::STDERR_FILENO,
                                        msg.as_ptr().cast::<libc::c_void>(),
                                        msg.len(),
                                    );
                                }
                            }
                        }
                    }
                }

                // If the parent determined that seccomp proxy fallback is needed
                // (Landlock ABI lacks AccessNet + ProxyOnly mode), install the
                // proxy filter and send its notify fd to the parent.
                // On WSL2 this flag should already be false (guarded in main.rs),
                // but check again to avoid EBUSY / _exit(126).
                if config.seccomp_proxy_fallback && nono::sandbox::is_wsl2() {
                    let msg = b"nono: WSL2 detected, skipping seccomp proxy filter (proxy network filtering unavailable)\n";
                    unsafe {
                        libc::write(
                            libc::STDERR_FILENO,
                            msg.as_ptr().cast::<libc::c_void>(),
                            msg.len(),
                        );
                    }
                } else if config.seccomp_proxy_fallback {
                    let has_bind = match effective_caps.network_mode() {
                        nono::NetworkMode::ProxyOnly { bind_ports, .. } => !bind_ports.is_empty(),
                        _ => false,
                    };
                    if let Some(fd) = child_sock_fd {
                        match nono::sandbox::install_seccomp_proxy_filter(has_bind) {
                            Ok(proxy_notify_fd) => {
                                if let Err(e) = nono::supervisor::socket::send_fd_via_socket(
                                    fd,
                                    proxy_notify_fd.as_raw_fd(),
                                ) {
                                    let detail = format!(
                                        "nono: failed to send proxy seccomp notify fd: {}\n",
                                        e
                                    );
                                    let msg = detail.as_bytes();
                                    unsafe {
                                        libc::write(
                                            libc::STDERR_FILENO,
                                            msg.as_ptr().cast::<libc::c_void>(),
                                            msg.len(),
                                        );
                                        libc::_exit(126);
                                    }
                                }
                            }
                            Err(e) => {
                                let detail =
                                    format!("nono: seccomp proxy filter not available: {}\n", e);
                                let msg = detail.as_bytes();
                                unsafe {
                                    libc::write(
                                        libc::STDERR_FILENO,
                                        msg.as_ptr().cast::<libc::c_void>(),
                                        msg.len(),
                                    );
                                    libc::_exit(126);
                                }
                            }
                        }
                    }
                }

                if !linux_child_requires_dumpable(
                    config.capability_elevation,
                    config.seccomp_proxy_fallback,
                ) {
                    use nix::sys::prctl;

                    if let Err(e) = prctl::set_dumpable(false) {
                        let detail = format!(
                            "nono: failed to set PR_SET_DUMPABLE(0) in supervised child: {}\n",
                            e
                        );
                        let msg = detail.as_bytes();
                        unsafe {
                            libc::write(
                                libc::STDERR_FILENO,
                                msg.as_ptr().cast::<libc::c_void>(),
                                msg.len(),
                            );
                            libc::_exit(126);
                        }
                    }
                }
            }

            #[cfg(target_os = "macos")]
            {
                const PT_DENY_ATTACH: libc::c_int = 31;
                unsafe {
                    libc::ptrace(PT_DENY_ATTACH, 0, std::ptr::null_mut::<libc::c_char>(), 0);
                }
            }

            // Close inherited FDs (but keep stdin/stdout/stderr and supervisor socket)
            close_inherited_fds(max_fd, &child_keep_fds);

            // SAFETY: `current_dir_c` was prepared before fork and remains valid
            // for the lifetime of the child. `chdir` is async-signal-safe.
            let chdir_result = unsafe { libc::chdir(current_dir_c.as_ptr()) };
            if chdir_result != 0 {
                const MSG: &[u8] = b"nono: failed to enter child working directory\n";
                // SAFETY: `write` and `_exit` are async-signal-safe and we're in
                // the post-fork child path where higher-level Rust APIs are unsafe.
                unsafe {
                    libc::write(
                        libc::STDERR_FILENO,
                        MSG.as_ptr().cast::<libc::c_void>(),
                        MSG.len(),
                    );
                    libc::_exit(126);
                }
            }

            // Execute using pre-prepared CStrings (no allocation)
            unsafe {
                libc::execve(program_c.as_ptr(), argv_ptrs.as_ptr(), envp_ptrs.as_ptr());
            }

            // execve only returns on error - exit without cleanup
            unsafe { libc::_exit(127) }
        }
        Ok(ForkResult::Parent { child }) => {
            if let Some(callback) = on_fork {
                callback(child.as_raw() as u32);
            }

            let mut pty_proxy = if let Some(pty) = pty_pair {
                drop(pty.slave);
                let session_id = pty_session_id
                    .or_else(|| supervisor.map(|s| s.session_id))
                    .unwrap_or("unknown");
                let attach_initial_client =
                    supervisor.map(|s| s.attach_initial_client).unwrap_or(true);
                let detach_sequence = supervisor.and_then(|s| s.detach_sequence);
                match crate::pty_proxy::PtyProxy::new(
                    pty.master,
                    session_id,
                    attach_initial_client,
                    detach_sequence,
                ) {
                    Ok(proxy) => Some(proxy),
                    Err(e) => {
                        let _ = signal::kill(child, Signal::SIGKILL);
                        let _ = waitpid(child, None);
                        return Err(NonoError::SandboxInit(format!(
                            "Failed to create PTY proxy: {}",
                            e
                        )));
                    }
                }
            } else {
                None
            };

            // Destructure socket pair: close child's end, keep supervisor's end
            let supervisor_sock = if let Some((sup, child_end)) = socket_pair {
                drop(child_end);
                Some(sup)
            } else {
                None
            };

            // PARENT: Apply ptrace hardening immediately. This is CRITICAL
            // because the parent is unsandboxed in Supervised mode.
            // Failure to harden is fatal - we kill the child and abort.

            // On Linux, set PR_SET_DUMPABLE(0) on the parent to prevent
            // ptrace attachment. The child stays dumpable only when
            // seccomp-driven procfs inspection is active.
            #[cfg(target_os = "linux")]
            {
                use nix::sys::prctl;
                if let Err(e) = prctl::set_dumpable(false) {
                    let _ = signal::kill(child, Signal::SIGKILL);
                    let _ = waitpid(child, None);
                    return Err(NonoError::SandboxInit(format!(
                        "Failed to verify PR_SET_DUMPABLE(0) on supervised parent: {}. \
                         Aborting: unsandboxed parent must not be ptrace-attachable.",
                        e
                    )));
                }
            }

            #[cfg(target_os = "macos")]
            {
                const PT_DENY_ATTACH: libc::c_int = 31;
                let result = unsafe {
                    libc::ptrace(PT_DENY_ATTACH, 0, std::ptr::null_mut::<libc::c_char>(), 0)
                };
                if result != 0 {
                    let err = std::io::Error::last_os_error();
                    let _ = signal::kill(child, Signal::SIGKILL);
                    let _ = waitpid(child, None);
                    return Err(NonoError::SandboxInit(format!(
                        "Failed to set PT_DENY_ATTACH on supervised parent: {} (errno: {}). \
                         Aborting: unsandboxed parent must not be debugger-attachable.",
                        result, err
                    )));
                }
            }

            // On Linux with capability elevation: receive the seccomp notify fd
            // from the child. The child installed a seccomp-notify filter and
            // sent the fd via SCM_RIGHTS on the supervisor socket.
            // Only attempt recv when elevation is active (child sends the fd).
            #[cfg(target_os = "linux")]
            let seccomp_notify_fd: Option<OwnedFd> = if config.capability_elevation {
                if let Some(ref sup_sock) = supervisor_sock {
                    match sup_sock.recv_fd() {
                        Ok(fd) => {
                            debug!("Received seccomp notify fd from child");
                            Some(fd)
                        }
                        Err(e) => {
                            warn!("Failed to receive seccomp notify fd: {}", e);
                            None
                        }
                    }
                } else {
                    None
                }
            } else {
                None
            };

            // On Linux: if the parent determined seccomp proxy fallback is needed,
            // receive the proxy notify fd from the child. Only attempt recv when
            // we know the child will send it (both sides use the same flag).
            #[cfg(target_os = "linux")]
            let proxy_notify_fd: Option<OwnedFd> = if config.seccomp_proxy_fallback {
                if let Some(ref sup_sock) = supervisor_sock {
                    match sup_sock.recv_fd() {
                        Ok(fd) => {
                            debug!("Received proxy seccomp notify fd from child");
                            Some(fd)
                        }
                        Err(e) => {
                            warn!("Failed to receive proxy seccomp notify fd: {}", e);
                            None
                        }
                    }
                } else {
                    None
                }
            } else {
                None
            };

            // Set up signal forwarding.
            setup_signal_forwarding(child, pty_proxy.as_ref().map(|p| p.poll_fds().0));
            let _signal_forwarding_guard = SignalForwardingGuard;

            // NOTE: peer_pid() is NOT called here. For socketpair() created
            // before fork, LOCAL_PEERPID/SO_PEERCRED return the parent's own PID
            // (credentials are captured at creation time, not updated after fork).
            // Socketpairs are inherently secure: anonymous (no filesystem path),
            // only our forked child has the other end. peer_pid() is useful for
            // named sockets (bind/connect), not socketpair+fork.

            #[cfg(target_os = "macos")]
            let sandbox_log_collector = if supervisor.is_some() {
                let command_name = config
                    .command
                    .first()
                    .and_then(|c| std::path::Path::new(c).file_name())
                    .and_then(|n| n.to_str())
                    .map(str::to_string);
                crate::sandbox_log::SandboxLogCollector::start(child.as_raw(), command_name)
            } else {
                None
            };

            // Build initial-set path lookup for seccomp fast-path (Linux)
            // Stores (resolved_path, is_file) to distinguish file vs directory semantics:
            // - File capabilities: exact match only (no subpath access)
            // - Directory capabilities: subpath access allowed via starts_with
            #[cfg(target_os = "linux")]
            let initial_caps: Vec<supervisor_linux::InitialCapability> = {
                let mut supervisor_caps = config.caps.clone();
                supervisor_caps.remap_procfs_self_references(child.as_raw() as u32, None);
                supervisor_caps
                    .fs_capabilities()
                    .iter()
                    .map(|cap| supervisor_linux::InitialCapability {
                        path: cap.resolved.clone(),
                        access: cap.access,
                        is_file: cap.is_file,
                    })
                    .collect()
            };

            let (status, denials) =
                if let (Some(sup_cfg), Some(mut sup_sock)) = (supervisor, supervisor_sock) {
                    #[cfg(target_os = "linux")]
                    {
                        run_supervisor_loop(
                            child,
                            &mut sup_sock,
                            sup_cfg,
                            config.startup_timeout,
                            seccomp_notify_fd.as_ref(),
                            proxy_notify_fd.as_ref(),
                            &initial_caps,
                            trust_interceptor,
                            pty_proxy.as_mut(),
                        )?
                    }
                    #[cfg(not(target_os = "linux"))]
                    {
                        run_supervisor_loop(
                            child,
                            &mut sup_sock,
                            sup_cfg,
                            config.startup_timeout,
                            trust_interceptor,
                            pty_proxy.as_mut(),
                        )?
                    }
                } else {
                    let status =
                        wait_for_child_with_pty(child, pty_proxy.as_mut(), config.startup_timeout)?;
                    (status, Vec::new())
                };

            // Close the attach listener immediately so no new attach
            // connections can sneak in during teardown.  Without this,
            // the kernel keeps accepting connections into the listen
            // backlog even though nobody is calling accept(), and the
            // attaching client gets EPIPE ("Broken pipe") when it
            // tries to send the handshake.
            if let Some(ref mut p) = pty_proxy {
                p.shutdown_attach_listener();
            }

            let exit_code = match status {
                WaitStatus::Exited(_, code) => {
                    debug!("Supervised child exited with code {}", code);
                    let by_signal = (129..=143).contains(&code);
                    if by_signal && !config.no_diagnostics {
                        print_terminal_safe_stderr("[nono] Session stopped.");
                    }
                    code
                }
                WaitStatus::Signaled(_, sig, _) => {
                    debug!("Supervised child killed by signal {}", sig);
                    if !config.no_diagnostics {
                        print_terminal_safe_stderr("[nono] Session stopped.");
                    }
                    128 + sig as i32
                }
                other => {
                    warn!("Unexpected wait status: {:?}", other);
                    1
                }
            };

            // Analyze PTY screen content for sandbox-related errors.
            let error_observation = pty_proxy
                .as_ref()
                .map(|p| {
                    nono::diagnostic::analyze_error_output(
                        &p.screen_plaintext(),
                        config.protected_paths,
                        Some(config.current_dir),
                    )
                })
                .unwrap_or_default();

            let mode = if supervisor.is_some() {
                DiagnosticMode::Supervised
            } else {
                DiagnosticMode::Standard
            };

            let should_print_diagnostics = !config.no_diagnostics
                && (exit_code != 0 || !denials.is_empty() || error_observation.has_findings());

            // Print diagnostic footer on non-zero exit or when the PTY
            // output shows a likely sandbox-related issue.
            if should_print_diagnostics {
                #[cfg(target_os = "macos")]
                let sandbox_violations = if supervisor.is_some() {
                    sandbox_log_collector
                        .map(crate::sandbox_log::SandboxLogCollector::finish)
                        .unwrap_or_default()
                } else {
                    Vec::new()
                };
                #[cfg(not(target_os = "macos"))]
                let sandbox_violations = Vec::new();

                let diag_session_id = if supervisor.is_some() {
                    pty_session_id
                        .or_else(|| supervisor.map(|s| s.session_id))
                        .map(str::to_string)
                } else {
                    None
                };

                // Resolve policy explanations for denied paths so the
                // diagnostic can show group names and fix guidance inline.
                let policy_explanations =
                    build_policy_explanations(&denials, &sandbox_violations, config.caps);
                let prompt_policy_explanations = policy_explanations.clone();
                let prompt_error_observation = error_observation.clone();

                let mut formatter = DiagnosticFormatter::new(config.caps)
                    .with_mode(mode)
                    .with_denials(&denials)
                    .with_sandbox_violations(&sandbox_violations)
                    .with_protected_paths(config.protected_paths)
                    .with_error_observation(error_observation)
                    .with_current_dir(config.current_dir)
                    .with_session_id(diag_session_id)
                    .with_policy_explanations(policy_explanations);
                if let Some(program) = config.command.first() {
                    formatter = formatter.with_command(nono::diagnostic::CommandContext {
                        program: program.clone(),
                        resolved_path: config.resolved_program.to_path_buf(),
                        args: config.command.to_vec(),
                    });
                }
                let footer = formatter.format_footer(exit_code);
                crate::output::print_diagnostic_footer(&footer);

                if exit_code != 0 {
                    // Clear the forwarding target before prompting. The child is
                    // already dead; keeping CHILD_PID set would cause forward_signal
                    // to send Ctrl-C to the dead PID, swallowing it silently.
                    clear_signal_forwarding_target();
                    offer_profile_save_for_child(
                        pty_proxy.as_mut(),
                        &prompt_policy_explanations,
                        &prompt_error_observation,
                        config.caps,
                        config.command,
                        config.profile_save_base,
                    )?;
                }
            }

            Ok(exit_code)
        }
        Err(e) => Err(NonoError::SandboxInit(format!("fork() failed: {}", e))),
    }
}

/// Resolve policy explanations for denied paths by querying `query_path`.
///
/// This runs the same logic as `nono why` but inline, so the diagnostic
/// footer can show group names and fix guidance without asking the user
/// to run a separate command.
fn build_policy_explanations(
    denials: &[nono::diagnostic::DenialRecord],
    sandbox_violations: &[nono::SandboxViolation],
    caps: &nono::CapabilitySet,
) -> Vec<nono::diagnostic::PolicyExplanation> {
    use nono::diagnostic::PolicyExplanation;
    use nono::AccessMode;
    use std::collections::BTreeMap;

    // Merge access modes per path so a path denied for both Read and Write
    // produces a single ReadWrite query. Querying each (path, mode) pair
    // independently would let the first insert win and drop the other mode,
    // yielding an incomplete "Fix:" suggestion.
    let mut paths: BTreeMap<std::path::PathBuf, AccessMode> = BTreeMap::new();

    let merge = |existing: AccessMode, incoming: AccessMode| -> AccessMode {
        if existing == incoming {
            existing
        } else {
            AccessMode::ReadWrite
        }
    };

    for denial in denials {
        paths
            .entry(denial.path.clone())
            .and_modify(|a| *a = merge(*a, denial.access))
            .or_insert(denial.access);
    }

    for violation in sandbox_violations {
        let Some(access) = nono::diagnostic::seatbelt_operation_to_access(&violation.operation)
        else {
            continue;
        };
        let Some(target) = violation.target.as_ref() else {
            continue;
        };
        paths
            .entry(std::path::PathBuf::from(target))
            .and_modify(|a| *a = merge(*a, access))
            .or_insert(access);
    }

    let mut explanations = Vec::new();
    for (path, access) in paths {
        match crate::query_ext::query_path(&path, access, caps, &[]) {
            Ok(crate::query_ext::QueryResult::Denied {
                reason,
                details,
                policy_source,
                suggested_flag,
                ..
            }) => {
                explanations.push(PolicyExplanation {
                    path,
                    access,
                    reason,
                    details,
                    policy_source,
                    suggested_flag,
                });
            }
            Ok(crate::query_ext::QueryResult::Allowed { .. }) => {
                // Path is actually allowed by policy — the denial came from
                // a different layer (e.g. Landlock timing). Skip.
            }
            Ok(crate::query_ext::QueryResult::NotSandboxed { .. }) | Err(_) => {}
        }
    }

    explanations
}

/// Close inherited file descriptors, keeping stdin/stdout/stderr and specified FDs.
///
/// `max_fd` must be computed in the parent before fork (get_max_fd may allocate).
fn close_inherited_fds(max_fd: i32, keep_fds: &[i32]) {
    for fd in 3..=max_fd {
        if !keep_fds.contains(&fd) {
            unsafe { libc::close(fd) };
        }
    }
}

/// Get the maximum file descriptor number to iterate over.
fn get_max_fd() -> i32 {
    #[cfg(target_os = "linux")]
    {
        if let Ok(entries) = std::fs::read_dir("/proc/self/fd") {
            let max = entries
                .filter_map(|e| e.ok())
                .filter_map(|e| e.file_name().to_str().and_then(|s| s.parse::<i32>().ok()))
                .max()
                .unwrap_or(1024);
            return max;
        }
    }

    let max = unsafe { libc::sysconf(libc::_SC_OPEN_MAX) };
    if max > 0 {
        std::cmp::min(max as i32, 65536)
    } else {
        1024
    }
}

/// Wait for child process while proxying PTY I/O.
fn wait_for_child_with_pty(
    child: Pid,
    pty: Option<&mut crate::pty_proxy::PtyProxy>,
    startup_timeout: Option<StartupTimeoutConfig<'_>>,
) -> Result<WaitStatus> {
    let pty = match pty {
        Some(pty) => pty,
        None => return wait_for_child_with_startup_timeout(child, startup_timeout),
    };
    let startup_deadline = startup_timeout.map(|cfg| (Instant::now() + cfg.timeout, cfg));
    let mut startup_prompted = false;

    loop {
        let (master_fd, client_fd, attach_fd, resize_fd) = pty.poll_fds();
        let mut pfds = [
            libc::pollfd {
                fd: master_fd,
                events: libc::POLLIN,
                revents: 0,
            },
            libc::pollfd {
                fd: client_fd,
                events: libc::POLLIN,
                revents: 0,
            },
            libc::pollfd {
                fd: attach_fd,
                events: libc::POLLIN,
                revents: 0,
            },
            libc::pollfd {
                fd: resize_fd,
                events: libc::POLLIN,
                revents: 0,
            },
        ];

        let ret = unsafe { libc::poll(pfds.as_mut_ptr(), 4, 200) };

        if ret > 0 {
            if !handle_pty_poll_events(
                pty,
                pfds[0].revents,
                pfds[1].revents,
                pfds[2].revents,
                pfds[3].revents,
                "PTY wait loop",
            ) {
                break;
            }
        } else if ret < 0 {
            let err = std::io::Error::last_os_error();
            if err.kind() != std::io::ErrorKind::Interrupted {
                warn!("poll() error in PTY wait loop: {}", err);
                break;
            }
        }

        let pause_requested = drain_pause_pipe();
        if pause_requested {
            pty.sync_current_terminal_winsize();
        }
        let in_band_detach_requested = pty.take_detach_request();
        handle_pty_detach_request(Some(pty), pause_requested, in_band_detach_requested);

        match waitpid(child, Some(WaitPidFlag::WNOHANG)) {
            Ok(WaitStatus::StillAlive) => {
                if let Some((deadline, timeout_cfg)) = startup_deadline {
                    let has_output = pty.has_observed_output();
                    if Instant::now() >= deadline && !has_output && !startup_prompted {
                        startup_prompted = true;
                        let terminate = prompt_startup_termination_for_child(
                            child,
                            timeout_cfg,
                            has_output,
                            Some(pty),
                        );
                        if terminate {
                            let _ = signal::kill(child, Signal::SIGKILL);
                            let status = wait_for_child(child)?;
                            return Ok(status);
                        }
                    }
                }
                continue;
            }
            Ok(WaitStatus::Stopped(_, sig)) => {
                debug!("Child stopped by signal {}, keeping supervisor alive", sig);
                continue;
            }
            Ok(WaitStatus::Continued(_)) => {
                debug!("Child continued, waiting for terminal exit");
                continue;
            }
            Ok(status) => return Ok(status),
            Err(nix::errno::Errno::EINTR) => continue,
            Err(e) => {
                return Err(NonoError::SandboxInit(format!("waitpid() failed: {}", e)));
            }
        }
    }

    wait_for_child(child)
}

fn wait_for_child_with_startup_timeout(
    child: Pid,
    startup_timeout: Option<StartupTimeoutConfig<'_>>,
) -> Result<WaitStatus> {
    let startup_deadline = startup_timeout.map(|cfg| (Instant::now() + cfg.timeout, cfg));
    let mut startup_prompted = false;

    loop {
        match waitpid(child, Some(WaitPidFlag::WNOHANG)) {
            Ok(WaitStatus::StillAlive) => {
                if let Some((deadline, timeout_cfg)) = startup_deadline {
                    if Instant::now() >= deadline && !startup_prompted {
                        startup_prompted = true;
                        if prompt_startup_termination_for_child(child, timeout_cfg, true, None) {
                            let _ = signal::kill(child, Signal::SIGKILL);
                            return wait_for_child(child);
                        }
                    }
                }
                std::thread::sleep(Duration::from_millis(200));
            }
            Ok(status) => return Ok(status),
            Err(nix::errno::Errno::EINTR) => continue,
            Err(e) => {
                return Err(NonoError::SandboxInit(format!("waitpid() failed: {}", e)));
            }
        }
    }
}

/// Wait for child process, handling EINTR from signals.
fn wait_for_child(child: Pid) -> Result<WaitStatus> {
    loop {
        match waitpid(child, Some(WaitPidFlag::empty())) {
            Ok(status) => return Ok(status),
            Err(nix::errno::Errno::EINTR) => {
                // Interrupted by signal, retry
                continue;
            }
            Err(e) => {
                return Err(NonoError::SandboxInit(format!("waitpid() failed: {}", e)));
            }
        }
    }
}

/// Set up signal forwarding from parent to child.
///
/// Signals received by the parent are forwarded to the child process.
/// This ensures Ctrl+C, SIGTERM, etc. properly reach the sandboxed command.
///
/// # Process-Global State
///
/// This function uses process-global static storage for the child PID because
/// Unix signal handlers cannot access thread-local or instance-specific state.
/// This means:
///
/// - Only one `execute_supervised` invocation can be active at a time
/// - Concurrent calls from different threads would corrupt the child PID
/// - This is enforced by the thread count check in `execute_supervised`
///
/// This is acceptable because:
/// 1. `execute_supervised` is CLI code, not library code (per DESIGN-supervisor.md)
/// 2. The fork+wait model inherently requires single-threaded execution
/// 3. Library consumers would use `Sandbox::apply()` directly, not the fork machinery
fn setup_signal_forwarding(child: Pid, pty_master_fd: Option<i32>) {
    // ==================== SAFETY INVARIANT ====================
    // This static variable is ONLY safe because execute_supervised()
    // verifies single-threaded execution BEFORE calling this function.
    //
    // DO NOT call this function without first verifying:
    //   get_thread_count() == 1
    //
    // If threading is ever introduced before this point, this code
    // becomes a race condition where signals could be forwarded to
    // the wrong process (or a non-existent one).
    // ===========================================================
    //
    // Why this design:
    // - Unix signal handlers cannot access thread-local storage
    // - Unix signal handlers cannot access instance data
    // - The only safe option is process-global static storage
    // - AtomicI32 ensures atomic reads/writes
    CHILD_PID.store(child.as_raw(), std::sync::atomic::Ordering::SeqCst);
    PTY_MASTER_FD.store(
        pty_master_fd.unwrap_or(-1),
        std::sync::atomic::Ordering::SeqCst,
    );
    create_pause_pipe();

    // Install signal handlers for common signals
    // SAFETY: signal handlers are async-signal-safe (only call kill())
    unsafe {
        for sig in &[
            Signal::SIGINT,
            Signal::SIGTERM,
            Signal::SIGHUP,
            Signal::SIGQUIT,
            Signal::SIGUSR1,
        ] {
            if let Err(e) = signal::signal(*sig, signal::SigHandler::Handler(forward_signal)) {
                debug!("Failed to install handler for {:?}: {}", sig, e);
            }
        }

        if pty_master_fd.is_some() {
            if let Err(e) = signal::signal(
                Signal::SIGWINCH,
                signal::SigHandler::Handler(forward_signal),
            ) {
                debug!("Failed to install SIGWINCH handler: {:?}", e);
            }
        }
    }
}

static CHILD_PID: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0);
static PTY_MASTER_FD: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(-1);
static PAUSE_PIPE_WRITE: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(-1);
static PAUSE_PIPE_READ: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(-1);

fn create_pause_pipe() -> i32 {
    let mut fds = [0i32; 2];
    let ret = unsafe { libc::pipe(fds.as_mut_ptr()) };
    if ret != 0 {
        return -1;
    }
    unsafe {
        libc::fcntl(fds[0], libc::F_SETFL, libc::O_NONBLOCK);
        libc::fcntl(fds[1], libc::F_SETFL, libc::O_NONBLOCK);
        libc::fcntl(fds[0], libc::F_SETFD, libc::FD_CLOEXEC);
        libc::fcntl(fds[1], libc::F_SETFD, libc::FD_CLOEXEC);
    }
    PAUSE_PIPE_READ.store(fds[0], std::sync::atomic::Ordering::SeqCst);
    PAUSE_PIPE_WRITE.store(fds[1], std::sync::atomic::Ordering::SeqCst);
    fds[0]
}

fn drain_pause_pipe() -> bool {
    let read_fd = PAUSE_PIPE_READ.load(std::sync::atomic::Ordering::SeqCst);
    if read_fd < 0 {
        return false;
    }
    let mut buf = [0u8; 16];
    let n = unsafe { libc::read(read_fd, buf.as_mut_ptr().cast(), buf.len()) };
    n > 0
}

fn close_pause_pipe() {
    let r = PAUSE_PIPE_READ.swap(-1, std::sync::atomic::Ordering::SeqCst);
    let w = PAUSE_PIPE_WRITE.swap(-1, std::sync::atomic::Ordering::SeqCst);
    if r >= 0 {
        unsafe { libc::close(r) };
    }
    if w >= 0 {
        unsafe { libc::close(w) };
    }
}

extern "C" fn forward_signal(sig: libc::c_int) {
    let child_raw = CHILD_PID.load(std::sync::atomic::Ordering::SeqCst);
    if child_raw > 0 {
        if sig == libc::SIGWINCH {
            let master_fd = PTY_MASTER_FD.load(std::sync::atomic::Ordering::SeqCst);
            if master_fd >= 0 {
                let mut ws: libc::winsize = unsafe { std::mem::zeroed() };
                unsafe {
                    if libc::ioctl(libc::STDOUT_FILENO, libc::TIOCGWINSZ, &mut ws) == 0 {
                        libc::ioctl(master_fd, libc::TIOCSWINSZ as libc::c_ulong, &ws);
                    }
                }
            }
        } else if sig == libc::SIGUSR1 {
            let wfd = PAUSE_PIPE_WRITE.load(std::sync::atomic::Ordering::SeqCst);
            if wfd >= 0 {
                unsafe {
                    libc::write(wfd, b"P".as_ptr().cast(), 1);
                }
            }
        } else {
            unsafe {
                libc::kill(child_raw, sig);
            }
        }
    } else if matches!(
        sig,
        libc::SIGINT | libc::SIGTERM | libc::SIGHUP | libc::SIGQUIT
    ) {
        // No child to forward to (e.g. during the post-exit profile-save prompt).
        // For termination signals, restore the default handler and re-raise so
        // the signal takes its default action (terminating nono) rather than
        // being swallowed. Non-termination signals (SIGWINCH, SIGUSR1) are
        // ignored here — their forwarding targets (PTY master, pause pipe) are
        // already torn down.
        unsafe {
            libc::signal(sig, libc::SIG_DFL);
            libc::raise(sig);
        }
    }
}

fn clear_signal_forwarding_target() {
    CHILD_PID.store(0, std::sync::atomic::Ordering::SeqCst);
    PTY_MASTER_FD.store(-1, std::sync::atomic::Ordering::SeqCst);
    close_pause_pipe();
}

fn detach_client_for_session(pty: &mut crate::pty_proxy::PtyProxy) -> bool {
    pty.detach()
}

fn restore_terminal_after_detach() {
    crate::pty_proxy::write_detach_terminal_reset(libc::STDOUT_FILENO);
    crate::pty_proxy::write_detach_notice(libc::STDERR_FILENO);
}

fn handle_pty_poll_events(
    pty: &mut crate::pty_proxy::PtyProxy,
    master_revents: libc::c_short,
    client_revents: libc::c_short,
    attach_revents: libc::c_short,
    resize_revents: libc::c_short,
    loop_name: &str,
) -> bool {
    if master_revents & libc::POLLIN != 0 && !pty.proxy_master_to_client() {
        debug!("Stopping {loop_name} after PTY master relay failure");
        return false;
    }
    if client_revents & libc::POLLIN != 0 && !pty.proxy_client_to_master() {
        debug!("Stopping {loop_name} after PTY client relay failure");
        return false;
    }
    if attach_revents & libc::POLLIN != 0 {
        pty.try_accept();
    }
    if resize_revents & libc::POLLIN != 0 {
        pty.apply_resize_update();
    }
    true
}

fn handle_pty_detach_request(
    pty: Option<&mut crate::pty_proxy::PtyProxy>,
    pause_requested: bool,
    in_band_detach_requested: bool,
) {
    if pause_requested {
        info!("PTY detach requested via SIGUSR1 control signal");
    }
    if in_band_detach_requested {
        info!("PTY detach requested via in-band key sequence");
    }
    if (pause_requested || in_band_detach_requested) && pty.is_some_and(detach_client_for_session) {
        restore_terminal_after_detach();
    }
}

struct SignalForwardingGuard;

impl Drop for SignalForwardingGuard {
    fn drop(&mut self) {
        clear_signal_forwarding_target();
    }
}
/// Get the current thread count for the process.
///
/// Used to verify single-threaded execution before fork().
/// Returns an error if the count cannot be determined, since fork()
/// safety depends on knowing the exact thread count.
fn get_thread_count() -> Result<usize> {
    #[cfg(target_os = "linux")]
    {
        // On Linux, read /proc/self/status for accurate thread count
        let status = std::fs::read_to_string("/proc/self/status").map_err(|e| {
            NonoError::SandboxInit(format!(
                "Cannot read /proc/self/status for thread count: {e}"
            ))
        })?;
        for line in status.lines() {
            if let Some(count_str) = line.strip_prefix("Threads:") {
                return count_str.trim().parse::<usize>().map_err(|e| {
                    NonoError::SandboxInit(format!("Cannot parse thread count: {e}"))
                });
            }
        }
        Err(NonoError::SandboxInit(
            "Thread count not found in /proc/self/status".to_string(),
        ))
    }

    #[cfg(target_os = "macos")]
    {
        // On macOS, use mach APIs to get thread count
        // SAFETY: These are read-only queries about our own process
        #[allow(deprecated)] // libc recommends mach2 crate, but this is a simple defensive check
        unsafe {
            let task = libc::mach_task_self();
            let mut thread_list: libc::thread_act_array_t = std::ptr::null_mut();
            let mut thread_count: libc::mach_msg_type_number_t = 0;

            // task_threads returns all threads in the task
            let result = libc::task_threads(task, &mut thread_list, &mut thread_count);

            if result == libc::KERN_SUCCESS && !thread_list.is_null() {
                // Deallocate the thread list (required by mach API contract)
                let list_size = thread_count as usize * std::mem::size_of::<libc::thread_act_t>();
                libc::vm_deallocate(task, thread_list as libc::vm_address_t, list_size);
                return Ok(thread_count as usize);
            }
        }
        Err(NonoError::SandboxInit(
            "Cannot determine thread count via mach task_threads API".to_string(),
        ))
    }

    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    {
        Err(NonoError::SandboxInit(
            "Cannot determine thread count on this platform".to_string(),
        ))
    }
}

/// Supervisor IPC event loop (non-Linux).
///
/// Polls the supervisor socket and PTY relay fds for activity.
/// Uses `poll(2)` with a 200ms timeout to periodically check child status.
/// Returns the child's wait status and any denial records collected.
#[cfg(not(target_os = "linux"))]
fn run_supervisor_loop(
    child: Pid,
    sock: &mut SupervisorSocket,
    config: &SupervisorConfig<'_>,
    startup_timeout: Option<StartupTimeoutConfig<'_>>,
    mut trust_interceptor: Option<crate::trust_intercept::TrustInterceptor>,
    mut pty: Option<&mut crate::pty_proxy::PtyProxy>,
) -> Result<(WaitStatus, Vec<DenialRecord>)> {
    let sock_fd = sock.as_raw_fd();
    let mut denials = Vec::new();
    let mut seen_request_ids = HashSet::new();
    let startup_deadline = startup_timeout.map(|cfg| (Instant::now() + cfg.timeout, cfg));
    let mut startup_prompted = false;

    loop {
        let (pty_master, pty_client, pty_attach, pty_resize) =
            pty.as_ref().map_or((-1, -1, -1, -1), |p| p.poll_fds());
        let mut pfds = [
            libc::pollfd {
                fd: sock_fd,
                events: libc::POLLIN,
                revents: 0,
            },
            libc::pollfd {
                fd: pty_master,
                events: libc::POLLIN,
                revents: 0,
            },
            libc::pollfd {
                fd: pty_client,
                events: libc::POLLIN,
                revents: 0,
            },
            libc::pollfd {
                fd: pty_attach,
                events: libc::POLLIN,
                revents: 0,
            },
            libc::pollfd {
                fd: pty_resize,
                events: libc::POLLIN,
                revents: 0,
            },
        ];

        let ret = unsafe { libc::poll(pfds.as_mut_ptr(), 5, 200) };

        if ret > 0 {
            if pfds[0].revents & (libc::POLLHUP | libc::POLLERR) != 0 {
                debug!("Supervisor socket closed by child");
                break;
            }
            if pfds[0].revents & libc::POLLIN != 0 {
                match sock.recv_message() {
                    Ok(msg) => {
                        if let Err(e) = handle_supervisor_message(
                            sock,
                            msg,
                            child,
                            config,
                            &mut denials,
                            &mut seen_request_ids,
                            trust_interceptor.as_mut(),
                        ) {
                            warn!("Error handling supervisor message: {}", e);
                        }
                    }
                    Err(e) => {
                        debug!("Error receiving supervisor message: {}", e);
                        break;
                    }
                }
            }

            if let Some(ref mut p) = pty {
                if !handle_pty_poll_events(
                    p,
                    pfds[1].revents,
                    pfds[2].revents,
                    pfds[3].revents,
                    pfds[4].revents,
                    "supervisor loop",
                ) {
                    break;
                }
            }
        } else if ret < 0 {
            let err = std::io::Error::last_os_error();
            if err.kind() != std::io::ErrorKind::Interrupted {
                warn!("poll() error in supervisor loop: {}", err);
                break;
            }
        }

        let pause_requested = drain_pause_pipe();
        if let Some(ref mut p) = pty {
            if pause_requested {
                p.sync_current_terminal_winsize();
            }
        }
        let in_band_detach_requested = pty.as_mut().is_some_and(|p| p.take_detach_request());
        handle_pty_detach_request(
            pty.as_deref_mut(),
            pause_requested,
            in_band_detach_requested,
        );

        match waitpid(child, Some(WaitPidFlag::WNOHANG)) {
            Ok(WaitStatus::StillAlive) => {
                if let Some((deadline, timeout_cfg)) = startup_deadline {
                    let has_output = pty.as_ref().is_some_and(|p| p.has_observed_output());
                    if Instant::now() >= deadline && !has_output && !startup_prompted {
                        startup_prompted = true;
                        let terminate = prompt_startup_termination_for_child(
                            child,
                            timeout_cfg,
                            has_output,
                            pty.as_deref_mut(),
                        );
                        if terminate {
                            let _ = signal::kill(child, Signal::SIGKILL);
                            return Ok((wait_for_child(child)?, denials));
                        }
                    }
                }
                continue;
            }
            Ok(WaitStatus::Stopped(_, sig)) => {
                debug!("Child stopped by signal {}, keeping supervisor alive", sig);
                continue;
            }
            Ok(WaitStatus::Continued(_)) => {
                debug!("Child continued, keeping supervisor alive");
                continue;
            }
            Ok(status) => return Ok((status, denials)),
            Err(nix::errno::Errno::EINTR) => continue,
            Err(nix::errno::Errno::ECHILD) => {
                warn!("Child already reaped in supervisor loop");
                return Ok((WaitStatus::Exited(child, 1), denials));
            }
            Err(e) => {
                return Err(NonoError::SandboxInit(format!(
                    "waitpid() failed in supervisor loop: {}",
                    e
                )));
            }
        }
    }

    let status = wait_for_child(child)?;
    Ok((status, denials))
}

/// Supervisor IPC event loop for capability expansion (Linux).
///
/// Multiplexes between:
/// - seccomp notify fd (openat/openat2 interceptions from the child)
/// - supervisor socket (explicit capability requests from SDK clients)
/// - PTY relay (real terminal <-> PTY master), when present
/// - child process exit via non-blocking `waitpid()`
///
/// When a seccomp notification requires interactive approval, the relay is
/// paused (terminal restored to canonical mode) so the user can type a response.
/// After the prompt, raw mode is re-entered and relay resumes.
///
/// The relay is optional: when `capability_elevation` is off, no PTY is
/// allocated but the supervisor loop still runs for trust interception over
/// the IPC socket.
///
/// Returns the child's wait status and any denial records collected.
#[cfg(target_os = "linux")]
#[allow(clippy::too_many_arguments)]
fn run_supervisor_loop(
    child: Pid,
    sock: &mut SupervisorSocket,
    config: &SupervisorConfig<'_>,
    startup_timeout: Option<StartupTimeoutConfig<'_>>,
    seccomp_fd: Option<&OwnedFd>,
    proxy_seccomp_fd: Option<&OwnedFd>,
    initial_caps: &[supervisor_linux::InitialCapability],
    mut trust_interceptor: Option<crate::trust_intercept::TrustInterceptor>,
    mut pty: Option<&mut crate::pty_proxy::PtyProxy>,
) -> Result<(WaitStatus, Vec<DenialRecord>)> {
    let sock_fd = sock.as_raw_fd();
    let notify_raw_fd = seccomp_fd.map(|fd| fd.as_raw_fd());
    let proxy_notify_raw_fd = proxy_seccomp_fd.map(|fd| fd.as_raw_fd());
    let mut rate_limiter = supervisor_linux::RateLimiter::new(10, 5);
    let mut denials = Vec::new();
    let mut seen_request_ids = HashSet::new();
    let mut sock_fd_active = true;
    let startup_deadline = startup_timeout.map(|cfg| (Instant::now() + cfg.timeout, cfg));
    let mut startup_prompted = false;

    loop {
        let mut pfds: Vec<libc::pollfd> = vec![libc::pollfd {
            fd: if sock_fd_active { sock_fd } else { -1 },
            events: libc::POLLIN,
            revents: 0,
        }];
        let notify_idx = notify_raw_fd.map(|nfd| {
            let idx = pfds.len();
            pfds.push(libc::pollfd {
                fd: nfd,
                events: libc::POLLIN,
                revents: 0,
            });
            idx
        });
        let proxy_notify_idx = proxy_notify_raw_fd.map(|pfd| {
            let idx = pfds.len();
            pfds.push(libc::pollfd {
                fd: pfd,
                events: libc::POLLIN,
                revents: 0,
            });
            idx
        });
        let pty_base_idx = pfds.len();
        let (pty_master, pty_client, pty_attach, pty_resize) =
            pty.as_ref().map_or((-1, -1, -1, -1), |p| p.poll_fds());
        pfds.push(libc::pollfd {
            fd: pty_master,
            events: libc::POLLIN,
            revents: 0,
        });
        pfds.push(libc::pollfd {
            fd: pty_client,
            events: libc::POLLIN,
            revents: 0,
        });
        pfds.push(libc::pollfd {
            fd: pty_attach,
            events: libc::POLLIN,
            revents: 0,
        });
        pfds.push(libc::pollfd {
            fd: pty_resize,
            events: libc::POLLIN,
            revents: 0,
        });

        let ret = unsafe { libc::poll(pfds.as_mut_ptr(), pfds.len() as libc::nfds_t, 200) };

        match ret.cmp(&0) {
            std::cmp::Ordering::Greater => {
                if sock_fd_active && pfds[0].revents & (libc::POLLHUP | libc::POLLERR) != 0 {
                    if notify_raw_fd.is_some() || proxy_notify_raw_fd.is_some() || pty.is_some() {
                        debug!("Supervisor socket closed, continuing for seccomp/proxy/PTY");
                        sock_fd_active = false;
                    } else {
                        debug!("Supervisor socket closed by child");
                        break;
                    }
                }
                if sock_fd_active && pfds[0].revents & libc::POLLIN != 0 {
                    match sock.recv_message() {
                        Ok(msg) => {
                            if let Err(e) = handle_supervisor_message(
                                sock,
                                msg,
                                child,
                                config,
                                &mut denials,
                                &mut seen_request_ids,
                                trust_interceptor.as_mut(),
                            ) {
                                warn!("Error handling supervisor message: {}", e);
                            }
                        }
                        Err(e) => {
                            debug!("Error receiving supervisor message: {}", e);
                            if notify_raw_fd.is_none()
                                && proxy_notify_raw_fd.is_none()
                                && pty.is_none()
                            {
                                break;
                            }
                            sock_fd_active = false;
                        }
                    }
                }

                if let Some(notify_idx) = notify_idx {
                    if pfds[notify_idx].revents & libc::POLLIN != 0 {
                        if let Some(nfd) = notify_raw_fd {
                            if let Err(e) = supervisor_linux::handle_seccomp_notification(
                                nfd,
                                child,
                                config,
                                initial_caps,
                                &mut rate_limiter,
                                &mut denials,
                                trust_interceptor.as_mut(),
                            ) {
                                debug!("Error handling seccomp notification: {}", e);
                            }
                        }
                    }
                }

                if let Some(proxy_notify_idx) = proxy_notify_idx {
                    if pfds[proxy_notify_idx].revents & libc::POLLIN != 0 {
                        if let Some(pfd) = proxy_notify_raw_fd {
                            if let Err(e) = supervisor_linux::handle_network_notification(
                                pfd,
                                config,
                                &mut rate_limiter,
                            ) {
                                debug!("Error handling proxy seccomp notification: {}", e);
                            }
                        }
                    }
                }

                if let Some(ref mut p) = pty {
                    if !handle_pty_poll_events(
                        p,
                        pfds[pty_base_idx].revents,
                        pfds[pty_base_idx + 1].revents,
                        pfds[pty_base_idx + 2].revents,
                        pfds[pty_base_idx + 3].revents,
                        "supervisor loop",
                    ) {
                        break;
                    }
                }
            }
            std::cmp::Ordering::Less => {
                let err = std::io::Error::last_os_error();
                if err.kind() != std::io::ErrorKind::Interrupted {
                    warn!("poll() error in supervisor loop: {}", err);
                    break;
                }
            }
            std::cmp::Ordering::Equal => {}
        }

        let pause_requested = drain_pause_pipe();
        if let Some(ref mut p) = pty {
            if pause_requested {
                p.sync_current_terminal_winsize();
            }
        }
        let in_band_detach_requested = pty.as_mut().is_some_and(|p| p.take_detach_request());
        handle_pty_detach_request(
            pty.as_deref_mut(),
            pause_requested,
            in_band_detach_requested,
        );

        match waitpid(child, Some(WaitPidFlag::WNOHANG)) {
            Ok(WaitStatus::StillAlive) => {
                if let Some((deadline, timeout_cfg)) = startup_deadline {
                    let has_output = pty.as_ref().is_some_and(|p| p.has_observed_output());
                    if Instant::now() >= deadline && !has_output && !startup_prompted {
                        startup_prompted = true;
                        let terminate = prompt_startup_termination_for_child(
                            child,
                            timeout_cfg,
                            has_output,
                            pty.as_deref_mut(),
                        );
                        if terminate {
                            let _ = signal::kill(child, Signal::SIGTERM);
                            return Ok((wait_for_child(child)?, denials));
                        }
                    }
                }
                continue;
            }
            Ok(WaitStatus::Stopped(_, sig)) => {
                debug!("Child stopped by signal {}, keeping supervisor alive", sig);
                continue;
            }
            Ok(WaitStatus::Continued(_)) => {
                debug!("Child continued, keeping supervisor alive");
                continue;
            }
            Ok(status) => return Ok((status, denials)),
            Err(nix::errno::Errno::EINTR) => continue,
            Err(nix::errno::Errno::ECHILD) => {
                warn!("Child already reaped in supervisor loop");
                return Ok((WaitStatus::Exited(child, 1), denials));
            }
            Err(e) => {
                return Err(NonoError::SandboxInit(format!(
                    "waitpid() failed in supervisor loop: {}",
                    e
                )));
            }
        }
    }

    let status = wait_for_child(child)?;
    Ok((status, denials))
}

/// Handle a single supervisor IPC message.
///
/// Flow:
/// 1. Check protected nono state roots - those paths are rejected immediately
/// 2. Delegate to `ApprovalBackend` for the decision
/// 3. If granted, open the path and send the fd via `SCM_RIGHTS`
/// 4. Send the decision response
/// 5. Record denials for diagnostic footer
fn handle_supervisor_message(
    sock: &mut SupervisorSocket,
    msg: SupervisorMessage,
    child: Pid,
    config: &SupervisorConfig<'_>,
    denials: &mut Vec<DenialRecord>,
    seen_request_ids: &mut HashSet<String>,
    mut trust_interceptor: Option<&mut crate::trust_intercept::TrustInterceptor>,
) -> Result<()> {
    match msg {
        SupervisorMessage::Request(request) => {
            let decision_started = Instant::now();
            // Replay detection and bounded request-id cache.
            let replay_denial_reason = if seen_request_ids.contains(&request.request_id) {
                Some("Duplicate request_id rejected (replay detected)")
            } else if seen_request_ids.len() >= MAX_TRACKED_REQUEST_IDS {
                Some("Request replay cache is full; refusing request")
            } else {
                None
            };

            if let Some(reason) = replay_denial_reason {
                record_denial(
                    denials,
                    DenialRecord {
                        path: request.path.clone(),
                        access: request.access,
                        reason: DenialReason::PolicyBlocked,
                    },
                );
                let response = SupervisorResponse::Decision {
                    request_id: request.request_id.clone(),
                    decision: ApprovalDecision::Denied {
                        reason: reason.to_string(),
                    },
                };
                sock.send_response(&response)?;
                record_capability_audit(
                    config,
                    request,
                    decision_started,
                    response_decision(&response),
                )?;
                return Ok(());
            }
            seen_request_ids.insert(request.request_id.clone());

            // Digest from trust verification, used for TOCTOU re-check at open time.
            // Set by the trust interceptor branch when an instruction file is verified.
            let mut verified_digest: Option<String> = None;

            let decision = if let Some(protected_root) =
                crate::protected_paths::overlapping_protected_root(
                    &request.path,
                    false,
                    config.protected_roots,
                ) {
                debug!(
                    "Supervisor: path {} blocked by protected root {}",
                    request.path.display(),
                    protected_root.display()
                );
                record_denial(
                    denials,
                    DenialRecord {
                        path: request.path.clone(),
                        access: request.access,
                        reason: DenialReason::PolicyBlocked,
                    },
                );
                ApprovalDecision::Denied {
                    reason: format!(
                        "Path overlaps protected nono state root '{}': {}",
                        protected_root.display(),
                        request.path.display()
                    ),
                }
            } else if let Some(trust_result) = trust_interceptor
                .as_mut()
                .and_then(|ti| ti.check_path(&request.path))
            {
                // 2. Trust verification for instruction files
                match trust_result {
                    Ok(verified) => {
                        debug!(
                            "Supervisor: instruction file {} verified (publisher: {})",
                            request.path.display(),
                            verified.publisher,
                        );
                        // Stash the verified digest for TOCTOU re-check at open time
                        verified_digest = Some(verified.digest);
                        // Instruction file verified — proceed to approval backend
                        match config.approval_backend.request_capability(&request) {
                            Ok(d) => {
                                if d.is_denied() {
                                    record_denial(
                                        denials,
                                        DenialRecord {
                                            path: request.path.clone(),
                                            access: request.access,
                                            reason: DenialReason::UserDenied,
                                        },
                                    );
                                }
                                d
                            }
                            Err(e) => {
                                warn!("Approval backend error: {}", e);
                                record_denial(
                                    denials,
                                    DenialRecord {
                                        path: request.path.clone(),
                                        access: request.access,
                                        reason: DenialReason::BackendError,
                                    },
                                );
                                ApprovalDecision::Denied {
                                    reason: format!("Approval backend error: {e}"),
                                }
                            }
                        }
                    }
                    Err(reason) => {
                        // Instruction file failed trust verification — auto-deny
                        debug!(
                            "Supervisor: instruction file {} failed trust verification: {}",
                            request.path.display(),
                            reason
                        );
                        record_denial(
                            denials,
                            DenialRecord {
                                path: request.path.clone(),
                                access: request.access,
                                reason: DenialReason::PolicyBlocked,
                            },
                        );
                        ApprovalDecision::Denied {
                            reason: format!("Instruction file failed trust verification: {reason}"),
                        }
                    }
                }
            } else {
                // 3. Delegate to approval backend (non-instruction files)
                match config.approval_backend.request_capability(&request) {
                    Ok(d) => {
                        if d.is_denied() {
                            record_denial(
                                denials,
                                DenialRecord {
                                    path: request.path.clone(),
                                    access: request.access,
                                    reason: DenialReason::UserDenied,
                                },
                            );
                        }
                        d
                    }
                    Err(e) => {
                        warn!("Approval backend error: {}", e);
                        record_denial(
                            denials,
                            DenialRecord {
                                path: request.path.clone(),
                                access: request.access,
                                reason: DenialReason::BackendError,
                            },
                        );
                        ApprovalDecision::Denied {
                            reason: format!("Approval backend error: {e}"),
                        }
                    }
                }
            };

            // 3. If granted, open the path and send fd before the response
            if decision.is_granted() {
                match open_path_for_access(
                    &request.path,
                    &request.access,
                    config.protected_roots,
                    verified_digest.as_deref(),
                    Some(ProcfsAccessContext::new(child.as_raw() as u32, None)),
                ) {
                    Ok(file) => {
                        if let Err(e) = sock.send_fd(file.as_raw_fd()) {
                            warn!("Failed to send fd: {}", e);
                            let response = SupervisorResponse::Decision {
                                request_id: request.request_id.clone(),
                                decision: ApprovalDecision::Denied {
                                    reason: format!("Failed to send file descriptor: {e}"),
                                },
                            };
                            sock.send_response(&response)?;
                            record_capability_audit(
                                config,
                                request,
                                decision_started,
                                response_decision(&response),
                            )?;
                            return Ok(());
                        }
                    }
                    Err(e) => {
                        warn!("Failed to open path: {}", e);
                        let response = SupervisorResponse::Decision {
                            request_id: request.request_id.clone(),
                            decision: ApprovalDecision::Denied {
                                reason: format!("Supervisor failed to open path: {e}"),
                            },
                        };
                        sock.send_response(&response)?;
                        record_capability_audit(
                            config,
                            request,
                            decision_started,
                            response_decision(&response),
                        )?;
                        return Ok(());
                    }
                }
            }

            // 4. Send decision response
            let response = SupervisorResponse::Decision {
                request_id: request.request_id.clone(),
                decision,
            };
            sock.send_response(&response)?;
            record_capability_audit(
                config,
                request,
                decision_started,
                response_decision(&response),
            )?;
        }
        SupervisorMessage::OpenUrl(url_request) => {
            let request_id = url_request.request_id.clone();

            let (success, error) = match validate_and_open_url(&url_request.url, config) {
                Ok(()) => {
                    info!("Supervisor: opened URL {} for child", url_request.url);
                    (true, None)
                }
                Err(reason) => {
                    warn!(
                        "Supervisor: URL open denied for {}: {}",
                        url_request.url, reason
                    );
                    (false, Some(reason))
                }
            };
            let response = SupervisorResponse::UrlOpened {
                request_id,
                success,
                error: error.clone(),
            };
            sock.send_response(&response)?;
            if let Some(recorder_mutex) = config.audit_recorder {
                let mut recorder = recorder_mutex
                    .lock()
                    .map_err(|_| NonoError::Snapshot("Audit recorder lock poisoned".to_string()))?;
                recorder.record_open_url(url_request, success, error)?;
            }
        }
    }

    Ok(())
}

fn response_decision(response: &SupervisorResponse) -> ApprovalDecision {
    match response {
        SupervisorResponse::Decision { decision, .. } => decision.clone(),
        SupervisorResponse::UrlOpened { .. } => ApprovalDecision::Denied {
            reason: "invalid supervisor response type for capability decision".to_string(),
        },
    }
}

fn record_capability_audit(
    config: &SupervisorConfig<'_>,
    request: nono::supervisor::CapabilityRequest,
    decision_started: Instant,
    decision: ApprovalDecision,
) -> Result<()> {
    if let Some(recorder_mutex) = config.audit_recorder {
        let entry = AuditEntry {
            timestamp: std::time::SystemTime::now(),
            request,
            decision,
            backend: config.approval_backend.backend_name().to_string(),
            duration_ms: decision_started.elapsed().as_millis() as u64,
        };
        let mut recorder = recorder_mutex
            .lock()
            .map_err(|_| NonoError::Snapshot("Audit recorder lock poisoned".to_string()))?;
        recorder.record_capability_decision(entry)?;
    }
    Ok(())
}

/// Maximum URL length to prevent abuse via oversized URLs.
const MAX_URL_LENGTH: usize = 8192;

/// Validate a URL against the profile's allowed origins, then open it in the user's browser.
///
/// The supervisor (unsandboxed parent) performs this operation so the browser
/// launches outside the sandbox with full access to its own config files.
fn validate_and_open_url(
    url: &str,
    config: &SupervisorConfig<'_>,
) -> std::result::Result<(), String> {
    validate_url(url, config)?;
    open_url_in_browser(url)
}

/// Validate a URL against the profile's allowed origins and scheme rules.
///
/// Returns `Ok(())` if the URL passes all checks. Does not open the browser.
fn validate_url(url: &str, config: &SupervisorConfig<'_>) -> std::result::Result<(), String> {
    // Length check
    if url.len() > MAX_URL_LENGTH {
        return Err(format!(
            "URL exceeds maximum length ({} > {})",
            url.len(),
            MAX_URL_LENGTH
        ));
    }

    // Parse URL to extract origin
    let parsed = url::Url::parse(url).map_err(|e| format!("Invalid URL: {e}"))?;

    let scheme = parsed.scheme();
    let host = parsed.host_str().unwrap_or("");

    // Check localhost first
    let is_localhost = host == "localhost" || host == "127.0.0.1" || host == "::1";
    if is_localhost {
        if scheme != "http" && scheme != "https" {
            return Err(format!(
                "Localhost URL must use http or https scheme, got: {scheme}"
            ));
        }
        if !config.open_url_allow_localhost {
            return Err("Localhost URLs are not allowed by this profile".to_string());
        }
    } else {
        // Non-localhost: must be https
        if scheme != "https" {
            return Err(format!(
                "Only https:// URLs are allowed (got {scheme}://). \
                 file://, javascript:, data:, and other schemes are blocked."
            ));
        }

        // Check against allowed origins
        let url_origin = parsed.origin().unicode_serialization();
        let origin_allowed = config.open_url_origins.contains(&url_origin);

        if !origin_allowed {
            return Err(format!(
                "Origin {url_origin} is not in the profile's open_urls.allow_origins list"
            ));
        }
    }

    Ok(())
}

/// Open a URL in the user's default browser.
///
/// Uses `open` on macOS and `xdg-open` on Linux. Runs in the unsandboxed
/// parent process so the browser has full system access.
fn open_url_in_browser(url: &str) -> std::result::Result<(), String> {
    #[cfg(target_os = "macos")]
    let result = std::process::Command::new("open")
        .arg(url)
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status();

    #[cfg(target_os = "linux")]
    let result = std::process::Command::new("xdg-open")
        .arg(url)
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status();

    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
    let result: std::result::Result<std::process::ExitStatus, std::io::Error> =
        Err(std::io::Error::new(
            std::io::ErrorKind::Unsupported,
            "URL opening not supported on this platform",
        ));

    match result {
        Ok(status) if status.success() => Ok(()),
        Ok(status) => Err(format!("Browser opener exited with status: {status}")),
        Err(e) => Err(format!("Failed to launch browser: {e}")),
    }
}

/// Clear `FD_CLOEXEC` on a file descriptor so it survives `execve()`.
fn clear_close_on_exec(fd: i32) -> Result<()> {
    // SAFETY: `fcntl` is called with a valid fd owned by this process.
    let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
    if flags < 0 {
        return Err(NonoError::SandboxInit(format!(
            "fcntl(F_GETFD) failed: {}",
            std::io::Error::last_os_error()
        )));
    }

    let new_flags = flags & !libc::FD_CLOEXEC;
    if new_flags != flags {
        // SAFETY: `fcntl` is called with a valid fd and descriptor flags.
        let rc = unsafe { libc::fcntl(fd, libc::F_SETFD, new_flags) };
        if rc < 0 {
            return Err(NonoError::SandboxInit(format!(
                "fcntl(F_SETFD) failed: {}",
                std::io::Error::last_os_error()
            )));
        }
    }

    Ok(())
}

pub(super) fn record_denial(denials: &mut Vec<DenialRecord>, record: DenialRecord) {
    if denials.len() < MAX_DENIAL_RECORDS {
        denials.push(record);
    }
}

/// Create a temporary directory containing an `open` shim script on macOS.
///
/// The shim intercepts calls to `open` (which the Node.js `open` package
/// uses on macOS) and routes URL arguments through `nono open-url-helper`.
/// Non-URL arguments are passed through to `/usr/bin/open` so that
/// non-browser `open` invocations (e.g. opening files) still work.
///
/// Returns the path to the shim directory, or `None` on failure.
#[cfg(any(target_os = "linux", target_os = "macos"))]
struct BrowserShim {
    #[cfg_attr(target_os = "linux", allow(dead_code))]
    dir: tempfile::TempDir,
    launcher: std::path::PathBuf,
}

#[cfg(target_os = "linux")]
fn create_linux_browser_shim(
    nono_exe: &std::path::Path,
    supervisor_fd: i32,
) -> Option<BrowserShim> {
    use std::os::unix::fs::PermissionsExt;

    let shim_dir = tempfile::Builder::new()
        .prefix("nono-browser-")
        .tempdir()
        .ok()?;
    let shim_dir_path = shim_dir.path();

    let helper_path = shim_dir_path.join("nono-open-url-helper");
    if std::fs::copy(nono_exe, &helper_path).is_err() {
        return None;
    }
    if std::fs::set_permissions(&helper_path, std::fs::Permissions::from_mode(0o755)).is_err() {
        return None;
    }

    let launcher_path = shim_dir_path.join("nono-browser");
    let quoted_helper = shell_quote(&helper_path.display().to_string());
    let script = format!(
        r#"#!/bin/sh
NONO_SUPERVISOR_FD={supervisor_fd} exec {quoted_helper} open-url-helper "$@"
"#
    );

    if std::fs::write(&launcher_path, script).is_err() {
        return None;
    }
    if std::fs::set_permissions(&launcher_path, std::fs::Permissions::from_mode(0o755)).is_err() {
        return None;
    }

    Some(BrowserShim {
        dir: shim_dir,
        launcher: launcher_path,
    })
}

#[cfg(target_os = "macos")]
fn create_open_shim(nono_exe: &std::path::Path, supervisor_fd: i32) -> Option<BrowserShim> {
    use std::os::unix::fs::PermissionsExt;

    let shim_dir = tempfile::Builder::new()
        .prefix("nono-shim-")
        .tempdir()
        .ok()?;
    let shim_dir_path = shim_dir.path();

    // Keep the helper inside the shim directory so it is always readable and
    // executable under the sandbox's temp-dir allowlist, regardless of where
    // the original `nono` binary was launched from.
    let helper_path = shim_dir_path.join("nono-open-url-helper");
    if std::fs::copy(nono_exe, &helper_path).is_err() {
        return None;
    }
    if std::fs::set_permissions(&helper_path, std::fs::Permissions::from_mode(0o755)).is_err() {
        return None;
    }

    let shim_path = shim_dir_path.join("open");
    let quoted_helper = shell_quote(&helper_path.display().to_string());

    // The shim script scans all arguments for the first URL-like value. If one
    // is present, delegate to nono open-url-helper. Otherwise fall through to
    // /usr/bin/open for non-URL uses (opening files, apps, etc.).
    let script = format!(
        r#"#!/bin/sh
# nono URL open shim — intercepts `open` calls for browser URL delegation
url_arg=""
for arg in "$@"; do
    case "$arg" in
        http://*|https://*)
            url_arg="$arg"
            break
            ;;
    esac
done

if [ -n "$url_arg" ]; then
    NONO_SUPERVISOR_FD={supervisor_fd} exec {quoted_helper} open-url-helper "$url_arg"
else
    exec /usr/bin/open "$@"
fi
"#
    );

    if std::fs::write(&shim_path, script).is_err() {
        return None;
    }
    if std::fs::set_permissions(&shim_path, std::fs::Permissions::from_mode(0o755)).is_err() {
        return None;
    }

    Some(BrowserShim {
        dir: shim_dir,
        launcher: shim_path,
    })
}

/// Shell-quote a string for safe embedding in `sh -c` commands.
/// If the string contains no special characters, returns it unchanged.
/// Otherwise wraps it in single quotes, escaping embedded single quotes.
fn shell_quote(s: &str) -> String {
    // If the string is safe as-is, skip quoting
    if !s.is_empty()
        && s.bytes()
            .all(|b| b.is_ascii_alphanumeric() || b"/-_.".contains(&b))
    {
        return s.to_string();
    }
    // Single-quote the string, replacing ' with '\'' (end quote, escaped quote, start quote)
    let mut quoted = String::with_capacity(s.len() + 2);
    quoted.push('\'');
    for ch in s.chars() {
        if ch == '\'' {
            quoted.push_str("'\\''");
        } else {
            quoted.push(ch);
        }
    }
    quoted.push('\'');
    quoted
}

/// Generate a unique request ID from timestamp + monotonic counter.
#[cfg(target_os = "linux")]
fn unique_request_id() -> String {
    use std::sync::atomic::{AtomicU64, Ordering};
    use std::time::{SystemTime, UNIX_EPOCH};

    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0) as u64;
    let seq = COUNTER.fetch_add(1, Ordering::Relaxed);

    // Combine timestamp with monotonic counter for uniqueness
    format!("{:x}-{:x}", nanos, seq)
}

/// Resolve `/proc/self` and `/proc/thread-self` against the sandboxed child.
///
/// Without this rewrite, canonicalizing `/proc/self/...` in the supervisor would
/// resolve to the supervisor's procfs view instead of the child's.
fn resolve_procfs_path_for_child(
    path: &Path,
    procfs_context: Option<ProcfsAccessContext>,
) -> Result<PathBuf> {
    let Some(procfs_context) = procfs_context else {
        return Ok(path.to_path_buf());
    };

    let mut components = path.components();
    if components.next() != Some(Component::RootDir)
        || components.next() != Some(Component::Normal(OsStr::new("proc")))
    {
        return Ok(path.to_path_buf());
    }

    let Some(proc_component) = components.next() else {
        return Ok(path.to_path_buf());
    };

    let mut rewritten = PathBuf::from("/proc");
    match proc_component {
        Component::Normal(part) if part == OsStr::new("self") => {
            rewritten.push(procfs_context.process_pid.to_string());
        }
        Component::Normal(part) if part == OsStr::new("thread-self") => {
            let thread_pid = procfs_context.thread_pid.ok_or_else(|| {
                NonoError::SandboxInit(
                    "Cannot resolve /proc/thread-self without a requesting thread ID".to_string(),
                )
            })?;
            rewritten.push(procfs_context.process_pid.to_string());
            rewritten.push("task");
            rewritten.push(thread_pid.to_string());
        }
        _ => return Ok(path.to_path_buf()),
    }

    for component in components {
        match component {
            Component::Normal(part) => rewritten.push(part),
            Component::CurDir => rewritten.push("."),
            Component::ParentDir => rewritten.push(".."),
            Component::RootDir | Component::Prefix(_) => {}
        }
    }

    Ok(rewritten)
}

/// Enforce the supervisor's procfs deny rules before canonicalization.
///
/// This must run on the resolved procfs path before `canonicalize()`, because
/// procfs links such as `/proc/<pid>/fd/<n>` and `/proc/<pid>/cwd` would
/// otherwise erase their `/proc` provenance during resolution.
fn validate_procfs_access(
    resolved_path: &Path,
    procfs_context: Option<ProcfsAccessContext>,
) -> std::result::Result<(), OpenPathError> {
    const SELF_BLOCKED_PROC_NAMES: &[&str] =
        &["fd", "ns", "pagemap", "exe", "cwd", "root", "mountinfo"];

    let Some(suffix) = resolved_path
        .to_str()
        .and_then(|s| s.strip_prefix("/proc/"))
    else {
        return Ok(());
    };

    let allowed_pid = procfs_context.map(|ctx| ctx.process_pid.to_string());
    let components: Vec<&str> = suffix.split('/').collect();

    if components.is_empty() || !components[0].chars().all(|c| c.is_ascii_digit()) {
        return Ok(());
    }

    let (pid_component, sensitive_component) = if components.len() >= 4
        && components[1] == "task"
        && components[2].chars().all(|c| c.is_ascii_digit())
    {
        (components[0], components.get(3).copied())
    } else {
        (components[0], components.get(1).copied())
    };

    if allowed_pid.as_deref() != Some(pid_component) {
        return Err(OpenPathError::policy_blocked(format!(
            "Access to {} is blocked by policy",
            resolved_path.display(),
        )));
    }

    if let Some(component) = sensitive_component {
        if SELF_BLOCKED_PROC_NAMES.contains(&component) {
            return Err(OpenPathError::policy_blocked(format!(
                "Access to {} is blocked by policy",
                resolved_path.display(),
            )));
        }
    }

    Ok(())
}

#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
#[derive(Debug)]
struct OpenPathError {
    errno: i32,
    message: String,
    policy_blocked: bool,
}

#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
impl OpenPathError {
    fn policy_blocked(message: String) -> Self {
        Self {
            errno: libc::EPERM,
            message,
            policy_blocked: true,
        }
    }

    fn io(message: String, source: &std::io::Error) -> Self {
        Self {
            errno: source.raw_os_error().unwrap_or(libc::EIO),
            message,
            policy_blocked: false,
        }
    }

    fn internal(message: String) -> Self {
        Self {
            errno: libc::EIO,
            message,
            policy_blocked: false,
        }
    }

    fn errno(&self) -> i32 {
        self.errno
    }

    fn is_policy_blocked(&self) -> bool {
        self.policy_blocked
    }
}

impl std::fmt::Display for OpenPathError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.message)
    }
}

impl std::error::Error for OpenPathError {}

/// Open a filesystem path with the requested access mode.
///
/// Used by the supervisor to open files on behalf of the sandboxed child
/// before passing the fd via `SCM_RIGHTS` or seccomp fd injection.
///
/// # Security
///
/// This function canonicalizes the path and re-checks it against protected
/// nono state roots AFTER resolution. This prevents symlink-based bypasses
/// where a child creates `/tmp/innocent -> ~/.nono` and requests access to the
/// innocuous alias.
///
/// File creation is intentionally disabled (`create(false)`) -- the
/// supervisor only grants access to existing files. File creation should
/// go through the initial capability set, not capability expansion.
fn open_path_for_access(
    path: &Path,
    access: &nono::AccessMode,
    protected_roots: &[PathBuf],
    trust_digest: Option<&str>,
    procfs_context: Option<ProcfsAccessContext>,
) -> std::result::Result<std::fs::File, OpenPathError> {
    let resolved_path = resolve_procfs_path_for_child(path, procfs_context)
        .map_err(|e| OpenPathError::internal(e.to_string()))?;

    validate_procfs_access(&resolved_path, procfs_context)?;

    // Canonicalize to resolve symlinks before opening. This ensures
    // we check and open the real target, not a symlink alias.
    let canonical = std::fs::canonicalize(&resolved_path).map_err(|e| {
        OpenPathError::io(
            format!(
                "Failed to canonicalize {} for access: {}",
                path.display(),
                e
            ),
            &e,
        )
    })?;

    if let Some(protected_root) =
        crate::protected_paths::overlapping_protected_root(&canonical, false, protected_roots)
    {
        return Err(OpenPathError::policy_blocked(format!(
            "Path {} resolves to {} which overlaps protected nono state root '{}'",
            path.display(),
            canonical.display(),
            protected_root.display(),
        )));
    }

    let file = open_canonical_path_no_symlinks(&canonical, access).map_err(|e| {
        OpenPathError::io(
            format!(
                "Failed to open {} for {:?} access: {}",
                canonical.display(),
                access,
                e
            ),
            &e,
        )
    })?;

    // TOCTOU re-verification: if this file was trust-verified, re-compute the
    // digest from the opened fd and compare against the verification-time digest.
    // This closes the window between check_path() (which reads the file by path)
    // and open (which opens a potentially different file if an attacker performed
    // an atomic rename between the two operations).
    if let Some(expected_digest) = trust_digest {
        use sha2::Digest as _;
        use std::io::{Read, Seek};
        let mut hasher = sha2::Sha256::new();
        let mut buf = [0u8; 8192];
        loop {
            let n = (&file).read(&mut buf).map_err(|e| {
                OpenPathError::io(
                    format!(
                        "Failed to read {} for digest re-check: {}",
                        canonical.display(),
                        e,
                    ),
                    &e,
                )
            })?;
            if n == 0 {
                break;
            }
            hasher.update(&buf[..n]);
        }
        let hash = hasher.finalize();
        let actual_digest: String = hash
            .iter()
            .flat_map(|b| {
                [
                    char::from_digit((u32::from(*b) >> 4) & 0xF, 16).unwrap_or('0'),
                    char::from_digit(u32::from(*b) & 0xF, 16).unwrap_or('0'),
                ]
            })
            .collect();
        if actual_digest != expected_digest {
            return Err(OpenPathError::policy_blocked(format!(
                "Instruction file {} was modified between trust verification and open \
                 (expected digest {}, got {}). Possible TOCTOU attack.",
                path.display(),
                expected_digest,
                actual_digest,
            )));
        }
        // Seek back to start so the child reads from the beginning
        (&file).seek(std::io::SeekFrom::Start(0)).map_err(|e| {
            OpenPathError::io(
                format!(
                    "Failed to seek {} after digest re-check: {}",
                    canonical.display(),
                    e,
                ),
                &e,
            )
        })?;
    }

    Ok(file)
}

/// Open a canonical absolute path by traversing path components using `openat`.
///
/// Every component is opened with `O_NOFOLLOW` to prevent symlink substitution
/// between canonicalization and open time (TOCTOU).
fn open_canonical_path_no_symlinks(
    canonical: &std::path::Path,
    access: &nono::AccessMode,
) -> std::io::Result<std::fs::File> {
    use std::os::unix::ffi::OsStrExt;

    if !canonical.is_absolute() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "canonical path must be absolute",
        ));
    }

    let components: Vec<_> = canonical
        .components()
        .filter_map(|c| match c {
            std::path::Component::Normal(part) => Some(part),
            _ => None,
        })
        .collect();

    if components.is_empty() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "cannot open root path",
        ));
    }

    // Start resolution from the real root directory.
    let root = CString::new("/")
        .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidInput, "invalid path"))?;
    let root_fd = unsafe {
        libc::open(
            root.as_ptr(),
            libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC,
        )
    };
    if root_fd < 0 {
        return Err(std::io::Error::last_os_error());
    }
    let mut dir_fd = unsafe { OwnedFd::from_raw_fd(root_fd) };

    for part in &components[..components.len() - 1] {
        let c_part = CString::new(part.as_bytes())
            .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidInput, "invalid path"))?;
        let next_fd = unsafe {
            libc::openat(
                dir_fd.as_raw_fd(),
                c_part.as_ptr(),
                libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
            )
        };
        if next_fd < 0 {
            return Err(std::io::Error::last_os_error());
        }
        dir_fd = unsafe { OwnedFd::from_raw_fd(next_fd) };
    }

    let flags = match access {
        nono::AccessMode::Read => libc::O_RDONLY,
        nono::AccessMode::Write => libc::O_WRONLY,
        nono::AccessMode::ReadWrite => libc::O_RDWR,
    } | libc::O_NOFOLLOW
        | libc::O_CLOEXEC;

    let leaf = CString::new(components[components.len() - 1].as_bytes())
        .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidInput, "invalid path"))?;
    let file_fd = unsafe { libc::openat(dir_fd.as_raw_fd(), leaf.as_ptr(), flags) };
    if file_fd < 0 {
        return Err(std::io::Error::last_os_error());
    }

    let file_fd = unsafe { OwnedFd::from_raw_fd(file_fd) };
    Ok(std::fs::File::from(file_fd))
}

#[cfg(test)]
mod tests {
    use super::*;
    use nix::sys::termios::{
        ControlFlags, InputFlags, LocalFlags, OutputFlags, SpecialCharacterIndices,
    };

    #[cfg(target_os = "linux")]
    #[test]
    fn test_linux_child_requires_dumpable_only_for_seccomp_driven_features() {
        assert!(!linux_child_requires_dumpable(false, false));
        assert!(linux_child_requires_dumpable(true, false));
        assert!(linux_child_requires_dumpable(false, true));
        assert!(linux_child_requires_dumpable(true, true));
    }

    #[test]
    fn test_exec_strategy_default_is_supervised() {
        assert_eq!(ExecStrategy::default(), ExecStrategy::Supervised);
    }

    #[test]
    fn test_configure_startup_prompt_termios_restores_cooked_input() {
        let mut termios = unsafe { std::mem::zeroed::<nix::sys::termios::Termios>() };
        termios.input_flags = InputFlags::IGNBRK | InputFlags::INLCR | InputFlags::IGNCR;
        termios.output_flags = OutputFlags::empty();
        termios.local_flags = LocalFlags::empty();
        termios.control_flags = ControlFlags::CSIZE | ControlFlags::PARENB;
        termios.control_chars[SpecialCharacterIndices::VMIN as usize] = 0;
        termios.control_chars[SpecialCharacterIndices::VTIME as usize] = 9;

        crate::profile_save_runtime::configure_prompt_termios(&mut termios);

        assert!(termios
            .input_flags
            .contains(InputFlags::ICRNL | InputFlags::IXON));
        assert!(!termios
            .input_flags
            .intersects(InputFlags::IGNBRK | InputFlags::INLCR | InputFlags::IGNCR));
        assert!(termios.output_flags.contains(OutputFlags::OPOST));
        assert!(termios.local_flags.contains(
            LocalFlags::ECHO
                | LocalFlags::ECHONL
                | LocalFlags::ICANON
                | LocalFlags::ISIG
                | LocalFlags::IEXTEN
        ));
        assert!(!termios.control_flags.contains(ControlFlags::PARENB));
        assert!(termios.control_flags.contains(ControlFlags::CS8));
        assert_eq!(
            termios.control_chars[SpecialCharacterIndices::VMIN as usize],
            1
        );
        assert_eq!(
            termios.control_chars[SpecialCharacterIndices::VTIME as usize],
            0
        );
    }

    #[test]
    fn test_exec_strategy_variants() {
        assert_ne!(ExecStrategy::Direct, ExecStrategy::Supervised);
    }

    #[test]
    fn test_dangerous_env_vars_linker_injection() {
        assert!(is_dangerous_env_var("LD_PRELOAD"));
        assert!(is_dangerous_env_var("LD_LIBRARY_PATH"));
        assert!(is_dangerous_env_var("LD_AUDIT"));
        assert!(is_dangerous_env_var("DYLD_INSERT_LIBRARIES"));
        assert!(is_dangerous_env_var("DYLD_LIBRARY_PATH"));
        assert!(is_dangerous_env_var("DYLD_FRAMEWORK_PATH"));
    }

    #[test]
    fn test_dangerous_env_vars_shell_injection() {
        assert!(is_dangerous_env_var("BASH_ENV"));
        assert!(is_dangerous_env_var("ENV"));
        assert!(is_dangerous_env_var("CDPATH"));
        assert!(is_dangerous_env_var("GLOBIGNORE"));
        assert!(is_dangerous_env_var("BASH_FUNC_foo%%"));
        assert!(is_dangerous_env_var("PROMPT_COMMAND"));
    }

    #[test]
    fn test_dangerous_env_vars_interpreter_injection() {
        assert!(is_dangerous_env_var("PYTHONSTARTUP"));
        assert!(is_dangerous_env_var("PYTHONPATH"));
        assert!(is_dangerous_env_var("NODE_OPTIONS"));
        assert!(is_dangerous_env_var("NODE_PATH"));
        assert!(is_dangerous_env_var("PERL5OPT"));
        assert!(is_dangerous_env_var("PERL5LIB"));
        assert!(is_dangerous_env_var("RUBYOPT"));
        assert!(is_dangerous_env_var("RUBYLIB"));
        assert!(is_dangerous_env_var("GEM_PATH"));
        assert!(is_dangerous_env_var("GEM_HOME"));
    }

    #[test]
    fn test_dangerous_env_vars_jvm_dotnet_go() {
        assert!(is_dangerous_env_var("JAVA_TOOL_OPTIONS"));
        assert!(is_dangerous_env_var("_JAVA_OPTIONS"));
        assert!(is_dangerous_env_var("DOTNET_STARTUP_HOOKS"));
        assert!(is_dangerous_env_var("GOFLAGS"));
    }

    #[test]
    fn test_dangerous_env_vars_shell_ifs() {
        assert!(is_dangerous_env_var("IFS"));
    }

    #[test]
    fn test_exec_strategy_supervised_selection() {
        let strategy = ExecStrategy::Supervised;
        assert_eq!(strategy, ExecStrategy::Supervised);
        assert_ne!(ExecStrategy::Supervised, ExecStrategy::Direct);
    }

    #[test]
    fn test_safe_env_vars_allowed() {
        assert!(!is_dangerous_env_var("HOME"));
        assert!(!is_dangerous_env_var("PATH"));
        assert!(!is_dangerous_env_var("SHELL"));
        assert!(!is_dangerous_env_var("TERM"));
        assert!(!is_dangerous_env_var("LANG"));
        assert!(!is_dangerous_env_var("USER"));
        assert!(!is_dangerous_env_var("TMPDIR"));
        assert!(!is_dangerous_env_var("EDITOR"));
        assert!(!is_dangerous_env_var("XDG_CONFIG_HOME"));
        assert!(!is_dangerous_env_var("CARGO_HOME"));
        assert!(!is_dangerous_env_var("RUST_LOG"));
        assert!(!is_dangerous_env_var("SSH_AUTH_SOCK"));
    }

    #[test]
    fn test_record_denial_is_capped() {
        let mut denials = Vec::new();
        for _ in 0..(MAX_DENIAL_RECORDS + 10) {
            record_denial(
                &mut denials,
                DenialRecord {
                    path: "/tmp/test".into(),
                    access: nono::AccessMode::Read,
                    reason: DenialReason::PolicyBlocked,
                },
            );
        }
        assert_eq!(denials.len(), MAX_DENIAL_RECORDS);
    }

    #[test]
    fn test_resolve_procfs_self_for_child() {
        let path = resolve_procfs_path_for_child(
            Path::new("/proc/self/maps"),
            Some(ProcfsAccessContext::new(4242, Some(4343))),
        );
        assert_eq!(path.ok(), Some(PathBuf::from("/proc/4242/maps")));
    }

    #[test]
    fn test_resolve_procfs_thread_self_for_child() {
        let path = resolve_procfs_path_for_child(
            Path::new("/proc/thread-self/maps"),
            Some(ProcfsAccessContext::new(4242, Some(4343))),
        );
        assert_eq!(path.ok(), Some(PathBuf::from("/proc/4242/task/4343/maps")));
    }

    #[test]
    fn test_resolve_procfs_thread_self_requires_thread_context() {
        let result = resolve_procfs_path_for_child(
            Path::new("/proc/thread-self/maps"),
            Some(ProcfsAccessContext::new(4242, None)),
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_procfs_access_allows_child_sensitive_proc_path() {
        let result = validate_procfs_access(
            Path::new("/proc/4242/maps"),
            Some(ProcfsAccessContext::new(4242, Some(4343))),
        );
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_procfs_access_blocks_foreign_sensitive_proc_path() {
        let result = validate_procfs_access(
            Path::new("/proc/1/maps"),
            Some(ProcfsAccessContext::new(4242, Some(4343))),
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_procfs_access_allows_child_task_sensitive_proc_path() {
        let result = validate_procfs_access(
            Path::new("/proc/4242/task/9999/maps"),
            Some(ProcfsAccessContext::new(4242, Some(4343))),
        );
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_procfs_access_blocks_foreign_proc_fd_path() {
        let result = validate_procfs_access(
            Path::new("/proc/1/fd/3"),
            Some(ProcfsAccessContext::new(4242, Some(4343))),
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_procfs_access_blocks_child_proc_fd_path() {
        let result = validate_procfs_access(
            Path::new("/proc/4242/fd/3"),
            Some(ProcfsAccessContext::new(4242, Some(4343))),
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_procfs_access_blocks_foreign_proc_cwd_path_before_canonicalization() {
        let result = validate_procfs_access(
            Path::new("/proc/1/cwd"),
            Some(ProcfsAccessContext::new(4242, Some(4343))),
        );
        assert!(result.is_err());
    }

    // --- Grandchild procfs regression tests (issue #602) ---
    //
    // When bun is a grandchild (nono→sh→bun), notifying_tgid=bun's PID (e.g. 1001),
    // not the direct child sh's PID (e.g. 1000). These tests verify the fix uses
    // the correct PID for /proc/self resolution and access validation.

    #[test]
    fn test_resolve_procfs_self_for_grandchild_tgid() {
        // After the fix, process_pid=notifying_tgid=1001 (bun).
        // /proc/self/maps must resolve to /proc/1001/maps, not /proc/1000/maps.
        let path = resolve_procfs_path_for_child(
            Path::new("/proc/self/maps"),
            Some(ProcfsAccessContext::new(1001, Some(1001))),
        );
        assert_eq!(path.ok(), Some(PathBuf::from("/proc/1001/maps")));
    }

    #[test]
    fn test_validate_procfs_access_allows_grandchild_own_path() {
        // notifying_tgid=1001 (bun): accessing /proc/1001/maps is allowed.
        let result = validate_procfs_access(
            Path::new("/proc/1001/maps"),
            Some(ProcfsAccessContext::new(1001, Some(1001))),
        );
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_procfs_access_blocks_grandchild_accessing_sibling() {
        // notifying_tgid=1001 (bun): accessing /proc/1000/maps (sh's maps) is blocked.
        // This verifies the fix does NOT allow cross-process procfs reads.
        let result = validate_procfs_access(
            Path::new("/proc/1000/maps"),
            Some(ProcfsAccessContext::new(1001, Some(1001))),
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_resolve_procfs_self_wrong_pid_demonstrates_bug() {
        // Demonstrates the pre-fix bug: if process_pid=1000 (sh) but the requesting
        // process is bun (1001), /proc/self/maps incorrectly resolves to /proc/1000/maps.
        // After the fix, process_pid is always notifying_tgid, so this construction
        // would never be used for bun's request.
        let path = resolve_procfs_path_for_child(
            Path::new("/proc/self/maps"),
            Some(ProcfsAccessContext::new(1000, Some(1001))), // broken: sh's PID for bun's request
        );
        // This produces the wrong path (sh's maps instead of bun's maps).
        assert_eq!(path.ok(), Some(PathBuf::from("/proc/1000/maps")));
    }

    /// Verify that the supervisor loop runs and exits cleanly without a PTY relay.
    ///
    /// This tests the `capability_elevation = false` code path where no PTY is
    /// allocated but the supervisor loop must still service the IPC socket for
    /// trust interception. The child fork closes its socket end and exits,
    /// causing the loop to see POLLHUP and return.
    #[test]
    fn test_supervisor_loop_runs_without_pty_relay() {
        use std::os::unix::net::UnixStream;

        struct DenyAll;
        impl ApprovalBackend for DenyAll {
            fn request_capability(
                &self,
                _req: &nono::supervisor::CapabilityRequest,
            ) -> nono::Result<ApprovalDecision> {
                Ok(ApprovalDecision::Denied {
                    reason: "test".to_string(),
                })
            }
            fn backend_name(&self) -> &str {
                "deny-all-test"
            }
        }

        let (parent_stream, child_stream) = UnixStream::pair()
            .map_err(|e| format!("socketpair: {e}"))
            .expect("socketpair failed in test");

        let backend = DenyAll;
        let sup_cfg = SupervisorConfig {
            protected_roots: &[],
            approval_backend: &backend,
            session_id: "test-session",
            attach_initial_client: false,
            detach_sequence: None,
            open_url_origins: &[],
            open_url_allow_localhost: false,
            audit_recorder: None,
            allow_launch_services_active: false,
            #[cfg(target_os = "linux")]
            proxy_port: 0,
            #[cfg(target_os = "linux")]
            proxy_bind_ports: Vec::new(),
        };

        // Fork a child that closes its socket end and exits immediately.
        // SAFETY: We are in a test; the child does minimal work and _exit()s.
        match unsafe { fork() } {
            Ok(ForkResult::Child) => {
                drop(child_stream);
                drop(parent_stream);
                unsafe { libc::_exit(42) };
            }
            Ok(ForkResult::Parent { child }) => {
                drop(child_stream);
                let mut sock = SupervisorSocket::from_stream(parent_stream);

                // Run supervisor loop with relay: None (the capability_elevation=false path).
                // It should poll the socket, see POLLHUP when child exits, and return.
                #[cfg(target_os = "linux")]
                let result = run_supervisor_loop(
                    child,
                    &mut sock,
                    &sup_cfg,
                    None, // no startup timeout
                    None, // no seccomp
                    None, // no proxy seccomp
                    &[],  // no initial caps
                    None, // no trust interceptor
                    None, // no PTY relay — this is what we're testing
                );

                #[cfg(not(target_os = "linux"))]
                let result = run_supervisor_loop(
                    child, &mut sock, &sup_cfg, None, // no startup timeout
                    None, // no trust interceptor
                    None, // no PTY relay
                );

                let (status, denials) = result
                    .map_err(|e| format!("supervisor loop: {e}"))
                    .expect("supervisor loop failed");
                assert!(denials.is_empty(), "no denials expected");

                // Child exited with code 42
                match status {
                    WaitStatus::Exited(_, code) => assert_eq!(code, 42),
                    other => panic!("unexpected wait status: {other:?}"),
                }
            }
            Err(e) => panic!("fork failed: {e}"),
        }
    }

    /// Verify that ProxyOnly mode on V4+ kernels does NOT deadlock.
    ///
    /// On Landlock V4+ kernels, ProxyOnly is handled by Landlock natively.
    /// The seccomp_proxy_fallback flag should be false, so the parent must
    /// NOT attempt to recv a proxy notify fd. This test verifies the
    /// supervisor loop starts and exits cleanly with ProxyOnly caps but
    /// no proxy seccomp filter.
    #[cfg(target_os = "linux")]
    #[test]
    fn test_supervisor_loop_proxy_only_v4_no_deadlock() {
        use std::os::unix::net::UnixStream;

        struct DenyAll;
        impl ApprovalBackend for DenyAll {
            fn request_capability(
                &self,
                _req: &nono::supervisor::CapabilityRequest,
            ) -> nono::Result<ApprovalDecision> {
                Ok(ApprovalDecision::Denied {
                    reason: "test".to_string(),
                })
            }
            fn backend_name(&self) -> &str {
                "deny-all-test"
            }
        }

        let (parent_stream, child_stream) = UnixStream::pair()
            .map_err(|e| format!("socketpair: {e}"))
            .expect("socketpair failed in test");

        let backend = DenyAll;
        // ProxyOnly mode with proxy_port set, but seccomp_proxy_fallback is false
        // (simulating V4+ where Landlock handles networking).
        let sup_cfg = SupervisorConfig {
            protected_roots: &[],
            approval_backend: &backend,
            session_id: "test-proxy-v4",
            attach_initial_client: false,
            detach_sequence: None,
            open_url_origins: &[],
            open_url_allow_localhost: false,
            audit_recorder: None,
            allow_launch_services_active: false,
            #[cfg(target_os = "linux")]
            proxy_port: 8080,
            #[cfg(target_os = "linux")]
            proxy_bind_ports: Vec::new(),
        };

        match unsafe { fork() } {
            Ok(ForkResult::Child) => {
                // Child: close socket and exit. Does NOT send a proxy notify fd.
                drop(child_stream);
                drop(parent_stream);
                unsafe { libc::_exit(0) };
            }
            Ok(ForkResult::Parent { child }) => {
                drop(child_stream);
                let mut sock = SupervisorSocket::from_stream(parent_stream);

                // Run supervisor loop with NO proxy seccomp fd.
                // If the bug from before were present (unconditional recv_fd),
                // this would deadlock because the child never sends a second fd.
                let result = run_supervisor_loop(
                    child,
                    &mut sock,
                    &sup_cfg,
                    None, // no startup timeout
                    None, // no openat seccomp
                    None, // no proxy seccomp — V4+ Landlock handles it
                    &[],  // no initial caps
                    None, // no trust interceptor
                    None, // no PTY relay
                );

                let (status, denials) = result
                    .map_err(|e| format!("supervisor loop: {e}"))
                    .expect("supervisor loop should not deadlock");
                assert!(denials.is_empty());

                match status {
                    WaitStatus::Exited(_, code) => assert_eq!(code, 0),
                    other => panic!("unexpected wait status: {other:?}"),
                }
            }
            Err(e) => panic!("fork failed: {e}"),
        }
    }

    struct TestDenyBackend;
    impl ApprovalBackend for TestDenyBackend {
        fn request_capability(
            &self,
            _req: &nono::supervisor::CapabilityRequest,
        ) -> nono::Result<ApprovalDecision> {
            Ok(ApprovalDecision::Denied {
                reason: "test".to_string(),
            })
        }
        fn backend_name(&self) -> &str {
            "test-deny"
        }
    }

    #[test]
    fn test_validate_url_allowed_origin() {
        let backend = TestDenyBackend;
        let origins = vec!["https://claude.ai".to_string()];
        let config = SupervisorConfig {
            protected_roots: &[],
            approval_backend: &backend,
            session_id: "test",
            attach_initial_client: false,
            detach_sequence: None,
            open_url_origins: &origins,
            open_url_allow_localhost: false,
            audit_recorder: None,
            allow_launch_services_active: false,
            #[cfg(target_os = "linux")]
            proxy_port: 0,
            #[cfg(target_os = "linux")]
            proxy_bind_ports: Vec::new(),
        };

        // Allowed origin: validation passes
        let result = validate_url("https://claude.ai/oauth/authorize?state=xyz", &config);
        assert!(result.is_ok(), "Expected validation to pass: {result:?}");

        // Disallowed origin: must fail validation
        let result = validate_url("https://evil.example.com/phishing", &config);
        assert!(result.is_err());
        assert!(result
            .as_ref()
            .err()
            .map(|e| e.contains("not in the profile"))
            .unwrap_or(false));
    }

    #[test]
    fn test_validate_url_blocks_non_https() {
        let backend = TestDenyBackend;
        let config = SupervisorConfig {
            protected_roots: &[],
            approval_backend: &backend,
            session_id: "test",
            attach_initial_client: false,
            detach_sequence: None,
            open_url_origins: &[],
            open_url_allow_localhost: false,
            audit_recorder: None,
            allow_launch_services_active: false,
            #[cfg(target_os = "linux")]
            proxy_port: 0,
            #[cfg(target_os = "linux")]
            proxy_bind_ports: Vec::new(),
        };

        let result = validate_url("file:///etc/passwd", &config);
        assert!(result.is_err());
        assert!(result
            .as_ref()
            .err()
            .map(|e| e.contains("Only https://"))
            .unwrap_or(false));

        let result = validate_url("javascript:alert(1)", &config);
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_url_localhost() {
        let backend = TestDenyBackend;
        let config_allow = SupervisorConfig {
            protected_roots: &[],
            approval_backend: &backend,
            session_id: "test",
            attach_initial_client: false,
            detach_sequence: None,
            open_url_origins: &[],
            open_url_allow_localhost: true,
            audit_recorder: None,
            allow_launch_services_active: false,
            #[cfg(target_os = "linux")]
            proxy_port: 0,
            #[cfg(target_os = "linux")]
            proxy_bind_ports: Vec::new(),
        };
        let config_deny = SupervisorConfig {
            protected_roots: &[],
            approval_backend: &backend,
            session_id: "test",
            attach_initial_client: false,
            detach_sequence: None,
            open_url_origins: &[],
            open_url_allow_localhost: false,
            audit_recorder: None,
            allow_launch_services_active: false,
            #[cfg(target_os = "linux")]
            proxy_port: 0,
            #[cfg(target_os = "linux")]
            proxy_bind_ports: Vec::new(),
        };

        // Localhost denied when not allowed
        let result = validate_url("http://localhost:8080/callback", &config_deny);
        assert!(result.is_err());
        assert!(result
            .as_ref()
            .err()
            .map(|e| e.contains("not allowed"))
            .unwrap_or(false));

        // Localhost allowed when configured
        let result = validate_url("http://localhost:8080/callback", &config_allow);
        assert!(
            result.is_ok(),
            "Expected localhost validation to pass: {result:?}"
        );
    }

    #[test]
    fn test_validate_url_max_length() {
        let backend = TestDenyBackend;
        let config = SupervisorConfig {
            protected_roots: &[],
            approval_backend: &backend,
            session_id: "test",
            attach_initial_client: false,
            detach_sequence: None,
            open_url_origins: &[],
            open_url_allow_localhost: false,
            audit_recorder: None,
            allow_launch_services_active: false,
            #[cfg(target_os = "linux")]
            proxy_port: 0,
            #[cfg(target_os = "linux")]
            proxy_bind_ports: Vec::new(),
        };

        let long_url = format!("https://example.com/{}", "a".repeat(MAX_URL_LENGTH));
        let result = validate_url(&long_url, &config);
        assert!(result.is_err());
        assert!(result
            .as_ref()
            .err()
            .map(|e| e.contains("maximum length"))
            .unwrap_or(false));
    }

    #[test]
    fn test_shell_quote_simple_path() {
        assert_eq!(shell_quote("/usr/bin/nono"), "/usr/bin/nono");
    }

    #[test]
    fn test_shell_quote_path_with_spaces() {
        assert_eq!(shell_quote("/opt/my app/nono"), "'/opt/my app/nono'");
    }

    #[test]
    fn test_shell_quote_path_with_single_quote() {
        assert_eq!(shell_quote("/opt/it's/nono"), "'/opt/it'\\''s/nono'");
    }

    #[test]
    fn test_shell_quote_empty_string() {
        assert_eq!(shell_quote(""), "''");
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn test_create_linux_browser_shim_installs_launcher_and_helper() {
        let exe = std::env::current_exe().expect("current_exe");
        let shim = create_linux_browser_shim(&exe, 42).expect("create shim");

        assert!(shim.launcher.exists(), "browser launcher should exist");
        assert_eq!(
            shim.launcher.parent(),
            Some(shim.dir.path()),
            "launcher should live inside shim dir"
        );

        let script = std::fs::read_to_string(&shim.launcher).expect("read shim");
        assert!(
            script.contains("nono-open-url-helper"),
            "launcher should reference the copied helper"
        );
        assert!(
            script.contains("NONO_SUPERVISOR_FD=42"),
            "launcher should export the supervisor fd only for helper execution"
        );
        assert!(
            script.contains("open-url-helper \"$@\""),
            "launcher should exec the copied helper"
        );
    }

    #[test]
    fn test_clear_close_on_exec_clears_flag() {
        use std::os::fd::AsRawFd;
        use std::os::unix::net::UnixStream;

        let (a, _b) = UnixStream::pair().expect("socketpair");
        let fd = a.as_raw_fd();

        let before = unsafe { libc::fcntl(fd, libc::F_GETFD) };
        assert!(before >= 0, "F_GETFD before failed");
        assert_ne!(before & libc::FD_CLOEXEC, 0, "fd should start CLOEXEC");

        clear_close_on_exec(fd).expect("clear cloexec");

        let after = unsafe { libc::fcntl(fd, libc::F_GETFD) };
        assert!(after >= 0, "F_GETFD after failed");
        assert_eq!(after & libc::FD_CLOEXEC, 0, "fd should not be CLOEXEC");
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn test_create_open_shim_installs_helper_in_shim_dir() {
        let exe = std::env::current_exe().expect("current_exe");
        let shim = create_open_shim(&exe, 42).expect("create shim");

        assert!(shim.launcher.exists(), "open shim should exist");

        let script = std::fs::read_to_string(&shim.launcher).expect("read shim");
        assert!(
            script.contains("for arg in \"$@\"; do"),
            "shim should scan all arguments for a URL"
        );
        assert!(
            script.contains("nono-open-url-helper"),
            "shim should reference the copied helper"
        );
        assert!(
            script.contains("NONO_SUPERVISOR_FD=42"),
            "shim should export the supervisor fd only for helper execution"
        );
        assert!(
            script.contains("open-url-helper \"$url_arg\""),
            "shim should exec the copied helper"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn test_should_install_macos_open_shim_respects_launch_services_flag() {
        struct TestBackend;
        impl ApprovalBackend for TestBackend {
            fn request_capability(
                &self,
                _req: &nono::supervisor::CapabilityRequest,
            ) -> nono::Result<ApprovalDecision> {
                Ok(ApprovalDecision::Denied {
                    reason: "test".to_string(),
                })
            }
            fn backend_name(&self) -> &str {
                "test"
            }
        }

        let backend = TestBackend;
        let config = SupervisorConfig {
            protected_roots: &[],
            approval_backend: &backend,
            session_id: "test",
            attach_initial_client: false,
            detach_sequence: None,
            open_url_origins: &[],
            open_url_allow_localhost: false,
            audit_recorder: None,
            allow_launch_services_active: true,
            #[cfg(target_os = "linux")]
            proxy_port: 0,
            #[cfg(target_os = "linux")]
            proxy_bind_ports: Vec::new(),
        };

        assert!(
            !should_install_macos_open_shim(Some(&config)),
            "launch services sessions should skip the macOS open shim"
        );
        assert!(
            !should_install_macos_open_shim(None),
            "without supervisor config, the helper should not install the macOS open shim"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn test_open_shim_drop_cleans_up_directory() {
        let exe = std::env::current_exe().expect("current_exe");
        let shim = create_open_shim(&exe, 42).expect("create shim");
        let dir = shim.dir.path().to_path_buf();

        assert!(dir.exists(), "shim dir should exist before drop");
        drop(shim);
        assert!(!dir.exists(), "shim dir should be removed on drop");
    }
}