dracon-system 0.112.45

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

#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;

/// Serializes the "create an executable fixture, then exec it" window
/// across the test binary's threads. ADDED 2026-09-30.
///
/// WHY THIS EXISTS (root cause of the long-standing ETXTBSY flakes in
/// `renice_process_with_bin_reports_success_and_failure`,
/// `nix_cleanup_apply_preserves_configured_profile_generations`,
/// `restore_runtime_adjustments_composes_overlapping_nice_limiters`,
/// `restore_runtime_adjustments_preserves_current_pid_incarnation`,
/// `restore_runtime_adjustments_restores_renice_and_oom` and
/// `restore_runtime_adjustments_retains_failed_cpu_cap`):
///
/// `execve()` of a file that this process created milliseconds earlier
/// can fail with `ETXTBSY` ("Text file busy", os error 26). The kernel
/// refuses to execute an inode it still considers write-busy, and the
/// window in which a just-written ext4 inode stays in that state is
/// long enough for a sibling test thread to collide with it. `libtest`
/// runs tests in parallel threads inside one process, so several
/// fixtures are being written and exec'd concurrently by construction.
///
/// The contended resource is the fixture inode of THIS process, and
/// that is what fixes the scope of the remedy. Discriminators measured
/// with a standalone 8-thread reproducer containing none of this crate's
/// code (write -> chmod -> fork -> execv, unique paths, 4800-6400 execs
/// per configuration):
///
///   | configuration                          | ETXTBSY |
///   |----------------------------------------|---------|
///   | 1 thread, no contention                |       0 |
///   | 4 threads, nothing serialized          |  27-155 |
///   | 8 threads, nothing serialized          |      25 |
///   | 8 threads, whole create->exec serialized|       0 |
///   | 8 threads, ONLY the write serialized   |       5 |
///   | 8 threads, ONLY the exec serialized    |       0 |
///   | 8 threads, per-thread interpreter copy  |      53 |
///   | 8 threads, path reuse (O_TRUNC)        |     155 |
///   | 8 threads, fsync(fd) before close      |    3033 |
///   | 8 threads + 4 external /bin/sh hammer
///     processes, whole window serialized    |       0 |
///
/// Read together: concurrent *execs* are required, serializing the
/// writes alone does not help, and a private interpreter copy does not
/// help — so it is neither a shared `/bin/sh` inode nor inode reuse.
/// The last row is why this is a process-local lock: 24,000 external
/// `/bin/sh` execs running against a serialized fixture test produced
/// zero failures, so a test binary running twice at once, or any other
/// process on the host, cannot reintroduce the flake.
///
/// THE LOCK MUST SPAN THE WRITE *AND* THE EXEC. In the C sketch
/// serializing only the exec half looks sufficient, but the Rust harness
/// disagrees: the tripwire below was first written that way and still
/// failed (`left: 1`) twice in ~89 suite runs. The broader window is
/// therefore the invariant: with the guard held across
/// `write_test_script` and the exec, the tripwire gave 140 consecutive
/// clean runs (112,000 create->exec cycles), while removing the guard
/// from the same test was detected in 20/20 runs. That statistical
/// tripwire has since been replaced by the deterministic guards named
/// below, for the reason given under "SERIALIZATION IS NECESSARY BUT NOT
/// SUFFICIENT".
///
/// SERIALIZATION IS NECESSARY BUT NOT SUFFICIENT UNDER LOAD. With the
/// lock in place the flake still appeared in 3 of 48 full-suite runs
/// (all inside the test that measures the raw hazard, 1-2 ETXTBSY per 800
/// cycles) while this host
/// was running at load average 87: with the process descheduled between
/// the write and the exec, a serialized create->exec can still land
/// inside the busy window. So the lock removes the in-process collision
/// — the reported root cause — and `settle_fixture` closes what is left.
/// Settling is not a retry of an assertion: it establishes a real
/// invariant, namely that the fixture has been exec'd at least once, and
/// a fixture that has been exec'd once is provably no longer write-busy
/// (re-exec'ing a pre-written script never failed, even from many
/// threads at once). `write_test_script` therefore settles every fixture
/// it creates, so the tests' own execs always run against a settled
/// inode no matter how busy the machine is.
///
/// Re-verify any of the above without this crate, in seconds:
/// `cc -O2 -pthread -o repro scripts/etxtbsy-repro.c && ./repro 600 1`
/// (0 failures) versus `./repro 600 8` (dozens of ETXTBSY). The shipped
/// copy of that program documents every variant measured here and sets
/// `O_CLOEXEC` on its fixtures because `std::fs` always does; its numbers
/// are a mechanism sketch, and the authoritative measurements are the
/// Rust ones in the tripwire below.
///
/// INVARIANT: any test that writes an executable fixture and then execs
/// it must hold `fixture_exec_guard()` from before the first
/// `write_test_script` until after the last exec — the write must be
/// inside the critical section, not just the exec — and must obtain the
/// fixture through `write_test_script`, which settles it.
/// `fixture_writing_tests_hold_the_fixture_exec_guard` enforces the first
/// half on every fixture-writing test in this module;
/// `settle_fixture_probes_without_side_effects_and_fails_loudly` and
/// `settled_fixture_survives_parallel_reexec` cover the second. All three
/// are deterministic, because an assertion of the form "zero ETXTBSY" on
/// the raw hazard is statistical and host load alone breaks it. `libtest`
/// prints captured
/// stdout only for failing tests, which is why the earlier
/// instrumentation also reported `Is a directory (os error 21)` and
/// `process identity unavailable` — those are by-design fixtures in
/// `restore_runtime_adjustments_restores_renice_and_oom` (a missing
/// proc root, a `renice` that exits 1, and a directory standing in for
/// an unwritable `oom_score_adj`), not additional failure modes.
///
/// THE PRODUCTION CODE IS NOT INVOLVED and needs no change: it only ever
/// execs resolved system binaries (`resolve_bin_strict("renice")`,
/// `nix-env`, `systemctl`, `ps`), which the process never writes. That
/// is also why "400 concurrent /bin/sh spawns succeed" never disproved
/// this: spawning a pre-existing binary concurrently is safe; it is a
/// write immediately before the exec of that same file that opens the
/// window.
#[cfg(unix)]
static FIXTURE_EXEC_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

/// Hold the fixture-exec lock for the whole create->exec window.
///
/// Poisoning is recovered rather than propagated: one panicking fixture
/// test must not cascade into every other test that needs the lock.
#[cfg(unix)]
fn fixture_exec_guard() -> std::sync::MutexGuard<'static, ()> {
    FIXTURE_EXEC_LOCK
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
}

#[test]
fn defaults_are_expected() {
    assert_eq!(default_min_size_mb(), 512);
    assert_eq!(default_kinds(), "rust-build,node-deps,build-output,cache");
}

#[test]
fn nix_delete_generations_arg_means_keep_last_n() {
    assert_eq!(nix_delete_generations_arg(5), Some("+5".to_string()));
    assert_eq!(nix_delete_generations_arg(1), Some("+1".to_string()));
    assert_eq!(nix_delete_generations_arg(0), None);
}

#[cfg(unix)]
#[tokio::test]
async fn nix_cleanup_apply_preserves_configured_profile_generations() {
    let _fixture_exec = fixture_exec_guard();
    fn shell_quote(value: &str) -> String {
        format!("'{}'", value.replace('\'', "'\\''"))
    }

    let root = std::env::temp_dir().join(format!(
        "dracon_system_nix_cleanup_test_{}_{}",
        std::process::id(),
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time")
            .as_nanos()
    ));
    fs::create_dir_all(&root).expect("create temp dir");
    let log = root.join("calls.log");
    let quoted_log = shell_quote(log.to_str().expect("log path"));
    let nix_env = root.join("nix-env");
    let nix_gc = root.join("nix-collect-garbage");
    write_test_script(
        &nix_env,
        &format!("echo \"nix-env:$*\" >> {quoted_log}\nexit 0"),
    );
    write_test_script(
        &nix_gc,
        &format!(
            r#"echo "nix-gc:$*" >> {quoted_log}
if [ "$1" = "-d" ]; then
    echo 'would delete retained profile generations' >&2
    exit 99
fi
exit 0"#
        ),
    );

    let result = clean_nix_garbage_with_bins(5, true, &nix_env, &nix_gc)
        .await
        .expect("Nix cleanup should succeed without destructive garbage mode");
    assert_eq!(result, (0, Vec::new()));

    let calls = fs::read_to_string(&log).expect("read command log");
    let lines: Vec<&str> = calls.lines().collect();
    assert_eq!(
        lines.len(),
        3,
        "two profile prunes and one store GC expected"
    );
    assert_eq!(lines[0], "nix-env:--delete-generations +5");
    assert_eq!(
        lines[1],
        "nix-env:--delete-generations +5 -p /nix/var/nix/profiles/default"
    );
    assert_eq!(lines[2], "nix-gc:");
    assert!(
        !lines[2].contains("-d"),
        "apply must not use nix-collect-garbage -d, which discards retained generations"
    );
    let _ = fs::remove_dir_all(&root);
}

#[test]
fn guard_clean_bare_command_selects_all_targets() {
    let cli = Cli::try_parse_from(["dracon-system", "guard", "clean"])
        .expect("bare guard clean should parse");
    let Commands::Guard {
        cmd:
            GuardCommands::Clean {
                all,
                rust,
                trash,
                nix,
                caches,
                node_modules,
                docker,
                ..
            },
    } = cli.cmd
    else {
        panic!("expected guard clean command");
    };
    assert!(
        !all,
        "the bare command should not need an explicit --all flag"
    );

    let targets = resolve_clean_targets(
        all,
        &CleanTargets {
            rust,
            trash,
            nix,
            caches,
            node_modules,
            docker,
        },
    );
    assert!(
        targets.rust
            && targets.trash
            && targets.nix
            && targets.caches
            && targets.node_modules
            && targets.docker,
        "bare guard clean must resolve every cleanup target"
    );
}

#[test]
fn guard_clean_target_flags_remain_selective_and_all_overrides_them() {
    let rust_only = CleanTargets {
        rust: true,
        ..CleanTargets::default()
    };
    let resolved = resolve_clean_targets(false, &rust_only);
    assert!(resolved.rust);
    assert!(!resolved.trash);

    let resolved_all = resolve_clean_targets(true, &rust_only);
    assert!(resolved_all.rust && resolved_all.trash && resolved_all.docker);
}

#[cfg(unix)]
#[tokio::test]
async fn renice_process_with_bin_reports_success_and_failure() {
    let _fixture_exec = fixture_exec_guard();
    let tmp = std::env::temp_dir().join(format!(
        "dracon_system_renice_test_{}_{}",
        std::process::id(),
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time")
            .as_nanos()
    ));
    fs::create_dir_all(&tmp).expect("temp dir");
    let success = tmp.join("renice-success");
    write_test_script(&success, "echo 'ok' >&2\nexit 0");

    let failure = tmp.join("renice-failure");
    write_test_script(&failure, "echo 'permission denied' >&2\nexit 1");

    renice_process_with_bin(&success, 123, 5)
        .await
        .expect("success renice");
    let err = renice_process_with_bin(&failure, 123, 5)
        .await
        .expect_err("failure renice");
    assert!(err.to_string().contains("permission denied"));
    let _ = fs::remove_dir_all(&tmp);
}

#[cfg(unix)]
fn write_process_fixture(
    root: &std::path::Path,
    pid: i32,
    comm: &str,
    starttime: u64,
    oom_score_adj: Option<i32>,
    cgroup: Option<&str>,
) {
    // Mirror the `/proc/self` availability marker used by the production
    // identity check so this fixture can distinguish a gone PID from a
    // missing/unavailable proc tree.
    fs::create_dir_all(root.join("self")).expect("create proc availability fixture");
    let dir = root.join(pid.to_string());
    fs::create_dir_all(&dir).expect("create process fixture");
    fs::write(dir.join("comm"), format!("{comm}\n")).expect("write comm fixture");
    let mut stat_fields = vec!["S".to_string()];
    stat_fields.extend(std::iter::repeat_n("0".to_string(), 18));
    stat_fields.push(starttime.to_string());
    fs::write(
        dir.join("stat"),
        format!("{pid} ({comm}) {}\n", stat_fields.join(" ")),
    )
    .expect("write stat fixture");
    if let Some(adj) = oom_score_adj {
        fs::write(dir.join("oom_score_adj"), format!("{adj}\n")).expect("write oom fixture");
    }
    if let Some(cgroup) = cgroup {
        fs::write(dir.join("cgroup"), cgroup).expect("write cgroup fixture");
    }
}

/// Marker argument used only by `settle_fixture`. No production caller
/// passes it, so a fixture that short-circuits on it is a no-op.
const FIXTURE_SETTLE_ARG: &str = "--dracon-fixture-settle";

/// Prove that `path` is executable *now*.
///
/// `execve` of a file this process just wrote can fail with `ETXTBSY`
/// because the kernel still considers the inode write-busy, and the
/// window survives a millisecond or two of quiet. That transient is
/// indistinguishable from a real test failure, so rather than retrying
/// an assertion this establishes the invariant the tests actually need:
/// *a fixture that has been exec'd once is no longer write-busy.*
/// Measured: re-exec'ing an already-exec'd script is always safe even
/// from many threads at once, so once this probe succeeds every later
/// exec of the same inode is safe too.
///
/// Bounded and loud by design — it is fixture construction, not a
/// swallow: a fixture that cannot be exec'd within the budget is a real
/// bug (missing interpreter, no execute bit) and must fail loudly.
#[cfg(unix)]
fn settle_fixture(path: &std::path::Path) {
    const ETXTBSY: i32 = 26;
    const ATTEMPTS: usize = 40;
    for attempt in 0..ATTEMPTS {
        match std::process::Command::new(path)
            .arg(FIXTURE_SETTLE_ARG)
            .output()
        {
            Ok(_) => return,
            Err(e) if e.raw_os_error() == Some(ETXTBSY) => {
                std::thread::sleep(std::time::Duration::from_millis(1 + (attempt as u64) / 8));
            }
            Err(e) => panic!("fixture {} is not executable: {e}", path.display()),
        }
    }
    panic!(
        "fixture {} stayed exec-busy (ETXTBSY) across {ATTEMPTS} settle attempts",
        path.display()
    );
}

/// Write an executable `#!/bin/sh` fixture without settling it.
///
/// The settle-marker guard is prepended here rather than in each body so
/// that no test can forget it: a fixture invoked with the marker exits
/// immediately, so probing it can never append to the log file (or emit
/// the stderr) that the real invocation is asserted against. Fixtures
/// that must observe a zero-argument call — `nix-collect-garbage` runs
/// without arguments — are covered by the marker too, because the probe
/// always passes exactly one argument.
#[cfg(unix)]
fn write_executable_script(path: &std::path::Path, body: &str) {
    fs::write(
        path,
        format!("#!/bin/sh\ncase \"$1\" in\n{FIXTURE_SETTLE_ARG}) exit 0;;\nesac\n{body}\n"),
    )
    .expect("write test script");
    fs::set_permissions(path, fs::Permissions::from_mode(0o755)).expect("chmod test script");
}

/// Write an executable fixture and settle it before any test can depend
/// on it. Every fixture a test actually asserts on goes through here.
#[cfg(unix)]
fn write_test_script(path: &std::path::Path, body: &str) {
    write_executable_script(path, body);
    settle_fixture(path);
}

/// Guards the settling half of the fix: once `settle_fixture` has
/// exec'd a fixture, re-exec'ing it must be safe no matter how busy the
/// host is.
///
/// This is the pattern every fixture test actually uses, and it is
/// deterministic rather than statistical: settling retries until the
/// inode has been exec'd once, and nothing writes the fixture afterwards,
/// so the busy window cannot reopen. Run on a host at load average 100+,
/// where an *unsettled* serialized create->exec still produced ETXTBSY in
/// 3 of 48 full-suite runs.
#[cfg(unix)]
#[test]
fn settled_fixture_survives_parallel_reexec() {
    const THREADS: usize = 8;
    const REEXECS: usize = 100;
    const ETXTBSY: i32 = 26;

    let etxtbsy = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0));
    let workers: Vec<_> = (0..THREADS)
        .map(|thread| {
            let etxtbsy = std::sync::Arc::clone(&etxtbsy);
            std::thread::spawn(move || {
                let dir = unique_test_home(&format!("settled_{thread}"));
                fs::create_dir_all(&dir).expect("create fixture dir");
                let script = dir.join("fixture");
                {
                    // Settling happens inside the guard; the re-execs below
                    // need no lock because settling already proved the
                    // inode has been exec'd.
                    let _fixture_exec = fixture_exec_guard();
                    write_test_script(&script, "exit 0");
                }
                for _ in 0..REEXECS {
                    if let Err(e) = std::process::Command::new(&script).output() {
                        if e.raw_os_error() == Some(ETXTBSY) {
                            etxtbsy.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                        } else {
                            panic!("settled fixture exec failed unexpectedly: {e}");
                        }
                    }
                }
                let _ = fs::remove_dir_all(&dir);
            })
        })
        .collect();
    for worker in workers {
        worker.join().expect("worker thread must not panic");
    }

    assert_eq!(
        etxtbsy.load(std::sync::atomic::Ordering::SeqCst),
        0,
        "a settled fixture must never come back exec-busy ({} execs across {} threads)",
        THREADS * REEXECS,
        THREADS
    );
}

/// Guards the settling half of the fix, deterministically.
///
/// `settle_fixture` is what makes the fixture execs safe, so what needs
/// guarding is its contract rather than the raw kernel hazard it absorbs:
/// that the probe it runs has no side effects, and that a fixture it
/// cannot exec fails loudly instead of being swallowed. Asserting "zero
/// ETXTBSY" here instead would be a 1-in-20 statistical check that host
/// load alone can break.
#[cfg(unix)]
#[test]
fn settle_fixture_probes_without_side_effects_and_fails_loudly() {
    let dir = unique_test_home("settle_contract");
    fs::create_dir_all(&dir).expect("create fixture dir");

    // (1) The probe must not touch what the test asserts on. A fixture
    // that appends its argv to a log must leave that log untouched by
    // settling, and must still record exactly the real invocation later.
    let log = dir.join("calls.log");
    let escaped = log.to_string_lossy().replace('\'', "'\\''");
    let script = dir.join("recording");
    write_test_script(&script, &format!("printf '%s\\n' \"$*\" >> '{escaped}'"));
    assert!(
        !log.exists(),
        "settling must not run the fixture body: the probe created the log"
    );
    std::process::Command::new(&script)
        .args(["-n", "5", "-p", "123"])
        .output()
        .expect("a settled fixture must exec");
    assert_eq!(
        fs::read_to_string(&log).expect("log written by the real exec"),
        "-n 5 -p 123\n",
        "the real invocation must record exactly one line, probe or no probe"
    );

    // (2) A fixture that cannot be exec'd must fail loudly, naming the
    // path, rather than hanging or silently succeeding. The panic is
    // caught so the expectation is explicit instead of fatal.
    let broken = dir.join("not-executable");
    fs::write(&broken, "#!/bin/sh\nexit 0\n").expect("write broken fixture");
    fs::set_permissions(&broken, fs::Permissions::from_mode(0o644)).expect("clear the execute bit");
    let outcome = std::panic::catch_unwind(|| settle_fixture(&broken));
    let payload = outcome.expect_err("settling a non-executable fixture must panic, not swallow");
    let message = payload
        .downcast_ref::<String>()
        .cloned()
        .unwrap_or_else(|| "<non-string panic payload>".to_string());
    assert!(
        message.contains("is not executable") && message.contains("not-executable"),
        "the panic must name the fixture and the reason, got: {message}"
    );

    let _ = fs::remove_dir_all(&dir);
}

