dracon-system 0.112.45

Disk, process, storage, and service diagnostics for local development machines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
//! Tests for guard.rs (guard daemon runtime, disk monitoring, process management)
//!
//! These tests verify the guard runtime components after extraction from main.rs.

use super::*;

// ---------------------------------------------------------------------------
// GuardRuntimeState
// ---------------------------------------------------------------------------

#[test]
fn guard_runtime_state_default_is_empty() {
    let state = crate::GuardRuntimeState::default();
    assert!(state.heavy_since.is_empty());
    assert!(state.notify_cooldowns.is_empty());
    assert!(state.last_disk_state.is_empty());
    assert!(state.oom_known_descendants.is_empty());
    assert!(state.oom_pending_descendants.is_empty());
}

#[test]
fn oom_descendant_candidates_only_select_new_untracked_user_processes() {
    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(10, 1, 10, "root"),
        sample(11, 10, 11, "existing-child"),
        sample(12, 10, 12, "new-child"),
        sample(13, 12, 13, "new-grandchild"),
        sample(14, 1, 14, "unrelated"),
        sample(15, 10, 15, "kworker/0:1"),
        sample(16, 10, 16, "editor"),
        sample(17, 10, 17, "tracked-child"),
    ];
    let known = HashSet::from([(11, 11)]);
    let tracked = HashSet::from([10, 17]);
    let exempt = HashSet::from(["editor".to_string()]);

    let descendants = crate::process_descendant_samples(&samples, 10);
    assert_eq!(
        descendants
            .iter()
            .map(|sample| sample.pid)
            .collect::<Vec<_>>(),
        vec![11, 12, 13, 15, 16, 17]
    );
    let candidates = crate::oom_descendant_candidates(&samples, 10, &known, &tracked, &exempt);
    assert_eq!(
        candidates
            .iter()
            .map(|sample| sample.pid)
            .collect::<Vec<_>>(),
        vec![12, 13]
    );
}

#[test]
fn runtime_adjustment_plan_includes_every_reversible_limiter() {
    let mut state = crate::GuardRuntimeState::default();
    state.reniced_pids.insert(
        101,
        crate::LegacyReniceState {
            original_nice: 0,
            applied_nice: 5,
            identity: crate::ProcessIdentity {
                comm: "legacy-worker".to_string(),
                starttime: 1,
            },
        },
    );
    state.memory_reniced_pids.insert(
        102,
        crate::MemoryReniceState {
            original_nice: 3,
            applied_nice: 10,
            identity: crate::ProcessIdentity {
                comm: "memory-worker".to_string(),
                starttime: 2,
            },
        },
    );
    state.oom_biased_pids.insert(
        103,
        (
            -100,
            crate::ProcessIdentity {
                comm: "oom-worker".to_string(),
                starttime: 3,
            },
        ),
    );
    state.capped_pids.insert(
        104,
        (
            "dracon-cap.service".to_string(),
            "user.slice".to_string(),
            crate::ProcessIdentity {
                comm: "cap-worker".to_string(),
                starttime: 4,
            },
        ),
    );

    let plan = crate::runtime_adjustment_plan(&state);
    assert_eq!(plan.len(), 4);
    assert!(plan.contains(&crate::RuntimeAdjustment::Nice {
        pid: 101,
        original_nice: 0,
        identity: crate::ProcessIdentity {
            comm: "legacy-worker".to_string(),
            starttime: 1,
        },
        scope: crate::NiceRestoreScope::Legacy,
    }));
    assert!(plan.contains(&crate::RuntimeAdjustment::Nice {
        pid: 102,
        original_nice: 3,
        identity: crate::ProcessIdentity {
            comm: "memory-worker".to_string(),
            starttime: 2,
        },
        scope: crate::NiceRestoreScope::Memory,
    }));
    assert!(plan.contains(&crate::RuntimeAdjustment::OomBias {
        pid: 103,
        orig_adj: -100,
        identity: crate::ProcessIdentity {
            comm: "oom-worker".to_string(),
            starttime: 3,
        },
    }));
    assert!(plan.contains(&crate::RuntimeAdjustment::CpuCap {
        pid: 104,
        scope: "dracon-cap.service".to_string(),
        orig_cgroup: "user.slice".to_string(),
        identity: crate::ProcessIdentity {
            comm: "cap-worker".to_string(),
            starttime: 4,
        },
    }));
}

#[test]
fn guard_runtime_state_insert_and_retrieve_heavy_process() {
    let mut state = crate::GuardRuntimeState::default();
    state.heavy_since.insert(1234, (Instant::now(), 0));
    assert!(state.heavy_since.contains_key(&1234));
    state.heavy_since.remove(&1234);
    assert!(!state.heavy_since.contains_key(&1234));
}

// ---------------------------------------------------------------------------
// GuardPolicy — disk threshold accessors (pub fields)
// ---------------------------------------------------------------------------

#[test]
fn guard_policy_disk_thresholds_are_public() {
    let guard = GuardPolicy::default();
    assert_eq!(guard.disk_warn_percent, 80);
    assert_eq!(guard.disk_action_percent, 90);
    assert_eq!(guard.disk_critical_percent, 95);
    assert_eq!(guard.disk_early_warn_percent, 70);
}

// ---------------------------------------------------------------------------
// GuardReport
// ---------------------------------------------------------------------------

#[test]
fn guard_report_can_be_created_with_alerts() {
    use crate::GuardProcessAlert;
    use crate::GuardReport;

    let report = GuardReport {
        enabled: true,
        disk_use_percent: 72,
        disk_state: "warn".to_string(),
        sync_frozen: false,
        extra_mounts: Vec::new(),
        relocate_candidates: Vec::new(),
        relocated_count: 0,
        relocated_bytes: 0,
        alerts: vec![GuardProcessAlert {
            pid: 12345,
            ppid: 1,
            command: "cargo".to_string(),
            args: "build".to_string(),
            cpu_percent: 250.0,
            rss_mb: 1024,
            sustained_secs: 35,
            action: "reniced".to_string(),
            nice_value: 5,
        }],
        memory: None,
        zombies: Vec::new(),
        reap_candidates: Vec::new(),
        reaped: Vec::new(),
        disk_fill_gbph: None,
    };
    assert!(report.enabled);
    assert_eq!(report.disk_use_percent, 72);
    assert_eq!(report.alerts.len(), 1);
    assert_eq!(report.alerts[0].pid, 12345);
}

// ---------------------------------------------------------------------------
// graduated_nice_value
// ---------------------------------------------------------------------------

#[test]
fn graduated_nice_value_cpu_tier_180_percent() {
    // CPU >= 180% → nice 5
    assert_eq!(crate::graduated_nice_value(180.0, 0, 5, 0), 5);
    assert_eq!(crate::graduated_nice_value(200.0, 0, 5, 0), 5);
}

#[test]
fn graduated_nice_value_cpu_tier_300_percent() {
    // CPU >= 300% → nice 10
    assert_eq!(crate::graduated_nice_value(300.0, 0, 5, 0), 10);
    assert_eq!(crate::graduated_nice_value(350.0, 0, 5, 0), 10);
}

