rch-common 2.1.18

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

use serde::{Deserialize, Serialize};

use schemars::JsonSchema;
use schemars::generate::SchemaSettings;

use crate::incident_ledger::{IncidentLedgerConfig, default_ledger_path};
use crate::proof_intent::{ReplayConstraints, StaleSourcePolicy};
// Single source of truth for path masking lives in the shared redaction policy.
use crate::redaction::redact_path;

// ── Canonical default constants ──────────────────────────────────────────────
//
// Each constant is the single documented default for one knob. The values are
// copied from (and drift-guarded against, where the runtime struct lives in
// rch-common) the subsystems that consume them:
//   - temporary bypass backoff  → `bypass_record::BypassBackoff`
//   - auto-rejoin criteria       → `bypass_record::AutoRejoinCriteria`
//   - auto-rejoin probe thresholds → `rchd::bypass_recovery_service::BypassRecoveryConfig`
//   - reconciliation windows     → `rchd::repo_convergence` module constants
//   - incident ledger retention  → `incident_ledger::IncidentLedgerConfig`
//   - build-root safety          → `rchd::build_root_policy` module constants
//   - pooled target / reaper     → `rchd::config::StaleTargetReapConfig`
//   - log retention              → `log_retention::LogRetentionPolicy`
//   - disk pressure              → `disk_pressure_report::PressureThresholds`

/// Default temporary-bypass backoff window (30s; mirrors `BypassBackoff`).
pub const DEFAULT_BACKOFF_INITIAL_SECS: u64 = 30;
/// Default temporary-bypass backoff ceiling (15min; mirrors `BypassBackoff`).
pub const DEFAULT_BACKOFF_MAX_SECS: u64 = 900;

/// Default consecutive passes required before a worker may auto-rejoin.
pub const DEFAULT_REQUIRED_CONSECUTIVE_PASSES: u32 = 2;
/// Default cadence at which the recovery service scans for due probes (30s).
pub const DEFAULT_CHECK_INTERVAL_SECS: u64 = 30;
/// Default SSH/probe timeout for a single capability probe or canary (10s).
pub const DEFAULT_PROBE_TIMEOUT_SECS: u64 = 10;
/// Default minimum free disk (GB) a probed root must report.
pub const DEFAULT_MIN_DISK_FREE_GB: f64 = 5.0;
/// Default minimum free inodes a probed root must report.
pub const DEFAULT_MIN_DISK_INODES: u64 = 10_000;
/// Default maximum load-per-core a recovered worker may report.
pub const DEFAULT_MAX_LOAD_PER_CORE: f64 = 4.0;
/// Default minimum worker wire protocol (held at 0 until rch-wkr exposes one).
pub const DEFAULT_MIN_PROTOCOL: u32 = 0;
/// Default canary command run over the SSH path before a full rejoin.
pub const DEFAULT_CANARY_COMMAND: &str = "rustc --version";

/// Default maximum convergence attempts before a worker enters `Failed`.
pub const DEFAULT_RECONCILE_MAX_ATTEMPTS: u32 = 3;
/// Default wall-clock budget per convergence cycle (seconds).
pub const DEFAULT_RECONCILE_TIME_BUDGET_SECS: u64 = 120;
/// Default minimum dwell time before a state transition (hysteresis, ms).
pub const DEFAULT_RECONCILE_HYSTERESIS_MS: u64 = 5_000;
/// Default retained per-worker transition-history entries.
pub const DEFAULT_RECONCILE_MAX_TRANSITION_HISTORY: usize = 64;
/// Default retained global convergence-outcome entries.
pub const DEFAULT_RECONCILE_MAX_OUTCOME_HISTORY: usize = 256;
/// Default staleness threshold for a worker's last status check (seconds).
pub const DEFAULT_RECONCILE_STALENESS_SECS: u64 = 300;

/// Default retained-event count for the incident ledger after compaction.
pub const DEFAULT_INCIDENT_MAX_ENTRIES: usize = 5_000;
/// Default incident-ledger size that triggers compaction (4 MiB).
pub const DEFAULT_INCIDENT_MAX_BYTES: u64 = 4 * 1024 * 1024;

/// Default minimum free bytes a build root must have (2 GiB).
pub const DEFAULT_BUILD_ROOT_MIN_FREE_BYTES: u64 = 2 * 1024 * 1024 * 1024;
/// Default minimum free inodes a build root must have.
pub const DEFAULT_BUILD_ROOT_MIN_FREE_INODES: u64 = 50_000;

/// Default idle window before a pooled target dir is reaped (hours).
pub const DEFAULT_POOLED_REAPER_IDLE_HOURS: u32 = 12;
/// Default sweep cadence for the pooled-target stale reaper (minutes).
pub const DEFAULT_POOLED_REAPER_INTERVAL_MINS: u64 = 120;
/// Default LONG idle window before a POOLED (`-pool-`) target dir is reaped
/// (hours). Pooled dirs are reused across jobs — the warm cache is the point —
/// so they get a much longer window than per-job dirs: seven days of zero file
/// activity means the pool key's build dimensions are gone (toolchain bumped,
/// project retired) and the dir is a corpse, not a cache (observed live
/// 2026-08-09: ~670h-idle pooled dirs accumulating forever, bead 6dj11).
/// `0` disables pooled reaping entirely.
pub const DEFAULT_POOLED_REAPER_POOLED_IDLE_HOURS: u32 = 168;
/// Default per-worker byte budget (GiB) across ALL reap-class target dirs
/// (per-job + pooled + legacy). `0` disables the cap. When the total exceeds
/// the budget after the TTL passes, the sweep evicts oldest-idle-first among
/// dirs past the SHORT idle window — never an actively-written dir — until
/// back under budget (bead 6dj11: the css incident was ~300 GB of target
/// trees; a TTL alone cannot bound a burst of still-fresh dirs). Ships 0
/// (off): the cap pass re-stats every candidate tree, and an autonomous
/// eviction budget is an operator decision.
pub const DEFAULT_POOLED_REAPER_MAX_CACHE_GB: u32 = 0;
/// Default remote base under which pooled target dirs live.
pub const DEFAULT_POOLED_REMOTE_BASE: &str = "/data/projects";

/// Default idle window, in DAYS, before `rch gc` will collect a durable
/// per-worker Cargo cache dir (`rch-cargo-cache-*`, issue #42).
///
/// These caches hold the registry and git-dependency state every offloaded
/// build reuses, and each job refreshes the dir's mtime, so an idle age this
/// long means no job has touched the worker's cache for two weeks — a cold
/// corpse, not a warm cache. Collection additionally requires the open-fd and
/// live-process gates, so this window is a floor, never the sole authority.
/// `0` disables cache collection entirely.
pub const DEFAULT_GC_CARGO_CACHE_IDLE_DAYS: u32 = 14;

/// Default maximum telemetry age that still counts as "fresh" (seconds).
pub const DEFAULT_TELEMETRY_MAX_AGE_SECS: u64 = 120;