/// Guards the locking half of the fix, deterministically and without
/// running any fixture.
///
/// Rather than assert a property of the raw kernel hazard — which is
/// statistical, and which host load alone can still produce even with the
/// lock correctly held — this checks the invariant directly: every test in
/// this module that writes an executable fixture obtains
/// `fixture_exec_guard()` in the same body. A fixture test that forgets
/// the guard is the actual regression, and it is caught here instantly
/// instead of resurfacing as a 1-in-125 flake. Same shape as the coverage
/// tripwires elsewhere in this fleet: a developer adding a fixture test
/// cannot make the suite flaky by omission, they make this test fail.
#[cfg(unix)]
#[test]
fn fixture_writing_tests_hold_the_fixture_exec_guard() {
    const SOURCE: &str = include_str!("tests.rs");
    // The two writer helpers themselves: their bodies name them in the
    // signature and they create no fixtures of their own.
    const HELPERS: [&str; 2] = ["write_test_script", "write_executable_script"];

    // Slice the module into top-level function bodies. Every test and
    // helper here is a free function, so a body spans from one
    // column-zero `fn`/`async fn` line to the next.
    let mut bodies: Vec<(String, String)> = Vec::new();
    for line in SOURCE.lines() {
        if line.starts_with("fn ") || line.starts_with("async fn ") {
            let name = line
                .split_once('(')
                .map(|(head, _)| head)
                .unwrap_or(line)
                .trim_start_matches("async fn ")
                .trim_start_matches("fn ")
                .trim()
                .to_string();
            bodies.push((name, String::new()));
            continue;
        }
        if let Some((_, body)) = bodies.last_mut() {
            body.push_str(line);
            body.push('\n');
        }
    }

    let mut guarded = 0usize;
    let mut offenders: Vec<&str> = Vec::new();
    for (name, body) in &bodies {
        if HELPERS.contains(&name.as_str()) {
            continue;
        }
        let writes_fixture = ["write_test_script(", "write_executable_script("]
            .iter()
            .any(|call| body.contains(call));
        if !writes_fixture {
            continue;
        }
        guarded += 1;
        if !body.contains("fixture_exec_guard()") {
            offenders.push(name.as_str());
        }
    }

    assert!(
        guarded >= 10,
        "the source scan should find every fixture-writing test; found {guarded}, \
         which means the top-level body parser drifted from this module's layout"
    );
    assert!(
        offenders.is_empty(),
        "these tests write an executable fixture and then exec it but never hold \
         fixture_exec_guard() for the create->exec window (see FIXTURE_EXEC_LOCK): \
         {offenders:?}"
    );
}

#[cfg(unix)]
#[tokio::test]
async fn restore_runtime_adjustments_restores_renice_and_oom() {
    let _fixture_exec = fixture_exec_guard();
    let tmp = std::env::temp_dir().join(format!(
        "dracon_system_restore_test_{}_{}",
        std::process::id(),
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time")
            .as_nanos()
    ));
    fs::create_dir_all(&tmp).expect("create temp dir");
    let renice = tmp.join("renice");
    let systemctl = tmp.join("systemctl");
    write_test_script(&renice, "exit 0");
    write_test_script(&systemctl, "exit 0");
    write_process_fixture(&tmp, 101, "zsh", 77, Some(250), None);

    let identity = ProcessIdentity {
        comm: "zsh".to_string(),
        starttime: 77,
    };
    assert_eq!(
        process_identity_status(&tmp, 101, &identity),
        ProcessIdentityStatus::Match
    );
    assert_eq!(
        process_identity_status(
            &tmp,
            101,
            &ProcessIdentity {
                comm: "zsh".to_string(),
                starttime: 78,
            },
        ),
        ProcessIdentityStatus::Mismatch
    );
    assert_eq!(
        process_identity_status(&tmp, 102, &identity),
        ProcessIdentityStatus::Gone
    );
    let missing_proc_root = tmp.join("missing-proc-root");
    assert_eq!(
        process_identity_status(&missing_proc_root, 101, &identity),
        ProcessIdentityStatus::Unavailable,
        "a missing proc root must not be treated as a gone PID"
    );
    let mut unavailable_state = GuardRuntimeState::default();
    unavailable_state.reniced_pids.insert(
        101,
        LegacyReniceState {
            original_nice: 0,
            applied_nice: 5,
            identity: identity.clone(),
        },
    );
    unavailable_state.capped_pids.insert(
        101,
        (
            "dracon-cap.service".to_string(),
            "user.slice".to_string(),
            identity.clone(),
        ),
    );
    assert!(
        !restore_runtime_adjustments_with(
            &mut unavailable_state,
            &renice,
            &systemctl,
            &missing_proc_root,
        )
        .await,
        "missing proc root must retain every indeterminate adjustment"
    );
    assert!(unavailable_state.reniced_pids.contains_key(&101));
    assert!(unavailable_state.capped_pids.contains_key(&101));

    // Failed renice and OOM writes must retain their entries for the next
    // release retry rather than reporting success and dropping tracking.
    let failing_renice = tmp.join("renice-failure");
    write_test_script(&failing_renice, "exit 1");
    write_process_fixture(&tmp, 103, "worker", 79, None, None);
    write_process_fixture(&tmp, 104, "worker", 80, None, None);
    fs::create_dir(tmp.join("104/oom_score_adj")).expect("create failing oom fixture");
    let mut failure_state = GuardRuntimeState::default();
    failure_state.reniced_pids.insert(
        103,
        LegacyReniceState {
            original_nice: 0,
            applied_nice: 5,
            identity: ProcessIdentity {
                comm: "worker".to_string(),
                starttime: 79,
            },
        },
    );
    failure_state.oom_biased_pids.insert(
        104,
        (
            -100,
            ProcessIdentity {
                comm: "worker".to_string(),
                starttime: 80,
            },
        ),
    );
    assert!(
        !restore_runtime_adjustments_with(&mut failure_state, &failing_renice, &systemctl, &tmp)
            .await,
        "failed release operations must prevent runtime reset"
    );
    assert!(failure_state.reniced_pids.contains_key(&103));
    assert!(failure_state.oom_biased_pids.contains_key(&104));

    // A kernel comm name can be truncated or differ from argv[0]. The
    // release identity check must use the stable starttime, not cmdline.
    write_process_fixture(&tmp, 105, "very-long-process", 81, None, None);
    let long_comm_identity = ProcessIdentity {
        comm: "very-long".to_string(),
        starttime: 81,
    };
    assert_eq!(
        process_identity_status(&tmp, 105, &long_comm_identity),
        ProcessIdentityStatus::Match
    );

    write_process_fixture(&tmp, 106, "memory-worker", 82, None, None);
    let renice_log = tmp.join("renice.log");
    let recording_renice = tmp.join("renice-recording");
    let escaped_renice_log = renice_log.to_string_lossy().replace('\'', "'\\''");
    write_test_script(
        &recording_renice,
        &format!("printf '%s\\n' \"$*\" >> '{escaped_renice_log}'\nexit 0"),
    );

    let mut state = GuardRuntimeState::default();
    state.reniced_pids.insert(
        101,
        LegacyReniceState {
            original_nice: 0,
            applied_nice: 5,
            identity: identity.clone(),
        },
    );
    state.reniced_pids.insert(
        105,
        LegacyReniceState {
            original_nice: 0,
            applied_nice: 5,
            identity: long_comm_identity,
        },
    );
    state.oom_biased_pids.insert(101, (-100, identity));
    state.memory_reniced_pids.insert(
        106,
        MemoryReniceState {
            original_nice: 10,
            applied_nice: 5,
            identity: ProcessIdentity {
                comm: "memory-worker".to_string(),
                starttime: 82,
            },
        },
    );

    assert!(
        restore_runtime_adjustments_with(&mut state, &recording_renice, &systemctl, &tmp).await,
        "all successful restorations should permit runtime reset"
    );
    assert!(state.reniced_pids.is_empty());
    assert!(state.memory_reniced_pids.is_empty());
    assert!(state.oom_biased_pids.is_empty());
    assert_eq!(
        fs::read_to_string(tmp.join("101/oom_score_adj")).unwrap(),
        "-100\n"
    );
    let renice_calls = fs::read_to_string(&renice_log).unwrap();
    assert!(
        renice_calls.lines().any(|call| call == "-n 10 -p 106"),
        "memory release must restore the captured original nice value"
    );
    let _ = fs::remove_dir_all(&tmp);
}

#[cfg(unix)]
#[tokio::test]
async fn restore_runtime_adjustments_composes_overlapping_nice_limiters() {
    let _fixture_exec = fixture_exec_guard();
    let tmp = std::env::temp_dir().join(format!(
        "dracon_system_overlap_restore_test_{}_{}",
        std::process::id(),
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time")
            .as_nanos()
    ));
    fs::create_dir_all(&tmp).expect("create temp dir");
    let renice_log = tmp.join("renice.log");
    let renice = tmp.join("renice");
    let systemctl = tmp.join("systemctl");
    let escaped_log = renice_log.to_string_lossy().replace('\'', "'\\''");
    write_test_script(
        &renice,
        &format!("printf '%s\\n' \"$*\" >> '{escaped_log}'\nexit 0"),
    );
    write_test_script(&systemctl, "exit 0");
    write_process_fixture(&tmp, 107, "overlap-worker", 83, None, None);

    let identity = ProcessIdentity {
        comm: "overlap-worker".to_string(),
        starttime: 83,
    };
    let mut state = GuardRuntimeState::default();
    state.reniced_pids.insert(
        107,
        LegacyReniceState {
            original_nice: 3,
            applied_nice: 8,
            identity: identity.clone(),
        },
    );
    state.memory_reniced_pids.insert(
        107,
        MemoryReniceState {
            original_nice: 3,
            applied_nice: 12,
            identity,
        },
    );

    assert!(
        restore_runtime_adjustments_with(&mut state, &renice, &systemctl, &tmp).await,
        "overlapping nice limiters should restore successfully"
    );
    assert!(state.reniced_pids.is_empty());
    assert!(state.memory_reniced_pids.is_empty());
    assert_eq!(
        fs::read_to_string(&renice_log)
            .expect("read renice log")
            .lines()
            .collect::<Vec<_>>(),
        vec!["-n 3 -p 107"],
        "one compositional restore must target the pre-limiter nice value"
    );
    let _ = fs::remove_dir_all(&tmp);
}

#[cfg(unix)]
#[tokio::test]
async fn restore_runtime_adjustments_retains_overlapping_nice_limiters_on_failure() {
    let _fixture_exec = fixture_exec_guard();
    let tmp = std::env::temp_dir().join(format!(
        "dracon_system_overlap_failure_test_{}_{}",
        std::process::id(),
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time")
            .as_nanos()
    ));
    fs::create_dir_all(&tmp).expect("create temp dir");
    let renice = tmp.join("renice-failure");
    let systemctl = tmp.join("systemctl");
    write_test_script(&renice, "exit 1");
    write_test_script(&systemctl, "exit 0");
    write_process_fixture(&tmp, 108, "overlap-worker", 84, None, None);

    let identity = ProcessIdentity {
        comm: "overlap-worker".to_string(),
        starttime: 84,
    };
    let mut state = GuardRuntimeState::default();
    state.reniced_pids.insert(
        108,
        LegacyReniceState {
            original_nice: 4,
            applied_nice: 9,
            identity: identity.clone(),
        },
    );
    state.memory_reniced_pids.insert(
        108,
        MemoryReniceState {
            original_nice: 4,
            applied_nice: 13,
            identity,
        },
    );

    assert!(
        !restore_runtime_adjustments_with(&mut state, &renice, &systemctl, &tmp).await,
        "a failed compositional restore must remain retryable"
    );
    assert!(state.reniced_pids.contains_key(&108));
    assert!(state.memory_reniced_pids.contains_key(&108));
    let _ = fs::remove_dir_all(&tmp);
}

#[cfg(unix)]
#[tokio::test]
async fn restore_runtime_adjustments_preserves_current_pid_incarnation() {
    let _fixture_exec = fixture_exec_guard();
    let tmp = std::env::temp_dir().join(format!(
        "dracon_system_pid_reuse_restore_test_{}_{}",
        std::process::id(),
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time")
            .as_nanos()
    ));
    fs::create_dir_all(&tmp).expect("create temp dir");
    let renice_log = tmp.join("renice.log");
    let renice = tmp.join("renice");
    let systemctl = tmp.join("systemctl");
    let escaped_log = renice_log.to_string_lossy().replace('\'', "'\\''");
    write_test_script(
        &renice,
        &format!("printf '%s\\n' \"$*\" >> '{escaped_log}'\nexit 0"),
    );
    write_test_script(&systemctl, "exit 0");
    // The legacy entry belongs to an exited incarnation; the memory entry is
    // for the replacement process now occupying the same PID.
    write_process_fixture(&tmp, 109, "reused-worker", 86, None, None);
    let mut state = GuardRuntimeState::default();
    state.reniced_pids.insert(
        109,
        LegacyReniceState {
            original_nice: 3,
            applied_nice: 8,
            identity: ProcessIdentity {
                comm: "reused-worker".to_string(),
                starttime: 85,
            },
        },
    );
    state.memory_reniced_pids.insert(
        109,
        MemoryReniceState {
            original_nice: 7,
            applied_nice: 12,
            identity: ProcessIdentity {
                comm: "reused-worker".to_string(),
                starttime: 86,
            },
        },
    );

    assert!(
        restore_runtime_adjustments_with(&mut state, &renice, &systemctl, &tmp).await,
        "stale PID state must not prevent current-incarnation restoration"
    );
    assert!(state.reniced_pids.is_empty());
    assert!(state.memory_reniced_pids.is_empty());
    assert_eq!(
        fs::read_to_string(&renice_log)
            .expect("read renice log")
            .lines()
            .collect::<Vec<_>>(),
        vec!["-n 7 -p 109"],
        "the replacement process must restore its own captured nice value"
    );
    let _ = fs::remove_dir_all(&tmp);
}

#[cfg(unix)]
#[test]
fn stale_nice_state_does_not_override_current_pid_incarnation() {
    let mut state = GuardRuntimeState::default();
    state.reniced_pids.insert(
        110,
        LegacyReniceState {
            original_nice: 2,
            applied_nice: 8,
            identity: ProcessIdentity {
                comm: "worker".to_string(),
                starttime: 90,
            },
        },
    );
    state.memory_reniced_pids.insert(
        110,
        MemoryReniceState {
            original_nice: 6,
            applied_nice: 12,
            identity: ProcessIdentity {
                comm: "worker".to_string(),
                starttime: 91,
            },
        },
    );
    let current_identity = ProcessIdentity {
        comm: "worker".to_string(),
        starttime: 91,
    };

    drop_stale_nice_adjustments(&mut state, 110, &current_identity);

    assert!(!state.reniced_pids.contains_key(&110));
    assert_eq!(
        state
            .memory_reniced_pids
            .get(&110)
            .map(|entry| entry.original_nice),
        Some(6)
    );
}

#[cfg(unix)]
#[test]
fn sweep_stranded_oom_descendants_restores_only_post_bias_children() {
    let tmp = std::env::temp_dir().join(format!(
        "dracon_system_oom_descendants_test_{}_{}",
        std::process::id(),
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time")
            .as_nanos()
    ));
    fs::create_dir_all(&tmp).expect("create temp dir");
    write_process_fixture(&tmp, 101, "oom-parent", 77, Some(250), None);
    write_process_fixture(&tmp, 102, "existing-child", 78, Some(250), None);
    write_process_fixture(&tmp, 103, "forked-child", 79, Some(250), None);
    write_process_fixture(&tmp, 104, "unrelated", 80, Some(250), None);
    write_process_fixture(&tmp, 105, "failed-child", 81, None, None);
    fs::create_dir(tmp.join("105/oom_score_adj")).expect("create failing child oom fixture");

    let sample = |pid: i32, ppid: i32, starttime: u64, command: &str| ProcSample {
        pid,
        ppid,
        cpu_percent: 0.0,
        rss_mb: 1,
        nice: 0,
        command: command.to_string(),
        args: String::new(),
        starttime,
    };
    let samples = vec![
        sample(101, 1, 77, "oom-parent"),
        sample(102, 101, 78, "existing-child"),
        sample(103, 101, 79, "forked-child"),
        sample(104, 1, 80, "unrelated"),
        sample(105, 101, 81, "failed-child"),
    ];
    let identity = ProcessIdentity {
        comm: "oom-parent".to_string(),
        starttime: 77,
    };
    let mut state = GuardRuntimeState::default();
    state.oom_biased_pids.insert(101, (-100, identity));
    state
        .oom_known_descendants
        .insert(101, std::collections::HashSet::from([(102, 78)]));

    let actions = sweep_stranded_oom_descendants(
        &tmp,
        &samples,
        &mut state,
        &std::collections::HashSet::new(),
    );
    assert_eq!(
        actions.restored,
        vec!["oom-restore-descendant forked-child=-100"]
    );
    assert_eq!(actions.deferred, 1);
    assert!(state.oom_pending_descendants.contains_key(&(105, 81)));
    remove_oom_bias(&mut state, 101);
    assert!(
        state.oom_biased_pids.contains_key(&101),
        "root bias must remain tracked while child restoration is pending"
    );
    assert_eq!(
        fs::read_to_string(tmp.join("102/oom_score_adj")).unwrap(),
        "250\n"
    );
    assert_eq!(
        fs::read_to_string(tmp.join("103/oom_score_adj")).unwrap(),
        "-100\n"
    );
    assert_eq!(
        fs::read_to_string(tmp.join("104/oom_score_adj")).unwrap(),
        "250\n"
    );
    assert!(state
        .oom_known_descendants
        .get(&101)
        .unwrap()
        .contains(&(103, 79)));

    fs::remove_dir(tmp.join("105/oom_score_adj")).expect("remove failing child fixture");
    fs::write(tmp.join("105/oom_score_adj"), "250\n").expect("restore child fixture");
    let retry = sweep_stranded_oom_descendants(
        &tmp,
        &samples,
        &mut state,
        &std::collections::HashSet::new(),
    );
    assert_eq!(
        retry.restored,
        vec!["oom-restore-descendant failed-child=-100"]
    );
    assert_eq!(retry.deferred, 0);
    assert!(!state.oom_pending_descendants.contains_key(&(105, 81)));
    remove_oom_bias(&mut state, 101);
    assert!(!state.oom_biased_pids.contains_key(&101));
    let _ = fs::remove_dir_all(&tmp);
}

#[cfg(unix)]
#[test]
fn sweep_stranded_oom_descendants_uses_nearest_biased_ancestor() {
    let tmp = std::env::temp_dir().join(format!(
        "dracon_system_nested_oom_test_{}_{}",
        std::process::id(),
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time")
            .as_nanos()
    ));
    fs::create_dir_all(&tmp).expect("create temp dir");
    write_process_fixture(&tmp, 201, "outer", 91, Some(250), None);
    write_process_fixture(&tmp, 202, "inner", 92, Some(250), None);
    write_process_fixture(&tmp, 203, "nested-child", 93, Some(250), None);
    let sample = |pid: i32, ppid: i32, starttime: u64, command: &str| ProcSample {
        pid,
        ppid,
        cpu_percent: 0.0,
        rss_mb: 1,
        nice: 0,
        command: command.to_string(),
        args: String::new(),
        starttime,
    };
    let samples = vec![
        sample(201, 1, 91, "outer"),
        sample(202, 201, 92, "inner"),
        sample(203, 202, 93, "nested-child"),
    ];
    let mut state = GuardRuntimeState::default();
    state.oom_biased_pids.insert(
        201,
        (
            -100,
            ProcessIdentity {
                comm: "outer".to_string(),
                starttime: 91,
            },
        ),
    );
    state.oom_biased_pids.insert(
        202,
        (
            25,
            ProcessIdentity {
                comm: "inner".to_string(),
                starttime: 92,
            },
        ),
    );
    state
        .oom_known_descendants
        .insert(201, std::collections::HashSet::from([(202, 92)]));
    state
        .oom_known_descendants
        .insert(202, std::collections::HashSet::new());

    let result = sweep_stranded_oom_descendants(
        &tmp,
        &samples,
        &mut state,
        &std::collections::HashSet::new(),
    );
    assert_eq!(
        result.restored,
        vec!["oom-restore-descendant nested-child=25"]
    );
    assert_eq!(result.deferred, 0);
    assert_eq!(
        fs::read_to_string(tmp.join("203/oom_score_adj")).unwrap(),
        "25\n"
    );
    let _ = fs::remove_dir_all(&tmp);
}