#[test]
fn graduated_nice_value_cpu_tier_500_percent() {
    // CPU >= 500% → nice 15
    assert_eq!(crate::graduated_nice_value(500.0, 0, 5, 0), 15);
    assert_eq!(crate::graduated_nice_value(600.0, 0, 5, 0), 15);
}

#[test]
fn graduated_nice_value_memory_4gb() {
    // 4 GB in MB = 4096
    assert_eq!(crate::graduated_nice_value(0.0, 4096, 5, 0), 5);
}

#[test]
fn graduated_nice_value_memory_8gb() {
    // 8 GB in MB = 8192
    assert_eq!(crate::graduated_nice_value(0.0, 8192, 10, 0), 10);
}

#[test]
fn graduated_nice_value_below_all_tiers_uses_base() {
    // Below all thresholds → base nice value
    assert_eq!(crate::graduated_nice_value(50.0, 100, 3, 0), 3);
    assert_eq!(crate::graduated_nice_value(100.0, 500, 7, 0), 7);
}

#[test]
fn graduated_nice_value_preserves_current_nice() {
    // A process already at a lower priority must not be raised to a tier's
    // smaller absolute nice value.
    assert_eq!(crate::graduated_nice_value(180.0, 0, 5, 10), 10);
    assert_eq!(crate::graduated_nice_value(50.0, 100, 5, 10), 10);
}

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

#[test]
fn graduated_nice_value_high_base_clamped_to_max() {
    // Nice values are capped at 19
    assert_eq!(crate::graduated_nice_value(0.0, 0, 20, 0), 19);
}

// ---------------------------------------------------------------------------
// ProcSample parsing
// ---------------------------------------------------------------------------

#[test]
fn parse_ps_output_extracts_all_fields() {
    // ps output uses KB for RSS (ps man page: rss: resident set size in KB)
    let output = "12345  1  50.0  1024  3  cargo\n  23456  12345  25.0  2048  7  rustc";
    let samples = crate::parse_ps_output(output);
    assert_eq!(samples.len(), 2);

    assert_eq!(samples[0].pid, 12345);
    assert_eq!(samples[0].ppid, 1);
    assert_eq!(samples[0].cpu_percent, 50.0);
    // RSS is in KB, converted to MB via /1024
    assert_eq!(samples[0].rss_mb, 1024 / 1024); // 1024 KB = 1 MB
    assert_eq!(samples[0].nice, 3);
    assert_eq!(samples[0].command, "cargo");

    assert_eq!(samples[1].pid, 23456);
    assert_eq!(samples[1].ppid, 12345);
    assert_eq!(samples[1].cpu_percent, 25.0);
    assert_eq!(samples[1].rss_mb, 2048 / 1024); // 2048 KB = 2 MB
    assert_eq!(samples[1].nice, 7);
    assert_eq!(samples[1].command, "rustc");
}

#[test]
fn parse_ps_output_empty_input() {
    let samples = crate::parse_ps_output("");
    assert!(samples.is_empty());
}

#[test]
fn parse_ps_output_malformed_lines_skipped() {
    // Malformed lines should be skipped, good lines parsed
    let output = "not_valid\n12345  1  75.0  512  0  cargo";
    let samples = crate::parse_ps_output(output);
    assert_eq!(samples.len(), 1);
    assert_eq!(samples[0].pid, 12345);
    assert_eq!(samples[0].cpu_percent, 75.0);
}

#[test]
fn nice_restore_privilege_requires_root_or_cap_sys_nice() {
    let unprivileged = "Uid:\t1000\t1000\t1000\t1000\nCapEff:\t0000000000000000\n";
    let privileged = "Uid:\t1000\t1000\t1000\t1000\nCapEff:\t0000000000800000\n";
    let root = "Uid:\t0\t0\t0\t0\nCapEff:\t0000000000000000\n";

    assert!(!crate::has_nice_restore_privilege_from_status(unprivileged));
    assert!(crate::has_nice_restore_privilege_from_status(privileged));
    assert!(crate::has_nice_restore_privilege_from_status(root));
}

// ---------------------------------------------------------------------------
// disk_state
// ---------------------------------------------------------------------------

// Note: disk_state() in main.rs doesn't handle early-warn state.
// That state is managed in the guard daemon loop via check_disk_early_warning.
// The basic disk_state() only classifies: critical > action > warn > ok.

#[test]
fn disk_state_ok_below_warn() {
    let guard = GuardPolicy::default();
    assert_eq!(crate::disk_state(50, &guard), "ok");
    assert_eq!(crate::disk_state(79, &guard), "ok");
}

#[test]
fn disk_state_warn_between_warn_and_action() {
    let guard = GuardPolicy::default();
    assert_eq!(crate::disk_state(80, &guard), "warn");
    assert_eq!(crate::disk_state(89, &guard), "warn");
}

#[test]
fn disk_state_action_between_action_and_critical() {
    let guard = GuardPolicy::default();
    assert_eq!(crate::disk_state(90, &guard), "action");
    assert_eq!(crate::disk_state(94, &guard), "action");
}

#[test]
fn disk_state_critical_at_or_above_critical() {
    let guard = GuardPolicy::default();
    assert_eq!(crate::disk_state(95, &guard), "critical");
    assert_eq!(crate::disk_state(100, &guard), "critical");
}

// ---------------------------------------------------------------------------
// df parsing
// ---------------------------------------------------------------------------

#[test]
fn parse_df_use_percent_works() {
    // Typical df -P output
    let output = "Filesystem   1024-blocks    Used Available Capacity Mounted on\n/dev/sda1      19512345  15678901   3823444      80% /";
    assert_eq!(crate::parse_df_use_percent(output), Some(80));
}

#[test]
fn parse_df_use_percent_parses_without_percent_sign() {
    // parse_df_use_percent takes the 4th column and parses it as a number.
    // If the value is "80" without %, it still parses as Some(80).
    // This is normal df output behavior when the Use% column lacks the % sign.
    let output = "Filesystem   1024-blocks    Used Available Capacity Mounted on\n/dev/sda1      19512345  15678901   3823444      80 /";
    assert_eq!(crate::parse_df_use_percent(output), Some(80));
}

#[test]
fn parse_df_use_percent_no_matching_line() {
    assert_eq!(crate::parse_df_use_percent(""), None);
    assert_eq!(crate::parse_df_use_percent("no df output here"), None);
}

// ---------------------------------------------------------------------------
// should_notify cooldown logic
// ---------------------------------------------------------------------------

#[test]
fn should_notify_first_time_allowed() {
    let mut state = crate::GuardRuntimeState::default();
    let result = crate::should_notify(&mut state, "test-key", 300);
    assert!(result);
}

#[test]
fn should_notify_respects_cooldown() {
    let mut state = crate::GuardRuntimeState::default();
    // First call — allowed, records cooldown
    let first = crate::should_notify(&mut state, "my-event", 300);
    assert!(first);

    // Immediate second call — still in cooldown (cooldown recorded with future time)
    let second = crate::should_notify(&mut state, "my-event", 300);
    assert!(!second);

    // Remove the cooldown entry to simulate time passing — should be allowed again
    state.notify_cooldowns.remove("my-event");
    let third = crate::should_notify(&mut state, "my-event", 300);
    assert!(third);
}