/// Default rotation trigger for an active managed log (16 MiB).
pub const DEFAULT_LOG_MAX_FILE_BYTES: u64 = 16 * 1024 * 1024;
/// Default rotated generations retained per managed log.
pub const DEFAULT_LOG_KEEP_ROTATED: usize = 3;
/// Default managed-log total at/above which pressure is `Warning` (64 MiB).
pub const DEFAULT_LOG_WARN_TOTAL_BYTES: u64 = 64 * 1024 * 1024;
/// Default managed-log total at/above which pressure is `Critical` (256 MiB).
pub const DEFAULT_LOG_CRITICAL_TOTAL_BYTES: u64 = 256 * 1024 * 1024;

/// Default available-percent below which disk pressure is `Warning`.
pub const DEFAULT_PRESSURE_WARNING_AVAIL_PCT: f64 = 15.0;
/// Default available-percent below which disk pressure is `Critical`.
pub const DEFAULT_PRESSURE_CRITICAL_AVAIL_PCT: f64 = 5.0;
/// Default available-inodes below which disk pressure is `Warning`.
pub const DEFAULT_PRESSURE_WARNING_AVAIL_INODES: u64 = 100_000;
/// Default available-inodes below which disk pressure is `Critical`.
pub const DEFAULT_PRESSURE_CRITICAL_AVAIL_INODES: u64 = 10_000;

/// Default real-fleet smoke/soak iteration count.
pub const DEFAULT_SMOKE_ITERATIONS: usize = 20;
/// Default deterministic seed for the soak workload.
pub const DEFAULT_SMOKE_SEED: u64 = 42;

/// Absolute path prefixes RCH treats as managed/standard (no operator warning).
const RCH_MANAGED_ROOT_PREFIXES: &[&str] =
    &["/tmp/rch", "/tmp", "/data/tmp/rch", "/data/projects", "/dp"];

/// Default disk roots whose capacity/inodes the recovery probe reports.
#[must_use]
fn default_disk_roots() -> Vec<String> {
    vec![
        "/tmp".to_string(),
        "/tmp/rch".to_string(),
        crate::types::default_remote_base(),
    ]
}

// ── Top-level policy ─────────────────────────────────────────────────────────

/// The failure-mode policy: what RCH does when a remediation path errors.
///
/// The defaults encode the project's core invariant — ordinary command paths
/// fail open (run locally) while explicit proof mode fails closed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct RemediationPolicy {
    /// Ordinary hook / `rch exec` paths fall back to local execution on error.
    pub hook_exec_fail_open: bool,
    /// Explicit proof mode refuses local fallback before running locally.
    pub proof_mode_fail_closed: bool,
}

impl Default for RemediationPolicy {
    fn default() -> Self {
        Self {
            hook_exec_fail_open: true,
            proof_mode_fail_closed: true,
        }
    }
}

// ── Temporary bypass ─────────────────────────────────────────────────────────

/// Temporary-bypass retention and probe backoff knobs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct TemporaryBypassConfig {
    /// Initial backoff window before the first recovery probe (seconds).
    pub backoff_initial_secs: u64,
    /// Ceiling for the exponential backoff window (seconds).
    pub backoff_max_secs: u64,
}

impl Default for TemporaryBypassConfig {
    fn default() -> Self {
        Self {
            backoff_initial_secs: DEFAULT_BACKOFF_INITIAL_SECS,
            backoff_max_secs: DEFAULT_BACKOFF_MAX_SECS,
        }
    }
}

// ── Auto-rejoin ──────────────────────────────────────────────────────────────

/// Auto-rejoin canary thresholds and recovery-probe dimensions.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct AutoRejoinConfig {
    /// Consecutive successful recovery probes required before a canary build.
    pub required_consecutive_passes: u32,
    /// Whether one canary build is required before full rejoin.
    pub canary_required: bool,
    /// How often the recovery service scans for due probes (seconds).
    pub check_interval_secs: u64,
    /// SSH/probe timeout for a single capability probe or canary (seconds).
    pub probe_timeout_secs: u64,
    /// Minimum free disk (GB) a worker must report on every probed root.
    pub min_disk_free_gb: f64,
    /// Minimum free inodes a worker must report on every probed root.
    pub min_disk_inodes: u64,
    /// Disk roots whose capacity/inodes the probe reports.
    pub disk_roots: Vec<String>,
    /// Maximum load-per-core a worker may report to pass the load dimension.
    pub max_load_per_core: f64,
    /// Minimum worker wire protocol required to pass the protocol dimension.
    pub min_protocol: u32,
    /// rustup targets a recovered worker must have (empty = cargo/rustc only).
    pub required_targets: Vec<String>,
    /// rustup toolchains a recovered worker must have (prefix-matched).
    pub required_toolchains: Vec<String>,
    /// The canary command run over the SSH path before full rejoin.
    pub canary_command: String,
}

impl Default for AutoRejoinConfig {
    fn default() -> Self {
        Self {
            required_consecutive_passes: DEFAULT_REQUIRED_CONSECUTIVE_PASSES,
            canary_required: true,
            check_interval_secs: DEFAULT_CHECK_INTERVAL_SECS,
            probe_timeout_secs: DEFAULT_PROBE_TIMEOUT_SECS,
            min_disk_free_gb: DEFAULT_MIN_DISK_FREE_GB,
            min_disk_inodes: DEFAULT_MIN_DISK_INODES,
            disk_roots: default_disk_roots(),
            max_load_per_core: DEFAULT_MAX_LOAD_PER_CORE,
            min_protocol: DEFAULT_MIN_PROTOCOL,
            required_targets: Vec::new(),
            required_toolchains: Vec::new(),
            canary_command: DEFAULT_CANARY_COMMAND.to_string(),
        }
    }
}

// ── Desired-state reconciliation ─────────────────────────────────────────────

/// Desired-state fleet reconciliation windows and history bounds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct ReconciliationConfig {
    /// Maximum convergence attempts before a worker enters `Failed`.
    pub max_attempts: u32,
    /// Wall-clock budget per convergence cycle (seconds).
    pub time_budget_secs: u64,
    /// Minimum dwell time before a state transition (hysteresis, ms).
    pub state_hysteresis_ms: u64,
    /// Retained per-worker transition-history entries.
    pub max_transition_history: usize,
    /// Retained global convergence-outcome entries.
    pub max_outcome_history: usize,
    /// Staleness threshold for a worker's last status check (seconds).
    pub staleness_threshold_secs: u64,
}

impl Default for ReconciliationConfig {
    fn default() -> Self {
        Self {
            max_attempts: DEFAULT_RECONCILE_MAX_ATTEMPTS,
            time_budget_secs: DEFAULT_RECONCILE_TIME_BUDGET_SECS,
            state_hysteresis_ms: DEFAULT_RECONCILE_HYSTERESIS_MS,
            max_transition_history: DEFAULT_RECONCILE_MAX_TRANSITION_HISTORY,
            max_outcome_history: DEFAULT_RECONCILE_MAX_OUTCOME_HISTORY,
            staleness_threshold_secs: DEFAULT_RECONCILE_STALENESS_SECS,
        }
    }
}

// ── Proof mode / deferred proof queue ────────────────────────────────────────