#[cfg(unix)]
#[tokio::test]
async fn restore_runtime_adjustments_retains_failed_cpu_cap() {
    let _fixture_exec = fixture_exec_guard();
    let tmp = std::env::temp_dir().join(format!(
        "dracon_system_cap_restore_test_{}_{}",
        std::process::id(),
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time")
            .as_nanos()
    ));
    fs::create_dir_all(&tmp).expect("create temp dir");
    fs::create_dir_all(tmp.join("self")).expect("create proc availability marker");
    let renice = tmp.join("renice");
    let systemctl = tmp.join("systemctl");
    write_test_script(&renice, "exit 0");
    write_test_script(&systemctl, "exit 1");
    let mut state = GuardRuntimeState::default();
    state.capped_pids.insert(
        999_999,
        (
            "dracon-cap.service".to_string(),
            "user.slice".to_string(),
            ProcessIdentity {
                comm: "gone".to_string(),
                starttime: 1,
            },
        ),
    );

    assert!(
        !restore_runtime_adjustments_with(&mut state, &renice, &systemctl, &tmp).await,
        "failed systemd cleanup must prevent runtime reset"
    );
    assert!(state.capped_pids.contains_key(&999_999));

    // Once systemd succeeds, the previously retained cap may be removed.
    write_test_script(&systemctl, "exit 0");
    assert!(restore_runtime_adjustments_with(&mut state, &renice, &systemctl, &tmp).await);
    assert!(state.capped_pids.is_empty());

    // A live process whose cgroup cannot be read is indeterminate and must
    // also remain tracked even when systemd itself reports success.
    write_process_fixture(&tmp, 1000, "worker", 88, None, None);
    fs::create_dir(tmp.join("1000/cgroup")).expect("create unreadable cgroup fixture");
    state.capped_pids.insert(
        1000,
        (
            "dracon-cap.service".to_string(),
            "user.slice".to_string(),
            ProcessIdentity {
                comm: "worker".to_string(),
                starttime: 88,
            },
        ),
    );
    assert!(
        !restore_runtime_adjustments_with(&mut state, &renice, &systemctl, &tmp).await,
        "cgroup read failure must prevent runtime reset"
    );
    assert!(state.capped_pids.contains_key(&1000));

    let systemctl_probe = tmp.join("systemctl-probe");
    let probe_log = tmp.join("systemctl-probe.log");
    let escaped_probe_log = probe_log.to_string_lossy().replace('\'', "'\\''");
    write_test_script(
        &systemctl_probe,
        &format!("printf 'called\\n' >> '{escaped_probe_log}'\nexit 0"),
    );

    // A missing cgroup file with a live PID directory is also indeterminate;
    // it may mean the cgroup source is unavailable rather than that the
    // process exited.
    write_process_fixture(&tmp, 1001, "worker", 89, None, None);
    state.capped_pids.insert(
        1001,
        (
            "dracon-cap.service".to_string(),
            "user.slice".to_string(),
            ProcessIdentity {
                comm: "worker".to_string(),
                starttime: 89,
            },
        ),
    );
    assert!(
        !restore_runtime_adjustments_with(&mut state, &renice, &systemctl_probe, &tmp).await,
        "a missing live-PID cgroup file must prevent runtime reset"
    );
    assert!(state.capped_pids.contains_key(&1001));

    // Malformed cgroup data is equally indeterminate and must not trigger
    // systemd cleanup or allow the cap entry to be discarded.
    write_process_fixture(&tmp, 1002, "worker", 90, None, Some("malformed\n"));
    state.capped_pids.insert(
        1002,
        (
            "dracon-cap.service".to_string(),
            "user.slice".to_string(),
            ProcessIdentity {
                comm: "worker".to_string(),
                starttime: 90,
            },
        ),
    );
    assert!(
        !restore_runtime_adjustments_with(&mut state, &renice, &systemctl_probe, &tmp).await,
        "malformed cgroup data must prevent runtime reset"
    );
    assert!(state.capped_pids.contains_key(&1002));
    assert!(
        !probe_log.exists(),
        "indeterminate cgroup state must not stop the transient service"
    );
    let _ = fs::remove_dir_all(&tmp);
}

#[test]
fn human_bytes_formats_units() {
    assert_eq!(human_bytes(1), "1.0 B");
    assert_eq!(human_bytes(1024), "1.0 KiB");
    assert_eq!(human_bytes(1024 * 1024), "1.0 MiB");
}

#[test]
fn parse_kinds_trims_and_dedupes() {
    let kinds = parse_kinds(" rust-build, node-deps ,rust-build,,cache ");
    assert_eq!(kinds.len(), 3);
    assert!(kinds.contains("rust-build"));
    assert!(kinds.contains("node-deps"));
    assert!(kinds.contains("cache"));
}

#[test]
fn expand_tilde_resolves_to_home_dir() {
    // dirs::home_dir() uses getpwuid() on Linux, not $HOME.
    // Just verify ~ expands to whatever dirs reports.
    let home = dirs::home_dir().expect("home dir should exist");
    assert_eq!(expand_tilde("~"), home);
    assert_eq!(expand_tilde("~/foo/bar"), home.join("foo/bar"));
    assert_eq!(expand_tilde("/x/y"), PathBuf::from("/x/y"));
}

#[test]
fn expand_tilde_with_home_unset_falls_back_to_dot() {
    // We can't actually unset home for dirs::home_dir() (it uses getpwuid),
    // but we can verify the fallback path is wired correctly by testing
    // the helper directly if we could mock it. Instead, just verify
    // non-tilde paths pass through unchanged.
    assert_eq!(
        expand_tilde("/absolute/path"),
        PathBuf::from("/absolute/path")
    );
    assert_eq!(
        expand_tilde("relative/path"),
        PathBuf::from("relative/path")
    );
}

#[test]
fn guard_log_path_expands_the_example_configuration() {
    let policy: SystemPolicy = toml::from_str(include_str!("../dracon-system.example.toml"))
        .expect("shipped example policy should parse");
    assert_eq!(
        policy.guard.guard_log_file,
        "~/.local/state/dracon/dracon-system-guard.log"
    );

    let home = dirs::home_dir().expect("home directory");
    let resolved = resolve_guard_log_path(&policy.guard.guard_log_file)
        .expect("example guard log path should be enabled");
    assert_eq!(
        resolved,
        home.join(".local/state/dracon/dracon-system-guard.log")
    );
    assert!(!resolved.to_string_lossy().contains('~'));
    assert!(resolve_guard_log_path("  ").is_none());
    assert_eq!(
        resolve_guard_log_path("logs/guard.log"),
        Some(PathBuf::from("logs/guard.log"))
    );
}

#[test]
fn guard_log_example_path_writes_and_startup_rotates_in_isolated_home() {
    let policy: SystemPolicy = toml::from_str(include_str!("../dracon-system.example.toml"))
        .expect("shipped example policy should parse");
    assert_eq!(
        policy.guard.guard_log_file,
        "~/.local/state/dracon/dracon-system-guard.log"
    );

    let home = std::env::temp_dir().join(format!(
        "dracon_system_guard_log_home_{}_{}",
        std::process::id(),
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("clock after Unix epoch")
            .as_nanos()
    ));
    let mut guard = policy.guard;
    guard.guard_log_max_mb = 1;
    let path = resolve_guard_log_path_with_home(&guard.guard_log_file, Some(&home))
        .expect("example guard log path should be enabled");
    assert_eq!(
        path,
        home.join(".local/state/dracon/dracon-system-guard.log")
    );

    fs::create_dir_all(path.parent().expect("guard log parent")).expect("create guard log parent");
    fs::write(&path, vec![b'x'; 1024 * 1024 + 1]).expect("seed oversized guard log");
    rotate_guard_log_for_policy_with_home(&guard, true, Some(&home));
    assert!(
        !path.exists(),
        "startup rotation must use the expanded advertised log path"
    );

    log_guard_event_with_home(&guard, "f66-test", "expanded path", Some(&home));
    let contents = fs::read_to_string(&path).expect("expanded guard log should be written");
    let record: serde_json::Value =
        serde_json::from_str(contents.trim()).expect("guard log should contain JSONL");
    assert_eq!(record["event"], "f66-test");
    assert_eq!(record["details"], "expanded path");
    assert!(
        fs::metadata(&path).expect("guard log metadata").len() < 1024 * 1024,
        "guard log should remain below the configured limit after rotation"
    );

    fs::remove_dir_all(&home).expect("remove isolated guard log home");
}

#[test]
fn build_link_report_counts_states() {
    let policy = SystemPolicy {
        storage: StoragePolicy::default(),
        links: LinkPolicy {
            entries: vec![LinkEntry {
                link: "/tmp/does-not-exist-link".into(),
                target: "/tmp/does-not-exist-target".into(),
            }],
        },
        guard: GuardPolicy::default(),
    };
    let report = build_link_report(&policy);
    assert_eq!(report.total, 1);
    assert_eq!(report.healthy, 0);
    assert_eq!(report.drifted, 1);
    assert_eq!(report.missing_target, 1);
}

#[cfg(unix)]
#[test]
fn evaluate_link_handles_missing_and_sync_cases() {
    let base = std::env::temp_dir().join(format!(
        "dracon_system_test_{}_{}",
        std::process::id(),
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time")
            .as_nanos()
    ));
    fs::create_dir_all(&base).expect("base dir");

    let target = base.join("target.txt");
    fs::write(&target, "x").expect("target");

    let missing_link = LinkEntry {
        link: base.join("missing-link").display().to_string(),
        target: target.display().to_string(),
    };
    let s1 = evaluate_link(&missing_link);
    assert_eq!(s1.issue, "link_missing");

    let normal_file_link = base.join("normal-file");
    fs::write(&normal_file_link, "x").expect("file");
    let not_symlink = LinkEntry {
        link: normal_file_link.display().to_string(),
        target: target.display().to_string(),
    };
    let s2 = evaluate_link(&not_symlink);
    assert_eq!(s2.issue, "path_not_symlink");

    let good_link = base.join("good-link");
    symlink(&target, &good_link).expect("symlink");
    let synced = LinkEntry {
        link: good_link.display().to_string(),
        target: target.display().to_string(),
    };
    let s3 = evaluate_link(&synced);
    assert_eq!(s3.issue, "ok");
    assert!(s3.in_sync);

    let wrong_target = base.join("other.txt");
    fs::write(&wrong_target, "y").expect("other");
    let mismatch_link = base.join("mismatch-link");
    symlink(&wrong_target, &mismatch_link).expect("symlink mismatch");
    let mismatch = LinkEntry {
        link: mismatch_link.display().to_string(),
        target: target.display().to_string(),
    };
    let s4 = evaluate_link(&mismatch);
    assert_eq!(s4.issue, "link_target_mismatch");

    let _ = fs::remove_dir_all(&base);
}

#[test]
fn parse_and_format_repeated_scenarios() {
    for i in 0..220usize {
        let csv = if i % 2 == 0 {
            "rust-build,node-deps,cache"
        } else {
            " rust-build , build-output , cache , rust-build "
        };
        let kinds = parse_kinds(csv);
        assert!(kinds.contains("rust-build"));
        assert!(kinds.contains("cache"));

        let bytes = (i as u64 + 1) * 2048;
        let out = human_bytes(bytes);
        assert!(!out.is_empty());
        assert!(out.contains(' '));
    }
}

#[test]
fn parse_df_use_percent_works() {
    let sample =
        "Filesystem 1024-blocks Used Available Capacity Mounted on\n/dev/root 100 91 9 91% /\n";
    assert_eq!(parse_df_use_percent(sample), Some(91));
}

/// 2026-10-03 (audit R4-SYS-15): absurd block counts saturate instead
/// of panicking (debug) or wrapping (release) — a panic kills the
/// daemon pass. `u64::MAX` blocks × 1024 must yield `u64::MAX` bytes.
#[test]
fn parse_df_details_saturates_absurd_blocks() {
    let huge = format!(
        "Filesystem 1024-blocks Used Available Capacity Mounted on\n/dev/x {} {} {} 50% /x\n",
        u64::MAX,
        u64::MAX,
        u64::MAX
    );
    let details = parse_df_details(&huge).expect("absurd input must saturate, not fail");
    assert_eq!(details.total_bytes, u64::MAX);
    assert_eq!(details.used_bytes, u64::MAX);
    assert_eq!(details.avail_bytes, u64::MAX);
    assert_eq!(details.use_percent, 50);

    // Normal values still scale exactly.
    let sample =
        "Filesystem 1024-blocks Used Available Capacity Mounted on\n/dev/root 100 91 9 91% /\n";
    let details = parse_df_details(sample).expect("normal input parses");
    assert_eq!(
        (details.total_bytes, details.used_bytes, details.avail_bytes),
        (100 * 1024, 91 * 1024, 9 * 1024)
    );
}

#[test]
fn parse_ps_output_works() {
    let sample = "123 1 250.5 4194304 5 git\n456 2 12.0 2048 0 zsh\n";
    let rows = parse_ps_output(sample);
    assert_eq!(rows.len(), 2);
    assert_eq!(rows[0].pid, 123);
    assert_eq!(rows[0].ppid, 1);
    assert_eq!(rows[0].command, "git");
    assert_eq!(rows[0].rss_mb, 4096);
    assert_eq!(rows[0].nice, 5);
    assert_eq!(rows[0].args, "");
}

#[test]
fn is_protected_ancestor_exact_match() {
    assert!(is_protected_ancestor("/home", "/home"));
    assert!(is_protected_ancestor("/etc", "/etc"));
    assert!(is_protected_ancestor("/", "/"));
}

#[test]
fn is_protected_ancestor_descendant_match() {
    assert!(is_protected_ancestor("/home/dracon", "/home"));
    assert!(is_protected_ancestor("/home/dracon/Dev", "/home"));
    assert!(is_protected_ancestor("/etc/nginx/nginx.conf", "/etc"));
}

#[test]
fn is_protected_ancestor_rejects_partial_prefix() {
    assert!(!is_protected_ancestor("/homefoo", "/home"));
    assert!(!is_protected_ancestor("/homefoo/bar", "/home"));
    assert!(!is_protected_ancestor("/etcnginx", "/etc"));
}

#[test]
fn is_protected_ancestor_root_matches_exact_only() {
    assert!(is_protected_ancestor("/", "/"));
    assert!(!is_protected_ancestor("/anything", "/")); // root only matches exact to allow cleanup
    assert!(!is_protected_ancestor("/home", "/"));
}

#[test]
fn check_path_str_blocks_descendants() {
    assert!(!check_path_str("/home/dracon", &[]));
    assert!(!check_path_str("/home/dracon/Dev", &[]));
    assert!(!check_path_str("/etc/nginx", &[]));
    assert!(check_path_str("/safe/path", &[]));
    assert!(check_path_str("/homefoo", &[])); // partial prefix should be safe
}

#[test]
fn parse_ps_output_extracts_all_fields() {
    let sample = "9999 1 75.0 8192000 0 git-fetch origin main\n";
    let rows = parse_ps_output(sample);
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0].pid, 9999);
    assert_eq!(rows[0].ppid, 1);
    assert_eq!(rows[0].cpu_percent, 75.0);
    assert_eq!(rows[0].rss_mb, 8192000 / 1024);
    assert_eq!(rows[0].command, "git-fetch");
    assert_eq!(rows[0].args, "origin main");
}

#[test]
fn process_cmdline_is_sanitized_for_logs() {
    let raw = b"python3\0worker.py\0line\nwith\tcontrol\0";
    assert_eq!(
        sanitize_process_cmdline(raw, false),
        "python3 worker.py line\\nwith\\tcontrol"
    );
}

#[test]
fn process_cmdline_is_bounded() {
    let raw = vec![b'x'; MAX_PROCESS_CMDLINE_BYTES];
    let output = sanitize_process_cmdline(&raw, true);
    assert!(output.ends_with(" [truncated]"));
    assert!(output.len() <= MAX_PROCESS_CMDLINE_BYTES + " [truncated]".len());
}

#[test]
fn disk_state_transitions_at_thresholds() {
    let guard = GuardPolicy {
        disk_warn_percent: 70,
        disk_action_percent: 85,
        disk_critical_percent: 95,
        ..GuardPolicy::default()
    };
    assert_eq!(disk_state(50, &guard), "ok");
    assert_eq!(disk_state(70, &guard), "warn");
    assert_eq!(disk_state(84, &guard), "warn");
    assert_eq!(disk_state(85, &guard), "action");
    assert_eq!(disk_state(94, &guard), "action");
    assert_eq!(disk_state(95, &guard), "critical");
    assert_eq!(disk_state(100, &guard), "critical");
}

#[test]
fn should_notify_respects_cooldown() {
    let mut state = GuardRuntimeState::default();
    let key = "test-key";
    assert!(
        should_notify(&mut state, key, 60),
        "first notify should succeed"
    );
    assert!(
        !should_notify(&mut state, key, 60),
        "immediate second notify should be blocked"
    );
    assert!(
        should_notify(&mut state, "other-key", 60),
        "different key should succeed"
    );
}

#[test]
fn predict_fill_time_requires_minimum_samples() {
    let history: Vec<(Instant, u8)> = vec![(Instant::now(), 50), (Instant::now(), 51)];
    assert!(
        predict_fill_time(&history).is_none(),
        "needs at least 3 samples"
    );
}

#[test]
fn predict_fill_time_returns_none_for_stable_disk() {
    let base = Instant::now();
    let history: Vec<(Instant, u8)> = vec![
        (base, 50),
        (base + Duration::from_secs(10), 50),
        (base + Duration::from_secs(20), 50),
    ];
    assert!(
        predict_fill_time(&history).is_none(),
        "stable disk should not predict fill"
    );
}

#[test]
fn predict_fill_time_estimates_for_filling_disk() {
    let base = Instant::now();
    let history: Vec<(Instant, u8)> = vec![
        (base, 50),
        (base + Duration::from_secs(3600), 60),
        (base + Duration::from_secs(7200), 70),
    ];
    let hours = predict_fill_time(&history);
    assert!(hours.is_some(), "should predict fill time for rising disk");
    let h = hours.unwrap();
    assert!(h > 0.0, "predicted hours should be positive");
    assert!(
        h < 100.0,
        "predicted hours should be reasonable for 10%/hr rate"
    );
}

#[tokio::test]
async fn docker_prune_returns_zero_on_dry_run() {
    // When apply=false, docker_prune should return immediately without
    // invoking docker, yielding 0 bytes reclaimed.
    let result = docker_prune(false, true, true).await;
    assert!(result.is_ok(), "dry-run docker_prune should not error");
    assert_eq!(result.unwrap(), 0, "dry-run should reclaim 0 bytes");
}

#[tokio::test]
async fn empty_trash_credential_guard_blocks_dry_run_estimate() {
    let home = std::env::temp_dir().join(format!(
        "dracon_system_trash_guard_test_{}_{}",
        std::process::id(),
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time")
            .as_nanos()
    ));
    let trash_files = home.join(".local/share/Trash/files");
    fs::create_dir_all(&trash_files).expect("create trash fixture");
    let credential_fixture = trash_files.join("CREDENTIALS.md");
    fs::write(&credential_fixture, b"fixture contents").expect("write credential fixture");

    let (reclaimed, cleaned) = empty_trash_at(&home, false, &[], true, 0)
        .await
        .expect("dry-run trash scan");
    assert_eq!(
        reclaimed, 0,
        "blocked dry-run must not report reclaimable bytes"
    );
    assert!(
        cleaned.is_empty(),
        "blocked dry-run must report no cleanup action"
    );
    assert!(
        credential_fixture.exists(),
        "dry-run must not delete the credential-like fixture"
    );

    let _ = fs::remove_dir_all(&home);
}

// --- 2026-08-25 (v0.112.39): age-based trash + tmp cleanup regression tests ---

fn write_file_with_mtime(path: &std::path::Path, contents: &[u8], age_secs: u64) {
    fs::write(path, contents).expect("write fixture");
    let f = fs::OpenOptions::new()
        .append(true)
        .open(path)
        .expect("open fixture for mtime set");
    let mtime = SystemTime::now() - Duration::from_secs(age_secs);
    f.set_modified(mtime).expect("set_modified");
}

/// Guard-facing variant pinned to `/tmp`: `std::env::temp_dir()`
/// honours `$TMPDIR`, and the nix build sandbox sets it to `/build`,
/// which is not under `/tmp` — every clean-tmp test that handed such a
/// root to `clean_tmp_paths` failed there with "invalid
/// tmp_search_paths entry". The SUT contract is a `/tmp` descendant
/// (see `check_safe_tmp_root`), so the fixtures must create one.
fn unique_test_tmp_root(tag: &str) -> std::path::PathBuf {
    std::path::Path::new("/tmp").join(format!(
        "dracon_system_{}_{}_{}",
        tag,
        std::process::id(),
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time")
            .as_nanos()
    ))
}

fn unique_test_home(tag: &str) -> std::path::PathBuf {
    std::env::temp_dir().join(format!(
        "dracon_system_{}_{}_{}",
        tag,
        std::process::id(),
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time")
            .as_nanos()
    ))
}

#[tokio::test]
async fn empty_trash_min_age_keeps_recent_entries() {
    let home = unique_test_home("trash_age");
    let trash_files = home.join(".local/share/Trash/files");
    let trash_info = home.join(".local/share/Trash/info");
    fs::create_dir_all(&trash_files).expect("create trash fixture");
    fs::create_dir_all(&trash_info).expect("create info fixture");

    // Old entry (30 days) must go; recent entry (1 hour) must stay.
    let old = trash_files.join("old-stuff.txt");
    let recent = trash_files.join("recent-stuff.txt");
    write_file_with_mtime(&old, b"old", 30 * 86_400);
    write_file_with_mtime(&recent, b"new", 3_600);
    fs::write(trash_info.join("old-stuff.txt.trashinfo"), b"[Trash Info]").expect("info old");
    fs::write(
        trash_info.join("recent-stuff.txt.trashinfo"),
        b"[Trash Info]",
    )
    .expect("info recent");

    let (reclaimed, cleaned) = empty_trash_at(&home, true, &[], false, 7)
        .await
        .expect("aged purge");
    assert!(reclaimed > 0, "aged purge should reclaim the old entry");
    assert_eq!(cleaned.len(), 1, "exactly one cleanup line expected");
    assert!(!old.exists(), "old entry must be removed");
    assert!(recent.exists(), "recent entry must be kept");
    assert!(
        !trash_info.join("old-stuff.txt.trashinfo").exists(),
        "paired .trashinfo for the old entry must be removed"
    );
    assert!(
        trash_info.join("recent-stuff.txt.trashinfo").exists(),
        "paired .trashinfo for the kept entry must survive"
    );

    let _ = fs::remove_dir_all(&home);
}