#[test]
fn report_state_transition_suppresses_unchanged_events() {
    let mut state = crate::GuardRuntimeState::default();
    let (previous, first) = crate::report_state_transition(&mut state, "memory", "warn", 1800);
    assert!(previous.is_none());
    assert!(first);

    let (previous, repeated) = crate::report_state_transition(&mut state, "memory", "warn", 1800);
    assert_eq!(previous.as_deref(), Some("warn"));
    assert!(!repeated, "unchanged state must not emit every guard cycle");

    let (previous, recovery) = crate::report_state_transition(&mut state, "memory", "ok", 1800);
    assert_eq!(previous.as_deref(), Some("warn"));
    assert!(recovery, "state transitions should emit immediately");
}

#[test]
fn memory_pressure_ignores_swap_occupancy_without_active_pressure() {
    assert_eq!(
        crate::classify_memory_pressure(false, true, false),
        "ok",
        "cold pages in swap are not active pressure"
    );
    assert_eq!(crate::classify_memory_pressure(true, false, false), "warn");
    assert_eq!(
        crate::classify_memory_pressure(true, true, false),
        "critical"
    );
    assert_eq!(crate::classify_memory_pressure(false, false, true), "warn");
}

#[test]
fn swapin_velocity_flags_thrash_at_or_above_threshold() {
    // 2026-10-04: si ran at 100k+ pages/s while PSI sat at 3.9 and the
    // verdict read "ok", because velocity was only measured as a
    // PSI-absent fallback. Velocity is now a first-class thrash signal.
    assert!(!crate::swapin_velocity_thrash(None, 1000));
    assert!(!crate::swapin_velocity_thrash(Some(0.0), 1000));
    assert!(!crate::swapin_velocity_thrash(Some(999.9), 1000));
    assert!(crate::swapin_velocity_thrash(Some(1000.0), 1000));
    assert!(crate::swapin_velocity_thrash(Some(170_000.0), 1000));
}

#[test]
fn swapin_velocity_threshold_defaults_to_the_legacy_fallback() {
    // The old hardcoded PSI-fallback constant was 1000 pages/s; the knob
    // keeps that value, so PSI-absent hosts see no behavior change.
    assert_eq!(
        crate::GuardPolicy::default().mem_swapin_warn_pages_per_sec,
        1000
    );
}

#[test]
fn memory_pressure_requires_persistence_before_transition() {
    let mut state = crate::GuardRuntimeState::default();
    let start = Instant::now();

    let (stable, previous, changed) =
        crate::stabilize_memory_pressure_at(&mut state, "warn", 120, start);
    assert_eq!(stable, "ok");
    assert!(previous.is_none());
    assert!(!changed);

    let (stable, _, changed) = crate::stabilize_memory_pressure_at(
        &mut state,
        "warn",
        120,
        start + Duration::from_secs(119),
    );
    assert_eq!(stable, "ok");
    assert!(!changed);

    let (stable, previous, changed) = crate::stabilize_memory_pressure_at(
        &mut state,
        "warn",
        120,
        start + Duration::from_secs(120),
    );
    assert_eq!(stable, "warn");
    assert_eq!(previous.as_deref(), Some("ok"));
    assert!(changed);

    let (stable, _, changed) = crate::stabilize_memory_pressure_at(
        &mut state,
        "ok",
        120,
        start + Duration::from_secs(121),
    );
    assert_eq!(stable, "warn");
    assert!(!changed);

    let (stable, previous, changed) = crate::stabilize_memory_pressure_at(
        &mut state,
        "ok",
        120,
        start + Duration::from_secs(241),
    );
    assert_eq!(stable, "ok");
    assert_eq!(previous.as_deref(), Some("warn"));
    assert!(changed);
}

// ---------------------------------------------------------------------------
// prediction
// ---------------------------------------------------------------------------

#[test]
fn predict_fill_time_requires_minimum_samples() {
    // Empty history → none
    let history: Vec<(Instant, u8)> = vec![];
    assert!(crate::predict_fill_time(&history).is_none());

    // Only 1 sample → none (need at least 2)
    let history = vec![(Instant::now(), 70)];
    assert!(crate::predict_fill_time(&history).is_none());
}

#[test]
fn predict_fill_time_returns_none_for_stable_disk() {
    // Stable disk (no change) → infinite fill time → none
    let now = Instant::now();
    let history: Vec<(Instant, u8)> = vec![
        (now - std::time::Duration::from_secs(3600), 50u8),
        (now - std::time::Duration::from_secs(1800), 50u8),
        (now, 50u8),
    ];
    assert!(crate::predict_fill_time(&history).is_none());
}

#[test]
fn predict_fill_time_estimates_for_filling_disk() {
    // predict_fill_time requires at least 3 samples
    let now = Instant::now();
    let history: Vec<(Instant, u8)> = vec![
        (now - std::time::Duration::from_secs(7200), 30u8), // 2 hours ago: 30%
        (now - std::time::Duration::from_secs(3600), 60u8), // 1 hour ago: 60%
        (now, 90u8),                                        // now: 90%
    ];
    let result = crate::predict_fill_time(&history);
    assert!(result.is_some());
    // 30% in 2 hours → 15%/hour → 10% remaining → ~40 minutes
    let hours = result.unwrap();
    assert!(hours > 0.0 && hours < 5.0); // Should be roughly 0.67 hours (40 min)
}

// ---------------------------------------------------------------------------
// AutoCleanupResult
// ---------------------------------------------------------------------------

#[test]
fn auto_cleanup_result_default() {
    let result = crate::AutoCleanupResult::default();
    assert_eq!(result.cleaned_count, 0);
    assert_eq!(result.reclaimed_bytes, 0);
    assert!(result.cleaned_paths.is_empty());
    assert!(result.protected_paths.is_empty());
}

// ---------------------------------------------------------------------------
// Memory pressure (ADDED 2026-08-10, v0.112.35)
// ---------------------------------------------------------------------------

#[test]
fn parse_meminfo_reads_all_four_fields() {
    let sample = r#"MemTotal:       32754688 kB
MemFree:         1098776 kB
MemAvailable:    9010908 kB
SwapTotal:      32680964 kB
SwapFree:       11556016 kB
"#;
    let m = crate::parse_meminfo(sample).expect("meminfo should parse");
    assert_eq!(m.mem_total_kb, 32754688);
    assert_eq!(m.mem_available_kb, 9010908);
    assert_eq!(m.swap_total_kb, 32680964);
    assert_eq!(m.swap_free_kb, 11556016);
    // 9010908 / 32754688 ≈ 27%
    assert_eq!(m.mem_available_percent(), 27);
    // (32680964 - 11556016) / 32680964 ≈ 64.6%
    assert_eq!(m.swap_used_percent(), 64);
}

#[test]
fn parse_meminfo_missing_swap_reports_zero_used() {
    let sample = "MemTotal:       1048576 kB\nMemAvailable:     65536 kB\n";
    let m = crate::parse_meminfo(sample).expect("meminfo should parse");
    assert_eq!(m.mem_available_percent(), 6);
    assert_eq!(m.swap_used_percent(), 0);
}