/// Proof intent store location and default replay policy.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct ProofConfig {
    /// Override path for the proof-intent JSONL store. `None` resolves under the
    /// RCH-managed state dir (alongside the incident ledger).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub store_path: Option<String>,
    /// Default stale-source policy when an intent does not specify one.
    pub default_stale_source_policy: StaleSourcePolicy,
    // Note: this nested table must be serialized last so the scalar keys above
    // precede it (TOML requires scalar keys before sub-tables).
    /// Default constraints applied to a stored intent at replay time.
    pub default_replay_constraints: ReplayConstraints,
}

impl Default for ProofConfig {
    fn default() -> Self {
        Self {
            store_path: None,
            default_replay_constraints: ReplayConstraints::default(),
            // Conservative default: only replay byte-identical sources.
            default_stale_source_policy: StaleSourcePolicy::RejectIfChanged,
        }
    }
}

// ── Incident ledger ──────────────────────────────────────────────────────────

/// Incident-ledger retention bounds and optional path override.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct IncidentLedgerPolicy {
    /// Override path for the ledger JSONL file. `None` uses the RCH state dir.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    /// Events retained after a compaction (most-recent wins).
    pub max_entries: usize,
    /// File size that triggers a compaction, in bytes.
    pub max_bytes: u64,
}

impl Default for IncidentLedgerPolicy {
    fn default() -> Self {
        Self {
            path: None,
            max_entries: DEFAULT_INCIDENT_MAX_ENTRIES,
            max_bytes: DEFAULT_INCIDENT_MAX_BYTES,
        }
    }
}

// ── Mount-aware build root ───────────────────────────────────────────────────

/// Mount-aware build-root / cargo-home safety thresholds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct BuildRootConfig {
    /// Minimum free bytes a build root must have to be considered safe.
    pub min_free_bytes: u64,
    /// Minimum free inodes a build root must have to be considered safe.
    pub min_free_inodes: u64,
}

impl Default for BuildRootConfig {
    fn default() -> Self {
        Self {
            min_free_bytes: DEFAULT_BUILD_ROOT_MIN_FREE_BYTES,
            min_free_inodes: DEFAULT_BUILD_ROOT_MIN_FREE_INODES,
        }
    }
}

// ── Pooled target dirs ───────────────────────────────────────────────────────

/// Pooled target-dir policy and conservative stale reaper.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct PooledTargetConfig {
    /// Whether per-key pooled target dirs are used for remote builds.
    pub pooling_enabled: bool,
    /// Whether the stale-target reaper runs (ships off pending canary soak).
    pub reaper_enabled: bool,
    /// Idle window before a pooled target dir is reaped (hours).
    pub reaper_idle_hours: u32,
    /// Sweep cadence for the stale reaper (minutes).
    pub reaper_interval_mins: u64,
    /// Remote base under which pooled target dirs live.
    pub remote_base: String,
    /// LONG idle window before a POOLED (`-pool-`) dir is reaped (hours);
    /// `0` disables pooled reaping. Floored at 24h when non-zero — pooled
    /// dirs are warm caches, never short-TTL targets (bead 6dj11).
    pub reaper_pooled_idle_hours: u32,
    /// Per-worker byte budget (GiB) across all reap-class target dirs; `0`
    /// disables. Over budget, the sweep evicts oldest-idle-first among dirs
    /// past the short idle window until back under (bead 6dj11).
    pub reaper_max_cache_gb: u32,
    /// Where pooled Cargo target stores are PLACED on the worker (issue #64).
    ///
    /// Unset (the default) keeps today's behavior: the pooled store lives
    /// inside the project mirror, i.e. under the worker's canonical project
    /// root, on whatever filesystem holds it. Set to an absolute path to move
    /// every pooled store to `<store_base>/<project_id>/.rch-target-…-pool-…`,
    /// which is how a worker with a small root disk keeps multi-GB warm pools
    /// on a larger volume.
    ///
    /// Distinct from [`Self::remote_base`], which is where the reaper *scans*;
    /// when this is set the reaper scans both, and
    /// [`Self::reaper_max_cache_gb`] then applies per scan root rather than
    /// per worker. Ignored for Windows workers, which keep their drive-letter
    /// build base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub store_base: Option<String>,

    /// EXTRA roots `rch gc` scans, beyond the ones rch derives itself.
    ///
    /// The derived set ([`crate::gc_roots::derive_gc_roots`]) already covers
    /// [`Self::remote_base`], [`Self::store_base`] and the worker temp base
    /// resolved by
    /// [`crate::gc_roots::remote_cargo_home_base_prelude`]. This
    /// list exists for runtime roots rch cannot know about — an operator build
    /// root on a mounted volume, a per-host scratch tree — which is precisely
    /// how ~700 GB of `.rch-target-*-pool-*` and `rch-cargo-cache-*` went
    /// uncollected fleet-wide while `rch gc` reported "0 dirs, 0 MB".
    ///
    /// Each entry must pass [`crate::stale_target_reap::is_safe_reap_base`]:
    /// absolute, no `..`, at least one segment, built only from
    /// `[A-Za-z0-9/._-]` (the value is embedded in a remote shell command).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub gc_extra_roots: Vec<String>,

    /// Idle window in DAYS before `rch gc` may collect a durable per-worker
    /// Cargo cache dir (`rch-cargo-cache-*`); `0` disables cache collection.
    /// See [`DEFAULT_GC_CARGO_CACHE_IDLE_DAYS`].
    pub gc_cargo_cache_idle_days: u32,
}

impl Default for PooledTargetConfig {
    fn default() -> Self {
        Self {
            pooling_enabled: true,
            reaper_enabled: false,
            reaper_idle_hours: DEFAULT_POOLED_REAPER_IDLE_HOURS,
            reaper_interval_mins: DEFAULT_POOLED_REAPER_INTERVAL_MINS,
            remote_base: DEFAULT_POOLED_REMOTE_BASE.to_string(),
            reaper_pooled_idle_hours: DEFAULT_POOLED_REAPER_POOLED_IDLE_HOURS,
            reaper_max_cache_gb: DEFAULT_POOLED_REAPER_MAX_CACHE_GB,
            store_base: None,
            gc_extra_roots: Vec::new(),
            gc_cargo_cache_idle_days: DEFAULT_GC_CARGO_CACHE_IDLE_DAYS,
        }
    }
}

// ── Telemetry freshness ──────────────────────────────────────────────────────

/// Telemetry freshness tolerance.
///
/// The freshness model itself ([`crate::telemetry_freshness`]) is adaptive and
/// pure; this knob is the base maximum age the recovery path treats as "fresh"
/// when it cannot derive a tighter, observer-aware tolerance.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct TelemetryFreshnessConfig {
    /// Maximum telemetry age that still counts as fresh (seconds).
    pub max_age_secs: u64,
}

impl Default for TelemetryFreshnessConfig {
    fn default() -> Self {
        Self {
            max_age_secs: DEFAULT_TELEMETRY_MAX_AGE_SECS,
        }
    }
}

// ── Log retention ────────────────────────────────────────────────────────────

/// Daemon log rotation/retention policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct LogRetentionConfig {
    /// Rotate an active log once it exceeds this many bytes.
    pub max_file_bytes: u64,
    /// Rotated generations to retain per log.
    pub keep_rotated: usize,
    /// Managed total at/above which pressure is `Warning`.
    pub warn_total_bytes: u64,
    /// Managed total at/above which pressure is `Critical`.
    pub critical_total_bytes: u64,
}