#[tokio::test]
async fn empty_trash_zero_age_empties_everything() {
    let home = unique_test_home("trash_zero");
    let trash_files = home.join(".local/share/Trash/files");
    fs::create_dir_all(&trash_files).expect("create trash fixture");
    write_file_with_mtime(&trash_files.join("a.txt"), b"a", 0);
    write_file_with_mtime(&trash_files.join("b.txt"), b"b", 0);

    let (_reclaimed, _cleaned) = empty_trash_at(&home, true, &[], false, 0)
        .await
        .expect("whole-empty purge");
    assert!(!trash_files.join("a.txt").exists());
    assert!(!trash_files.join("b.txt").exists());

    let _ = fs::remove_dir_all(&home);
}

fn set_mtime_old(path: &std::path::Path, age_secs: u64) {
    let f = fs::File::open(path).expect("open fixture for mtime set");
    let mtime = SystemTime::now() - Duration::from_secs(age_secs);
    f.set_modified(mtime).expect("set_modified");
}

#[tokio::test]
async fn empty_trash_credential_guard_skips_flagged_purges_rest() {
    // 2026-09-20 (space audit): a single flagged entry must not abort the
    // whole purge. The old all-or-nothing return let one trashed target/
    // dir (cargo fingerprints named *mint_dev_token*) block 46 GiB of
    // unrelated trash every cycle at 100% disk.
    let home = unique_test_home("trash_skip");
    let trash_files = home.join(".local/share/Trash/files");
    let trash_info = home.join(".local/share/Trash/info");
    fs::create_dir_all(&trash_files).expect("create trash fixture");
    fs::create_dir_all(&trash_info).expect("create info fixture");

    // Flagged OLD entry: nested credential-signal filename inside a dir
    // whose own mtime is past the age cutoff (so only the skip set keeps
    // it, not the age gate).
    let flagged = trash_files.join("target");
    fs::create_dir_all(flagged.join("debug/.fingerprint/x")).expect("flagged nest");
    write_file_with_mtime(
        &flagged.join("debug/.fingerprint/x/example-mint_dev_token"),
        b"t",
        30 * 86_400,
    );
    set_mtime_old(&flagged, 30 * 86_400);
    let benign = trash_files.join("old-notes.txt");
    write_file_with_mtime(&benign, b"notes", 30 * 86_400);
    fs::write(trash_info.join("target.trashinfo"), b"[Trash Info]").expect("info flagged");
    fs::write(trash_info.join("old-notes.txt.trashinfo"), b"[Trash Info]").expect("info benign");

    let (reclaimed, _cleaned) = empty_trash_at(&home, true, &[], true, 7)
        .await
        .expect("purge with flagged entry");
    assert!(
        reclaimed > 0,
        "benign entry must be purged despite the flag"
    );
    assert!(!benign.exists(), "benign old entry must be removed");
    assert!(flagged.exists(), "flagged entry must be kept");
    assert!(
        trash_info.join("target.trashinfo").exists(),
        "kept entry's .trashinfo must survive"
    );
    assert!(
        !trash_info.join("old-notes.txt.trashinfo").exists(),
        "purged entry's .trashinfo must be removed"
    );

    let _ = fs::remove_dir_all(&home);
}

#[tokio::test]
async fn empty_trash_zero_age_with_flagged_keeps_flagged() {
    // Age-0 whole-empty mode must degrade to per-entry purge (not a wipe
    // and not an abort) when the guard flags entries.
    let home = unique_test_home("trash_zero_skip");
    let trash_files = home.join(".local/share/Trash/files");
    let trash_info = home.join(".local/share/Trash/info");
    fs::create_dir_all(&trash_files).expect("create trash fixture");
    fs::create_dir_all(&trash_info).expect("create info fixture");
    write_file_with_mtime(&trash_files.join("id_ed25519.key"), b"k", 0);
    write_file_with_mtime(&trash_files.join("a.txt"), b"a", 0);
    fs::write(trash_info.join("id_ed25519.key.trashinfo"), b"[Trash Info]").expect("info flagged");
    fs::write(trash_info.join("a.txt.trashinfo"), b"[Trash Info]").expect("info benign");

    let (reclaimed, _cleaned) = empty_trash_at(&home, true, &[], true, 0)
        .await
        .expect("zero-age purge with flagged entry");
    assert!(reclaimed > 0, "benign entry must be purged");
    assert!(!trash_files.join("a.txt").exists());
    assert!(
        trash_files.join("id_ed25519.key").exists(),
        "flagged entry must be kept"
    );
    assert!(
        trash_info.join("id_ed25519.key.trashinfo").exists(),
        "kept entry's .trashinfo must survive the zero-age path"
    );

    let _ = fs::remove_dir_all(&home);
}

#[tokio::test]
async fn empty_trash_credential_guard_keeps_depth_capped_subtree() {
    // 2026-10-02 (audit L6): the scan is capped at max_depth(8) — a
    // directory AT the cap has unobservable children, so its whole
    // top-level entry must be kept (fail closed per-entry). The nested
    // content here is BENIGN: the keep must happen with no credential
    // signal at all, purely because the depth-9 file cannot be seen.
    let home = unique_test_home("trash_capped");
    let trash_files = home.join(".local/share/Trash/files");
    let trash_info = home.join(".local/share/Trash/info");
    fs::create_dir_all(&trash_files).expect("create trash fixture");
    fs::create_dir_all(&trash_info).expect("create info fixture");

    // deep(1)/d1(2)/d2(3)/d3(4)/d4(5)/d5(6)/d6(7)/d7(8)/notes.txt(9):
    // d7 sits AT the cap, notes.txt is never yielded.
    let mut deep = trash_files.join("deep");
    for d in ["d1", "d2", "d3", "d4", "d5", "d6", "d7"] {
        deep = deep.join(d);
    }
    fs::create_dir_all(&deep).expect("deep nest");
    write_file_with_mtime(&deep.join("notes.txt"), b"benign", 0);
    write_file_with_mtime(&trash_files.join("a.txt"), b"a", 0);
    fs::write(trash_info.join("deep.trashinfo"), b"[Trash Info]").expect("info deep");
    fs::write(trash_info.join("a.txt.trashinfo"), b"[Trash Info]").expect("info benign");

    let (reclaimed, _cleaned) = empty_trash_at(&home, true, &[], true, 0)
        .await
        .expect("zero-age purge with capped subtree");
    assert!(reclaimed > 0, "benign entry must be purged");
    assert!(
        !trash_files.join("a.txt").exists(),
        "benign entry must be removed"
    );
    assert!(
        trash_files.join("deep").exists(),
        "depth-capped entry must be kept (children unobservable)"
    );

    let _ = fs::remove_dir_all(&home);
}

#[cfg(unix)]
#[tokio::test]
async fn empty_trash_credential_guard_keeps_unreadable_subtree() {
    // 2026-10-02 (audit L6): a walk error (EPERM here) must fail closed
    // per-entry — the old `_ => {}` swallowed it and purged a subtree
    // the guard never saw.
    use std::os::unix::fs::PermissionsExt;

    let home = unique_test_home("trash_unreadable");
    let trash_files = home.join(".local/share/Trash/files");
    let trash_info = home.join(".local/share/Trash/info");
    fs::create_dir_all(&trash_files).expect("create trash fixture");
    fs::create_dir_all(&trash_info).expect("create info fixture");

    let locked = trash_files.join("top").join("locked");
    fs::create_dir_all(&locked).expect("locked nest");
    fs::write(locked.join("inner.txt"), b"x").expect("inner file");
    write_file_with_mtime(&trash_files.join("a.txt"), b"a", 0);
    fs::write(trash_info.join("top.trashinfo"), b"[Trash Info]").expect("info top");
    fs::write(trash_info.join("a.txt.trashinfo"), b"[Trash Info]").expect("info benign");
    fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).expect("lock dir");

    let (reclaimed, _cleaned) = empty_trash_at(&home, true, &[], true, 0)
        .await
        .expect("zero-age purge with unreadable subtree");
    fs::set_permissions(&locked, fs::Permissions::from_mode(0o755)).expect("unlock dir");
    assert!(reclaimed > 0, "benign entry must be purged");
    assert!(
        !trash_files.join("a.txt").exists(),
        "benign entry must be removed"
    );
    assert!(
        trash_files.join("top").exists(),
        "entry with an unreadable subtree must be kept"
    );

    let _ = fs::remove_dir_all(&home);
}

#[cfg(unix)]
#[tokio::test]
async fn nix_cleanup_gen_prune_failure_still_runs_gc() {
    let _fixture_exec = fixture_exec_guard();
    // 2026-09-20 (space audit): nix-env prune failures (a user-session
    // guard can never prune the root-owned system profile) must not fail
    // the pass or discard store-GC results.
    let root = unique_test_home("nix_warn");
    fs::create_dir_all(&root).expect("create temp dir");
    let nix_env = root.join("nix-env");
    let nix_gc = root.join("nix-collect-garbage");
    write_test_script(&nix_env, "echo 'cannot lock profile' >&2\nexit 1");
    write_test_script(&nix_gc, "echo 'deleting /nix/store/abc'\nexit 0");

    let (_bytes, cleaned) = clean_nix_garbage_with_bins(5, true, &nix_env, &nix_gc)
        .await
        .expect("GC success must win over prune failure");
    assert_eq!(cleaned.len(), 1, "GC results must survive prune failure");

    let _ = fs::remove_dir_all(&root);
}

#[cfg(unix)]
#[tokio::test]
async fn critical_tier_bypass_cleans_fresh_target() {
    // 2026-09-20 (space audit): the lingering age gate must lift at the
    // critical tier — a fresh 79 GiB workspace target held a 100% disk
    // hostage. Gated pass protects it; bypass pass (dry-run) candidates it.
    let root = unique_test_home("critical_rust");
    let proj = root.join("proj");
    let target = proj.join("target");
    fs::create_dir_all(target.join("debug")).expect("target fixture");
    fs::write(proj.join("Cargo.toml"), b"[package]\nname = \"x\"\n").expect("manifest");
    fs::write(target.join("debug/blob"), vec![0u8; 1024]).expect("blob");
    // Fresh (1h: past the 60s active-build backstop, inside the 7d gate).
    set_mtime_old(&target, 3_600);

    let policy = GuardPolicy {
        rust_search_roots: root.to_str().expect("utf8 root").to_string(),
        cleanup_min_size_mb: 0,
        rust_target_action_min_age_days: 7,
        ..Default::default()
    };
    let mut gated_state = GuardRuntimeState::default();
    let gated = auto_cleanup_rust_targets(&policy, &mut gated_state, false, false)
        .await
        .expect("gated scan");
    assert_eq!(
        gated.cleaned_count, 0,
        "age gate must protect the fresh target on the normal path"
    );
    let mut crit_state = GuardRuntimeState::default();
    let crit = auto_cleanup_rust_targets(&policy, &mut crit_state, false, true)
        .await
        .expect("bypass scan");
    assert_eq!(
        crit.cleaned_count, 1,
        "critical bypass must candidate the fresh target"
    );

    let _ = fs::remove_dir_all(&root);
}

/// 2026-10-03 (audit R4-SYS-08): `tmp_min_age_hours = 0` DISABLES
/// tmp hygiene (early return) — the policy table used to claim it
/// swept regardless of age. A stale file must survive both modes.
#[tokio::test]
async fn clean_tmp_paths_zero_min_age_disables() {
    let root = unique_test_tmp_root("tmp_zero_age");
    fs::create_dir_all(&root).expect("create tmp root");
    let stale = root.join("stale.log");
    write_file_with_mtime(&stale, b"old log data", 2 * 86_400);
    let roots = vec![root.display().to_string()];

    let (dry_bytes, dry_lines) = clean_tmp_paths(false, &roots, 0, &[])
        .await
        .expect("dry run");
    assert_eq!(dry_bytes, 0, "0 must report nothing reclaimable");
    assert!(dry_lines.is_empty(), "0 must list no candidates");
    assert!(stale.exists(), "dry run must not delete");

    let (bytes, lines) = clean_tmp_paths(true, &roots, 0, &[]).await.expect("apply");
    assert_eq!(bytes, 0, "0 must reclaim nothing");
    assert!(lines.is_empty(), "0 must clean nothing");
    assert!(stale.exists(), "0 must leave even stale entries alone");

    let _ = fs::remove_dir_all(&root);
}

/// 2026-10-03 (audit R4-SYS-13): an unreadable tmp root is SKIPPED
/// (deletion-safe) with a diagnostic — never a pass failure. Pins the
/// skip direction so a future editor "fixing" the silence cannot turn
/// it into a bail that disables the whole tmp pass.
#[cfg(unix)]
#[tokio::test]
async fn clean_tmp_paths_skips_unreadable_root() {
    let root = unique_test_tmp_root("tmp_noread");
    fs::create_dir_all(&root).expect("create fixture");
    write_file_with_mtime(&root.join("stale.log"), b"stale", 2 * 86_400);
    fs::set_permissions(&root, fs::Permissions::from_mode(0o000)).expect("lock root");
    let roots = vec![root.display().to_string()];

    for apply in [false, true] {
        let (bytes, lines) = clean_tmp_paths(apply, &roots, 24, &[])
            .await
            .expect("unreadable root must skip, not fail the pass");
        assert_eq!(bytes, 0, "skipped root reclaims nothing");
        assert!(lines.is_empty(), "skipped root cleans nothing");
    }

    fs::set_permissions(&root, fs::Permissions::from_mode(0o755)).expect("restore for cleanup");
    assert!(
        root.join("stale.log").exists(),
        "skipped root must leave entries alone"
    );
    let _ = fs::remove_dir_all(&root);
}

#[tokio::test]
async fn clean_tmp_paths_respects_age_dry_run_and_open_fds() {
    let root = unique_test_tmp_root("tmp_clean");
    fs::create_dir_all(&root).expect("create tmp root");
    let old_file = root.join("stale-pi-bash.log");
    let new_file = root.join("active-session.log");
    write_file_with_mtime(&old_file, b"old log data", 2 * 86_400);
    write_file_with_mtime(&new_file, b"live", 60);

    // Hold an old-aged file open via this process so /proc/self/fd sees it.
    let held = root.join("held-open.bin");
    write_file_with_mtime(&held, b"held", 2 * 86_400);
    let handle = fs::File::open(&held).expect("open held file");

    let roots = vec![root.display().to_string()];

    // Dry-run measures but deletes nothing.
    let (dry_bytes, dry_lines) = clean_tmp_paths(false, &roots, 24, &[])
        .await
        .expect("dry run");
    assert!(dry_bytes > 0, "dry run should report reclaimable bytes");
    assert!(old_file.exists(), "dry run must not delete");
    assert!(
        !dry_lines.iter().any(|l| l.contains("active-session")),
        "young entries are not candidates"
    );
    assert!(
        !dry_lines.iter().any(|l| l.contains("held-open")),
        "open-held entries are skipped even when old"
    );

    // Apply removes only aged, unheld entries.
    let (bytes, lines) = clean_tmp_paths(true, &roots, 24, &[]).await.expect("apply");
    assert_eq!(
        bytes, dry_bytes,
        "apply should reclaim exactly what dry-run measured"
    );
    assert!(!old_file.exists(), "aged unheld entry must be removed");
    assert!(new_file.exists(), "young entry must be kept");
    assert!(
        held.exists(),
        "entry held open by a live process must be kept"
    );
    assert_eq!(lines.len(), 1);

    drop(handle);
    let _ = fs::remove_dir_all(&root);
}

#[tokio::test]
async fn clean_tmp_keeps_tree_with_fresh_nested_content() {
    // Audit MEDIUM: directory mtime only bumps on direct-child changes,
    // so a stale top dir can hide a freshly written nested file. The
    // cleaner must judge the tree by its newest entry, not the top dir.
    use std::time::Duration;
    let root = unique_test_tmp_root("tmp_nested");
    fs::create_dir_all(&root).expect("create tmp root");
    let stale_dir = root.join("old-run");
    let nested = stale_dir.join("logs");
    fs::create_dir_all(&nested).expect("create nested dir");
    write_file_with_mtime(&nested.join("fresh.log"), b"just written", 60);
    // Backdate everything except the fresh log, top dir included.
    let old = SystemTime::now() - Duration::from_secs(2 * 86_400);
    for p in [&stale_dir, &nested] {
        fs::OpenOptions::new()
            .read(true)
            .open(p)
            .expect("open dir for mtime set")
            .set_modified(old)
            .expect("backdate dir");
    }
    // A fully stale tree next to it must still be cleaned.
    let dead_dir = root.join("dead-run");
    fs::create_dir_all(&dead_dir).expect("create dead dir");
    write_file_with_mtime(&dead_dir.join("old.log"), b"stale", 2 * 86_400);
    fs::OpenOptions::new()
        .read(true)
        .open(&dead_dir)
        .expect("open dir for mtime set")
        .set_modified(old)
        .expect("backdate dir");

    let roots = vec![root.display().to_string()];
    let (bytes, lines) = clean_tmp_paths(true, &roots, 24, &[]).await.expect("apply");
    assert!(bytes > 0, "the dead tree must be reclaimed");
    assert!(!dead_dir.exists(), "fully stale tree must be removed");
    assert!(
        stale_dir.join("logs").join("fresh.log").exists(),
        "tree with fresh nested content must be kept: {lines:?}"
    );
    assert!(
        !lines.iter().any(|l| l.contains("old-run")),
        "kept tree must not be reported cleaned: {lines:?}"
    );
    let _ = fs::remove_dir_all(&root);
}

#[tokio::test]
async fn clean_tmp_paths_rejects_home_search_root_before_apply() {
    let home = dirs::home_dir().expect("home directory");
    let sentinel = home.join(format!(
        ".dracon_system_f65_home_sentinel_{}_{}",
        std::process::id(),
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time")
            .as_nanos()
    ));
    write_file_with_mtime(&sentinel, b"must survive", 2 * 86_400);

    let result = clean_tmp_paths(true, &["~".to_string()], 24, &[]).await;
    let sentinel_survived = sentinel.exists();
    let _ = fs::remove_file(&sentinel);

    let error = result.expect_err("home must not be accepted as a tmp root");
    assert!(
        error.to_string().contains("invalid tmp_search_paths entry"),
        "invalid root should be reported, got: {error:#}"
    );
    assert!(
        sentinel_survived,
        "an apply config targeting ~ must not delete home data"
    );
}

#[cfg(unix)]
#[tokio::test]
async fn clean_tmp_paths_keeps_old_process_cwd_directory() {
    let root = unique_test_tmp_root("tmp_cwd");
    let proc_root = unique_test_home("proc_cwd");
    let cwd_dir = root.join("stale-working-directory");
    let unheld_file = root.join("stale-unheld-file");
    fs::create_dir_all(&cwd_dir).expect("create cwd fixture");
    write_file_with_mtime(&unheld_file, b"unheld", 2 * 86_400);

    // A directory's mtime determines whether it is a tmp cleanup candidate.
    // Use an open directory handle so the fixture models an old process cwd,
    // rather than relying on the current time when the directory is created.
    let cwd_handle = File::open(&cwd_dir).expect("open cwd fixture for mtime");
    cwd_handle
        .set_modified(SystemTime::now() - Duration::from_secs(2 * 86_400))
        .expect("set cwd fixture mtime");
    drop(cwd_handle);

    // Model /proc/4242/cwd without changing this test process's real cwd.
    let process_dir = proc_root.join("4242");
    fs::create_dir_all(process_dir.join("fd")).expect("create proc fixture");
    symlink(&cwd_dir, process_dir.join("cwd")).expect("create cwd proc link");

    let roots = vec![root.display().to_string()];
    let unheld_bytes = unheld_file.metadata().expect("unheld metadata").len();
    let open_paths = collect_open_paths_under_from(&proc_root, std::slice::from_ref(&root))
        .await
        .expect("readable proc fixture must scan");
    assert!(
        open_paths.contains(&cwd_dir),
        "process cwd must be included in open-path protection"
    );

    let (reclaimed, cleaned) = clean_tmp_paths_with_proc(true, &roots, 24, &[], &proc_root)
        .await
        .expect("tmp cleanup");
    assert_eq!(reclaimed, unheld_bytes);
    assert_eq!(cleaned.len(), 1, "only the unheld old entry is removed");
    assert!(cwd_dir.exists(), "an old process cwd must remain protected");
    assert!(
        !unheld_file.exists(),
        "an old unheld entry remains removable"
    );

    let _ = fs::remove_dir_all(&root);
    let _ = fs::remove_dir_all(&proc_root);
}