#[test]
fn parse_meminfo_garbage_returns_none() {
    assert!(crate::parse_meminfo("not meminfo at all").is_none());
    assert!(crate::parse_meminfo("").is_none());
}

#[test]
fn parse_pressure_memory_extracts_full_and_some() {
    let psi = r#"some avg10=1.23 avg60=2.00 avg300=0.66 total=3743158654
full avg10=4.56 avg60=0.30 avg300=0.65 total=3579061268
"#;
    let (full, some) = crate::parse_pressure_memory(psi).expect("psi should parse");
    assert!((full - 4.56).abs() < 1e-9);
    assert!((some - 1.23).abs() < 1e-9);
}

#[test]
fn parse_pressure_memory_no_full_line_returns_none() {
    assert!(
        crate::parse_pressure_memory("some avg10=1.00 avg60=1.00 avg300=1.00 total=1").is_none()
    );
}

#[test]
fn parse_vmstat_swap_reads_counters() {
    let vmstat = "pswpin 1022648496\npswpout 1187700919\nnr_free_pages 12345\n";
    let (pin, pout) = crate::parse_vmstat_swap(vmstat).expect("vmstat should parse");
    assert_eq!(pin, 1022648496);
    assert_eq!(pout, 1187700919);
}

// ---------------------------------------------------------------------------
// Zombie parsing (ADDED 2026-08-10, v0.112.35)
// ---------------------------------------------------------------------------

#[test]
fn record_swap_counters_preserves_pswpout() {
    let mut state = crate::GuardRuntimeState::default();
    crate::record_swap_counters(&mut state, 123, 456);
    let (_, pswpin, pswpout) = state.prev_swap_counters.expect("counters recorded");
    assert_eq!(pswpin, 123);
    assert_eq!(pswpout, 456);
}

#[test]
fn parse_proc_stat_zombie_detects_z_state() {
    // pid=1234, comm contains a space (valid), state=Z, ppid=567,
    // starttime=999 (field 22, index 19 after pid+comm).
    let line = "1234 (chrome --type=renderer) Z 567 1 567 0 -1 4194304 42 0 0 0 0 0 0 0 20 0 1 0 999 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0";
    let (pid, comm, ppid, starttime) =
        crate::parse_proc_stat_zombie(line).expect("zombie stat should parse");
    assert_eq!(pid, 1234);
    assert_eq!(comm, "chrome --type=renderer");
    assert_eq!(ppid, 567);
    assert_eq!(starttime, 999);
}

#[test]
fn parse_proc_stat_zombie_ignores_non_zombies() {
    let line = "42 (bash) S 1 42 42 0 -1 4194304 100 0 0 0 0 0 0 0 20 0 1 0 123 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0";
    assert!(crate::parse_proc_stat_zombie(line).is_none());
}

// ---------------------------------------------------------------------------
// Trash credential guard (ADDED 2026-08-10, v0.112.35)
// ---------------------------------------------------------------------------

#[test]
fn looks_credential_like_matches_known_patterns() {
    assert!(crate::looks_credential_like("Login Data"));
    assert!(crate::looks_credential_like("CREDENTIALS.md"));
    assert!(crate::looks_credential_like("secrets.rs"));
    assert!(crate::looks_credential_like(".env"));
    assert!(crate::looks_credential_like("github.env"));
    assert!(crate::looks_credential_like("id_ed25519.key"));
    assert!(crate::looks_credential_like("backup.age"));
    assert!(crate::looks_credential_like(".git-credentials"));
    assert!(crate::looks_credential_like(".npmrc"));
    assert!(crate::looks_credential_like("hosts.yml"));
    assert!(crate::looks_credential_like("password-store"));
    assert!(crate::looks_credential_like("wallet-token-cache"));
}

#[test]
fn looks_credential_like_ignores_benign_names() {
    assert!(!crate::looks_credential_like("target"));
    assert!(!crate::looks_credential_like("node_modules"));
    assert!(!crate::looks_credential_like("ai-vid-editor"));
    assert!(!crate::looks_credential_like("nixpkgs"));
    assert!(!crate::looks_credential_like("go"));
    assert!(!crate::looks_credential_like("saved_stuff"));
    assert!(!crate::looks_credential_like("references"));
}

// ---------------------------------------------------------------------------
// Disk fill rate (ADDED 2026-08-10, v0.112.35)
// ---------------------------------------------------------------------------

#[test]
fn disk_fill_rate_gbph_computes_sustained_rate() {
    let now = Instant::now();
    // 10 GiB per hour for 2 hours = 20 GiB growth.
    let history: Vec<(Instant, u64)> = vec![
        (now - Duration::from_secs(7200), 500u64 * 1024 * 1024 * 1024),
        (now - Duration::from_secs(3600), 510u64 * 1024 * 1024 * 1024),
        (now, 520u64 * 1024 * 1024 * 1024),
    ];
    let rate = crate::disk_fill_rate_gbph(&history).expect("rate should compute");
    assert!((rate - 10.0).abs() < 0.5, "expected ~10 GiB/h, got {rate}");
}

#[test]
fn disk_fill_rate_gbph_requires_minimum_samples_and_span() {
    let now = Instant::now();
    assert!(crate::disk_fill_rate_gbph(&[]).is_none());
    assert!(crate::disk_fill_rate_gbph(&[(now, 100), (now, 200)]).is_none());
    // Span too short (10s < 60s).
    let short: Vec<(Instant, u64)> = vec![
        (now - Duration::from_secs(10), 100),
        (now - Duration::from_secs(5), 200),
        (now, 300),
    ];
    assert!(crate::disk_fill_rate_gbph(&short).is_none());
}

#[test]
fn disk_fill_rate_gbph_returns_none_when_disk_shrinks() {
    let now = Instant::now();
    let history: Vec<(Instant, u64)> = vec![
        (now - Duration::from_secs(7200), 600u64 * 1024 * 1024 * 1024),
        (now - Duration::from_secs(3600), 550u64 * 1024 * 1024 * 1024),
        (now, 500u64 * 1024 * 1024 * 1024),
    ];
    assert!(crate::disk_fill_rate_gbph(&history).is_none());
}

// ── OOM-bias steering (v0.112.36) ────────────────────────────────────────

#[test]
fn oom_bias_target_raises_neutral_values_to_250() {
    assert_eq!(crate::oom_bias_target(0), Some(250));
    assert_eq!(crate::oom_bias_target(100), Some(250));
    assert_eq!(crate::oom_bias_target(-100), Some(250));
    assert_eq!(crate::oom_bias_target(-300), Some(250));
}

#[test]
fn oom_bias_target_never_raises_already_biased_or_protected() {
    // Already at/above the target: leave alone.
    assert_eq!(crate::oom_bias_target(250), None);
    assert_eq!(crate::oom_bias_target(500), None);
    assert_eq!(crate::oom_bias_target(1000), None);
    // Deliberately protected (unkillable or strongly shielded): never touch.
    assert_eq!(crate::oom_bias_target(-500), None);
    assert_eq!(crate::oom_bias_target(-800), None);
    assert_eq!(crate::oom_bias_target(-1000), None);
}