impl Default for LogRetentionConfig {
    fn default() -> Self {
        Self {
            max_file_bytes: DEFAULT_LOG_MAX_FILE_BYTES,
            keep_rotated: DEFAULT_LOG_KEEP_ROTATED,
            warn_total_bytes: DEFAULT_LOG_WARN_TOTAL_BYTES,
            critical_total_bytes: DEFAULT_LOG_CRITICAL_TOTAL_BYTES,
        }
    }
}

// ── Disk pressure ────────────────────────────────────────────────────────────

/// Disk-pressure classification thresholds.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct DiskPressureConfig {
    /// Available-percent at/below which pressure is `Warning`.
    pub warning_avail_pct: f64,
    /// Available-percent at/below which pressure is `Critical`.
    pub critical_avail_pct: f64,
    /// Available-inodes at/below which pressure is `Warning`.
    pub warning_avail_inodes: u64,
    /// Available-inodes at/below which pressure is `Critical`.
    pub critical_avail_inodes: u64,
}

impl Default for DiskPressureConfig {
    fn default() -> Self {
        Self {
            warning_avail_pct: DEFAULT_PRESSURE_WARNING_AVAIL_PCT,
            critical_avail_pct: DEFAULT_PRESSURE_CRITICAL_AVAIL_PCT,
            warning_avail_inodes: DEFAULT_PRESSURE_WARNING_AVAIL_INODES,
            critical_avail_inodes: DEFAULT_PRESSURE_CRITICAL_AVAIL_INODES,
        }
    }
}

// ── Real-fleet smoke/soak ────────────────────────────────────────────────────

/// Real-fleet smoke and soak validation defaults.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct SmokeConfig {
    /// Iteration count for the soak workload.
    pub iterations: usize,
    /// Deterministic seed for the soak workload.
    pub seed: u64,
}

impl Default for SmokeConfig {
    fn default() -> Self {
        Self {
            iterations: DEFAULT_SMOKE_ITERATIONS,
            seed: DEFAULT_SMOKE_SEED,
        }
    }
}

// ── Aggregate ────────────────────────────────────────────────────────────────

/// The complete remediation config schema: one section per subsystem plus the
/// top-level failure-mode policy.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
#[serde(default)]
pub struct RemediationConfig {
    /// Failure-mode policy (fail-open hook/exec, fail-closed proof mode).
    pub policy: RemediationPolicy,
    /// Temporary-bypass retention and backoff.
    pub temporary_bypass: TemporaryBypassConfig,
    /// Auto-rejoin canary thresholds and recovery-probe dimensions.
    pub auto_rejoin: AutoRejoinConfig,
    /// Desired-state reconciliation windows.
    pub reconciliation: ReconciliationConfig,
    /// Proof intent store and default replay policy.
    pub proof: ProofConfig,
    /// Incident ledger retention.
    pub incident_ledger: IncidentLedgerPolicy,
    /// Mount-aware build-root safety thresholds.
    pub build_root: BuildRootConfig,
    /// Pooled target-dir policy and stale reaper.
    pub pooled_target: PooledTargetConfig,
    /// Telemetry freshness tolerance.
    pub telemetry_freshness: TelemetryFreshnessConfig,
    /// Daemon log rotation/retention.
    pub log_retention: LogRetentionConfig,
    /// Disk-pressure classification thresholds.
    pub disk_pressure: DiskPressureConfig,
    /// Real-fleet smoke/soak defaults.
    pub smoke: SmokeConfig,
}

/// Severity of a [`RemediationIssue`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IssueSeverity {
    /// A value that makes the config invalid and must be corrected.
    Error,
    /// A value that is accepted but worth flagging (e.g. an operator path
    /// outside the RCH-managed roots).
    Warning,
}

/// A single validation finding for a remediation knob.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemediationIssue {
    /// Dotted field path, e.g. `remediation.auto_rejoin.check_interval_secs`.
    pub field: String,
    /// Whether the finding is an error or an advisory warning.
    pub severity: IssueSeverity,
    /// Human-readable explanation.
    pub message: String,
}

impl RemediationIssue {
    fn error(field: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            field: field.into(),
            severity: IssueSeverity::Error,
            message: message.into(),
        }
    }

    fn warning(field: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            field: field.into(),
            severity: IssueSeverity::Warning,
            message: message.into(),
        }
    }
}

impl RemediationConfig {
    /// Whether ordinary hook / `rch exec` paths fall back to local on error.
    #[must_use]
    pub fn hook_exec_is_fail_open(&self) -> bool {
        self.policy.hook_exec_fail_open
    }

    /// Whether explicit proof mode refuses local fallback before running.
    #[must_use]
    pub fn proof_mode_is_fail_closed(&self) -> bool {
        self.policy.proof_mode_fail_closed
    }