// --- 2026-10-12 (obvious-fat fast path): e2e-litter tmp window + quarantine budget ---

/// Backdate a directory itself (creating children bumps it to now).
fn backdate_dir(path: &std::path::Path, age_secs: u64) {
    fs::OpenOptions::new()
        .read(true)
        .open(path)
        .expect("open dir for mtime set")
        .set_modified(SystemTime::now() - Duration::from_secs(age_secs))
        .expect("backdate dir");
}

#[test]
fn tmp_e2e_match_covers_glob_shapes() {
    let patterns = parse_tmp_e2e_patterns("reconcile-*,*-shield-*,hh-base,nb-run");
    assert!(tmp_e2e_match("reconcile-e2e-7m8NJm", &patterns), "prefix*");
    assert!(
        tmp_e2e_match("reconcile-batch3-6Bo2kj", &patterns),
        "prefix* batch"
    );
    assert!(
        tmp_e2e_match("deathrun-shield-JRmPNh", &patterns),
        "*infix*"
    );
    assert!(tmp_e2e_match("hh-base", &patterns), "exact");
    assert!(tmp_e2e_match("nb-run", &patterns), "exact fixed name");
    let defaults = parse_tmp_e2e_patterns(&default_tmp_e2e_patterns());
    assert!(
        tmp_e2e_match("puppeteer_dev_chrome_profile-s9EHBY", &defaults),
        "puppeteer profile (2026-10-12 162M orphan)"
    );
    assert!(
        tmp_e2e_match("playwright_chromiumdev_profile-9oNqZ3", &defaults),
        "playwright profile"
    );
    assert!(
        !tmp_e2e_match("nb-runner", &patterns),
        "exact must not prefix-match"
    );
    assert!(!tmp_e2e_match("my-notes.md", &patterns), "unrelated name");
    assert!(
        !tmp_e2e_match("reconcile", &patterns),
        "prefix needs the dash"
    );
    let suffix = parse_tmp_e2e_patterns("*-fresh");
    assert!(tmp_e2e_match("nb-fresh", &suffix), "*suffix");
    assert!(
        !tmp_e2e_match("fresh-produce", &suffix),
        "suffix must anchor right"
    );
    assert!(tmp_e2e_match("anything", &parse_tmp_e2e_patterns("*")));
    assert!(
        parse_tmp_e2e_patterns("  , ,").is_empty(),
        "blanks drop out"
    );
    assert!(!tmp_e2e_match("x", &[]), "no patterns matches nothing");
}

#[test]
fn quarantine_budget_boundary_is_exclusive() {
    assert_eq!(quarantine_budget_bytes(0), u64::MAX, "0 = unlimited");
    assert_eq!(
        quarantine_budget_bytes(10240),
        10240 * 1024 * 1024,
        "MiB to bytes"
    );
    let ten = quarantine_budget_bytes(10240);
    assert!(
        !quarantine_over_budget(0, ten, ten),
        "exactly at budget is allowed"
    );
    assert!(
        quarantine_over_budget(0, ten + 1, ten),
        "one byte over defers"
    );
    assert!(
        !quarantine_over_budget(ten, 0, ten),
        "zero-size entry always fits"
    );
    assert!(
        quarantine_over_budget(ten, 1, ten),
        "full budget defers anything"
    );
    assert!(
        !quarantine_over_budget(0, u64::MAX / 2, u64::MAX),
        "unlimited never defers"
    );
    assert!(
        !quarantine_over_budget(u64::MAX, u64::MAX, u64::MAX),
        "saturating add must not panic at the extremes"
    );
}

#[cfg(unix)]
#[tokio::test]
async fn tmp_e2e_fast_path_owns_only_the_general_skipped_window() {
    // Fast path owns e2e entries NEWER than the general cutoff; entries the
    // general pass would take (>= 24h stale) are left alone so dry-run
    // accounting never counts an entry twice.
    let root = unique_test_tmp_root("tmp_e2e_window");
    fs::create_dir_all(&root).expect("create tmp root");
    let e2e_old = root.join("reconcile-e2e-abcdef");
    fs::create_dir_all(&e2e_old).expect("e2e old");
    write_file_with_mtime(&e2e_old.join("data.bin"), b"stale e2e", 7 * 3600);
    backdate_dir(&e2e_old, 7 * 3600);
    let plain_old = root.join("plain-old");
    fs::create_dir_all(&plain_old).expect("plain old");
    write_file_with_mtime(&plain_old.join("data.bin"), b"stale plain", 7 * 3600);
    backdate_dir(&plain_old, 7 * 3600);
    let e2e_ancient = root.join("cw-browser-test-ancient");
    fs::create_dir_all(&e2e_ancient).expect("e2e ancient");
    write_file_with_mtime(&e2e_ancient.join("data.bin"), b"ancient e2e", 30 * 3600);
    backdate_dir(&e2e_ancient, 30 * 3600);
    let e2e_fresh = root.join("dr-audit-fresh");
    fs::create_dir_all(&e2e_fresh).expect("e2e fresh");
    write_file_with_mtime(&e2e_fresh.join("data.bin"), b"fresh e2e", 60);

    let roots = vec![root.display().to_string()];
    let general_cutoff = SystemTime::now() - Duration::from_secs(24 * 3600);
    let patterns = parse_tmp_e2e_patterns(&default_tmp_e2e_patterns());
    let (dry_bytes, dry_lines, dry_denied) = clean_tmp_e2e_fast_path_with_proc(
        false,
        &roots,
        general_cutoff,
        &patterns,
        6,
        false,
        &[],
        Path::new("/proc"),
    )
    .await
    .expect("dry run");
    assert!(dry_denied.is_empty());
    assert_eq!(
        dry_lines.len(),
        1,
        "only the windowed e2e entry: {dry_lines:?}"
    );
    assert!(dry_lines[0].contains("reconcile-e2e-abcdef"));
    assert!(dry_bytes > 0);

    let (_, lines, _) = clean_tmp_e2e_fast_path_with_proc(
        true,
        &roots,
        general_cutoff,
        &patterns,
        6,
        false,
        &[],
        Path::new("/proc"),
    )
    .await
    .expect("apply");
    assert_eq!(lines.len(), 1);
    assert!(!e2e_old.exists(), "windowed e2e litter must be removed");
    assert!(
        plain_old.exists(),
        "non-e2e entry is not fast-path business"
    );
    assert!(
        e2e_ancient.exists(),
        "general-owned entry left for the general pass"
    );
    assert!(e2e_fresh.exists(), "fresh entry must be kept");
    let _ = fs::remove_dir_all(&root);
}

#[cfg(unix)]
#[tokio::test]
async fn tmp_e2e_fast_path_zero_age_disables() {
    // 0 is the documented "fast path off" sentinel: matching stale entries
    // must survive untouched (the general gate still applies separately).
    let root = unique_test_tmp_root("tmp_e2e_zero");
    fs::create_dir_all(&root).expect("create tmp root");
    let e2e_old = root.join("reconcile-e2e-zero");
    fs::create_dir_all(&e2e_old).expect("e2e old");
    write_file_with_mtime(&e2e_old.join("data.bin"), b"stale e2e", 7 * 3600);
    backdate_dir(&e2e_old, 7 * 3600);

    let roots = vec![root.display().to_string()];
    let general_cutoff = SystemTime::now() - Duration::from_secs(24 * 3600);
    let patterns = parse_tmp_e2e_patterns(&default_tmp_e2e_patterns());
    let (bytes, lines, denied) = clean_tmp_e2e_fast_path_with_proc(
        true,
        &roots,
        general_cutoff,
        &patterns,
        0,
        false,
        &[],
        Path::new("/proc"),
    )
    .await
    .expect("apply with 0 age");
    assert!(bytes == 0 && lines.is_empty() && denied.is_empty());
    assert!(e2e_old.exists(), "0 age must disable the fast path");
    let _ = fs::remove_dir_all(&root);
}

#[cfg(unix)]
#[tokio::test]
async fn tmp_e2e_fast_path_bypass_takes_fresh_unheld() {
    // Critical-tier bypass lifts the fast age gate for UNHELD e2e litter;
    // without bypass the same entry is kept.
    let root = unique_test_tmp_root("tmp_e2e_bypass");
    fs::create_dir_all(&root).expect("create tmp root");
    let e2e_fresh = root.join("hh-base");
    fs::create_dir_all(&e2e_fresh).expect("e2e fresh");
    write_file_with_mtime(&e2e_fresh.join("data.bin"), b"fresh e2e", 60);

    let roots = vec![root.display().to_string()];
    let general_cutoff = SystemTime::now() - Duration::from_secs(24 * 3600);
    let patterns = parse_tmp_e2e_patterns(&default_tmp_e2e_patterns());
    let (_, gated_lines, _) = clean_tmp_e2e_fast_path_with_proc(
        false,
        &roots,
        general_cutoff,
        &patterns,
        6,
        false,
        &[],
        Path::new("/proc"),
    )
    .await
    .expect("gated dry run");
    assert!(
        gated_lines.is_empty(),
        "fresh entry kept under the age gate"
    );
    let (_, bypass_lines, _) = clean_tmp_e2e_fast_path_with_proc(
        false,
        &roots,
        general_cutoff,
        &patterns,
        6,
        true,
        &[],
        Path::new("/proc"),
    )
    .await
    .expect("bypass dry run");
    assert_eq!(
        bypass_lines.len(),
        1,
        "bypass lists fresh unheld e2e litter"
    );
    assert!(bypass_lines[0].contains("hh-base"));
    let _ = fs::remove_dir_all(&root);
}

#[cfg(unix)]
#[tokio::test]
async fn tmp_e2e_fast_path_keeps_open_held_tree() {
    // An entry held open by a live process is skipped even when old,
    // matching, and (via bypass) age-eligible.
    let root = unique_test_tmp_root("tmp_e2e_held");
    fs::create_dir_all(&root).expect("create tmp root");
    let e2e_old = root.join("jr-audit");
    fs::create_dir_all(&e2e_old).expect("e2e old");
    let held = e2e_old.join("held-open.bin");
    write_file_with_mtime(&held, b"held", 7 * 3600);
    backdate_dir(&e2e_old, 7 * 3600);
    let handle = fs::File::open(&held).expect("open held file");

    let roots = vec![root.display().to_string()];
    let general_cutoff = SystemTime::now() - Duration::from_secs(24 * 3600);
    let patterns = parse_tmp_e2e_patterns(&default_tmp_e2e_patterns());
    let (_, lines, _) = clean_tmp_e2e_fast_path_with_proc(
        true,
        &roots,
        general_cutoff,
        &patterns,
        6,
        true,
        &[],
        Path::new("/proc"),
    )
    .await
    .expect("bypass apply");
    assert!(
        lines.is_empty(),
        "open-held tree must be kept even on bypass"
    );
    assert!(e2e_old.exists());
    drop(handle);
    let _ = fs::remove_dir_all(&root);
}

#[cfg(unix)]
#[tokio::test]
async fn open_scan_skips_unreadable_fd_table_without_abandoning_pass() {
    // R4-SYS-11 contract: an unreadable fd table (another user's
    // process, or fds vanishing mid-iteration) skips THAT process's
    // fds — the pass still returns Some, other processes' fds are
    // still collected, and the broken process's cwd is still
    // collected via its independent path. Guards against a future
    // editor extending the pid-level `return None` down to fd level.
    let root = unique_test_tmp_root("tmp_fdfail");
    let proc_root = unique_test_home("proc_fdfail");
    let held = root.join("held-by-b.log");
    fs::create_dir_all(&root).expect("create fixture");
    fs::write(&held, b"held").expect("write held");

    // Pid 4242: fd table unreadable (chmod 000 proxy for another
    // user's process), cwd readable.
    let proc_a = proc_root.join("4242");
    let fd_a = proc_a.join("fd");
    fs::create_dir_all(&fd_a).expect("create fd fixture");
    symlink(&root, proc_a.join("cwd")).expect("create cwd link");
    fs::set_permissions(&fd_a, fs::Permissions::from_mode(0o000)).expect("lock fd dir");

    // Pid 4243: healthy, one fd under the roots.
    let proc_b = proc_root.join("4243");
    fs::create_dir_all(proc_b.join("fd")).expect("create fd fixture");
    symlink(&held, proc_b.join("fd").join("3")).expect("create fd link");

    let open = collect_open_paths_under_from(&proc_root, std::slice::from_ref(&root))
        .await
        .expect("one unreadable fd table must not fail the pass");
    assert!(
        open.contains(&held),
        "the healthy process's fd must still be collected"
    );
    assert!(
        open.contains(&root),
        "the broken process's cwd must still be collected via its own path"
    );

    fs::set_permissions(&fd_a, fs::Permissions::from_mode(0o755)).expect("restore for cleanup");
    let _ = fs::remove_dir_all(&root);
    let _ = fs::remove_dir_all(&proc_root);
}

#[cfg(unix)]
#[tokio::test]
async fn open_scan_collects_running_executable() {
    // R4-SYS-12: a running executable is not an fd entry — the scan
    // must record /proc/<pid>/exe or tmp cleanup unlinks a stale
    // binary from under its own process.
    let root = unique_test_tmp_root("tmp_exe");
    let proc_root = unique_test_home("proc_exe");
    let binary = root.join("stale-runner");
    fs::create_dir_all(&root).expect("create fixture");
    fs::write(&binary, b"fake-elf").expect("write binary");
    let process_dir = proc_root.join("4242");
    fs::create_dir_all(process_dir.join("fd")).expect("create proc fixture");
    symlink(&binary, process_dir.join("exe")).expect("create exe link");

    let open = collect_open_paths_under_from(&proc_root, std::slice::from_ref(&root))
        .await
        .expect("readable proc fixture must scan");
    assert!(
        open.contains(&binary),
        "the running executable must be protected"
    );

    let _ = fs::remove_dir_all(&root);
    let _ = fs::remove_dir_all(&proc_root);
}

#[cfg(unix)]
#[tokio::test]
async fn clean_tmp_paths_refuses_blind_cleanup_when_proc_unreadable() {
    // R3-L31: an unreadable /proc must abort the pass LOUD (no
    // silent empty protection set) and delete nothing — in BOTH
    // apply and dry-run (dry-run would otherwise over-report).
    let root = unique_test_tmp_root("tmp_blind");
    let stale = root.join("stale-file");
    fs::create_dir_all(&root).expect("create fixture");
    write_file_with_mtime(&stale, b"stale", 2 * 86_400);
    let roots = vec![root.display().to_string()];
    let missing_proc = root.join("no-such-proc");

    for apply in [false, true] {
        let err = clean_tmp_paths_with_proc(apply, &roots, 24, &[], &missing_proc)
            .await
            .expect_err("unreadable proc must fail the pass");
        assert!(
            err.to_string().contains("refusing tmp cleanup blind"),
            "failure must name the blind-cleanup refusal, got: {err:#}"
        );
        assert!(
            stale.exists(),
            "nothing may be deleted blind (apply={apply})"
        );
    }

    let _ = fs::remove_dir_all(&root);
}

#[test]
fn guard_policy_defaults_cover_tmp_and_trash_age_fields() {
    let guard = GuardPolicy::default();
    assert!(guard.clean_tmp, "clean_tmp should default on");
    assert_eq!(guard.tmp_search_paths, "/tmp");
    assert_eq!(guard.tmp_min_age_hours, 24);
    assert_eq!(guard.trash_min_age_days, 7);
}

#[test]
fn guard_startup_config_errors_use_non_restarting_status() {
    let wrapped = anyhow::Error::new(PolicyLoadError(anyhow::anyhow!("invalid policy")));
    assert_eq!(exit_status_for_error(&wrapped), CONFIG_ERROR_EXIT_STATUS);
    assert_eq!(
        exit_status_for_error(&anyhow::anyhow!("runtime failure")),
        1
    );
}

#[cfg(unix)]
#[test]
fn non_unicode_policy_override_is_authoritative() {
    use std::os::unix::ffi::OsStringExt;

    let custom = std::ffi::OsString::from_vec(b"/tmp/policy-\xff.toml".to_vec());
    let resolved = resolve_system_policy_path_with(Some(custom.clone()), PathBuf::from("/nowhere"));

    assert_eq!(resolved.unwrap(), Some(PathBuf::from(custom)));
}

#[test]
fn shipped_guard_service_exposes_host_tmp_for_clean_tmp() {
    let service = include_str!("../dracon-system-guard.service");
    assert!(
        service
            .lines()
            .any(|line| line.trim() == "PrivateTmp=false"),
        "the shipped guard must share the host temporary namespace"
    );
    assert!(
        !service.lines().any(|line| line.trim() == "PrivateTmp=true"),
        "the shipped guard must not use a private temporary namespace"
    );
    assert!(
        service
            .lines()
            .any(|line| line.trim() == "WorkingDirectory=%h"),
        "relative policy paths need a stable user-service working directory"
    );

    let writable_paths = service
        .lines()
        .find_map(|line| line.strip_prefix("ReadWritePaths="))
        .expect("the guard service must declare writable paths");
    assert!(
        writable_paths.split_whitespace().any(|path| path == "/tmp"),
        "host /tmp must be writable despite ProtectSystem=strict"
    );

    let guard = GuardPolicy::default();
    assert!(
        guard.clean_tmp,
        "the production default must enable clean_tmp"
    );
    assert_eq!(
        guard.tmp_search_paths, "/tmp",
        "the policy and service must target the same host namespace"
    );
}

#[test]
fn shipped_guard_service_restart_policy_handles_disabled_and_bad_config() {
    let service = include_str!("../dracon-system-guard.service");
    assert!(
        service
            .lines()
            .any(|line| line.trim() == "Restart=on-failure"),
        "clean enabled=false exits must not restart the guard"
    );
    assert!(
        !service.lines().any(|line| line.trim() == "Restart=always"),
        "the guard must not restart after a clean policy-disabled exit"
    );
    assert!(
        service
            .lines()
            .any(|line| line.trim() == "RestartPreventExitStatus=2 78"),
        "usage errors and EX_CONFIG policy errors must remain stopped"
    );
}

#[tokio::test]
async fn guard_report_completes_for_ok_disk() {
    let fixture = unique_test_home("guard_report");
    fs::create_dir(&fixture).expect("create report fixture");
    let mut state = GuardRuntimeState::default();
    // This is a report-assembly smoke test, not a cleanup integration test.
    // The host disk may be full. Force the OK branch and explicitly disable
    // every mutating/expensive subsystem instead of inheriting live defaults.
    // 101 is a test-only unreachable threshold for a percentage (0..=100).
    let guard = GuardPolicy {
        disk_early_warn_percent: 101,
        disk_warn_percent: 101,
        disk_action_percent: 101,
        disk_critical_percent: 101,
        proactive_cleanup_percent: 101,
        disk_mount_path: fixture.display().to_string(),
        sync_freeze_marker: fixture.join("freeze").display().to_string(),
        guard_log_file: fixture.join("guard.log").display().to_string(),
        freeze_sync_at_action: false,
        track_trends: false,
        notify: false,
        auto_cleanup_apply: false,
        auto_cleanup_rust: false,
        docker_prune: false,
        clean_package_caches: false,
        clean_trash: false,
        clean_nix_garbage: false,
        clean_node_modules: false,
        clean_tmp: false,
        monitor_inodes: false,
        monitor_zombies: false,
        monitor_memory: false,
        monitor_logs: false,
        auto_renice: false,
        auto_renice_on_memory: false,
        bias_oom_on_pressure: false,
        ..GuardPolicy::default()
    };
    let report = tokio::time::timeout(Duration::from_secs(10), run_guard_once(&guard, &mut state))
        .await
        .expect("report assembly must be bounded")
        .expect("report succeeds");
    assert_eq!(report.disk_state, "ok");
    assert!(!report.sync_frozen);
    assert!(!fixture.join("freeze").exists());
    fs::remove_dir_all(fixture).expect("remove report fixture");
}