#[test]
fn oom_bias_target_boundaries() {
    assert_eq!(crate::oom_bias_target(249), Some(250));
    assert_eq!(crate::oom_bias_target(250), None);
    assert_eq!(crate::oom_bias_target(-499), Some(250));
    assert_eq!(crate::oom_bias_target(-500), None);
}

// ── Memory-limiter policy defaults (v0.112.36) ──────────────────────────

#[test]
fn memory_limiter_policy_defaults_are_safe() {
    let p = crate::GuardPolicy::default();
    assert!(!p.freeze_sync_at_action, "sync freeze must be opt-in");
    assert!(!p.auto_renice, "CPU priority changes must be opt-in");
    assert!(p.auto_renice_on_memory, "renice-on-memory default on");
    assert!(p.bias_oom_on_pressure, "oom-bias default on");
    assert_eq!(p.memory_pressure_sustain_secs, 120);
    assert_eq!(p.report_repeat_secs, 1800);
    assert_eq!(
        p.cap_offenders_cpu_percent, 0,
        "CPUQuota offender caps default OFF (opt-in)"
    );
}

#[test]
fn normalize_guard_policy_clamps_cpu_cap_percent() {
    let mut policy = crate::GuardPolicy {
        cap_offenders_cpu_percent: u32::MAX,
        ..Default::default()
    };
    crate::normalize_guard_policy(&mut policy);
    assert_eq!(policy.cap_offenders_cpu_percent, 100);

    policy.cap_offenders_cpu_percent = 100;
    crate::normalize_guard_policy(&mut policy);
    assert_eq!(policy.cap_offenders_cpu_percent, 100);
}

#[test]
fn resolve_bin_falls_back_to_bare_name_off_nixos() {
    // The lenient helper preserves the old PATH-relative behavior for
    // non-privilege callers (nix tooling).
    assert_eq!(
        crate::resolve_bin("dracon-definitely-not-a-binary"),
        "dracon-definitely-not-a-binary"
    );
    // A repeated lookup hits the cache and agrees with itself.
    assert_eq!(
        crate::resolve_bin("dracon-definitely-not-a-binary"),
        "dracon-definitely-not-a-binary"
    );
}

#[test]
fn resolve_bin_strict_refuses_unresolvable_names() {
    // Audit falsification round: privilege-adjacent execs (renice,
    // systemctl) must never fall back to a bare PATH-relative name that
    // PATH poisoning could redirect. Unresolvable names are an error.
    let err = crate::resolve_bin_strict("dracon-definitely-not-a-binary").unwrap_err();
    assert!(
        format!("{err:#}").contains("refusing PATH-relative exec"),
        "strict resolve must refuse, not fall back: {err:#}"
    );
}

#[test]
fn reap_policy_from_guard_maps_thresholds_and_shares_exempts() {
    // Audit MEDIUM: the daemon wiring between policy knobs and the reap
    // scanner had zero coverage. The exempt list is shared with pressure
    // mitigation on purpose (too important to renice ⇒ too important to
    // look abandoned), so pin that coupling here.
    let guard = crate::GuardPolicy {
        reap_report_min_idle_hours: 48,
        reap_report_max_cpu_seconds: 120,
        reap_report_signatures: "vite,mytool".to_string(),
        process_exempt_names: "keepme,alsokeep".to_string(),
        ..Default::default()
    };
    let policy = crate::reap_policy_from_guard(&guard);
    assert_eq!(policy.min_idle_hours, 48);
    assert_eq!(policy.max_cpu_seconds, 120);
    assert_eq!(
        policy.signatures,
        vec!["mytool".to_string(), "vite".to_string()]
    );
    assert!(policy.exempt_names.contains(&"keepme".to_string()));
    assert!(policy.exempt_names.contains(&"alsokeep".to_string()));
}

#[test]
fn reap_candidates_runs_against_live_proc_without_panicking() {
    // Shape-only smoke test: the daemon wiring must degrade to an empty
    // (or populated) Vec on a real machine, never panic or block the pass.
    let guard = crate::GuardPolicy::default();
    let found = crate::reap_candidates(&guard);
    for c in &found {
        assert!(c.idle_hours >= guard.reap_report_min_idle_hours);
        assert!(c.cpu_seconds <= guard.reap_report_max_cpu_seconds);
        assert!(!c.args.is_empty());
    }
}

#[test]
fn zombie_since_keys_carry_starttime_and_prune() {
    // A recycled PID must not inherit a dead zombie's age: first-seen is
    // keyed by (pid, starttime), and keys for vanished pids are pruned.
    let mut state = crate::GuardRuntimeState::default();
    state
        .zombies_since
        .insert((999_998, 12345), std::time::Instant::now());
    let _ = crate::zombie_details(&mut state);
    assert!(
        !state.zombies_since.contains_key(&(999_998, 12345)),
        "stale zombie key for a vanished pid must be pruned"
    );
}

#[test]
fn unavailable_identity_defer_drops_at_retry_limit() {
    // The oom-restore and cpu-uncap loops must not retain an entry whose
    // process identity stays unreadable forever (audit LOW: unbounded
    // defer leaks the tracking maps inside the 250 MiB cgroup).
    let mut attempts = std::collections::HashMap::new();
    assert!(!crate::record_unavailable_attempt(&mut attempts, 4242));
    assert!(!crate::record_unavailable_attempt(&mut attempts, 4242));
    assert!(crate::record_unavailable_attempt(&mut attempts, 4242));
    assert_eq!(attempts.get(&4242), Some(&3));
    // A different pid counts independently.
    assert!(!crate::record_unavailable_attempt(&mut attempts, 4243));
}

#[test]
fn clean_node_modules_flag_defaults_true_and_gates_toml_off() {
    // Audit M3 (2026-08-21): node_modules cleanup was the only cleanup
    // kind with no feature flag. The knob must default true (behavior
    // preserved) and parse false from TOML; run_auto_cleanup consults it
    // exactly like its clean_trash / clean_nix_garbage siblings, while
    // explicit `guard clean --node-modules` stays ungated.
    let policy: crate::GuardPolicy = toml::from_str("").expect("empty policy parses with defaults");
    assert!(policy.clean_node_modules);
    let policy: crate::GuardPolicy =
        toml::from_str("clean_node_modules = false\n").expect("flag-off parses");
    assert!(!policy.clean_node_modules);
}

#[test]
fn policy_load_roundtrip_memory_limiter_knobs() {
    // TOML parse → defaults preserved when keys absent.
    let policy: crate::GuardPolicy = toml::from_str("").expect("empty policy parses with defaults");
    assert!(policy.auto_renice_on_memory);
    assert!(policy.bias_oom_on_pressure);
    assert_eq!(policy.cap_offenders_cpu_percent, 0);
    // Explicit values round-trip.
    let policy: crate::GuardPolicy = toml::from_str(
        "auto_renice_on_memory = false\nbias_oom_on_pressure = false\ncap_offenders_cpu_percent = 50\n",
    )
    .expect("explicit knobs parse");
    assert!(!policy.auto_renice_on_memory);
    assert!(!policy.bias_oom_on_pressure);
    assert_eq!(policy.cap_offenders_cpu_percent, 50);
}