    /// Validate every knob, returning any errors and advisory warnings.
    ///
    /// Range/ordering checks reject impossible values; path checks require
    /// operator paths to be absolute and flag any path outside the RCH-managed
    /// roots as an operator override (warning, not error).
    #[must_use]
    pub fn validate(&self) -> Vec<RemediationIssue> {
        let mut issues = Vec::new();

        // Temporary bypass backoff.
        if self.temporary_bypass.backoff_initial_secs == 0 {
            issues.push(RemediationIssue::error(
                "remediation.temporary_bypass.backoff_initial_secs",
                "backoff_initial_secs must be greater than 0",
            ));
        }
        if self.temporary_bypass.backoff_max_secs < self.temporary_bypass.backoff_initial_secs {
            issues.push(RemediationIssue::error(
                "remediation.temporary_bypass.backoff_max_secs",
                "backoff_max_secs must be >= backoff_initial_secs",
            ));
        }

        // Auto-rejoin.
        if self.auto_rejoin.required_consecutive_passes == 0 {
            issues.push(RemediationIssue::error(
                "remediation.auto_rejoin.required_consecutive_passes",
                "required_consecutive_passes must be at least 1",
            ));
        }
        if self.auto_rejoin.check_interval_secs == 0 {
            issues.push(RemediationIssue::error(
                "remediation.auto_rejoin.check_interval_secs",
                "check_interval_secs must be greater than 0",
            ));
        }
        if self.auto_rejoin.probe_timeout_secs == 0 {
            issues.push(RemediationIssue::error(
                "remediation.auto_rejoin.probe_timeout_secs",
                "probe_timeout_secs must be greater than 0",
            ));
        }
        if !self.auto_rejoin.min_disk_free_gb.is_finite() || self.auto_rejoin.min_disk_free_gb < 0.0
        {
            issues.push(RemediationIssue::error(
                "remediation.auto_rejoin.min_disk_free_gb",
                "min_disk_free_gb must be finite and >= 0",
            ));
        }
        if !self.auto_rejoin.max_load_per_core.is_finite()
            || self.auto_rejoin.max_load_per_core <= 0.0
        {
            issues.push(RemediationIssue::error(
                "remediation.auto_rejoin.max_load_per_core",
                "max_load_per_core must be finite and > 0",
            ));
        }
        if self.auto_rejoin.canary_command.trim().is_empty() {
            issues.push(RemediationIssue::error(
                "remediation.auto_rejoin.canary_command",
                "canary_command must not be empty",
            ));
        }
        for root in &self.auto_rejoin.disk_roots {
            check_managed_path("remediation.auto_rejoin.disk_roots", root, &mut issues);
        }

        // Reconciliation.
        if self.reconciliation.max_attempts == 0 {
            issues.push(RemediationIssue::error(
                "remediation.reconciliation.max_attempts",
                "max_attempts must be at least 1",
            ));
        }
        if self.reconciliation.time_budget_secs == 0 {
            issues.push(RemediationIssue::error(
                "remediation.reconciliation.time_budget_secs",
                "time_budget_secs must be greater than 0",
            ));
        }

        // Proof store path.
        if let Some(path) = &self.proof.store_path {
            check_managed_path("remediation.proof.store_path", path, &mut issues);
        }

        // Incident ledger.
        if self.incident_ledger.max_entries == 0 {
            issues.push(RemediationIssue::error(
                "remediation.incident_ledger.max_entries",
                "max_entries must be at least 1",
            ));
        }
        if self.incident_ledger.max_bytes == 0 {
            issues.push(RemediationIssue::error(
                "remediation.incident_ledger.max_bytes",
                "max_bytes must be greater than 0",
            ));
        }
        if let Some(path) = &self.incident_ledger.path {
            check_managed_path("remediation.incident_ledger.path", path, &mut issues);
        }

        // Build root.
        if self.build_root.min_free_bytes == 0 {
            issues.push(RemediationIssue::error(
                "remediation.build_root.min_free_bytes",
                "min_free_bytes must be greater than 0",
            ));
        }

        // Pooled target.
        if self.pooled_target.reaper_enabled && self.pooled_target.reaper_interval_mins == 0 {
            issues.push(RemediationIssue::error(
                "remediation.pooled_target.reaper_interval_mins",
                "reaper_interval_mins must be > 0 when the reaper is enabled",
            ));
        }
        check_managed_path(
            "remediation.pooled_target.remote_base",
            &self.pooled_target.remote_base,
            &mut issues,
        );
        if let Some(store_base) = self.pooled_target.store_base.as_deref() {
            check_managed_path(
                "remediation.pooled_target.store_base",
                store_base,
                &mut issues,
            );
            // The value is embedded in remote shell commands (sweep/enumerate)
            // and in CARGO_TARGET_DIR, so hold it to the same shape as every
            // other reap base: absolute, no traversal, at least two levels.
            if !crate::stale_target_reap::is_safe_reap_base(store_base) {
                issues.push(RemediationIssue::error(
                    "remediation.pooled_target.store_base",
                    format!(
                        "{store_base:?} is not a usable pooled-store base (absolute, no `..`, at least two levels deep)"
                    ),
                ));
            }
        }
        if self.pooled_target.reaper_pooled_idle_hours != 0
            && self.pooled_target.reaper_pooled_idle_hours < 24
        {
            issues.push(RemediationIssue::error(
                "remediation.pooled_target.reaper_pooled_idle_hours",
                "reaper_pooled_idle_hours must be 0 (disabled) or >= 24 — pooled dirs are warm caches, not short-TTL targets",
            ));
        }
        for (idx, root) in self.pooled_target.gc_extra_roots.iter().enumerate() {
            check_managed_path(
                "remediation.pooled_target.gc_extra_roots",
                root,
                &mut issues,
            );
            if !crate::stale_target_reap::is_safe_reap_base(root) {
                issues.push(RemediationIssue::error(
                    "remediation.pooled_target.gc_extra_roots",
                    format!(
                        "gc_extra_roots[{idx}] {root:?} is not a usable gc scan root (absolute, no `..`, no shell metacharacters)"
                    ),
                ));
            }
        }

        // Telemetry freshness.
        if self.telemetry_freshness.max_age_secs == 0 {
            issues.push(RemediationIssue::error(
                "remediation.telemetry_freshness.max_age_secs",
                "max_age_secs must be greater than 0",
            ));
        }

        // Log retention.
        if self.log_retention.max_file_bytes == 0 {
            issues.push(RemediationIssue::error(
                "remediation.log_retention.max_file_bytes",
                "max_file_bytes must be greater than 0",
            ));
        }
        if self.log_retention.critical_total_bytes < self.log_retention.warn_total_bytes {
            issues.push(RemediationIssue::error(
                "remediation.log_retention.critical_total_bytes",
                "critical_total_bytes must be >= warn_total_bytes",
            ));
        }

        // Disk pressure ordering and range.
        let dp = &self.disk_pressure;
        for (field, pct) in [
            (
                "remediation.disk_pressure.warning_avail_pct",
                dp.warning_avail_pct,
            ),
            (
                "remediation.disk_pressure.critical_avail_pct",
                dp.critical_avail_pct,
            ),
        ] {
            if !pct.is_finite() || !(0.0..=100.0).contains(&pct) {
                issues.push(RemediationIssue::error(
                    field,
                    "available-percent thresholds must be within [0.0, 100.0]",
                ));
            }
        }
        if dp.critical_avail_pct > dp.warning_avail_pct {
            issues.push(RemediationIssue::error(
                "remediation.disk_pressure.critical_avail_pct",
                "critical_avail_pct must be <= warning_avail_pct",
            ));
        }
        if dp.critical_avail_inodes > dp.warning_avail_inodes {
            issues.push(RemediationIssue::error(
                "remediation.disk_pressure.critical_avail_inodes",
                "critical_avail_inodes must be <= warning_avail_inodes",
            ));
        }

        // Smoke.
        if self.smoke.iterations == 0 {
            issues.push(RemediationIssue::error(
                "remediation.smoke.iterations",
                "iterations must be at least 1",
            ));
        }

        issues
    }

    /// A redacted clone: every path-like field has its home/user segment masked
    /// so the config is safe to print in status output, logs, and proof JSON.
    #[must_use]
    pub fn redacted(&self) -> Self {
        let mut out = self.clone();
        out.auto_rejoin.disk_roots = out
            .auto_rejoin
            .disk_roots
            .iter()
            .map(|p| redact_path(p))
            .collect();
        out.proof.store_path = out.proof.store_path.as_deref().map(redact_path);
        out.incident_ledger.path = out.incident_ledger.path.as_deref().map(redact_path);
        out.pooled_target.remote_base = redact_path(&out.pooled_target.remote_base);
        out.pooled_target.store_base = out.pooled_target.store_base.as_deref().map(redact_path);
        out.pooled_target.gc_extra_roots = out
            .pooled_target
            .gc_extra_roots
            .iter()
            .map(|root| redact_path(root.as_str()))
            .collect();
        out
    }

    /// The machine-readable JSON Schema for the remediation config.
    ///
    /// This is the "machine-readable schema" half of the documented-defaults
    /// acceptance criterion; [`RemediationConfig::human_help`] is the human half.
    #[must_use]
    pub fn schema_json() -> serde_json::Value {
        serde_json::to_value(
            SchemaSettings::draft07()
                .into_generator()
                .into_root_schema_for::<RemediationConfig>(),
        )
        .expect("RemediationConfig schema serializes")
    }