#[test]
fn guard_never_removes_or_overwrites_operator_freeze_marker() {
    let marker = std::env::temp_dir().join(format!(
        "dracon-system-freeze-operator-{}-{}",
        std::process::id(),
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time")
            .as_nanos()
    ));
    let operator_contents = "dracon-sync pause\n";
    fs::write(&marker, operator_contents).expect("write operator marker");

    let guard = GuardPolicy {
        freeze_sync_at_action: false,
        sync_freeze_marker: marker.display().to_string(),
        unfreeze_below_percent: 70,
        ..GuardPolicy::default()
    };
    let mut sync_frozen = true;
    manage_sync_freeze(&guard, 68, "ok", &mut sync_frozen);
    assert!(marker.exists(), "guard-disabled policy must not remove it");
    assert_eq!(
        fs::read_to_string(&marker).expect("read marker"),
        operator_contents
    );
    assert!(sync_frozen);

    // Even when automatic freezing is enabled, an existing marker written by
    // dracon-sync remains operator-owned and must not be replaced or removed.
    let enabled_guard = GuardPolicy {
        freeze_sync_at_action: true,
        ..guard
    };
    manage_sync_freeze(&enabled_guard, 95, "action", &mut sync_frozen);
    assert!(marker.exists(), "guard must not replace an operator marker");
    assert_eq!(
        fs::read_to_string(&marker).expect("read marker"),
        operator_contents
    );

    let _ = fs::remove_file(marker);
}

#[test]
fn guard_removes_only_its_own_freeze_marker() {
    let marker = std::env::temp_dir().join(format!(
        "dracon-system-freeze-owned-{}-{}",
        std::process::id(),
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time")
            .as_nanos()
    ));
    let guard = GuardPolicy {
        freeze_sync_at_action: true,
        sync_freeze_marker: marker.display().to_string(),
        unfreeze_below_percent: 70,
        ..GuardPolicy::default()
    };

    let mut sync_frozen = false;
    manage_sync_freeze(&guard, 95, "action", &mut sync_frozen);
    assert!(sync_frozen);
    assert!(marker.exists());
    assert!(fs::read_to_string(&marker)
        .expect("read guard marker")
        .starts_with(GUARD_FREEZE_MARKER_PREFIX));

    manage_sync_freeze(&guard, 68, "ok", &mut sync_frozen);
    assert!(!marker.exists(), "guard-owned marker should be released");
    assert!(!sync_frozen);
}

#[test]
fn test_graduated_nice_value_cpu_tiers() {
    assert_eq!(graduated_nice_value(100.0, 0, 5, 0), 5);
    assert_eq!(graduated_nice_value(180.0, 0, 5, 0), 5);
    assert_eq!(graduated_nice_value(250.0, 0, 5, 0), 5);
    assert_eq!(graduated_nice_value(300.0, 0, 5, 0), 10);
    assert_eq!(graduated_nice_value(450.0, 0, 5, 0), 10);
    assert_eq!(graduated_nice_value(500.0, 0, 5, 0), 15);
    assert_eq!(graduated_nice_value(900.0, 0, 5, 0), 15);
}

#[test]
fn test_graduated_nice_value_memory_tiers() {
    assert_eq!(graduated_nice_value(0.0, 2000, 5, 0), 5);
    assert_eq!(graduated_nice_value(0.0, 4096, 5, 0), 5);
    assert_eq!(graduated_nice_value(0.0, 5000, 5, 0), 5);
    assert_eq!(graduated_nice_value(0.0, 8192, 5, 0), 10);
    assert_eq!(graduated_nice_value(0.0, 16000, 5, 0), 10);
}

#[test]
fn test_graduated_nice_value_cpu_plus_memory() {
    assert_eq!(graduated_nice_value(300.0, 8192, 5, 0), 10);
    assert_eq!(graduated_nice_value(500.0, 4096, 5, 0), 15);
    assert_eq!(graduated_nice_value(180.0, 8192, 5, 0), 10);
}

#[test]
fn test_graduated_nice_value_clamped() {
    assert_eq!(graduated_nice_value(0.0, 0, 5, 0), 5);
    assert_eq!(graduated_nice_value(0.0, 0, 0, 0), 0);
}

#[test]
fn test_graduated_nice_value_negative_base_clamped() {
    assert_eq!(graduated_nice_value(0.0, 0, -5, 0), 0);
}

#[test]
fn test_graduated_nice_value_high_base_clamped() {
    assert_eq!(graduated_nice_value(0.0, 0, 20, 0), 19);
}

#[test]
fn test_graduated_nice_value_memory_boundary() {
    assert_eq!(graduated_nice_value(0.0, 4095, 0, 0), 0);
    assert_eq!(graduated_nice_value(0.0, 4096, 0, 0), 5);
    assert_eq!(graduated_nice_value(0.0, 8191, 0, 0), 5);
    assert_eq!(graduated_nice_value(0.0, 8192, 0, 0), 10);
}

/// Same nix-sandbox reasoning as `unique_test_tmp_root`: the guard
/// accepts only `/tmp` descendants.
fn guard_test_tmp(name: &str) -> std::path::PathBuf {
    std::path::Path::new("/tmp").join(format!(
        "dracon_test_{}_{}_{}",
        name,
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ))
}

#[test]
fn safe_tmp_root_policy_allows_tmp_descendants_and_rejects_home() {
    let tmp = guard_test_tmp("safe_tmp_root");
    std::fs::create_dir_all(&tmp).expect("tmp root");

    let resolved = check_safe_tmp_root(&tmp).expect("tmp descendant should be allowed");
    assert!(resolved.starts_with("/tmp"));

    let home = dirs::home_dir().expect("home directory");
    let error = check_safe_tmp_root(&home).expect_err("home must not be a tmp root");
    assert!(error.to_string().contains("must be /tmp (or a descendant)"));

    let _ = std::fs::remove_dir_all(&tmp);
}

/// Set a file or dir mtime `hours` in the past (`File::set_modified`
/// is stable; opening a dir read-only suffices for futimens on Linux).
fn set_mtime_hours_ago(path: &std::path::Path, hours: u64) {
    let f = std::fs::OpenOptions::new()
        .read(true)
        .open(path)
        .unwrap_or_else(|e| panic!("open {} to set mtime: {e}", path.display()));
    f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(hours * 3600))
        .unwrap_or_else(|e| panic!("set mtime on {}: {e}", path.display()));
}

#[tokio::test]
async fn tree_has_fresh_content_fails_closed_on_walk_errors() {
    // R3-L22: unreadable subtrees (or any walk error) must read as
    // FRESH (keep), never skip toward a delete verdict. Controls:
    // old content reads stale, fresh content reads fresh.
    use std::os::unix::fs::PermissionsExt;
    let now = std::time::SystemTime::now();
    let cutoff = now - std::time::Duration::from_secs(60);

    let stale = guard_test_tmp("fresh_closed_stale");
    std::fs::create_dir_all(&stale).unwrap();
    let old_file = stale.join("old");
    std::fs::write(&old_file, b"old").unwrap();
    set_mtime_hours_ago(&old_file, 1);
    set_mtime_hours_ago(&stale, 1);
    assert!(
        !tree_has_fresh_content(&stale, cutoff).await,
        "all-old tree must read stale"
    );

    let fresh = guard_test_tmp("fresh_closed_fresh");
    std::fs::create_dir_all(&fresh).unwrap();
    std::fs::write(fresh.join("new"), b"new").unwrap();
    assert!(
        tree_has_fresh_content(&fresh, cutoff).await,
        "tree with a fresh file must read fresh"
    );

    // chmod-000 subdir: readdir fails EACCES → fail closed (fresh).
    let locked = guard_test_tmp("fresh_closed_locked");
    let sub = locked.join("sub");
    std::fs::create_dir_all(&sub).unwrap();
    std::fs::write(sub.join("x"), b"x").unwrap();
    set_mtime_hours_ago(&sub.join("x"), 1);
    set_mtime_hours_ago(&sub, 1);
    set_mtime_hours_ago(&locked, 1);
    std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o000)).unwrap();
    let verdict = tree_has_fresh_content(&locked, cutoff).await;
    std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o755)).unwrap();
    assert!(verdict, "unreadable subtree must fail closed (fresh/keep)");

    let _ = std::fs::remove_dir_all(&stale);
    let _ = std::fs::remove_dir_all(&fresh);
    let _ = std::fs::remove_dir_all(&locked);
}

#[test]
fn tmp_entry_must_remain_under_validated_root() {
    let root = guard_test_tmp("tmp_root_containment");
    let outside = guard_test_tmp("tmp_outside_containment");
    std::fs::create_dir_all(&root).expect("tmp root");
    std::fs::create_dir_all(&outside).expect("outside root");

    let validated = check_safe_tmp_root(&root).expect("tmp root should be valid");
    let result = check_safe_to_delete_tmp_entry(&outside, &validated, &[]);
    assert!(
        result.is_err(),
        "a candidate outside the validated tmp root must be rejected"
    );

    let _ = std::fs::remove_dir_all(&root);
    let _ = std::fs::remove_dir_all(&outside);
}

#[test]
fn guard_safe_delete_allows_paths_under_system_protected() {
    let tmp = guard_test_tmp("guard_safe_1");
    let target = tmp.join("target");
    std::fs::create_dir_all(&target).unwrap();
    let result = check_safe_to_delete_guard(&target, &[]);
    assert!(
        result.is_ok(),
        "guard safe delete should allow paths under /home (system-protected skipped)"
    );
    let _ = std::fs::remove_dir_all(&tmp);
}

#[test]
fn guard_safe_delete_blocks_user_protected() {
    let tmp = guard_test_tmp("guard_safe_2");
    let target = tmp.join("target");
    std::fs::create_dir_all(&target).unwrap();
    let user_protected = vec![tmp.display().to_string()];
    let result = check_safe_to_delete_guard(&target, &user_protected);
    assert!(
        result.is_err(),
        "guard safe delete should block user-protected paths"
    );
    let _ = std::fs::remove_dir_all(&tmp);
}

#[test]
fn guard_safe_delete_rejects_symlink() {
    let tmp = guard_test_tmp("guard_safe_3");
    let real = tmp.join("real_target");
    std::fs::create_dir_all(&real).unwrap();
    let link = tmp.join("link_target");
    let _ = std::fs::remove_file(&link);
    std::os::unix::fs::symlink(&real, &link).unwrap();
    let result = check_safe_to_delete_guard(&link, &[]);
    assert!(result.is_err(), "guard safe delete should reject symlinks");
    let _ = std::fs::remove_dir_all(&tmp);
}

#[test]
fn guard_safe_delete_rejects_exact_system_roots() {
    for prot in SYSTEM_PROTECTED {
        // Some build sandboxes (including Nix) intentionally omit host roots
        // such as /home.  A missing path is already safe to delete, while
        // every existing protected root must still be rejected here.
        if !Path::new(prot).exists() {
            continue;
        }
        let result = check_safe_to_delete_guard(Path::new(prot), &[]);
        assert!(
            result.is_err(),
            "guard safe delete should reject exact protected system root {prot}"
        );
    }
}

#[test]
fn check_safe_to_delete_rejects_log_symlink_before_truncate() {
    let tmp = guard_test_tmp("log_symlink");
    std::fs::create_dir_all(&tmp).unwrap();
    let real = tmp.join("real.log");
    let link = tmp.join("link.log");
    std::fs::write(&real, "line1\nline2\nline3\n").unwrap();
    std::os::unix::fs::symlink(&real, &link).unwrap();

    let result = check_safe_to_delete(&link, &[]);
    assert!(
        result.is_err(),
        "symlink log should be rejected before truncate"
    );
    assert_eq!(
        std::fs::read_to_string(&real).unwrap(),
        "line1\nline2\nline3\n"
    );

    let _ = std::fs::remove_dir_all(&tmp);
}

#[test]
fn proactive_cleanup_defaults() {
    assert_eq!(default_proactive_cleanup_percent(), 80);
    assert_eq!(default_auto_cleanup_interval_secs(), 1800);
    assert_eq!(default_rust_target_max_age_days(), 14);
    assert_eq!(default_rust_target_action_min_age_days(), 7);
    assert_eq!(default_proactive_cleanup_interval_cycles(), 120);
}

#[test]
fn action_cleanup_age_gate_lingering_definition() {
    // 2026-09-14: action-level cleanup must not touch active projects.
    const DAY: u64 = 86400;
    // Freshly built (hours old) is never a candidate.
    assert!(!rust_target_old_enough_for_action_cleanup(3600, 7));
    // Touched yesterday is still active.
    assert!(!rust_target_old_enough_for_action_cleanup(DAY, 7));
    // Exactly at the boundary counts as lingering.
    assert!(rust_target_old_enough_for_action_cleanup(7 * DAY, 7));
    // Untouched for weeks is a candidate.
    assert!(rust_target_old_enough_for_action_cleanup(30 * DAY, 7));
}

#[test]
fn action_cleanup_age_gate_zero_disables() {
    // 0 restores the pre-fix delete-anything posture for operators who
    // want it; normalize must not clamp it away.
    assert!(rust_target_old_enough_for_action_cleanup(0, 0));
    let policy = GuardPolicy {
        rust_target_action_min_age_days: 0,
        ..Default::default()
    };
    let mut policy = policy;
    normalize_guard_policy(&mut policy);
    assert_eq!(policy.rust_target_action_min_age_days, 0);
}

#[test]
fn normalize_proactive_cleanup_percent_bounded_by_action() {
    let policy = GuardPolicy {
        disk_action_percent: 85,
        proactive_cleanup_percent: 90,
        ..Default::default()
    };
    let mut policy = policy;
    normalize_guard_policy(&mut policy);
    assert!(
        policy.proactive_cleanup_percent < policy.disk_action_percent,
        "proactive_cleanup_percent must be below disk_action_percent"
    );
}

#[test]
fn normalize_rust_target_max_age_days_min_1() {
    let policy = GuardPolicy {
        rust_target_max_age_days: 0,
        ..Default::default()
    };
    let mut policy = policy;
    normalize_guard_policy(&mut policy);
    assert!(policy.rust_target_max_age_days >= 1);
}

#[test]
fn normalize_proactive_interval_min_1() {
    let policy = GuardPolicy {
        proactive_cleanup_interval_cycles: 0,
        ..Default::default()
    };
    let mut policy = policy;
    normalize_guard_policy(&mut policy);
    assert!(policy.proactive_cleanup_interval_cycles >= 1);
}

#[test]
fn normalize_auto_cleanup_interval_min_60() {
    let policy = GuardPolicy {
        auto_cleanup_interval_secs: 0,
        ..Default::default()
    };
    let mut policy = policy;
    normalize_guard_policy(&mut policy);
    assert!(policy.auto_cleanup_interval_secs >= 60);
}

#[test]
fn auto_cleanup_cadence_is_stateful() {
    let now = Instant::now();
    let mut state = GuardRuntimeState::default();
    assert!(auto_cleanup_due_at(&state, 1800, now));

    state.last_auto_cleanup = Some(now - Duration::from_secs(1799));
    assert!(!auto_cleanup_due_at(&state, 1800, now));

    state.last_auto_cleanup = Some(now - Duration::from_secs(1800));
    assert!(auto_cleanup_due_at(&state, 1800, now));
}

#[test]
fn guard_runtime_state_default_cycle_zero() {
    let state = GuardRuntimeState::default();
    assert_eq!(state.guard_cycle, 0);
    assert!(state.last_proactive_cleanup.is_none());
    assert!(state.last_auto_cleanup.is_none());
}

#[test]
fn target_dir_info_has_mtime() {
    let info = TargetDirInfo {
        path: PathBuf::from("/tmp/test/target"),
        bytes: 1024,
        mtime_secs_ago: 86400 * 15,
    };
    assert_eq!(info.mtime_secs_ago, 86400 * 15);
    assert_eq!(info.bytes, 1024);
}