// ---------------------------------------------------------------------------
// SIGHUP reload — bounded, and never half-configured
//
// DECIDE #2 follow-up. The reload used to swap the policy unconditionally,
// so a partial restore of process adjustments could pair the NEW policy with
// the OLD policy's leftover runtime state. The concrete harm: if the new
// policy disables the mitigation that made an adjustment, nothing retries it
// and the process stays reniced for the daemon's lifetime.
// ---------------------------------------------------------------------------

fn runtime_with_pending_nice(pid: i32) -> GuardRuntimeState {
    let mut state = GuardRuntimeState::default();
    state.memory_reniced_pids.insert(
        pid,
        MemoryReniceState {
            original_nice: 3,
            applied_nice: 10,
            identity: ProcessIdentity {
                comm: "worker".to_string(),
                starttime: 42,
            },
        },
    );
    state
}

#[test]
fn a_fully_restored_reload_applies_the_new_policy_and_clears_runtime() {
    let mut guard = GuardPolicy::default();
    let mut runtime = runtime_with_pending_nice(4242);
    let new_policy = GuardPolicy {
        disk_warn_percent: 55,
        ..Default::default()
    };

    let outcome = apply_policy_reload(&mut guard, &mut runtime, new_policy, true);

    assert_eq!(outcome, ReloadOutcome::Applied);
    assert_eq!(guard.disk_warn_percent, 55, "new policy must be live");
    assert!(
        runtime.memory_reniced_pids.is_empty(),
        "a clean restore must reset the runtime so no old state survives"
    );
}

#[test]
fn a_partial_restore_keeps_the_previous_policy_live() {
    let mut guard = GuardPolicy {
        disk_warn_percent: 80,
        ..Default::default()
    };
    let mut runtime = runtime_with_pending_nice(4242);
    let new_policy = GuardPolicy {
        disk_warn_percent: 55,
        ..Default::default()
    };

    let outcome = apply_policy_reload(&mut guard, &mut runtime, new_policy, false);

    assert_eq!(outcome, ReloadOutcome::Deferred);
    assert_eq!(
        guard.disk_warn_percent, 80,
        "a deferred reload must not adopt the new policy"
    );
    assert_eq!(
        runtime.memory_reniced_pids.len(),
        1,
        "the pending adjustment must be retained so the still-armed mitigation retries it"
    );
}

/// The exact harm the ordering bug caused: a new policy that turns the
/// renice mitigation OFF, adopted on top of an unrestored adjustment, means
/// nothing ever restores the process.
#[test]
fn a_partial_restore_cannot_strand_an_adjustment_the_new_policy_disables() {
    let mut guard = GuardPolicy {
        auto_renice_on_memory: true,
        ..Default::default()
    };
    let mut runtime = runtime_with_pending_nice(4242);
    let new_policy = GuardPolicy {
        auto_renice_on_memory: false,
        ..Default::default()
    };

    let outcome = apply_policy_reload(&mut guard, &mut runtime, new_policy, false);

    assert_eq!(outcome, ReloadOutcome::Deferred);
    assert!(
        guard.auto_renice_on_memory,
        "the mitigation that produced the outstanding adjustment must stay armed, \
         otherwise the process is reniced forever with no path to restore it"
    );
    assert!(
        runtime.memory_reniced_pids.contains_key(&4242),
        "the outstanding adjustment must survive so it is retried"
    );
}

#[test]
fn a_partial_restore_with_only_threshold_changes_is_also_deferred() {
    // Deferral is not limited to mitigation toggles: any new policy is
    // refused, because the retained state is tied to the old one and we
    // cannot reason about the combination.
    let mut guard = GuardPolicy::default();
    let mut runtime = runtime_with_pending_nice(7);
    let new_policy = GuardPolicy {
        interval_secs: 5,
        ..Default::default()
    };

    assert_eq!(
        apply_policy_reload(&mut guard, &mut runtime, new_policy, false),
        ReloadOutcome::Deferred
    );
    assert_ne!(
        guard.interval_secs, 5,
        "the new interval must not be adopted"
    );
}

#[test]
fn disabling_the_guard_is_applied_even_after_a_partial_restore() {
    // Stopping is the safe direction, and the daemon's shutdown restore
    // re-tries the retained adjustments before it returns — so `enabled =
    // false` must not be blocked by a failed restore.
    let mut guard = GuardPolicy::default();
    let mut runtime = runtime_with_pending_nice(99);
    let new_policy = GuardPolicy {
        enabled: false,
        ..Default::default()
    };

    let outcome = apply_policy_reload(&mut guard, &mut runtime, new_policy, false);

    assert_eq!(outcome, ReloadOutcome::Applied);
    assert!(!guard.enabled, "enabled = false must always take effect");
    assert_eq!(
        runtime.memory_reniced_pids.len(),
        1,
        "state is retained for the shutdown restore, not dropped"
    );
}

#[test]
fn reload_is_idempotent_across_repeated_sighups() {
    let mut guard = GuardPolicy::default();
    let mut runtime = GuardRuntimeState::default();
    for _ in 0..5 {
        let p = GuardPolicy {
            disk_warn_percent: 70,
            ..Default::default()
        };
        assert_eq!(
            apply_policy_reload(&mut guard, &mut runtime, p, true),
            ReloadOutcome::Applied
        );
    }
    assert_eq!(guard.disk_warn_percent, 70);
    assert!(runtime.memory_reniced_pids.is_empty());
}

#[test]
fn a_reload_that_succeeds_after_a_deferred_one_recovers() {
    // A deferred reload must not wedge the daemon: once the restore
    // succeeds, the next SIGHUP applies normally.
    let mut guard = GuardPolicy::default();
    let mut runtime = runtime_with_pending_nice(1);
    let p1 = GuardPolicy {
        disk_warn_percent: 55,
        ..Default::default()
    };
    assert_eq!(
        apply_policy_reload(&mut guard, &mut runtime, p1, false),
        ReloadOutcome::Deferred
    );

    let p2 = GuardPolicy {
        disk_warn_percent: 55,
        ..Default::default()
    };
    assert_eq!(
        apply_policy_reload(&mut guard, &mut runtime, p2, true),
        ReloadOutcome::Applied
    );
    assert_eq!(guard.disk_warn_percent, 55);
    assert!(runtime.memory_reniced_pids.is_empty());
}

