dracon-system 0.112.42

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
use super::*;

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

#[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() {
    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 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");
    fs::write(&success, "#!/bin/sh\necho 'ok' >&2\nexit 0\n").expect("write success script");
    fs::set_permissions(&success, fs::Permissions::from_mode(0o755)).expect("chmod");

    let failure = tmp.join("renice-failure");
    fs::write(
        &failure,
        "#!/bin/sh\necho 'permission denied' >&2\nexit 1\n",
    )
    .expect("write failure script");
    fs::set_permissions(&failure, fs::Permissions::from_mode(0o755)).expect("chmod");

    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");
    }
}

#[cfg(unix)]
fn write_test_script(path: &std::path::Path, body: &str) {
    fs::write(path, format!("#!/bin/sh\n{body}\n")).expect("write test script");
    fs::set_permissions(path, fs::Permissions::from_mode(0o755)).expect("chmod test script");
}

#[cfg(unix)]
#[tokio::test]
async fn restore_runtime_adjustments_restores_renice_and_oom() {
    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 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 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 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 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));
}

#[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");
}

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);
}

#[cfg(unix)]
#[tokio::test]
async fn nix_cleanup_gen_prune_failure_still_runs_gc() {
    // 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);
}

#[tokio::test]
async fn clean_tmp_paths_respects_age_dry_run_and_open_fds() {
    let root = unique_test_home("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_home("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_home("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;
    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);
}

#[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);
}

fn guard_test_tmp(name: &str) -> std::path::PathBuf {
    std::env::temp_dir().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);
}

#[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);
}

#[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 node\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 node\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 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
    );
}