    /// A human-readable summary of every knob and its default value.
    #[must_use]
    pub fn human_help() -> String {
        let d = RemediationConfig::default();
        let mut s = String::new();
        s.push_str("[remediation] — session-history remediation defaults\n");
        s.push_str("  policy.hook_exec_fail_open      = ");
        s.push_str(&d.policy.hook_exec_fail_open.to_string());
        s.push_str("  (ordinary hook/exec falls back to local on error)\n");
        s.push_str("  policy.proof_mode_fail_closed   = ");
        s.push_str(&d.policy.proof_mode_fail_closed.to_string());
        s.push_str("  (proof mode refuses local fallback)\n");
        s.push_str(&format!(
            "  temporary_bypass.backoff_initial_secs = {}\n",
            d.temporary_bypass.backoff_initial_secs
        ));
        s.push_str(&format!(
            "  temporary_bypass.backoff_max_secs     = {}\n",
            d.temporary_bypass.backoff_max_secs
        ));
        s.push_str(&format!(
            "  auto_rejoin.required_consecutive_passes = {}\n",
            d.auto_rejoin.required_consecutive_passes
        ));
        s.push_str(&format!(
            "  auto_rejoin.canary_required           = {}\n",
            d.auto_rejoin.canary_required
        ));
        s.push_str(&format!(
            "  auto_rejoin.check_interval_secs       = {}\n",
            d.auto_rejoin.check_interval_secs
        ));
        s.push_str(&format!(
            "  auto_rejoin.probe_timeout_secs        = {}\n",
            d.auto_rejoin.probe_timeout_secs
        ));
        s.push_str(&format!(
            "  reconciliation.max_attempts           = {}\n",
            d.reconciliation.max_attempts
        ));
        s.push_str(&format!(
            "  reconciliation.time_budget_secs       = {}\n",
            d.reconciliation.time_budget_secs
        ));
        s.push_str(&format!(
            "  proof.default_stale_source_policy     = {:?}\n",
            d.proof.default_stale_source_policy
        ));
        s.push_str(&format!(
            "  incident_ledger.max_entries           = {}\n",
            d.incident_ledger.max_entries
        ));
        s.push_str(&format!(
            "  incident_ledger.max_bytes             = {}\n",
            d.incident_ledger.max_bytes
        ));
        s.push_str(&format!(
            "  build_root.min_free_bytes             = {}\n",
            d.build_root.min_free_bytes
        ));
        s.push_str(&format!(
            "  build_root.min_free_inodes            = {}\n",
            d.build_root.min_free_inodes
        ));
        s.push_str(&format!(
            "  pooled_target.pooling_enabled         = {}\n",
            d.pooled_target.pooling_enabled
        ));
        s.push_str(&format!(
            "  pooled_target.reaper_enabled          = {}\n",
            d.pooled_target.reaper_enabled
        ));
        s.push_str(&format!(
            "  telemetry_freshness.max_age_secs      = {}\n",
            d.telemetry_freshness.max_age_secs
        ));
        s.push_str(&format!(
            "  log_retention.max_file_bytes          = {}\n",
            d.log_retention.max_file_bytes
        ));
        s.push_str(&format!(
            "  disk_pressure.warning_avail_pct       = {}\n",
            d.disk_pressure.warning_avail_pct
        ));
        s.push_str(&format!(
            "  disk_pressure.critical_avail_pct      = {}\n",
            d.disk_pressure.critical_avail_pct
        ));
        s.push_str(&format!(
            "  smoke.iterations                      = {}\n",
            d.smoke.iterations
        ));
        s.push_str(&format!(
            "  smoke.seed                            = {}\n",
            d.smoke.seed
        ));
        s
    }
}

/// Whether `path` resolves under a known RCH-managed/standard root.
#[must_use]
fn is_managed_path(path: &str) -> bool {
    if path.contains("/rch") {
        return true;
    }
    RCH_MANAGED_ROOT_PREFIXES
        .iter()
        .any(|prefix| path == *prefix || path.starts_with(&format!("{prefix}/")))
}

/// Push an error for a relative path or a warning for an operator path outside
/// the RCH-managed roots. Empty strings are ignored (treated as "unset").
fn check_managed_path(field: &str, path: &str, issues: &mut Vec<RemediationIssue>) {
    if path.trim().is_empty() {
        return;
    }
    // A leading `~` expands to an absolute home path at use time.
    let absolute = path.starts_with('/') || path.starts_with('~');
    if !absolute {
        issues.push(RemediationIssue::error(
            field,
            format!("path must be absolute, got {path:?}"),
        ));
        return;
    }
    if !is_managed_path(path) {
        issues.push(RemediationIssue::warning(
            field,
            format!(
                "{path:?} is outside the RCH-managed roots; ensure it is an intended operator path"
            ),
        ));
    }
}

// ── Conversions into rch-common runtime structs ──────────────────────────────
//
// These let runtime consumers build their existing structs from the central
// config; drift-guard tests assert each conversion of the *default* config
// reproduces the runtime struct's own `::default()`.

impl From<&TemporaryBypassConfig> for crate::bypass_record::BypassBackoff {
    fn from(cfg: &TemporaryBypassConfig) -> Self {
        Self {
            current_ms: cfg.backoff_initial_secs.saturating_mul(1000),
            attempts: 0,
            max_ms: cfg.backoff_max_secs.saturating_mul(1000),
        }
    }
}

impl From<&AutoRejoinConfig> for crate::bypass_record::AutoRejoinCriteria {
    fn from(cfg: &AutoRejoinConfig) -> Self {
        Self {
            required_consecutive_passes: cfg.required_consecutive_passes,
            canary_required: cfg.canary_required,
        }
    }
}

impl From<&IncidentLedgerPolicy> for IncidentLedgerConfig {
    fn from(cfg: &IncidentLedgerPolicy) -> Self {
        Self {
            // Validation treats a blank path as unset and a leading `~` as
            // absolute; honour both here, where the path is actually used.
            path: cfg
                .path
                .as_deref()
                .map(str::trim)
                .filter(|path| !path.is_empty())
                .map_or_else(default_ledger_path, |path| {
                    std::path::PathBuf::from(shellexpand::tilde(path).into_owned())
                }),
            max_entries: cfg.max_entries,
            max_bytes: cfg.max_bytes,
        }
    }
}

impl From<&LogRetentionConfig> for crate::log_retention::LogRetentionPolicy {
    fn from(cfg: &LogRetentionConfig) -> Self {
        Self {
            max_file_bytes: cfg.max_file_bytes,
            keep_rotated: cfg.keep_rotated,
            warn_total_bytes: cfg.warn_total_bytes,
            critical_total_bytes: cfg.critical_total_bytes,
        }
    }
}