/// 2026-10-01 (audit HIGH): the `oom_score_adj` and CPUQuota RELEASES were inside
/// `if pressure == "ok" && can_restore_nice`, but their APPLIES are not gated by
/// that flag. On a host without CAP_SYS_NICE — a manual `guard daemon` run, or a
/// unit predating v0.112.39's `AmbientCapabilities` — the guard wrote
/// `oom_score_adj=250` and a CPUQuota cap under critical pressure and could then
/// never release either: the only recovery was SIGHUP or a restart, while the
/// sole warning printed said "renice mitigation disabled".
///
/// The defect was structural, so the guard is structural: the two release
/// halves must live OUTSIDE the `can_restore_nice` gate, which now wraps only
/// the renice half. Behavioural coverage would need the capability absent,
/// which this process cannot arrange, so `gated_release_markers` is a pure
/// function over the source text and is itself tested (see the next test).
fn gated_release_markers(src: &str) -> Result<Vec<String>, String> {
    let start = src
        .find("if pressure == \"ok\" {")
        .ok_or_else(|| "the pressure-release block was not found".to_string())?;
    let gate = src[start..]
        .find("if can_restore_nice {")
        .map(|i| start + i)
        .ok_or_else(|| {
            "the renice half is no longer gated on the restore capability".to_string()
        })?;
    let body = &src[gate..];

    // Brace-count to the gate's matching close.
    let mut depth = 0i32;
    let mut end = None;
    for (i, ch) in body.char_indices() {
        match ch {
            '{' => depth += 1,
            '}' => {
                depth -= 1;
                if depth == 0 {
                    end = Some(gate + i);
                    break;
                }
            }
            _ => {}
        }
    }
    let end = end.ok_or_else(|| "the capability gate is not brace-balanced".to_string())?;
    let gated = &src[gate..end];

    let mut wrongly_gated = Vec::new();
    for marker in [
        "Restore oom_score_adj after the release window",
        "Lift CPUQuota scopes after the release window",
    ] {
        if gated.contains(marker) {
            wrongly_gated.push(marker.to_string());
        }
        if !src[start..].contains(marker) {
            return Err(format!(
                "'{marker}' no longer exists: the release was deleted, not just ungated"
            ));
        }
    }
    // The renice half must still be inside the gate: it is the one that really
    // needs CAP_SYS_NICE, and its apply is gated too.
    if !gated.contains("mem-unrenice") {
        return Err(
            "the renice release left the can_restore_nice gate, but its apply is still gated"
                .to_string(),
        );
    }
    Ok(wrongly_gated)
}

#[test]
fn oom_and_cpu_releases_are_not_gated_by_the_nice_capability() {
    let wrongly = gated_release_markers(include_str!("main.rs"))
        .expect("the release block must be shaped as the fix requires");
    assert!(
        wrongly.is_empty(),
        "these releases are inside the can_restore_nice gate again, so a host without \
         CAP_SYS_NICE can never release them: {wrongly:?}"
    );
}

/// The guard above is only worth having if it FAILS on the old shape. This
/// feeds it a synthetic snippet with the pre-fix structure and requires it to
/// report both releases as gated.
#[test]
fn the_structural_guard_catches_a_reintroduced_defect() {
    let pre_fix = r#"
    if pressure == "ok" {
        if can_restore_nice {
            eprintln!("mem-unrenice");
        }
        // Restore oom_score_adj after the release window.
        let x = 1;
        // Lift CPUQuota scopes after the release window.
        let y = 2;
    } else {
    }
"#;
    // Nest the two releases back inside the gate, exactly as the old code had it.
    let pre_fix_nested = pre_fix.replace(
        "        if can_restore_nice {\n            eprintln!(\"mem-unrenice\");\n        }\n",
        "        if can_restore_nice {\n            eprintln!(\"mem-unrenice\");\n            // Restore oom_score_adj after the release window.\n            let x = 1;\n            // Lift CPUQuota scopes after the release window.\n            let y = 2;\n        }\n",
    );
    let wrongly = gated_release_markers(&pre_fix_nested)
        .expect("the synthetic snippet must still be parseable");
    assert_eq!(
        wrongly.len(),
        2,
        "the guard must flag both releases when they are nested in the gate: {wrongly:?}"
    );
}

/// 2026-10-01 (audit): the three `deferred += 1` sites in the descendant
/// oom-restoration sweep retried forever, so one child whose identity or
/// `oom_score_adj` was unreadable pinned its root at 250 for the life of the
/// process, grew the pending map without bound, and made every SIGHUP reload
/// permanently `Deferred`. The counter must stop the retries and the entry must
/// be dropped so the root can be released.
#[test]
fn pending_oom_descendant_retries_are_bounded() {
    let mut pending = OomPendingDescendant {
        root_pid: 1,
        original_adj: 0,
        identity: ProcessIdentity {
            starttime: 2,
            comm: "child".to_string(),
        },
        attempts: 0,
    };
    for attempt in 1..OOM_DESCENDANT_RETRY_LIMIT {
        assert!(
            !oom_descendant_attempts_exhausted(&mut pending),
            "attempt {attempt} must still be retried"
        );
        assert_eq!(pending.attempts, attempt);
    }
    assert!(
        oom_descendant_attempts_exhausted(&mut pending),
        "attempt {} must give up so the root is not pinned forever",
        OOM_DESCENDANT_RETRY_LIMIT
    );
    assert_eq!(pending.attempts, OOM_DESCENDANT_RETRY_LIMIT);
}

/// 2026-10-01 (audit): `oom_known_descendants` grew by one entry per descendant
/// incarnation ever seen and was only cleared when the root left
/// `oom_biased_pids`, so a long critical episode under a forking root
/// accumulated thousands of dead keys. The cap must actually prune.
#[test]
fn remembered_oom_descendants_are_pruned_past_the_cap() {
    use std::collections::HashSet;

    // A biased root with many dead descendants and one live one.
    let mut state = GuardRuntimeState::default();
    let identity = ProcessIdentity {
        starttime: 1,
        comm: "root".to_string(),
    };
    state.oom_biased_pids.insert(100, (0, identity.clone()));
    let live = (999, 42u64);
    let mut known: HashSet<(i32, u64)> = HashSet::new();
    known.insert(live);
    for i in 0..OOM_KNOWN_DESCENDANTS_CAP {
        known.insert((1000 + i as i32, u64::MAX - i as u64));
    }
    assert!(
        known.len() > OOM_KNOWN_DESCENDANTS_CAP,
        "the fixture must exceed the cap to exercise the prune"
    );
    state.oom_known_descendants.insert(100, known);
    // An unrelated, unbiased root must be dropped outright.
    state
        .oom_known_descendants
        .insert(200, HashSet::from([(1, 1)]));

    let all_processes = vec![crate::ProcSample {
        pid: live.0,
        ppid: 1,
        cpu_percent: 0.0,
        rss_mb: 0,
        nice: 0,
        command: "child".to_string(),
        args: String::new(),
        starttime: live.1,
    }];
    prune_oom_known_descendants(&mut state, &all_processes);

    assert!(
        !state.oom_known_descendants.contains_key(&200),
        "a root that is no longer biased must lose its bookkeeping"
    );
    let kept = &state.oom_known_descendants[&100];
    assert!(
        kept.len() <= OOM_KNOWN_DESCENDANTS_CAP,
        "the set must not stay above the cap, got {}",
        kept.len()
    );
    assert!(
        kept.contains(&live),
        "a descendant that is still alive must be remembered"
    );
}