#[test]
fn truncate_log_preserves_open_writer_inode() {
    let td =
        std::env::temp_dir().join(format!("dracon-system-truncate-log-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&td);
    std::fs::create_dir_all(&td).expect("temp dir");
    let path = td.join("guard.log");
    std::fs::write(&path, "header\nbody-one\nbody-two\n").expect("log");

    // Keep an append handle open as a long-running logger would. A rename-
    // based truncation leaves this handle on an unlinked inode; in-place
    // truncation keeps subsequent lines visible at the original path.
    let mut writer = std::fs::OpenOptions::new()
        .append(true)
        .open(&path)
        .expect("open writer");
    let reclaimed = truncate_log_file(&path, 12, 1).expect("truncate");
    assert!(reclaimed > 0);
    use std::io::Write;
    writer.write_all(b"tail\n").expect("append after truncate");

    let content = std::fs::read_to_string(&path).expect("read log");
    assert!(content.starts_with("header\n"));
    assert!(
        content.contains("tail\n"),
        "writer output must remain visible"
    );
    assert!(!content.contains("body-two"));
    let _ = std::fs::remove_dir_all(&td);
}

#[test]
fn truncate_log_preserves_non_utf8_lines_verbatim() {
    // 2026-10-02 (audit L8): `BufRead::lines()` yields Err on invalid
    // UTF-8 and both loops STOPPED there, silently dropping the bad
    // line AND everything after it. Byte-split lines preserve them.
    let td = std::env::temp_dir().join(format!(
        "dracon-system-truncate-utf8-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&td);
    std::fs::create_dir_all(&td).expect("temp dir");
    let path = td.join("app.log");
    let mut raw = b"header\nok-line\n".to_vec();
    raw.extend_from_slice(b"bad-\xff\xfe-bytes\n");
    raw.extend_from_slice(b"after-bad-line\n");
    raw.extend_from_slice(&[b'x'; 200]);
    std::fs::write(&path, &raw).expect("log");

    let reclaimed = truncate_log_file(&path, 64, 1).expect("truncate");
    assert!(reclaimed > 0);
    let out = std::fs::read(&path).expect("read log");
    assert!(out.starts_with(b"header\n"), "header must survive: {out:?}");
    assert!(
        out.windows(8).any(|w| w == b"bad-\xff\xfe-b"),
        "non-UTF8 line must be preserved verbatim: {out:?}"
    );
    assert!(
        out.windows(14).any(|w| w == b"after-bad-line"),
        "lines AFTER the bad line must survive (old code stopped): {out:?}"
    );
    assert!(
        out.len() as u64 <= 64,
        "budget must hold: {} bytes",
        out.len()
    );
    let _ = std::fs::remove_dir_all(&td);
}

#[test]
fn truncate_log_handles_missing_trailing_newline_and_blank_lines() {
    // Byte-split must not invent or drop lines at the edges: a missing
    // trailing newline gains one terminator (as before), blank lines
    // survive, and the terminator artifact is never kept as a line.
    let td = std::env::temp_dir().join(format!(
        "dracon-system-truncate-edge-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&td);
    std::fs::create_dir_all(&td).expect("temp dir");
    let path = td.join("app.log");
    std::fs::write(&path, b"h1\n\nbody-no-newline").expect("log");

    let reclaimed = truncate_log_file(&path, 10, 1).expect("truncate");
    assert!(reclaimed > 0);
    let out = std::fs::read(&path).expect("read log");
    assert_eq!(
        out, b"h1\n\n",
        "header + blank line, terminator artifact dropped"
    );
    let _ = std::fs::remove_dir_all(&td);
}

#[tokio::test]
async fn clean_old_node_modules_counts_nested_tree_once() {
    let td = std::env::temp_dir().join(format!(
        "dracon-system-node-modules-{}-{}",
        std::process::id(),
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time")
            .as_nanos()
    ));
    let outer = td.join("project/node_modules");
    let inner = outer.join("nested/node_modules");
    std::fs::create_dir_all(&inner).expect("create nested node_modules");
    std::fs::write(outer.join("outer.bin"), vec![b'o'; 17]).expect("write outer file");
    std::fs::write(inner.join("inner.bin"), vec![b'i'; 29]).expect("write inner file");

    let expected = get_dir_size(&outer).await.expect("measure outer tree");
    let (reclaimed, cleaned) = clean_old_node_modules(
        std::slice::from_ref(&td),
        0,
        false,
        &[],
        false,
        std::path::Path::new(""),
    )
    .await
    .expect("dry-run node_modules cleanup");

    assert_eq!(
        cleaned.len(),
        1,
        "nested node_modules must not be listed twice"
    );
    assert_eq!(reclaimed, expected, "outer tree must be counted once");
    let _ = std::fs::remove_dir_all(&td);
}

#[test]
fn rust_build_process_detection_covers_long_lived_tooling() {
    // Pre-existing classes stay detected (substring + exact).
    assert!(is_rust_build_process("cargo"));
    assert!(is_rust_build_process("cargo-build"));
    assert!(is_rust_build_process("rustc"));
    assert!(is_rust_build_process("rustc-1.94.1"));
    assert!(is_rust_build_process("clippy-driver"));
    // Long-lived Rust tooling added 2026-08-21 (detection gap): a running
    // analyzer or watch session holds the target dir just like a build.
    assert!(is_rust_build_process("rust-analyzer"));
    assert!(is_rust_build_process("cargo-watch"));
    // Unrelated processes must not match.
    assert!(!is_rust_build_process(""));
    assert!(!is_rust_build_process("firefox"));
    assert!(!is_rust_build_process("dracon-sync"));
    assert!(!is_rust_build_process("node"));
}

#[test]
fn package_cache_process_detection_covers_direct_and_wrapped_tools() {
    let proc_root = unique_test_home("package_proc");
    fs::create_dir_all(proc_root.join("self")).expect("create proc fixture");

    for (pid, cmdline) in [
        (101, b"/usr/bin/python3\0-m\0pip\0install\0".as_slice()),
        (
            102,
            b"/usr/bin/node\0/usr/lib/npm/npm-cli.js\0install\0".as_slice(),
        ),
        (103, b"/bin/sh\0-c\0go\0build\0./...\0".as_slice()),
    ] {
        let process_dir = proc_root.join(pid.to_string());
        fs::create_dir_all(&process_dir).expect("create process fixture");
        fs::write(process_dir.join("cmdline"), cmdline).expect("write cmdline fixture");
    }

    let active = detect_active_package_manager_operations_from(
        "100 cargo\n101 python3\n102 node\n103 sh\n104 firefox\n",
        &proc_root,
    )
    .expect("process metadata fixture should be readable");
    assert_eq!(active.len(), 4);
    assert!(active.contains(&PackageCacheKind::Cargo));
    assert!(active.contains(&PackageCacheKind::Npm));
    assert!(active.contains(&PackageCacheKind::Pip));
    assert!(active.contains(&PackageCacheKind::Go));

    let _ = fs::remove_dir_all(proc_root);
}

#[cfg(unix)]
#[test]
fn package_cache_process_detection_fails_closed_on_unreadable_cmdline() {
    let proc_root = unique_test_home("package_proc_unreadable");
    let process_dir = proc_root.join("201");
    fs::create_dir_all(proc_root.join("self")).expect("create proc fixture");
    fs::create_dir_all(&process_dir).expect("create process fixture");
    let cmdline = process_dir.join("cmdline");
    fs::write(
        &cmdline,
        b"/usr/bin/node\0/usr/lib/npm/npm-cli.js\0install\0",
    )
    .expect("write cmdline fixture");
    fs::set_permissions(&cmdline, fs::Permissions::from_mode(0o000))
        .expect("make cmdline unreadable");

    let result = detect_active_package_manager_operations_from("201 python3\n", &proc_root);
    assert!(
        result.is_err(),
        "an unreadable wrapper command line must abort cache protection"
    );

    let _ = fs::remove_dir_all(proc_root);
}

#[test]
fn package_cache_process_detection_fails_closed_on_missing_cmdline() {
    let proc_root = unique_test_home("package_proc_missing_cmdline");
    fs::create_dir_all(proc_root.join("self")).expect("create proc fixture");
    fs::create_dir_all(proc_root.join("202")).expect("create process fixture");

    let result = detect_active_package_manager_operations_from("202 python3\n", &proc_root);
    assert!(
        result.is_err(),
        "an existing process without cmdline metadata must abort cache protection"
    );

    let _ = fs::remove_dir_all(proc_root);
}

#[test]
fn package_cache_process_detection_rejects_malformed_ps_output() {
    let proc_root = unique_test_home("package_proc_malformed");
    fs::create_dir_all(proc_root.join("self")).expect("create proc fixture");

    let result = detect_active_package_manager_operations_from("not-a-process\n", &proc_root);
    assert!(
        result.is_err(),
        "partial process metadata must abort cache protection"
    );

    let _ = fs::remove_dir_all(proc_root);
}

#[cfg(unix)]
#[tokio::test]
async fn package_cache_process_listing_failure_is_an_error() {
    let _fixture_exec = fixture_exec_guard();
    let proc_root = unique_test_home("package_proc_failed_ps");
    let bin_root = unique_test_home("package_ps_failed");
    fs::create_dir_all(proc_root.join("self")).expect("create proc fixture");
    fs::create_dir_all(&bin_root).expect("create bin fixture");
    let ps = bin_root.join("ps");
    write_test_script(&ps, "exit 7");

    let result = detect_active_package_manager_operations_with(&ps, &proc_root).await;
    assert!(result.is_err(), "a failed ps command must fail closed");

    let _ = fs::remove_dir_all(proc_root);
    let _ = fs::remove_dir_all(bin_root);
}

#[tokio::test]
async fn package_cache_apply_refuses_all_cache_deletion() {
    let home = unique_test_home("package_cache_protection");
    let targets = [
        (PackageCacheKind::Cargo, ".cargo/registry/cache"),
        (PackageCacheKind::Npm, ".npm"),
        (PackageCacheKind::Pip, ".cache/pip"),
        (PackageCacheKind::Go, ".cache/go-build"),
    ];
    let mut active = HashSet::new();
    for (kind, relative) in targets {
        let cache = home.join(relative);
        fs::create_dir_all(&cache).expect("create cache fixture");
        fs::write(cache.join("in-use.bin"), b"must survive").expect("write cache fixture");
        active.insert(kind);
    }

    let (reclaimed, cleaned) =
        clean_package_caches_at(&home, true, true, true, true, true, &active)
            .await
            .expect("protected cache cleanup");
    assert_eq!(
        reclaimed, 0,
        "apply cache deletion is disabled, so caches must not be counted as reclaimed"
    );
    assert!(
        cleaned.is_empty(),
        "apply cache deletion is disabled, so caches must not be reported cleaned"
    );
    for (_, relative) in targets {
        assert!(
            home.join(relative).exists(),
            "package cache {relative} must survive apply"
        );
    }

    let _ = fs::remove_dir_all(home);
}

#[tokio::test]
async fn package_cache_apply_refuses_uncoordinated_start_after_snapshot() {
    let home = unique_test_home("package_cache_adversarial_start");
    let proc_root = unique_test_home("package_proc_adversarial_start");
    fs::create_dir_all(proc_root.join("self")).expect("create proc fixture");
    let initial_process = proc_root.join("400");
    fs::create_dir_all(&initial_process).expect("create initial process fixture");
    fs::write(initial_process.join("cmdline"), b"/usr/bin/sleep\0").expect("write initial cmdline");

    // The first snapshot sees no package operation.
    let initial = detect_active_package_manager_operations_from("400 sleep\n", &proc_root)
        .expect("initial process snapshot");
    assert!(initial.is_empty());

    // An npm operation starts after that snapshot, exactly in the window the
    // old detector-then-remove implementation could not coordinate.
    let new_process = proc_root.join("401");
    fs::create_dir_all(&new_process).expect("create adversarial process fixture");
    fs::write(
        new_process.join("cmdline"),
        b"/usr/bin/node\0/usr/lib/npm/npm-cli.js\0install\0",
    )
    .expect("write adversarial cmdline");

    let npm_cache = home.join(".npm");
    fs::create_dir_all(&npm_cache).expect("create npm cache fixture");
    fs::write(npm_cache.join("in-use.bin"), b"must survive").expect("write cache fixture");

    // Apply refuses all package-cache deletion because no lock shared with
    // external package managers can make this lifecycle-safe.
    let result = clean_package_caches_at(&home, false, true, false, false, true, &initial)
        .await
        .expect("uncoordinated apply must be a safe no-op");
    assert_eq!(result, (0, Vec::new()));
    assert!(
        npm_cache.exists(),
        "an operation starting after detection must not race deletion"
    );

    let _ = fs::remove_dir_all(home);
    let _ = fs::remove_dir_all(proc_root);
}

#[tokio::test]
async fn active_package_operations_skip_matching_cache_estimates_in_dry_run() {
    let home = unique_test_home("package_cache_dry_run");
    let cargo_cache = home.join(".cargo/registry/cache");
    let npm_cache = home.join(".npm");
    fs::create_dir_all(&cargo_cache).expect("create cargo cache fixture");
    fs::create_dir_all(&npm_cache).expect("create npm cache fixture");
    fs::write(cargo_cache.join("cargo.bin"), b"cargo").expect("write cargo fixture");
    fs::write(npm_cache.join("npm.bin"), b"npm").expect("write npm fixture");
    let active = HashSet::from([PackageCacheKind::Npm]);

    let result = clean_package_caches_at(&home, true, true, false, false, false, &active)
        .await
        .expect("dry-run cache estimate");
    assert_eq!(result.0, 5);
    assert!(result.1.iter().any(|entry| entry.contains("cargo")));
    assert!(!result.1.iter().any(|entry| entry.contains("npm")));
    assert!(cargo_cache.exists() && npm_cache.exists());

    let _ = fs::remove_dir_all(home);
}

#[test]
fn storage_cleanup_apply_accepts_home_artifact_dirs_and_refuses_system_roots() {
    // Regression (2026-08-21): `storage --cleanup --apply` used the strict
    // classifier, refusing EVERY path under /home ("under system root
    // /home") — i.e. every real candidate on a workstation — while the
    // guard's auto-cleanup deleted the same class of paths. The apply path
    // must accept an artifact dir under /home …
    let home = dirs::home_dir().expect("home dir available");
    let fixture = home.join(format!(
        ".dracon_storage_apply_test_{}_{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    std::fs::create_dir_all(&fixture).unwrap();
    let validated = validate_storage_cleanup_path(&fixture, &[]);
    assert!(
        validated.is_ok(),
        "apply must accept artifact dirs under /home: {:?}",
        validated.err()
    );
    let _ = std::fs::remove_dir_all(&fixture);

    // … while exact system roots stay refused.
    for prot in SYSTEM_PROTECTED {
        if !Path::new(prot).exists() {
            continue;
        }
        assert!(
            validate_storage_cleanup_path(Path::new(prot), &[]).is_err(),
            "apply must refuse exact system root {prot}"
        );
    }

    // The strict classifier remains strict: the two rule sets are
    // intentionally different, this pins WHY the apply path must not use it.
    if Path::new("/home").exists() {
        assert!(check_safe_to_delete(Path::new("/home"), &[]).is_err());
    }
}

#[test]
fn storage_cache_hotspots_share_package_apply_safety_gate() {
    assert!(storage_hotspot_apply_is_blocked("cache", true));
    assert!(!storage_hotspot_apply_is_blocked("cache", false));
    assert!(!storage_hotspot_apply_is_blocked("node-deps", true));
}

#[test]
fn filter_selectable_cleanup_kinds_drops_git_db_and_keeps_artifact_kinds() {
    // Audit M2 (2026-08-21): git-db is report-only — it must be filtered
    // out of every cleanup selection source.
    let requested: HashSet<String> = ["git-db", "rust-build", "node-deps"]
        .iter()
        .map(|s| s.to_string())
        .collect();
    let (kept, excluded) = filter_selectable_cleanup_kinds(requested);
    assert!(kept.contains("rust-build") && kept.contains("node-deps"));
    assert!(
        !kept.contains("git-db"),
        "git-db must never survive filtering"
    );
    assert_eq!(excluded, vec!["git-db".to_string()]);

    // Absent kind → no exclusions reported; empty request stays empty.
    let (kept, excluded) =
        filter_selectable_cleanup_kinds(["cache".to_string()].into_iter().collect());
    assert!(excluded.is_empty() && kept == ["cache".to_string()].into_iter().collect());
    let (kept, excluded) = filter_selectable_cleanup_kinds(HashSet::new());
    assert!(kept.is_empty() && excluded.is_empty());

    // Every entry in NON_CLEANUP_KINDS is actually enforced by the filter.
    for kind in NON_CLEANUP_KINDS {
        let (kept, excluded) =
            filter_selectable_cleanup_kinds([(kind.to_string())].into_iter().collect());
        assert!(!kept.contains(*kind));
        assert_eq!(excluded, vec![kind.to_string()]);
    }
}

#[test]
fn storage_cleanup_apply_refuses_git_database_dirs() {
    // Audit M2 backstop: even if a .git path ever reaches
    // validate_storage_cleanup_path directly, it must be refused — git
    // never tracks its own database, so the allow_tracked gate cannot
    // protect project history from remove_dir_all.
    let home = dirs::home_dir().expect("home dir available");
    let fixture = home.join(format!(
        ".dracon_storage_gitdb_test_{}_{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    let git_db = fixture.join("project").join(".git");
    std::fs::create_dir_all(&git_db).unwrap();
    let validated = validate_storage_cleanup_path(&git_db, &[]);
    let _ = std::fs::remove_dir_all(&fixture);
    let err = validated.expect_err("apply must refuse a .git directory");
    let msg = format!("{err:#}");
    assert!(
        msg.contains("git database"),
        "refusal must name the reason, got: {msg}"
    );
}

#[test]
fn storage_cleanup_apply_refuses_git_database_subpaths() {
    // ADDED 2026-09-09 (audit F38): the M2 backstop matched only
    // `file_name() == ".git"`, so `/repo/.git/objects` passed. Any
    // path with a `.git` component must be refused.
    let err = validate_storage_cleanup_path(Path::new("/home/user/Dev/project/.git/objects"), &[])
        .expect_err("apply must refuse paths under a .git directory");
    assert!(format!("{err:#}").contains("git database"));
}

#[test]
fn normalize_early_warn_clamped_to_warn() {
    // ADDED 2026-09-09 (audit F43): early > warn made the early band
    // (`used >= early && used < warn`) permanently empty.
    let policy = GuardPolicy {
        disk_early_warn_percent: 95,
        disk_warn_percent: 75,
        ..Default::default()
    };
    let mut policy = policy;
    normalize_guard_policy(&mut policy);
    assert!(
        policy.disk_early_warn_percent <= policy.disk_warn_percent,
        "early warn must not exceed warn, got early={} warn={}",
        policy.disk_early_warn_percent,
        policy.disk_warn_percent
    );
}

/// The 2026-10-01 audit: when the freeze marker disappears out from under the
/// daemon (the freeze watchdog's 30m auto-clear, or an operator running
/// `dracon-sync resume`), the in-memory flag used to stay true forever, so
/// every later pass re-entered the unfreeze branch and logged a remove failure
/// for a file that no longer existed. The flag must resync instead.
#[test]
fn sync_frozen_resyncs_when_the_marker_disappears_externally() {
    let fixture = std::env::temp_dir().join(format!(
        "dracon-system-freeze-resync-{}-{}",
        std::process::id(),
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time")
            .as_nanos()
    ));
    fs::create_dir_all(&fixture).expect("create fixture");
    let marker = fixture.join("freeze");

    let guard = GuardPolicy {
        freeze_sync_at_action: true,
        sync_freeze_marker: marker.display().to_string(),
        unfreeze_below_percent: 70,
        ..GuardPolicy::default()
    };

    // Action level with no marker yet: the guard writes it and claims the
    // freeze.
    let mut sync_frozen = false;
    manage_sync_freeze(&guard, 95, "action", &mut sync_frozen);
    assert!(sync_frozen, "guard must claim a freeze it just performed");
    assert!(marker.exists(), "guard must write its own marker");

    // Pressure recovers but the marker is still there: normal unfreeze.
    manage_sync_freeze(&guard, 68, "ok", &mut sync_frozen);
    assert!(!sync_frozen);
    assert!(!marker.exists(), "guard must remove its own marker");

    // Freeze again, then let something ELSE clear the marker, then recover.
    manage_sync_freeze(&guard, 95, "action", &mut sync_frozen);
    assert!(sync_frozen);
    fs::remove_file(&marker).expect("simulate an external clear");

    manage_sync_freeze(&guard, 68, "ok", &mut sync_frozen);
    assert!(
        !sync_frozen,
        "an externally cleared marker must resync the in-memory flag"
    );

    fs::remove_dir_all(fixture).expect("remove fixture");
}

/// The 2026-10-01 audit: `cleanup_stale_cooldowns` used
/// `Instant::now() - Duration::from_secs(cooldown * 2)`, and std PANICS on that
/// subtraction once the duration underflows the clock's representation. A
/// policy cooldown at 2^63 seconds or more killed the daemon on its first
/// pass. The subtraction must not be able to panic for any u64.
#[test]
fn cleanup_stale_cooldowns_survives_an_extreme_cooldown() {
    let mut state = GuardRuntimeState::default();
    state.notify_cooldowns.insert(
        "pid-1".to_string(),
        Instant::now() - Duration::from_secs(60),
    );
    // u64::MAX saturates at 2x itself and underflows Instant by construction.
    cleanup_stale_cooldowns(&mut state, u64::MAX);
    // u64::MAX/2 * 2 == u64::MAX - 1, the largest value that still subtracts.
    cleanup_stale_cooldowns(&mut state, u64::MAX / 2);
    // A normal cooldown still prunes an entry older than 2x the window.
    state.notify_cooldowns.insert(
        "pid-2".to_string(),
        Instant::now() - Duration::from_secs(600),
    );
    cleanup_stale_cooldowns(&mut state, 5);
    assert!(
        !state.notify_cooldowns.contains_key("pid-2"),
        "a 600s-old entry must be pruned at a 5s cooldown"
    );
}

#[test]
fn guard_runtime_state_default_no_expiry_yet() {
    let state = GuardRuntimeState::default();
    assert!(state.last_quarantine_expire.is_none());
}

#[test]
fn quarantine_expire_interval_zero_is_never_clamped() {
    // 0 means "never expire automatically". A floor!() here would silently
    // re-enable unattended deletion for an operator who explicitly opted out,
    // which is the opposite failure from the one a floor guards against.
    let mut policy = GuardPolicy {
        quarantine_expire_interval_secs: 0,
        ..Default::default()
    };
    normalize_guard_policy(&mut policy);
    assert_eq!(policy.quarantine_expire_interval_secs, 0);
}

#[test]
fn quarantine_expire_interval_defaults_to_a_day() {
    let policy = GuardPolicy::default();
    assert_eq!(policy.quarantine_expire_interval_secs, 86_400);
}

/// The two opt-outs that stop `maybe_expire_quarantine` from deleting anything.
/// Both are about not deleting what the operator did not ask to be deleted:
/// interval 0 disables the unattended path, and an unarmed
/// `clean_quarantine_first` means any entries present came from a human running
/// `quarantine move` by hand.
#[test]
fn maybe_expire_quarantine_respects_both_opt_outs() {
    let root = std::env::temp_dir().join(format!(
        "dracon-expire-gate-{}-{}",
        std::process::id(),
        "gate"
    ));
    let _ = std::fs::remove_dir_all(&root);
    let src = root.join("work").join("proj");
    std::fs::create_dir_all(&src).unwrap();
    std::fs::write(src.join("a.txt"), b"hello").unwrap();
    let qdir = root.join("q");
    // Move it in, then age the manifest far past any TTL so expiry WOULD act.
    let manifest = quarantine_move(&src, &qdir, &[]).unwrap();
    let aged = QuarantineManifest {
        name: manifest.name.clone(),
        origin: manifest.origin.clone(),
        moved_at_unix: now_unix().saturating_sub(400 * 86_400),
        bytes: manifest.bytes,
        files: manifest.files,
        auto: manifest.auto,
    };
    std::fs::write(
        qdir.join(&manifest.name).join(".quarantine.json"),
        serde_json::to_string_pretty(&aged).unwrap(),
    )
    .unwrap();
    let entry_dir = qdir.join(&manifest.name);

    let armed = GuardPolicy {
        quarantine_dir: qdir.display().to_string(),
        clean_quarantine_first: true,
        quarantine_ttl_days: 30,
        quarantine_expire_interval_secs: 0,
        ..Default::default()
    };
    let mut state = GuardRuntimeState::default();

    // Opt-out 1: interval 0.
    maybe_expire_quarantine(&armed, &mut state, Instant::now());
    assert!(
        entry_dir.exists(),
        "interval 0 must disable the unattended expiry entirely"
    );

    // Opt-out 2: quarantine not armed, interval positive.
    let unarmed = GuardPolicy {
        quarantine_expire_interval_secs: 86_400,
        clean_quarantine_first: false,
        ..armed.clone()
    };
    let mut state2 = GuardRuntimeState::default();
    maybe_expire_quarantine(&unarmed, &mut state2, Instant::now());
    assert!(
        entry_dir.exists(),
        "entries from a manual `quarantine move` must not become an unattended delete"
    );

    // Neither opt-out: the entry is past TTL and must actually be removed, and
    // the cooldown must be stamped so the next pass is a no-op.
    // (auto_cleanup_apply must be armed: audit M5 made expiry honor it.)
    let active = GuardPolicy {
        quarantine_expire_interval_secs: 86_400,
        auto_cleanup_apply: true,
        ..armed.clone()
    };
    let mut state3 = GuardRuntimeState::default();
    maybe_expire_quarantine(&active, &mut state3, Instant::now());
    assert!(!entry_dir.exists(), "a past-TTL entry must be expired");
    assert!(state3.last_quarantine_expire.is_some());

    // And the cooldown holds: a second immediate pass must not re-scan. Proven
    // by re-creating an expired entry and confirming it survives the next pass.
    let src2 = root.join("work2").join("proj");
    std::fs::create_dir_all(&src2).unwrap();
    std::fs::write(src2.join("b.txt"), b"world!").unwrap();
    let m2 = quarantine_move(&src2, &qdir, &[]).unwrap();
    let aged2 = QuarantineManifest {
        name: m2.name.clone(),
        origin: m2.origin.clone(),
        moved_at_unix: now_unix().saturating_sub(400 * 86_400),
        bytes: m2.bytes,
        files: m2.files,
        auto: m2.auto,
    };
    std::fs::write(
        qdir.join(&m2.name).join(".quarantine.json"),
        serde_json::to_string_pretty(&aged2).unwrap(),
    )
    .unwrap();
    maybe_expire_quarantine(&active, &mut state3, Instant::now());
    assert!(
        qdir.join(&m2.name).exists(),
        "the cooldown must stop a per-pass rescan"
    );

    let _ = std::fs::remove_dir_all(&root);
}

/// Audit M5 (2026-10-02): `maybe_expire_quarantine` must honor
/// `auto_cleanup_apply` — previously it hardcoded apply=true, arming
/// unattended deletes for operators who believed `false` meant dry-run.
/// A dry-run pass scans and reports but removes nothing.
#[test]
fn maybe_expire_quarantine_dry_run_deletes_nothing() {
    let root = std::env::temp_dir().join(format!(
        "dracon-expire-dryrun-{}-{}",
        std::process::id(),
        "dryrun"
    ));
    let _ = std::fs::remove_dir_all(&root);
    let src = root.join("work").join("proj");
    std::fs::create_dir_all(&src).unwrap();
    std::fs::write(src.join("a.txt"), b"hello").unwrap();
    let qdir = root.join("q");
    let manifest = quarantine_move(&src, &qdir, &[]).unwrap();
    let aged = QuarantineManifest {
        name: manifest.name.clone(),
        origin: manifest.origin.clone(),
        moved_at_unix: now_unix().saturating_sub(400 * 86_400),
        bytes: manifest.bytes,
        files: manifest.files,
        auto: manifest.auto,
    };
    std::fs::write(
        qdir.join(&manifest.name).join(".quarantine.json"),
        serde_json::to_string_pretty(&aged).unwrap(),
    )
    .unwrap();
    let entry_dir = qdir.join(&manifest.name);

    // Fully armed EXCEPT auto_cleanup_apply: the past-TTL entry must
    // survive, and the cooldown must still stamp (no rescan spam).
    let dry = GuardPolicy {
        quarantine_dir: qdir.display().to_string(),
        clean_quarantine_first: true,
        quarantine_ttl_days: 30,
        quarantine_expire_interval_secs: 86_400,
        auto_cleanup_apply: false,
        ..Default::default()
    };
    let mut state = GuardRuntimeState::default();
    maybe_expire_quarantine(&dry, &mut state, Instant::now());
    assert!(
        entry_dir.exists(),
        "dry-run expiry must not delete a past-TTL entry"
    );
    assert!(state.last_quarantine_expire.is_some());

    let _ = std::fs::remove_dir_all(&root);
}

/// The objective requires expiry to "tolerate absurd interval values without
/// panicking", and until now that held only by inspection. `cooldown_due` is the
/// only place the interval is used, and the classic failure here is
/// `Instant - Duration`, which PANICS on underflow rather than saturating —
/// `cleanup_stale_cooldowns` already guards that with `checked_sub` and a
/// comment saying a large policy must not kill the daemon. The same reasoning
/// has to hold for the expiry cadence, so it is pinned rather than reasoned.
///
/// Two halves, because the cadence has two distinct behaviours and conflating
/// them hides both:
///
/// - With a cooldown already recorded, an absurd interval must read as NOT
///   due, so a fat-fingered policy cannot turn into a per-pass delete storm.
/// - With no prior run, the very first pass is due for ANY interval — that is
///   the documented "nothing has run yet" case — so an absurd value must still
///   complete normally instead of panicking.
///
/// Values include `u64::MAX`: any `*2` overflows, any subtraction underflows,
/// and `Duration::from_secs` on it sits on the boundary `Instant` uses.
const ABSURD_INTERVALS: &[u64] = &[
    0,
    1,
    60,
    86_400,
    u32::MAX as u64,
    u64::MAX / 2,
    u64::MAX - 1,
    u64::MAX,
];

/// Build an expired entry in a fresh quarantine root, returning
/// `(root, quarantine_dir, entry_name)`.
fn absurd_interval_fixture(tag: &str) -> (PathBuf, PathBuf, String) {
    let root = std::env::temp_dir().join(format!(
        "dracon-expire-absurd-{}-{}",
        std::process::id(),
        tag
    ));
    let _ = std::fs::remove_dir_all(&root);
    let qdir = root.join("q");
    let src = root.join("work").join("proj");
    std::fs::create_dir_all(&src).unwrap();
    std::fs::write(src.join("a.txt"), b"hello").unwrap();
    let manifest = quarantine_move(&src, &qdir, &[]).unwrap();
    let aged = QuarantineManifest {
        name: manifest.name.clone(),
        origin: manifest.origin.clone(),
        moved_at_unix: now_unix().saturating_sub(400 * 86_400),
        bytes: manifest.bytes,
        files: manifest.files,
        auto: manifest.auto,
    };
    std::fs::write(
        qdir.join(&manifest.name).join(".quarantine.json"),
        serde_json::to_string_pretty(&aged).unwrap(),
    )
    .unwrap();
    (root, qdir, manifest.name)
}

fn expiry_policy(qdir: &Path, interval: u64) -> GuardPolicy {
    GuardPolicy {
        quarantine_dir: qdir.display().to_string(),
        clean_quarantine_first: true,
        quarantine_ttl_days: 30,
        quarantine_expire_interval_secs: interval,
        // FIXED 2026-10-03 (audit M5 follow-up): expiry honors
        // `auto_cleanup_apply` — the default false is dry-run (pinned
        // by `maybe_expire_quarantine_dry_run_deletes_nothing`), so
        // these interval tests must arm apply to exercise deletion.
        // This also strengthens the not-due test: the cooldown gates
        // even a fully armed policy.
        auto_cleanup_apply: true,
        ..Default::default()
    }
}

#[test]
fn absurd_expiry_intervals_are_not_due_once_the_cooldown_exists() {
    for &interval in ABSURD_INTERVALS {
        let (root, qdir, name) = absurd_interval_fixture("not-due");
        // Stamped 2s ago, not `now`: that is what pins the `.max(60)` floor.
        // With a zero-aged stamp even a dropped floor still reads "not due", so
        // the floor would go unpinned; 2 seconds is past a typo'd interval of 1
        // but far short of 60, so the floor is the only thing keeping this
        // entry alive. Without it a policy of 1 becomes a per-pass delete.
        let mut state = GuardRuntimeState {
            last_quarantine_expire: Some(Instant::now() - Duration::from_secs(2)),
            ..Default::default()
        };
        maybe_expire_quarantine(&expiry_policy(&qdir, interval), &mut state, Instant::now());
        if interval != 0 {
            assert!(
                qdir.join(&name).exists(),
                "a non-zero interval must not be due immediately (interval={interval})"
            );
        }
        let _ = std::fs::remove_dir_all(&root);
    }
}

#[test]
fn absurd_expiry_intervals_complete_normally_on_the_first_pass() {
    let (root, qdir, name) = absurd_interval_fixture("first-pass");
    // No prior run: the first pass is due for every interval, so this exercises
    // the actual expiry path with the knob at its extremes. It must not panic,
    // and it must expire the entry rather than silently doing nothing.
    for &interval in ABSURD_INTERVALS {
        let mut state = GuardRuntimeState::default();
        maybe_expire_quarantine(&expiry_policy(&qdir, interval), &mut state, Instant::now());
        if interval == 0 {
            // Opting out returns before the cooldown is touched, so the
            // runtime state is left exactly as an operator who never configured
            // the knob would leave it.
            assert!(
                state.last_quarantine_expire.is_none(),
                "interval 0 must leave the runtime state untouched"
            );
        } else {
            assert!(
                state.last_quarantine_expire.is_some(),
                "the cooldown must be stamped (interval={interval})"
            );
        }
    }
    assert!(
        !qdir.join(&name).exists(),
        "the first pass must still expire a past-TTL entry"
    );
    let _ = std::fs::remove_dir_all(&root);
}

/// The dry-run preview listed every user-protected tree as reclaimable and only
/// refused it at apply time, because the refusal lived inside the `if apply`
/// block. On this host that overstated reclaimable space by ~66 GiB and
/// misled the operator twice in one session.
///
/// This drives `auto_cleanup_rust_targets` in dry-run mode over a real tempdir
/// tree, because the preview is the thing that was wrong — asserting on the
/// apply path would pass even with the bug in place.
#[tokio::test]
async fn dry_run_preview_omits_user_protected_targets() {
    let root = std::env::temp_dir().join(format!(
        "dracon-preview-protected-{}-{}",
        std::process::id(),
        "t"
    ));
    let _ = std::fs::remove_dir_all(&root);

    // One target under a protected project, one under an unprotected sibling.
    // Both large enough to clear the min-size gate so the scan really sees them.
    let protected_proj = root.join("protected-proj");
    let free_proj = root.join("free-proj");
    for proj in [&protected_proj, &free_proj] {
        // The scanner only treats a `target/` as a Rust build cache when the
        // project parent has a Cargo.toml, so the fixture needs one or both
        // dirs are invisible and the test passes vacuously.
        std::fs::create_dir_all(proj).unwrap();
        std::fs::write(
            proj.join("Cargo.toml"),
            b"[package]\nname = \"probe\"\nversion = \"0.0.0\"\nedition = \"2021\"\n",
        )
        .unwrap();
        let target = proj.join("target");
        std::fs::create_dir_all(target.join("debug")).unwrap();
        std::fs::write(
            target.join("debug").join("blob.bin"),
            vec![7u8; 4 * 1024 * 1024],
        )
        .unwrap();
        // The scan has a "modified <60s ago means an active build" backstop, so
        // a fixture written a moment ago is protected on that ground alone and
        // the candidate list comes back empty. Age the tree instead of trying
        // to relax the guard: `touch -d` needs no new dependency, and the
        // alternative (setting mtime from Rust) needs a crate this repo does
        // not carry.
        let aged = std::process::Command::new("touch")
            .arg("-d")
            .arg("20 days ago")
            .arg(&target)
            .output()
            .expect("touch must be available to age the fixture");
        assert!(
            aged.status.success(),
            "touch failed: {}",
            String::from_utf8_lossy(&aged.stderr)
        );
    }

    let guard = GuardPolicy {
        rust_search_roots: root.display().to_string(),
        cleanup_min_size_mb: 1,
        protected_paths: vec![protected_proj.display().to_string()],
        // Nothing here may touch the real quarantine dir.
        quarantine_dir: root.join("q").display().to_string(),
        clean_quarantine_first: true,
        ..Default::default()
    };

    let mut runtime = GuardRuntimeState::default();
    // apply = false: this is the preview path that was broken.
    let result = auto_cleanup_rust_targets(&guard, &mut runtime, false, true)
        .await
        .expect("dry-run scan must succeed");

    let cleaned: Vec<&String> = result.cleaned_paths.iter().collect();
    assert!(
        !cleaned.iter().any(|p| p.contains("protected-proj")),
        "the protected tree must NOT appear as reclaimable, got: {:?}",
        result.cleaned_paths
    );
    assert!(
        cleaned.iter().any(|p| p.contains("free-proj")),
        "an unprotected sibling must still be offered, got: {:?}",
        result.cleaned_paths
    );
    assert!(
        result
            .protected_paths
            .iter()
            .any(|p| p.contains("protected-proj")),
        "the protected tree must be reported as protected, got: {:?}",
        result.protected_paths
    );
    // The reason must survive, or the operator sees a refusal with no cause.
    // Asserted on a phrase that cannot come from the PATH — an earlier version
    // matched on "protected", which the fixture directory name itself contains,
    // so it passed with the reason deleted entirely.
    assert!(
        result
            .protected_paths
            .iter()
            .any(|p| p.contains("refusing to delete protected path")),
        "the protected verdict must carry its reason, got: {:?}",
        result.protected_paths
    );
    // Nothing was deleted. `reclaimed_bytes` is non-zero in a dry run BY
    // DESIGN — it is the "would reclaim" figure the preview's
    // "Total reclaimable" line is built from — so the proof that this is a
    // preview and not a delete is that the trees are still on disk.
    assert!(protected_proj.join("target").exists());
    assert!(free_proj.join("target").exists());
    assert!(
        free_proj
            .join("target")
            .join("debug")
            .join("blob.bin")
            .exists(),
        "the offered candidate must still be intact after a dry run"
    );

    let _ = std::fs::remove_dir_all(&root);
}

/// A multi-line error must not be able to break the preview's table alignment
/// by embedding a newline in a cell.
#[test]
fn one_line_collapses_multiline_messages() {
    assert_eq!(
        one_line("refusing to delete protected path\n  under user-protected path X"),
        "refusing to delete protected path under user-protected path X"
    );
    assert_eq!(one_line("already one line"), "already one line");
    assert_eq!(one_line(""), "");
}

#[tokio::test]
async fn storage_cleanup_activity_refuses_recent_artifacts() {
    let project = tempfile::tempdir().unwrap();
    let target = project.path().join("target");
    fs::create_dir(&target).unwrap();
    let error = validate_storage_cleanup_activity("rust-build", &target)
        .await
        .unwrap_err();
    assert!(error.to_string().contains("modified <60s"), "{error}");
    assert!(target.exists());
}

#[cfg(target_os = "linux")]
#[tokio::test]
async fn storage_cleanup_activity_refuses_live_rust_and_node_processes() {
    // Run this same test in a child harness with an explicit Linux process
    // name. Multicall `sleep` binaries can reset comm after exec, so a link
    // named rustc is not a reliable live-process fixture on NixOS.
    if let Ok(comm) = std::env::var("DRACON_TEST_BUILD_COMM") {
        fs::write("/proc/self/comm", comm).unwrap();
        fs::write(".build-fixture-ready", b"ready").unwrap();
        loop {
            std::thread::sleep(Duration::from_secs(300));
        }
    }
    struct ChildGuard(std::process::Child);
    impl Drop for ChildGuard {
        fn drop(&mut self) {
            let _ = self.0.kill();
            let _ = self.0.wait();
        }
    }
    for (comm, kind, artifact) in [
        ("rustc", "rust-build", "target"),
        ("cargo", "build-output", "build"),
        ("node", "node-deps", "node_modules"),
    ] {
        let project = tempfile::tempdir().unwrap();
        let path = project.path().join(artifact);
        fs::create_dir(&path).unwrap();
        fs::write(path.join("keep"), b"synthetic artifact").unwrap();
        let old = SystemTime::now() - Duration::from_secs(120);
        File::open(&path)
            .unwrap()
            .set_times(std::fs::FileTimes::new().set_modified(old))
            .unwrap();
        let mut child = ChildGuard(
            std::process::Command::new(std::env::current_exe().unwrap())
                .args([
                    "--exact",
                    "tests::storage_cleanup_activity_refuses_live_rust_and_node_processes",
                ])
                .env("DRACON_TEST_BUILD_COMM", comm)
                .current_dir(project.path())
                .stdout(std::process::Stdio::null())
                .spawn()
                .unwrap(),
        );
        let ready = project.path().join(".build-fixture-ready");
        let deadline = Instant::now() + Duration::from_secs(5);
        while !ready.exists() && Instant::now() < deadline {
            assert!(
                child.0.try_wait().unwrap().is_none(),
                "fixture exited before ready"
            );
            std::thread::sleep(Duration::from_millis(10));
        }
        assert!(ready.exists(), "fixture did not become ready");
        let error = validate_storage_cleanup_activity(kind, &path)
            .await
            .unwrap_err();
        assert!(error.to_string().contains("active"), "{kind}: {error}");
        assert!(child.0.try_wait().unwrap().is_none());
        assert_eq!(fs::read(path.join("keep")).unwrap(), b"synthetic artifact");
    }
}

#[cfg(unix)]
#[tokio::test]
async fn rust_build_listing_failure_or_malformed_output_is_an_error() {
    let _fixture_exec = fixture_exec_guard();
    let bin = tempfile::tempdir().unwrap();
    for body in ["exit 7", "printf 'broken\\n'", "exit 0"] {
        let ps = bin.path().join("ps");
        write_test_script(&ps, body);
        assert!(detect_active_rust_builds_with(&ps).await.is_err());
    }
}

/// ADDED 2026-10-03 (audit R4-SYS-03): the read-only probe resolver
/// searches explicit dirs for a regular executable — first match
/// wins, empty entries / directories / non-executables are skipped,
/// and a miss is None (the caller degrades to Skipped, not Fail).
#[cfg(unix)]
#[test]
fn probe_path_search_finds_first_executable_only() {
    let _fixture_exec = fixture_exec_guard();
    let tmp = tempfile::tempdir().unwrap();
    let d1 = tmp.path().join("d1");
    let d2 = tmp.path().join("d2");
    std::fs::create_dir_all(&d1).unwrap();
    std::fs::create_dir_all(&d2).unwrap();
    // d1 holds a NON-executable decoy and a directory of the same
    // name is impossible — instead a same-named dir elsewhere.
    std::fs::write(d1.join("probe-me"), "not executable\n").unwrap();
    std::fs::create_dir_all(d1.join("probe-dir")).unwrap();
    write_test_script(&d2.join("probe-me"), "exit 0");
    let dirs = vec![d1.clone(), d2.clone()];
    // First match wins — and the non-executable decoy in d1 is
    // skipped in favour of the executable in d2.
    assert_eq!(
        search_path_for_executable("probe-me", &dirs),
        Some(d2.join("probe-me").to_string_lossy().to_string()),
        "must skip the non-executable decoy"
    );
    // Same-named directory is not a binary.
    assert_eq!(
        search_path_for_executable("probe-dir", &dirs),
        None,
        "directories must not resolve as binaries"
    );
    // Empty entries are skipped, not treated as cwd.
    let with_empty = vec![PathBuf::from(""), d2.clone()];
    assert_eq!(
        search_path_for_executable("probe-me", &with_empty),
        Some(d2.join("probe-me").to_string_lossy().to_string()),
        "empty PATH entries must be skipped"
    );
    // Total miss → None (caller degrades to Skipped).
    assert_eq!(search_path_for_executable("probe-missing", &dirs), None);
}

// --- ADDED 2026-10-09 (audit F131): the inode parsers assumed a fixed
// row offset AND fixed column index, so a wrapped `Filesystem` column
// silently produced zeros and the inode monitor read 0% forever. ------

#[test]
fn inode_parsers_accept_a_wrapped_filesystem_column() {
    // GNU df wraps a too-long Filesystem column onto its own line, which
    // pushes the data row to index 2 and breaks `lines().nth(1)`.
    let wrapped = "Filesystem      Inodes  IUsed   IFree IUse% Mounted on\n\
                   /dev/mapper/vgubuntu--vg-verylongrootname-that-wraps\n\
                                     12345   6789    5556   55% /\n";
    assert_eq!(parse_inode_use_percent(wrapped), Some(55));
    assert_eq!(parse_inode_info(wrapped).unwrap(), (12345, 6789, 5556));
}

#[test]
fn inode_parsers_accept_a_mount_path_containing_spaces() {
    let spaced = "Filesystem Inodes IUsed IFree IUse% Mounted on\n\
                  /dev/sda1 1000 200 800 20% /mnt/my backup\n";
    assert_eq!(parse_inode_use_percent(spaced), Some(20));
    assert_eq!(parse_inode_info(spaced).unwrap(), (1000, 200, 800));
}

#[test]
fn inode_parsers_reject_garbage_instead_of_reporting_zero() {
    // The defect: a layout the parser did not understand returned
    // (0, 0, 0) / 0% with no error. Now it must be None/Err.
    assert_eq!(parse_inode_use_percent("Filesystem Inodes\n"), None);
    assert!(parse_inode_info("Filesystem Inodes\n").is_err());
}

// --- ADDED 2026-10-09 (audit F130): sync_freeze_marker_path did not
// expand `~` while every sibling storage root did, so the documented
// example value wrote a literal RELATIVE `~/.dracon/...` path that
// `dracon-sync pause` never watched. ----------------------------------

#[test]
fn sync_freeze_marker_path_expands_the_documented_tilde_form() {
    let guard: crate::GuardPolicy = toml::from_str("[guard]\nfreeze_sync_at_action = true\n")
        .expect("guard policy should parse");
    let path = sync_freeze_marker_path(&guard);
    let home = dirs::home_dir().expect("home dir should exist");
    assert_eq!(path, home.join(".dracon/dracon-sync.freeze"));
    assert!(
        path.is_absolute(),
        "must not stay a literal relative `~/...`"
    );
}