impl From<&DiskPressureConfig> for crate::disk_pressure_report::PressureThresholds {
    fn from(cfg: &DiskPressureConfig) -> Self {
        Self {
            warning_avail_pct: cfg.warning_avail_pct,
            critical_avail_pct: cfg.critical_avail_pct,
            warning_avail_inodes: cfg.warning_avail_inodes,
            critical_avail_inodes: cfg.critical_avail_inodes,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bypass_record::{AutoRejoinCriteria, BypassBackoff};
    use crate::disk_pressure_report::PressureThresholds;
    use crate::log_retention::LogRetentionPolicy;

    /// Issue #64: the pooled store base is opt-in — an unset value keeps
    /// today's in-mirror placement, and a set value must survive a TOML
    /// round-trip under its documented key.
    #[test]
    fn pooled_store_base_is_opt_in_and_round_trips() {
        assert_eq!(RemediationConfig::default().pooled_target.store_base, None);

        let parsed: RemediationConfig = toml::from_str(
            r#"
            [pooled_target]
            store_base = "/bigdisk/rch-pools"
            "#,
        )
        .expect("parse pooled_target.store_base");
        assert_eq!(
            parsed.pooled_target.store_base.as_deref(),
            Some("/bigdisk/rch-pools")
        );
        assert!(
            parsed
                .validate()
                .iter()
                .all(|issue| issue.field != "remediation.pooled_target.store_base"),
            "an absolute, managed store_base must validate cleanly"
        );

        let round_trip: RemediationConfig =
            toml::from_str(&toml::to_string(&parsed).expect("serialize")).expect("reparse");
        assert_eq!(
            round_trip.pooled_target.store_base,
            parsed.pooled_target.store_base
        );

        // Unset stays absent from the serialized form, so existing configs are
        // not rewritten with a null placement.
        let default_toml =
            toml::to_string(&RemediationConfig::default()).expect("serialize default");
        assert!(
            !default_toml.contains("store_base"),
            "an unset store_base must not be emitted: {default_toml}"
        );
    }

    /// The value is embedded in remote shell commands and in
    /// `CARGO_TARGET_DIR`, so an unsafe base is a hard config error.
    /// The gc scan roots must be reachable from configuration alone: the whole
    /// bug was that a runtime root rch writes to could not be added without a
    /// code change.
    #[test]
    fn gc_extra_roots_are_opt_in_and_round_trip() {
        assert!(
            RemediationConfig::default()
                .pooled_target
                .gc_extra_roots
                .is_empty()
        );
        let parsed: RemediationConfig = toml::from_str(
            r#"
            [pooled_target]
            gc_extra_roots = ["/mnt/big/rch", "/srv/rch"]
            gc_cargo_cache_idle_days = 21
            "#,
        )
        .expect("parse pooled_target.gc_extra_roots");
        assert_eq!(
            parsed.pooled_target.gc_extra_roots,
            vec!["/mnt/big/rch".to_string(), "/srv/rch".to_string()]
        );
        assert_eq!(parsed.pooled_target.gc_cargo_cache_idle_days, 21);
        let issues = parsed.validate();
        assert!(
            issues
                .iter()
                .all(|i| i.field != "remediation.pooled_target.gc_extra_roots"
                    || i.severity != IssueSeverity::Error),
            "absolute, managed roots must validate cleanly: {issues:?}"
        );

        let round_trip: RemediationConfig =
            toml::from_str(&toml::to_string(&parsed).expect("serialize")).expect("round trip");
        assert_eq!(
            round_trip.pooled_target.gc_extra_roots,
            parsed.pooled_target.gc_extra_roots
        );

        // An unset list is not emitted, so a default config stays tidy.
        let default_toml =
            toml::to_string(&RemediationConfig::default()).expect("serialize default");
        assert!(
            !default_toml.contains("gc_extra_roots"),
            "an empty gc_extra_roots must not be emitted: {default_toml}"
        );
    }

    /// A gc root is embedded in a remote shell command, so anything that could
    /// break out of that context is an ERROR, not a sanitized value.
    #[test]
    fn unsafe_gc_extra_roots_are_rejected() {
        for bad in ["/", "relative/x", "/tmp/../etc", "/tmp/$(whoami)", "/a b/c"] {
            let mut config = RemediationConfig::default();
            config.pooled_target.gc_extra_roots = vec![bad.to_string()];
            let issues = config.validate();
            assert!(
                issues
                    .iter()
                    .any(|i| i.field == "remediation.pooled_target.gc_extra_roots"
                        && i.severity == IssueSeverity::Error),
                "{bad:?} must be rejected: {issues:?}"
            );
        }
    }

    #[test]
    fn gc_extra_roots_are_redacted_like_every_other_operator_path() {
        let mut config = RemediationConfig::default();
        config.pooled_target.gc_extra_roots = vec!["/home/carol/builds".to_string()];
        assert_eq!(
            config.redacted().pooled_target.gc_extra_roots,
            vec!["/home/<redacted>/builds".to_string()]
        );
    }

    #[test]
    fn unsafe_pooled_store_base_is_rejected() {
        for bad in ["relative/path", "/", "/tmp/../etc", "/toplevel"] {
            let mut config = RemediationConfig::default();
            config.pooled_target.store_base = Some(bad.to_string());
            assert!(
                config
                    .validate()
                    .iter()
                    .any(|issue| issue.field == "remediation.pooled_target.store_base"),
                "expected {bad:?} to be rejected"
            );
        }
    }

    #[test]
    fn default_construction_matches_documented_values() {
        let c = RemediationConfig::default();
        assert!(c.policy.hook_exec_fail_open);
        assert!(c.policy.proof_mode_fail_closed);
        assert_eq!(c.temporary_bypass.backoff_initial_secs, 30);
        assert_eq!(c.temporary_bypass.backoff_max_secs, 900);
        assert_eq!(c.auto_rejoin.required_consecutive_passes, 2);
        assert!(c.auto_rejoin.canary_required);
        assert_eq!(c.auto_rejoin.canary_command, "rustc --version");
        assert_eq!(c.reconciliation.max_attempts, 3);
        assert_eq!(c.incident_ledger.max_entries, 5_000);
        assert_eq!(c.incident_ledger.max_bytes, 4 * 1024 * 1024);
        assert_eq!(c.build_root.min_free_bytes, 2 * 1024 * 1024 * 1024);
        assert_eq!(c.telemetry_freshness.max_age_secs, 120);
        assert_eq!(c.smoke.iterations, 20);
    }

    #[test]
    fn default_is_valid() {
        let issues = RemediationConfig::default().validate();
        assert!(issues.is_empty(), "default must be valid, got {issues:?}");
    }

    #[test]
    fn serde_round_trip_via_toml() {
        let c = RemediationConfig::default();
        let toml_str = toml::to_string(&c).expect("serialize toml");
        let back: RemediationConfig = toml::from_str(&toml_str).expect("deserialize toml");
        assert_eq!(c, back);
    }

    #[test]
    fn serde_round_trip_via_json() {
        let c = RemediationConfig::default();
        let json = serde_json::to_string(&c).expect("serialize json");
        let back: RemediationConfig = serde_json::from_str(&json).expect("deserialize json");
        assert_eq!(c, back);
    }

    #[test]
    fn partial_toml_fills_missing_fields_from_default() {
        // Container-level #[serde(default)] must fill every omitted field.
        let partial = r#"
            [policy]
            hook_exec_fail_open = false

            [auto_rejoin]
            check_interval_secs = 99
        "#;
        let c: RemediationConfig = toml::from_str(partial).expect("parse partial");
        // Overridden:
        assert!(!c.policy.hook_exec_fail_open);
        assert_eq!(c.auto_rejoin.check_interval_secs, 99);
        // Untouched → defaults:
        assert!(c.policy.proof_mode_fail_closed);
        assert_eq!(c.auto_rejoin.required_consecutive_passes, 2);
        assert_eq!(c.incident_ledger.max_entries, 5_000);
    }

    #[test]
    fn malformed_values_are_rejected_by_validate() {
        let mut c = RemediationConfig::default();
        c.temporary_bypass.backoff_initial_secs = 0;
        c.auto_rejoin.check_interval_secs = 0;
        c.auto_rejoin.canary_command = "  ".to_string();
        c.disk_pressure_force_invalid();
        c.incident_ledger.max_entries = 0;
        let issues = c.validate();
        let fields: Vec<&str> = issues.iter().map(|i| i.field.as_str()).collect();
        assert!(fields.contains(&"remediation.temporary_bypass.backoff_initial_secs"));
        assert!(fields.contains(&"remediation.auto_rejoin.check_interval_secs"));
        assert!(fields.contains(&"remediation.auto_rejoin.canary_command"));
        assert!(fields.contains(&"remediation.incident_ledger.max_entries"));
        assert!(issues.iter().any(|i| i.severity == IssueSeverity::Error
            && i.field.starts_with("remediation.disk_pressure")));
    }

    #[test]
    fn malformed_toml_value_type_fails_to_parse() {
        // backoff_initial_secs must be an integer, not a string.
        let bad = r#"
            [temporary_bypass]
            backoff_initial_secs = "thirty"
        "#;
        assert!(toml::from_str::<RemediationConfig>(bad).is_err());
    }

    #[test]
    fn relative_path_is_an_error_managed_path_is_clean() {
        let mut c = RemediationConfig::default();
        c.incident_ledger.path = Some("relative/incidents.jsonl".to_string());
        let issues = c.validate();
        assert!(issues.iter().any(|i| {
            i.field == "remediation.incident_ledger.path" && i.severity == IssueSeverity::Error
        }));

        // A managed path under /tmp/rch is clean (no issue for that field).
        c.incident_ledger.path = Some("/tmp/rch/incidents.jsonl".to_string());
        let issues = c.validate();
        assert!(
            !issues
                .iter()
                .any(|i| i.field == "remediation.incident_ledger.path")
        );
    }

    #[test]
    fn operator_path_outside_managed_roots_warns() {
        let mut c = RemediationConfig::default();
        c.incident_ledger.path = Some("/var/lib/custom/incidents.jsonl".to_string());
        let issues = c.validate();
        let issue = issues
            .iter()
            .find(|i| i.field == "remediation.incident_ledger.path")
            .expect("operator path produces an issue");
        assert_eq!(issue.severity, IssueSeverity::Warning);
    }

    #[test]
    fn redaction_masks_home_and_user_segments() {
        let mut c = RemediationConfig::default();
        c.incident_ledger.path = Some("/home/alice/.local/state/rch/incidents.jsonl".to_string());
        c.proof.store_path = Some("/Users/bob/proofs.jsonl".to_string());
        c.auto_rejoin.disk_roots = vec!["/home/carol/builds".to_string(), "/tmp/rch".to_string()];
        let r = c.redacted();
        assert_eq!(
            r.incident_ledger.path.as_deref(),
            Some("/home/<redacted>/.local/state/rch/incidents.jsonl")
        );
        assert_eq!(
            r.proof.store_path.as_deref(),
            Some("/Users/<redacted>/proofs.jsonl")
        );
        assert_eq!(
            r.auto_rejoin.disk_roots,
            vec![
                "/home/<redacted>/builds".to_string(),
                "/tmp/rch".to_string()
            ]
        );
        // Non-sensitive paths are untouched.
        assert_eq!(redact_path("/tmp/rch"), "/tmp/rch");
        assert_eq!(redact_path("/data/projects"), "/data/projects");
    }

    #[test]
    fn schema_json_describes_the_struct() {
        let schema = RemediationConfig::schema_json();
        // Top-level object with our sections present.
        let props = schema
            .get("properties")
            .and_then(serde_json::Value::as_object)
            .expect("schema has properties");
        for section in [
            "policy",
            "temporary_bypass",
            "auto_rejoin",
            "reconciliation",
            "proof",
            "incident_ledger",
            "build_root",
            "pooled_target",
            "telemetry_freshness",
            "log_retention",
            "disk_pressure",
            "smoke",
        ] {
            assert!(
                props.contains_key(section),
                "schema missing section {section}"
            );
        }
    }

    #[test]
    fn human_help_lists_key_defaults() {
        let help = RemediationConfig::human_help();
        assert!(help.contains("hook_exec_fail_open"));
        assert!(help.contains("proof_mode_fail_closed"));
        assert!(help.contains("backoff_initial_secs"));
        assert!(help.contains("incident_ledger.max_entries"));
    }

    // ── Drift guards: central defaults reproduce runtime struct defaults ──

    #[test]
    fn drift_guard_bypass_backoff() {
        let from_cfg = BypassBackoff::from(&TemporaryBypassConfig::default());
        assert_eq!(from_cfg, BypassBackoff::default());
    }

    #[test]
    fn drift_guard_auto_rejoin_criteria() {
        let from_cfg = AutoRejoinCriteria::from(&AutoRejoinConfig::default());
        assert_eq!(from_cfg, AutoRejoinCriteria::default());
    }

    #[test]
    fn drift_guard_log_retention() {
        let from_cfg = LogRetentionPolicy::from(&LogRetentionConfig::default());
        assert_eq!(from_cfg, LogRetentionPolicy::default());
    }

    #[test]
    fn drift_guard_disk_pressure() {
        let from_cfg = PressureThresholds::from(&DiskPressureConfig::default());
        assert_eq!(from_cfg, PressureThresholds::default());
    }

    #[test]
    fn drift_guard_incident_ledger() {
        let from_cfg = IncidentLedgerConfig::from(&IncidentLedgerPolicy::default());
        let runtime = IncidentLedgerConfig::default();
        // IncidentLedgerConfig has no PartialEq; compare field-by-field.
        assert_eq!(from_cfg.max_entries, runtime.max_entries);
        assert_eq!(from_cfg.max_bytes, runtime.max_bytes);
        assert_eq!(from_cfg.path, runtime.path);
    }

    #[test]
    fn incident_ledger_path_expands_tilde_and_treats_blank_as_unset() {
        let with = |path: &str| {
            IncidentLedgerConfig::from(&IncidentLedgerPolicy {
                path: Some(path.to_owned()),
                ..IncidentLedgerPolicy::default()
            })
            .path
        };
        let expanded = with("~/state/incidents.jsonl");
        assert!(expanded.is_absolute(), "{expanded:?}");
        assert!(expanded.ends_with("state/incidents.jsonl"));
        assert_eq!(with("  "), IncidentLedgerConfig::default().path);
        assert_eq!(with("/x/i.jsonl"), std::path::PathBuf::from("/x/i.jsonl"));
    }

    // Test-only helper to force an invalid disk-pressure ordering.
    impl RemediationConfig {
        fn disk_pressure_force_invalid(&mut self) {
            self.disk_pressure.critical_avail_pct = 90.0;
            self.disk_pressure.warning_avail_pct = 10.0;
        }
    }
}