/// 2026-10-01 (audit): applied mitigations lived only in memory, so a panic or a
/// `MemoryMax=250M` OOM kill during a critical-pressure episode restarted the
/// guard with empty maps and left `nice`/`oom_score_adj`/CPUQuota applied to live
/// processes with no record that they needed restoring. The ledger must survive
/// the round trip that a restart performs.
#[test]
fn the_mitigation_ledger_survives_a_restart() {
    let dir = std::env::temp_dir().join(format!(
        "dracon-system-mitigation-ledger-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("time")
            .as_nanos()
    ));
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join("guard-mitigations.json");

    // The CURRENT process stands in for an adjusted one: its identity is
    // definitely current, so adoption must keep it.
    let me = std::process::id() as i32;
    let live_identity = {
        // Read the real starttime/comm so the identity check passes.
        let stat = std::fs::read_to_string(format!("/proc/{me}/stat")).unwrap_or_default();
        let after = stat.rsplit_once(") ").map(|(_, rest)| rest.to_string());
        let starttime = after
            .as_deref()
            .and_then(|rest| rest.split_whitespace().nth(19))
            .and_then(|v| v.parse::<u64>().ok())
            .unwrap_or(0);
        ProcessIdentity {
            starttime,
            comm: "self".to_string(),
        }
    };

    let mut before = GuardRuntimeState::default();
    before.memory_reniced_pids.insert(
        me,
        MemoryReniceState {
            original_nice: 0,
            applied_nice: 5,
            identity: live_identity.clone(),
        },
    );
    before
        .oom_biased_pids
        .insert(me, (0, live_identity.clone()));
    persist_mitigations_to(&mut before, &path);
    assert!(path.exists(), "the ledger must be written");
    // An unchanged pass must not rewrite the file.
    let first = std::fs::metadata(&path).unwrap().modified().unwrap();
    persist_mitigations_to(&mut before, &path);
    let second = std::fs::metadata(&path).unwrap().modified().unwrap();
    assert_eq!(
        first, second,
        "an unchanged pass must not rewrite the ledger"
    );

    // A fresh process (a restart) adopts them.
    let mut after_restart = GuardRuntimeState::default();
    hydrate_mitigations_from(&path, &mut after_restart);
    assert!(
        after_restart.memory_reniced_pids.contains_key(&me),
        "a renice left applied by the previous run must be adopted"
    );
    assert!(
        after_restart.oom_biased_pids.contains_key(&me),
        "an oom bias left applied by the previous run must be adopted"
    );

    // A RECYCLED pid is never adopted: a wrong starttime must not match.
    let mut recycled = GuardRuntimeState::default();
    let mut bad = std::fs::read_to_string(&path).unwrap();
    bad = bad.replace(
        &format!("\"starttime\":{}", live_identity.starttime),
        "\"starttime\":999999999",
    );
    std::fs::write(&path, bad).unwrap();
    hydrate_mitigations_from(&path, &mut recycled);
    assert!(
        recycled.memory_reniced_pids.is_empty() && recycled.oom_biased_pids.is_empty(),
        "a ledger entry whose identity does not match must be ignored, not adopted"
    );

    // A corrupt ledger is not fatal and not adopted.
    std::fs::write(&path, "{ not json").unwrap();
    let mut corrupt = GuardRuntimeState::default();
    hydrate_mitigations_from(&path, &mut corrupt);
    assert!(
        corrupt.memory_reniced_pids.is_empty(),
        "a corrupt ledger must not block the daemon"
    );

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

// ---------------------------------------------------------------------------
// Mitigation ledger: CPU-cap cgroup fidelity (audit 2026-10-01)
// ---------------------------------------------------------------------------

/// A unique scratch directory, and this process's real identity so the ledger's
/// identity check matches (same shape as the round-trip test above).
fn cap_cgroup_fixture(label: &str) -> (std::path::PathBuf, i32, ProcessIdentity) {
    let dir = std::env::temp_dir().join(format!(
        "dracon-system-{label}-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("time")
            .as_nanos()
    ));
    std::fs::create_dir_all(&dir).expect("scratch dir");
    let me = std::process::id() as i32;
    let stat = std::fs::read_to_string(format!("/proc/{me}/stat")).unwrap_or_default();
    let starttime = stat
        .rsplit_once(") ")
        .and_then(|(_, rest)| rest.split_whitespace().nth(19))
        .and_then(|v| v.parse::<u64>().ok())
        .unwrap_or(0);
    let identity = ProcessIdentity {
        starttime,
        comm: "self".to_string(),
    };
    (dir.join("guard-mitigations.json"), me, identity)
}

#[test]
fn mitigation_ledger_round_trips_the_capped_pids_original_cgroup() {
    let (path, me, identity) = cap_cgroup_fixture("ledger-cap-cgroup");
    let orig_cgroup = "user.slice/user-1000.slice/user@1000.service/app.slice";

    let mut before = GuardRuntimeState::default();
    before.capped_pids.insert(
        me,
        (
            "run-r1.service".to_string(),
            orig_cgroup.to_string(),
            identity.clone(),
        ),
    );
    persist_mitigations_to(&mut before, &path);

    let mut after_restart = GuardRuntimeState::default();
    hydrate_mitigations_from(&path, &mut after_restart);
    let (scope, restored_cgroup, _) = after_restart
        .capped_pids
        .get(&me)
        .expect("a cap left applied by the previous run must be adopted");
    assert_eq!(scope, "run-r1.service");
    assert_eq!(
        restored_cgroup, orig_cgroup,
        "the cgroup to restore to must survive the restart, not hydrate empty"
    );

    let _ = std::fs::remove_dir_all(path.parent().unwrap());
}

#[test]
fn a_legacy_ledger_without_the_cgroup_still_hydrates_and_never_guesses_a_path() {
    let (path, me, identity) = cap_cgroup_fixture("ledger-cap-legacy");
    // A ledger written before cap_orig_cgroup existed: the field is absent, and
    // serde must read it as None instead of rejecting the whole file.
    // Built with the real serializer, then asserted to carry no cap_orig_cgroup:
    // this is exactly the shape a ledger written before that field existed has.
    let legacy = serde_json::json!({
        "records": [{
            "pid": me,
            "original_nice": serde_json::Value::Null,
            "original_oom_adj": serde_json::Value::Null,
            "cap_scope": "run-r9.service",
            "identity": {"starttime": identity.starttime, "comm": "self"},
        }]
    })
    .to_string();
    assert!(
        !legacy.contains("cap_orig_cgroup"),
        "the legacy fixture must not contain the newer field"
    );
    std::fs::write(&path, legacy).unwrap();

    let mut after_restart = GuardRuntimeState::default();
    hydrate_mitigations_from(&path, &mut after_restart);
    let (_, restored_cgroup, _) = after_restart
        .capped_pids
        .get(&me)
        .expect("a legacy ledger entry with a matching identity must still be adopted");
    assert_eq!(
        restored_cgroup, "",
        "a legacy ledger has no cgroup, and must be adopted with it empty"
    );

    // The empty value resolves to the transient unit's PARENT cgroup, never to
    // the empty path `/sys/fs/cgroup//cgroup.procs` (the cgroup root).
    let current = "user.slice/user-1000.slice/user@1000.service/run-r9.service";
    assert_eq!(
        restore_cgroup_target("", current).as_deref(),
        Some("user.slice/user-1000.slice/user@1000.service"),
        "with no recorded cgroup the pid goes back to the scope unit's parent"
    );
    // A recorded cgroup always wins.
    assert_eq!(
        restore_cgroup_target("user.slice/app.slice", current).as_deref(),
        Some("user.slice/app.slice")
    );
    // No recorded cgroup AND no parent to derive: refuse rather than guess.
    assert_eq!(restore_cgroup_target("", "run-r9.service"), None);

    let _ = std::fs::remove_dir_all(path.parent().unwrap());
}