rchd 2.1.24

Remote Compilation Helper - Local daemon for worker orchestration
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
//! Configuration loading for the RCH daemon.
//!
//! Loads worker definitions from workers.toml and daemon settings from config.toml.

use anyhow::{Context, Result};
use rch_common::{RchConfig, SelfTestConfig, WorkerConfig, validate_remote_base};
use serde::{Deserialize, Serialize};
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use tracing::{debug, info, warn};

const RCH_CONFIG_DIR_ENV: &str = "RCH_CONFIG_DIR";

/// Default config directory name.
const CONFIG_DIR_NAME: &str = "rch";

/// Default workers config file name.
const WORKERS_FILE_NAME: &str = "workers.toml";

/// Default daemon config file name.
#[allow(dead_code)] // Used when daemon config loading is integrated
const DAEMON_FILE_NAME: &str = "daemon.toml";

/// Daemon configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DaemonConfig {
    /// Unix socket path for hook communication.
    #[serde(default = "default_socket_path")]
    pub socket_path: PathBuf,

    /// Health check interval in seconds.
    #[serde(default = "default_health_interval")]
    pub health_check_interval_secs: u64,

    /// Worker timeout before marking as unreachable.
    #[serde(default = "default_worker_timeout")]
    pub worker_timeout_secs: u64,

    /// Maximum concurrent jobs per worker slot.
    #[serde(default = "default_max_jobs_per_slot")]
    pub max_jobs_per_slot: u32,

    /// Enable SSH connection pooling.
    #[serde(default = "default_true")]
    pub connection_pooling: bool,

    /// Log level (trace, debug, info, warn, error).
    #[serde(default = "default_log_level")]
    pub log_level: String,

    /// Worker cache cleanup settings.
    #[serde(default)]
    pub cache_cleanup: CacheCleanupConfig,

    /// Stale per-job `.rch-target-*` directory reaper settings.
    #[serde(default)]
    pub stale_target_reap: StaleTargetReapConfig,

    /// Build queue settings.
    #[serde(default)]
    pub queue: QueueConfig,
}

/// Configuration for build queueing when all workers are busy.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueueConfig {
    /// Queue builds when all workers are busy instead of failing open to local.
    /// When false (default), builds fall back to local execution immediately.
    /// When true, builds wait in queue for an available worker.
    #[serde(default)]
    pub enabled: bool,

    /// Maximum number of builds that can be queued (0 = unlimited).
    /// When the queue is full, new builds fall back to local execution.
    #[serde(default = "default_max_queue_depth")]
    pub max_depth: usize,

    /// Maximum time a build can wait in queue (seconds) before timing out.
    /// Timed-out builds fall back to local execution.
    #[serde(default = "default_queue_timeout")]
    pub timeout_secs: u64,
}

fn default_max_queue_depth() -> usize {
    100
}

fn default_queue_timeout() -> u64 {
    300 // 5 minutes
}

impl Default for QueueConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            max_depth: default_max_queue_depth(),
            timeout_secs: default_queue_timeout(),
        }
    }
}

impl Default for DaemonConfig {
    fn default() -> Self {
        Self {
            socket_path: default_socket_path(),
            health_check_interval_secs: 30,
            worker_timeout_secs: 10,
            max_jobs_per_slot: 1,
            connection_pooling: true,
            log_level: "info".to_string(),
            cache_cleanup: CacheCleanupConfig::default(),
            stale_target_reap: StaleTargetReapConfig::default(),
            queue: QueueConfig::default(),
        }
    }
}

/// Configuration for the daemon-side worker sweep that reaps *stale* per-job
/// `.rch-target-*-job-*` / `.rch-target-*-pid-*` directories across **all**
/// project dirs under each worker's `remote_base`.
///
/// This complements the orchestrator-hook reaper (which only reaps the single
/// repo being built): orphaned per-job target dirs in repos nobody is currently
/// rch-building accumulate forever otherwise. Ships **default-OFF** in this
/// release: it is an autonomous periodic deleter pointed at `/data/projects`, the
/// exact class of mechanism behind a prior fleet-wide carnage incident, so it is
/// opt-in until canary-soaked (then the default may flip to ON). Enable with
/// `enabled = true` or env `RCH_WORKER_REAP_ENABLE=1`; conservative thresholds
/// apply once on (120-minute sweep interval, 12h idle floor).
///
/// `remote_base` is the **remote repo sync-root** — the directory rch rsyncs each
/// repo into on the worker (`<sync-root>/<repo>`), with per-job target dirs
/// landing directly inside as `<sync-root>/<repo>/.rch-target-*-job-*`. This is
/// the canonical remote root from `[path_topology]` (the value
/// `rch::hook::map_sync_root_to_remote_root` uses via `policy.canonical_root()`
/// when translating a local repo path to its on-worker destination), NOT the
/// `cache_cleanup`/`transfer` `/tmp/rch` base. It therefore defaults to
/// [`rch_common::DEFAULT_CANONICAL_PROJECT_ROOT`] (`/data/projects`) so the sweep
/// scans exactly where rch actually places per-job dirs and cannot drift.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StaleTargetReapConfig {
    /// Enable the periodic worker-side stale-target sweep.
    #[serde(default = "default_worker_reap_enabled")]
    pub enabled: bool,

    /// Sweep interval in minutes.
    #[serde(default = "default_worker_reap_interval_mins")]
    pub interval_mins: u64,

    /// Idle threshold in hours: a per-job dir is reaped only if neither it nor any
    /// descendant has been modified within this window. Floored at 1h.
    #[serde(default = "default_worker_reap_idle_hours")]
    pub idle_hours: u32,

    /// Remote repo sync-root holding `<repo>/.rch-target-*-job-*` (the on-worker
    /// destination rch rsyncs each repo into). Defaults to the canonical project
    /// root (`/data/projects`); override only if your `[path_topology]`
    /// `canonical_root` differs on the workers.
    #[serde(default = "default_reaper_remote_base")]
    pub remote_base: String,

    /// LONG idle window for POOLED (`-pool-`) dirs in hours; 0 disables the
    /// pooled pass (bead 6dj11). Pooled dirs are reused warm caches — default
    /// 168h (7 days), floored at 24h when non-zero.
    #[serde(default = "default_worker_reap_pooled_idle_hours")]
    pub pooled_idle_hours: u32,

    /// Per-worker byte budget (GiB) across all reap-class target dirs; 0
    /// disables (the ship default). Over budget after the TTL passes, the
    /// sweep evicts oldest-idle-first among dirs past the short idle window
    /// until back under (bead 6dj11).
    #[serde(default = "default_worker_reap_max_cache_gb")]
    pub max_cache_gb: u32,

    /// Where pooled target stores are PLACED on the worker (issue #64). When
    /// set, the sweep walks this root in addition to [`Self::remote_base`],
    /// since warm pools then live off the repo mirror tree. Unset keeps
    /// today's single-root sweep.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub store_base: Option<String>,
}

fn default_worker_reap_pooled_idle_hours() -> u32 {
    rch_common::remediation_config::DEFAULT_POOLED_REAPER_POOLED_IDLE_HOURS
}

fn default_worker_reap_max_cache_gb() -> u32 {
    rch_common::remediation_config::DEFAULT_POOLED_REAPER_MAX_CACHE_GB
}

fn default_worker_reap_enabled() -> bool {
    // Default-OFF: opt-in until canary-soaked. This is an autonomous periodic
    // deleter targeting /data/projects; do not auto-arm it fleet-wide in one
    // release. Flip to `true` (and bump the release) after a soak.
    false
}

fn default_worker_reap_interval_mins() -> u64 {
    120
}

fn default_worker_reap_idle_hours() -> u32 {
    12
}

/// Default scan base for the worker-side reaper: the remote repo sync-root where
/// rch places per-job target dirs (`<sync-root>/<repo>/.rch-target-*-job-*`).
///
/// This is the canonical project root (`/data/projects`), the SAME value
/// `rch::hook::map_sync_root_to_remote_root` resolves via `policy.canonical_root()`
/// when picking the on-worker rsync destination — so the reaper tracks rch's real
/// sync target and cannot drift. It is deliberately NOT the `/tmp/rch`
/// `cache_cleanup`/`transfer` base (no per-job target dirs live there).
fn default_reaper_remote_base() -> String {
    rch_common::DEFAULT_CANONICAL_PROJECT_ROOT.to_string()
}

impl Default for StaleTargetReapConfig {
    fn default() -> Self {
        Self {
            enabled: default_worker_reap_enabled(),
            interval_mins: default_worker_reap_interval_mins(),
            idle_hours: default_worker_reap_idle_hours(),
            remote_base: default_reaper_remote_base(),
            pooled_idle_hours: default_worker_reap_pooled_idle_hours(),
            max_cache_gb: default_worker_reap_max_cache_gb(),
            store_base: None,
        }
    }
}

impl StaleTargetReapConfig {
    /// Apply environment-variable overrides, mirroring the hook's env knobs so
    /// operators can tune the daemon sweep without editing config files.
    ///
    /// - `RCH_WORKER_REAP_DISABLE=1` (or `true`) force-disables the sweep.
    /// - `RCH_WORKER_REAP_INTERVAL_MINS` overrides the sweep interval (min 1).
    /// - `RCH_STALE_TARGET_REAP_HOURS` overrides the idle threshold (shared with
    ///   the orchestrator reaper), floored at 1h.
    pub fn with_env_overrides(mut self) -> Self {
        // Opt-in enable (the feature ships default-OFF). Applied before DISABLE so
        // that an explicit DISABLE always wins as the safety override.
        if let Ok(v) = std::env::var("RCH_WORKER_REAP_ENABLE") {
            let v = v.trim().to_ascii_lowercase();
            if v == "1" || v == "true" || v == "yes" {
                self.enabled = true;
            }
        }
        if let Ok(v) = std::env::var("RCH_WORKER_REAP_DISABLE") {
            let v = v.trim().to_ascii_lowercase();
            if v == "1" || v == "true" || v == "yes" {
                self.enabled = false;
            }
        }
        if let Ok(v) = std::env::var("RCH_WORKER_REAP_INTERVAL_MINS")
            && let Ok(mins) = v.trim().parse::<u64>()
        {
            self.interval_mins = mins.max(1);
        }
        if let Ok(v) = std::env::var("RCH_STALE_TARGET_REAP_HOURS")
            && let Ok(hours) = v.trim().parse::<u32>()
        {
            self.idle_hours = hours.max(rch_common::stale_target_reap::MIN_IDLE_HOURS);
        }
        self
    }

    /// Build the reaper config from the central remediation config
    /// (`remediation.pooled_target`) instead of this module's hardcoded defaults
    /// (bd-28xs5). Env overrides ([`Self::with_env_overrides`]) still apply on
    /// top of the result. The [`Default`] impl mirrors the central defaults; the
    /// `drift_guard_stale_target_reap` test fails if the two ever diverge.
    #[must_use]
    pub fn from_remediation(rem: &rch_common::remediation_config::RemediationConfig) -> Self {
        Self {
            enabled: rem.pooled_target.reaper_enabled,
            interval_mins: rem.pooled_target.reaper_interval_mins,
            idle_hours: rem.pooled_target.reaper_idle_hours,
            remote_base: rem.pooled_target.remote_base.clone(),
            pooled_idle_hours: rem.pooled_target.reaper_pooled_idle_hours,
            max_cache_gb: rem.pooled_target.reaper_max_cache_gb,
            store_base: rem.pooled_target.store_base.clone(),
        }
    }
}

/// Configuration for automatic cache cleanup on workers.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheCleanupConfig {
    /// Enable automatic cache cleanup.
    #[serde(default = "default_cleanup_enabled")]
    pub enabled: bool,

    /// Cleanup check interval in seconds.
    #[serde(default = "default_cleanup_interval")]
    pub interval_secs: u64,

    /// Maximum cache age in hours before pruning.
    #[serde(default = "default_max_cache_age")]
    pub max_cache_age_hours: u64,

    /// Minimum free disk space in GB to maintain.
    /// Cleanup is triggered more aggressively when below this threshold.
    #[serde(default = "default_min_free_gb")]
    pub min_free_gb: u64,

    /// Minimum idle time (seconds) for worker before cleanup is allowed.
    /// Prevents cleanup from interfering with active builds.
    #[serde(default = "default_idle_threshold")]
    pub idle_threshold_secs: u64,

    /// Remote base directory for cache (must match transfer.remote_base).
    #[serde(default = "default_remote_base")]
    pub remote_base: String,
}

fn default_cleanup_enabled() -> bool {
    true
}

fn default_cleanup_interval() -> u64 {
    3600 // 1 hour
}

fn default_max_cache_age() -> u64 {
    72 // 3 days
}

fn default_min_free_gb() -> u64 {
    10 // 10 GB minimum free space
}

fn default_idle_threshold() -> u64 {
    60 // 1 minute idle before cleanup
}

fn default_remote_base() -> String {
    // Must agree with rch_common::default_remote_base and reclaim.rs — the
    // managed `/data/tmp` ephemeral-build zone, not RAM-backed /tmp. See
    // rch_common::default_remote_base for the rationale.
    "/data/tmp/rch".to_string()
}

impl Default for CacheCleanupConfig {
    fn default() -> Self {
        Self {
            enabled: default_cleanup_enabled(),
            interval_secs: default_cleanup_interval(),
            max_cache_age_hours: default_max_cache_age(),
            min_free_gb: default_min_free_gb(),
            idle_threshold_secs: default_idle_threshold(),
            remote_base: default_remote_base(),
        }
    }
}

/// Workers configuration file structure.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct WorkersConfig {
    /// List of worker definitions.
    #[serde(default)]
    pub workers: Vec<WorkerEntry>,
}

/// Single worker entry in configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerEntry {
    /// Unique identifier for this worker.
    pub id: String,

    /// SSH hostname or IP address.
    pub host: String,

    /// SSH username.
    #[serde(default = "default_user")]
    pub user: String,

    /// Path to SSH private key.
    #[serde(default = "default_identity_file")]
    pub identity_file: String,

    /// Total CPU slots available on this worker.
    #[serde(default = "default_slots")]
    pub total_slots: u32,

    /// Priority for worker selection (higher = preferred).
    #[serde(default = "default_priority")]
    pub priority: u32,

    /// Optional tags for filtering.
    #[serde(default)]
    pub tags: Vec<String>,

    /// Operator-declared named tool probes:
    /// `tools = [{ name = "clang", command = ["clang", "--version"] }]`.
    ///
    /// Each is run on the worker as the configured user and verified by exit
    /// status, so `--require-tool` gates on evidence rather than on a tag
    /// somebody remembered to write.
    #[serde(default)]
    pub tools: Vec<rch_common::types::WorkerToolProbe>,

    /// Host OS this worker builds on (`linux`, `darwin`, `windows`).
    ///
    /// Unlike [`Self::tags`], which are descriptive, this **gates** admission:
    /// declaring it makes the worker exclusive to commands that require that OS
    /// (a `--target *-pc-windows-msvc` build, say). Omit it for an ordinary
    /// worker that should remain a candidate for any job.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub os: Option<String>,

    /// Whether this worker is enabled.
    #[serde(default = "default_true")]
    pub enabled: bool,
}

impl From<WorkerEntry> for WorkerConfig {
    fn from(entry: WorkerEntry) -> Self {
        // `os = "windows"` is normalized into the reserved `os:windows` tag so
        // the declaration rides the tag vector every downstream path already
        // carries, instead of a parallel field.
        let mut tags = entry.tags;
        if let Some(os) = entry
            .os
            .as_deref()
            .map(str::trim)
            .filter(|os| !os.is_empty())
        {
            let tag = rch_common::os_tag(os);
            if !tags.contains(&tag) {
                tags.push(tag);
            }
        }
        WorkerConfig {
            id: rch_common::WorkerId::new(entry.id),
            host: entry.host,
            user: entry.user,
            identity_file: entry.identity_file,
            total_slots: entry.total_slots,
            priority: entry.priority,
            tags,
            tools: entry.tools,
        }
    }
}

// Default value functions
pub(crate) fn default_socket_path() -> PathBuf {
    PathBuf::from(rch_common::default_socket_path())
}

fn default_health_interval() -> u64 {
    30
}

fn default_worker_timeout() -> u64 {
    10
}

fn default_max_jobs_per_slot() -> u32 {
    1
}

fn default_true() -> bool {
    true
}

fn default_log_level() -> String {
    "info".to_string()
}

fn default_user() -> String {
    "ubuntu".to_string()
}

fn default_identity_file() -> String {
    "~/.ssh/id_rsa".to_string()
}

fn default_slots() -> u32 {
    8
}

fn default_priority() -> u32 {
    100
}

/// Get the configuration directory path.
///
/// Resolution order (bd-9fgeu, kept identical to `rch::config::config_dir`):
/// 1. `RCH_CONFIG_DIR` env override.
/// 2. The docs-canonical XDG location (`$XDG_CONFIG_HOME/rch`, else
///    `~/.config/rch`) when it EXISTS — on macOS `ProjectDirs` diverges to
///    `~/Library/Application Support/com.rch.rch`, silently orphaning the
///    documented config location the Linux fleet uses.
/// 3. An EXISTING platform-native `ProjectDirs` dir (legacy installs).
/// 4. Fresh install: the XDG location, matching the docs.
pub fn config_dir() -> Option<PathBuf> {
    if let Some(path) = config_dir_from_env_value(std::env::var_os(RCH_CONFIG_DIR_ENV).as_deref()) {
        return Some(path);
    }

    let xdg_style = std::env::var_os("XDG_CONFIG_HOME")
        .filter(|v| !v.is_empty())
        .map(PathBuf::from)
        .or_else(|| {
            std::env::var_os("HOME")
                .filter(|v| !v.is_empty())
                .map(|home| PathBuf::from(home).join(".config"))
        })
        .map(|base| base.join(CONFIG_DIR_NAME));
    let native = directories::ProjectDirs::from("com", "rch", CONFIG_DIR_NAME)
        .map(|dirs| dirs.config_dir().to_path_buf());
    let xdg_exists = xdg_style.as_deref().is_some_and(Path::is_dir);
    let native_exists = native.as_deref().is_some_and(Path::is_dir);
    resolve_config_dir_preference(xdg_style, xdg_exists, native, native_exists)
}

/// Pure preference rule behind [`config_dir`]: existing XDG dir > existing
/// platform-native dir > XDG (fresh installs follow the docs) > native.
fn resolve_config_dir_preference(
    xdg_style: Option<PathBuf>,
    xdg_exists: bool,
    native: Option<PathBuf>,
    native_exists: bool,
) -> Option<PathBuf> {
    if xdg_exists && let Some(dir) = xdg_style {
        return Some(dir);
    }
    if native_exists && let Some(dir) = native {
        return Some(dir);
    }
    xdg_style.or(native)
}

fn config_dir_from_env_value(value: Option<&OsStr>) -> Option<PathBuf> {
    let raw = value?;
    if raw.is_empty() {
        return None;
    }

    let expanded = shellexpand::tilde(&raw.to_string_lossy()).into_owned();
    Some(PathBuf::from(expanded))
}

/// Load daemon configuration from file.
#[allow(dead_code)] // Will be used when daemon config CLI is added
pub fn load_daemon_config(path: Option<&Path>) -> Result<DaemonConfig> {
    let config_path = match path {
        Some(p) => p.to_path_buf(),
        None => {
            let dir = config_dir().context("Could not determine config directory")?;
            dir.join(DAEMON_FILE_NAME)
        }
    };

    if !config_path.exists() {
        debug!(
            "Daemon config not found at {:?}, using defaults",
            config_path
        );
        return Ok(DaemonConfig::default());
    }

    info!("Loading daemon config from {:?}", config_path);
    let contents = std::fs::read_to_string(&config_path)
        .with_context(|| format!("Failed to read daemon config from {:?}", config_path))?;

    let mut config: DaemonConfig = toml::from_str(&contents)
        .with_context(|| format!("Failed to parse daemon config from {:?}", config_path))?;

    // Validate remote_base for cache cleanup safety
    if config.cache_cleanup.enabled {
        let validated = validate_remote_base(&config.cache_cleanup.remote_base)
            .map_err(|e| anyhow::anyhow!("Invalid remote_base in {:?}: {}", config_path, e))?;
        config.cache_cleanup.remote_base = validated;
    }

    Ok(config)
}

/// Load workers configuration from file.
pub fn load_workers_config(path: Option<&Path>) -> Result<WorkersConfig> {
    let config_path = match path {
        Some(p) => p.to_path_buf(),
        None => {
            let dir = config_dir().context("Could not determine config directory")?;
            dir.join(WORKERS_FILE_NAME)
        }
    };

    if !config_path.exists() {
        warn!("Workers config not found at {:?}", config_path);
        return Ok(WorkersConfig::default());
    }

    info!("Loading workers config from {:?}", config_path);
    let contents = std::fs::read_to_string(&config_path)
        .with_context(|| format!("Failed to read workers config from {:?}", config_path))?;

    let config: WorkersConfig = toml::from_str(&contents)
        .with_context(|| format!("Failed to parse workers config from {:?}", config_path))?;

    // Tool probe declarations are validated HERE, at load, not at probe time: a
    // name that cannot survive the `RCH_FACT tool=<name>` wire format would come
    // back parsed as a different name, so the worker would advertise a
    // capability nobody asked for while silently lacking the one that was
    // declared. A loud config error beats a quiet capability lie.
    for worker in &config.workers {
        for tool in &worker.tools {
            rch_common::capability_probe::NamedToolProbe::try_from(tool).with_context(|| {
                format!(
                    "worker {:?} in {:?} declares an unusable tool probe",
                    worker.id, config_path
                )
            })?;
        }
    }

    info!("Loaded {} worker definitions", config.workers.len());
    Ok(config)
}

/// Load enabled workers as WorkerConfig instances.
pub fn load_workers(path: Option<&Path>) -> Result<Vec<WorkerConfig>> {
    let config = load_workers_config(path)?;

    let workers: Vec<WorkerConfig> = config
        .workers
        .into_iter()
        .filter(|w| w.enabled)
        .map(WorkerConfig::from)
        .collect();

    debug!("Loaded {} enabled workers", workers.len());
    Ok(workers)
}

/// Load self-test configuration from the main config.toml.
pub fn load_self_test_config() -> Result<SelfTestConfig> {
    let config = load_rch_config()?;
    Ok(config.self_test)
}

/// Load full RCH configuration from config.toml.
pub fn load_rch_config() -> Result<RchConfig> {
    let Some(dir) = config_dir() else {
        return Ok(RchConfig::default());
    };
    let path = dir.join("config.toml");
    if !path.exists() {
        return Ok(RchConfig::default());
    }

    let contents = std::fs::read_to_string(&path)
        .with_context(|| format!("Failed to read config {:?}", path))?;
    let config: RchConfig =
        toml::from_str(&contents).with_context(|| format!("Failed to parse {:?}", path))?;
    Ok(config)
}

/// Generate an example workers.toml configuration.
#[allow(dead_code)] // Will be used by config init command
pub fn example_workers_config() -> String {
    r#"# RCH Workers Configuration
# Place this file at ~/.config/rch/workers.toml

# Example worker definitions
[[workers]]
id = "server1"
host = "192.168.1.100"
user = "ubuntu"
identity_file = "~/.ssh/id_rsa"
total_slots = 16
priority = 100
tags = ["rust", "fast"]
enabled = true

[[workers]]
id = "server2"
host = "192.168.1.101"
user = "ubuntu"
identity_file = "~/.ssh/id_rsa"
total_slots = 8
priority = 80
tags = ["rust"]
enabled = true

# Disabled worker example
[[workers]]
id = "maintenance"
host = "192.168.1.102"
user = "admin"
identity_file = "~/.ssh/maintenance_key"
total_slots = 4
priority = 50
tags = ["backup"]
enabled = false
"#
    .to_string()
}

/// Generate an example daemon.toml configuration.
#[allow(dead_code)] // Will be used by config init command
pub fn example_daemon_config() -> String {
    r#"# RCH Daemon Configuration
# Place this file at ~/.config/rch/daemon.toml

# Unix socket path for hook communication
socket_path = "~/.cache/rch/rch.sock"

# Health check interval in seconds
health_check_interval_secs = 30

# Worker timeout before marking as unreachable (seconds)
worker_timeout_secs = 10

# Maximum concurrent jobs per worker slot
max_jobs_per_slot = 1

# Enable SSH connection pooling
connection_pooling = true

# Log level: trace, debug, info, warn, error
log_level = "info"
"#
    .to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use rch_common::test_guard;
    use tempfile::TempDir;

    fn init_test_logging() {
        let _ = tracing_subscriber::fmt()
            .with_test_writer()
            .with_max_level(tracing::Level::DEBUG)
            .try_init();
    }

    #[test]
    fn test_default_daemon_config() {
        let _guard = test_guard!();
        let config = DaemonConfig::default();
        let expected_socket = PathBuf::from(rch_common::default_socket_path());
        assert_eq!(config.socket_path, expected_socket);
        assert_eq!(config.health_check_interval_secs, 30);
        assert!(config.connection_pooling);
    }

    /// Drift guard (bd-28xs5): the reaper config built from the central
    /// `RemediationConfig` defaults must reproduce this module's own
    /// `StaleTargetReapConfig::default()`. Fails if the central `pooled_target`
    /// defaults diverge from the rchd reaper defaults.
    #[test]
    fn drift_guard_stale_target_reap() {
        let _guard = test_guard!();
        let from_cfg = StaleTargetReapConfig::from_remediation(
            &rch_common::remediation_config::RemediationConfig::default(),
        );
        let runtime = StaleTargetReapConfig::default();
        assert_eq!(from_cfg.enabled, runtime.enabled);
        assert_eq!(from_cfg.interval_mins, runtime.interval_mins);
        assert_eq!(from_cfg.idle_hours, runtime.idle_hours);
        assert_eq!(from_cfg.remote_base, runtime.remote_base);
        assert_eq!(from_cfg.store_base, runtime.store_base);
    }

    #[test]
    fn test_config_dir_env_value_override() {
        let _guard = test_guard!();
        let path = config_dir_from_env_value(Some(OsStr::new("~/rch-daemon-config")));
        assert_eq!(
            path,
            Some(PathBuf::from(format!(
                "{}/rch-daemon-config",
                std::env::var("HOME").expect("HOME should be set for tests")
            )))
        );

        assert_eq!(config_dir_from_env_value(Some(OsStr::new(""))), None);
        assert_eq!(config_dir_from_env_value(None), None);
    }

    #[test]
    fn test_parse_workers_config() {
        let _guard = test_guard!();
        let toml = r#"
[[workers]]
id = "test"
host = "localhost"
user = "testuser"
identity_file = "~/.ssh/id_rsa"
total_slots = 4
priority = 100
tags = ["test"]
enabled = true
"#;
        let config: WorkersConfig = toml::from_str(toml).unwrap();
        assert_eq!(config.workers.len(), 1);
        assert_eq!(config.workers[0].id, "test");
        assert_eq!(config.workers[0].total_slots, 4);
    }

    #[test]
    fn test_worker_entry_to_config() {
        let _guard = test_guard!();
        let entry = WorkerEntry {
            id: "worker1".to_string(),
            host: "192.168.1.100".to_string(),
            user: "ubuntu".to_string(),
            identity_file: "~/.ssh/id_rsa".to_string(),
            total_slots: 8,
            priority: 100,
            tags: vec!["rust".to_string()],
            tools: Vec::new(),
            os: None,
            enabled: true,
        };

        let config: WorkerConfig = entry.into();
        assert_eq!(config.id.as_str(), "worker1");
        assert_eq!(config.host, "192.168.1.100");
        assert_eq!(config.total_slots, 8);
    }

    #[test]
    fn test_example_configs_valid() {
        let _guard = test_guard!();
        let workers_toml = example_workers_config();
        let _: WorkersConfig =
            toml::from_str(&workers_toml).expect("Example workers config should parse");

        let daemon_toml = example_daemon_config();
        let _: DaemonConfig =
            toml::from_str(&daemon_toml).expect("Example daemon config should parse");
    }

    // =========================================================================
    // test_daemon_config_loading - Config file parsing, defaults, validation
    // =========================================================================

    #[test]
    fn test_daemon_config_loading_from_file() {
        let _guard = test_guard!();
        init_test_logging();

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("daemon.toml");

        let config_content = r#"
socket_path = "/custom/path/rch.sock"
health_check_interval_secs = 60
worker_timeout_secs = 30
max_jobs_per_slot = 2
connection_pooling = false
log_level = "debug"
"#;
        std::fs::write(&config_path, config_content).unwrap();

        let config = load_daemon_config(Some(&config_path)).unwrap();

        assert_eq!(config.socket_path, PathBuf::from("/custom/path/rch.sock"));
        assert_eq!(config.health_check_interval_secs, 60);
        assert_eq!(config.worker_timeout_secs, 30);
        assert_eq!(config.max_jobs_per_slot, 2);
        assert!(!config.connection_pooling);
        assert_eq!(config.log_level, "debug");
    }

    #[test]
    fn test_daemon_config_parses_cache_cleanup_section() {
        let _guard = test_guard!();
        init_test_logging();

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("daemon.toml");

        let config_content = r#"
[cache_cleanup]
enabled = false
interval_secs = 7200
max_cache_age_hours = 48
min_free_gb = 20
idle_threshold_secs = 300
remote_base = "/var/rch-builds"
"#;
        std::fs::write(&config_path, config_content).unwrap();

        let config = load_daemon_config(Some(&config_path)).unwrap();
        assert!(!config.cache_cleanup.enabled);
        assert_eq!(config.cache_cleanup.interval_secs, 7200);
        assert_eq!(config.cache_cleanup.max_cache_age_hours, 48);
        assert_eq!(config.cache_cleanup.min_free_gb, 20);
        assert_eq!(config.cache_cleanup.idle_threshold_secs, 300);
        assert_eq!(config.cache_cleanup.remote_base, "/var/rch-builds");
    }

    #[test]
    fn test_daemon_config_loading_missing_file_uses_defaults() {
        let _guard = test_guard!();
        init_test_logging();

        let temp_dir = TempDir::new().unwrap();
        let nonexistent_path = temp_dir.path().join("nonexistent.toml");

        let config = load_daemon_config(Some(&nonexistent_path)).unwrap();

        // Should use default values
        let expected_socket = PathBuf::from(rch_common::default_socket_path());
        assert_eq!(config.socket_path, expected_socket);
        assert_eq!(config.health_check_interval_secs, 30);
        assert_eq!(config.worker_timeout_secs, 10);
        assert_eq!(config.max_jobs_per_slot, 1);
        assert!(config.connection_pooling);
        assert_eq!(config.log_level, "info");
    }

    #[test]
    fn test_daemon_config_loading_partial_file() {
        let _guard = test_guard!();
        init_test_logging();

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("daemon.toml");

        // Only specify some fields - others should use defaults
        let config_content = r#"
socket_path = "/custom/rch.sock"
log_level = "warn"
"#;
        std::fs::write(&config_path, config_content).unwrap();

        let config = load_daemon_config(Some(&config_path)).unwrap();

        // Specified values
        assert_eq!(config.socket_path, PathBuf::from("/custom/rch.sock"));
        assert_eq!(config.log_level, "warn");

        // Default values for unspecified fields
        assert_eq!(config.health_check_interval_secs, 30);
        assert_eq!(config.worker_timeout_secs, 10);
        assert_eq!(config.max_jobs_per_slot, 1);
        assert!(config.connection_pooling);
    }

    #[test]
    fn test_daemon_config_loading_invalid_toml() {
        let _guard = test_guard!();
        init_test_logging();

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("daemon.toml");

        let config_content = "this is not valid toml {{{";
        std::fs::write(&config_path, config_content).unwrap();

        let result = load_daemon_config(Some(&config_path));
        assert!(result.is_err());
    }

    // =========================================================================
    // test_daemon_worker_loading - Workers.toml parsing, validation
    // =========================================================================

    #[test]
    fn test_worker_loading_from_file() {
        let _guard = test_guard!();
        init_test_logging();

        let temp_dir = TempDir::new().unwrap();
        let workers_path = temp_dir.path().join("workers.toml");

        let config_content = r#"
[[workers]]
id = "server1"
host = "192.168.1.100"
user = "ubuntu"
identity_file = "~/.ssh/id_rsa"
total_slots = 16
priority = 100
tags = ["rust", "fast"]
enabled = true

[[workers]]
id = "server2"
host = "192.168.1.101"
user = "admin"
identity_file = "~/.ssh/admin_key"
total_slots = 8
priority = 80
tags = ["backup"]
enabled = true
"#;
        std::fs::write(&workers_path, config_content).unwrap();

        let workers = load_workers(Some(&workers_path)).unwrap();

        assert_eq!(workers.len(), 2);
        assert_eq!(workers[0].id.as_str(), "server1");
        assert_eq!(workers[0].host, "192.168.1.100");
        assert_eq!(workers[0].total_slots, 16);
        assert_eq!(workers[1].id.as_str(), "server2");
        assert_eq!(workers[1].host, "192.168.1.101");
    }

    #[test]
    fn test_worker_loading_disabled_workers_filtered() {
        let _guard = test_guard!();
        init_test_logging();

        let temp_dir = TempDir::new().unwrap();
        let workers_path = temp_dir.path().join("workers.toml");

        let config_content = r#"
[[workers]]
id = "enabled-worker"
host = "192.168.1.100"
enabled = true

[[workers]]
id = "disabled-worker"
host = "192.168.1.101"
enabled = false
"#;
        std::fs::write(&workers_path, config_content).unwrap();

        let workers = load_workers(Some(&workers_path)).unwrap();

        assert_eq!(workers.len(), 1);
        assert_eq!(workers[0].id.as_str(), "enabled-worker");
    }

    #[test]
    fn test_worker_loading_missing_file_returns_empty() {
        let _guard = test_guard!();
        init_test_logging();

        let temp_dir = TempDir::new().unwrap();
        let nonexistent_path = temp_dir.path().join("nonexistent.toml");

        let workers = load_workers(Some(&nonexistent_path)).unwrap();

        assert!(workers.is_empty());
    }

    #[test]
    fn test_worker_loading_default_values() {
        let _guard = test_guard!();
        init_test_logging();

        let temp_dir = TempDir::new().unwrap();
        let workers_path = temp_dir.path().join("workers.toml");

        // Only specify required fields - others should use defaults
        let config_content = r#"
[[workers]]
id = "minimal"
host = "192.168.1.100"
"#;
        std::fs::write(&workers_path, config_content).unwrap();

        let config = load_workers_config(Some(&workers_path)).unwrap();

        assert_eq!(config.workers.len(), 1);
        let worker = &config.workers[0];

        assert_eq!(worker.id, "minimal");
        assert_eq!(worker.host, "192.168.1.100");
        // Default values
        assert_eq!(worker.user, "ubuntu"); // default_user()
        assert_eq!(worker.identity_file, "~/.ssh/id_rsa"); // default_identity_file()
        assert_eq!(worker.total_slots, 8); // default_slots()
        assert_eq!(worker.priority, 100); // default_priority()
        assert!(worker.tags.is_empty());
        assert!(worker.enabled); // default_true()
    }

    #[test]
    fn test_worker_loading_missing_required_id_fails() {
        let _guard = test_guard!();
        init_test_logging();

        let temp_dir = TempDir::new().unwrap();
        let workers_path = temp_dir.path().join("workers.toml");

        // Missing required 'id' field
        let config_content = r#"
[[workers]]
host = "192.168.1.100"
user = "ubuntu"
"#;
        std::fs::write(&workers_path, config_content).unwrap();

        let result = load_workers_config(Some(&workers_path));
        assert!(result.is_err());
    }

    #[test]
    fn test_worker_loading_missing_required_host_fails() {
        let _guard = test_guard!();
        init_test_logging();

        let temp_dir = TempDir::new().unwrap();
        let workers_path = temp_dir.path().join("workers.toml");

        // Missing required 'host' field
        let config_content = r#"
[[workers]]
id = "worker1"
user = "ubuntu"
"#;
        std::fs::write(&workers_path, config_content).unwrap();

        let result = load_workers_config(Some(&workers_path));
        assert!(result.is_err());
    }

    #[test]
    fn test_worker_loading_invalid_toml_fails() {
        let _guard = test_guard!();
        init_test_logging();

        let temp_dir = TempDir::new().unwrap();
        let workers_path = temp_dir.path().join("workers.toml");

        let config_content = "this is not valid toml {{{";
        std::fs::write(&workers_path, config_content).unwrap();

        let result = load_workers_config(Some(&workers_path));
        assert!(result.is_err());
    }

    #[test]
    fn test_worker_loading_empty_workers_array() {
        let _guard = test_guard!();
        init_test_logging();

        let temp_dir = TempDir::new().unwrap();
        let workers_path = temp_dir.path().join("workers.toml");

        let config_content = "# Empty workers config\n";
        std::fs::write(&workers_path, config_content).unwrap();

        let workers = load_workers(Some(&workers_path)).unwrap();
        assert!(workers.is_empty());
    }

    #[test]
    fn test_worker_loading_multiple_tags() {
        let _guard = test_guard!();
        init_test_logging();

        let temp_dir = TempDir::new().unwrap();
        let workers_path = temp_dir.path().join("workers.toml");

        let config_content = r#"
[[workers]]
id = "multi-tag"
host = "192.168.1.100"
tags = ["rust", "go", "python", "fast", "production"]
"#;
        std::fs::write(&workers_path, config_content).unwrap();

        let config = load_workers_config(Some(&workers_path)).unwrap();

        assert_eq!(config.workers[0].tags.len(), 5);
        assert!(config.workers[0].tags.contains(&"rust".to_string()));
        assert!(config.workers[0].tags.contains(&"production".to_string()));
    }

    #[test]
    fn test_named_tool_probes_load_and_malformed_names_fail_loudly() {
        let _guard = test_guard!();
        init_test_logging();

        let temp_dir = TempDir::new().unwrap();
        let workers_path = temp_dir.path().join("workers.toml");

        std::fs::write(
            &workers_path,
            r#"
[[workers]]
id = "with-tools"
host = "192.168.1.100"
tools = [
  { name = "clang", command = ["clang", "--version"] },
  { name = "ld.lld", command = ["/usr/bin/ld.lld", "--version"] },
]
"#,
        )
        .unwrap();
        let config = load_workers_config(Some(&workers_path)).unwrap();
        assert_eq!(config.workers[0].tools.len(), 2);
        assert_eq!(config.workers[0].tools[0].name, "clang");
        assert_eq!(config.workers[0].tools[1].command[0], "/usr/bin/ld.lld");
        // ...and the declaration rides through to the routing descriptor.
        let workers = load_workers(Some(&workers_path)).unwrap();
        assert_eq!(workers[0].tools.len(), 2);

        // A name that cannot survive the `RCH_FACT tool=<name>` wire format
        // would be parsed back as a DIFFERENT name, so the worker would
        // advertise a capability nobody asked for while silently lacking the
        // declared one. That must fail the load, not degrade quietly.
        for bad in [
            r#"{ name = "cl ang", command = ["true"] }"#,
            r#"{ name = "clang=1", command = ["true"] }"#,
            r#"{ name = "", command = ["true"] }"#,
            r#"{ name = "clang", command = [] }"#,
        ] {
            std::fs::write(
                &workers_path,
                format!("[[workers]]\nid = \"bad\"\nhost = \"h\"\ntools = [{bad}]\n"),
            )
            .unwrap();
            let error = load_workers_config(Some(&workers_path))
                .expect_err(&format!("{bad} must fail the load"));
            let rendered = format!("{error:#}");
            assert!(
                rendered.contains("unusable tool probe"),
                "{bad}: {rendered}"
            );
        }
    }

    #[test]
    fn test_declared_os_becomes_reserved_tag() {
        let _guard = test_guard!();
        init_test_logging();

        let temp_dir = TempDir::new().unwrap();
        let workers_path = temp_dir.path().join("workers.toml");

        std::fs::write(
            &workers_path,
            r#"
[[workers]]
id = "wsurf"
host = "100.68.2.11"
os = "Windows"
tags = ["rust"]
"#,
        )
        .unwrap();

        let workers = load_workers(Some(&workers_path)).unwrap();

        // Normalized to lowercase and carried as the reserved tag, which is what
        // the selection gate reads.
        assert_eq!(
            rch_common::declared_os(&workers[0].tags),
            Some("windows".to_string())
        );
        assert!(workers[0].tags.contains(&"rust".to_string()));
    }

    #[test]
    fn test_worker_without_declared_os_is_unfenced() {
        let _guard = test_guard!();
        init_test_logging();

        let temp_dir = TempDir::new().unwrap();
        let workers_path = temp_dir.path().join("workers.toml");

        // Every worker in the existing fleet looks like this. None may gain an
        // OS constraint, or the whole pool stops accepting ordinary builds.
        std::fs::write(
            &workers_path,
            r#"
[[workers]]
id = "vmi1149989"
host = "212.90.121.76"
tags = ["rust"]
"#,
        )
        .unwrap();

        let workers = load_workers(Some(&workers_path)).unwrap();
        assert_eq!(rch_common::declared_os(&workers[0].tags), None);
    }

    #[test]
    fn test_worker_entry_conversion_preserves_all_fields() {
        let _guard = test_guard!();
        init_test_logging();

        let entry = WorkerEntry {
            id: "test-worker".to_string(),
            host: "10.0.0.1".to_string(),
            user: "admin".to_string(),
            identity_file: "/path/to/key".to_string(),
            total_slots: 32,
            priority: 200,
            tags: vec!["tag1".to_string(), "tag2".to_string()],
            tools: Vec::new(),
            os: None,
            enabled: true,
        };

        let config: WorkerConfig = entry.into();

        assert_eq!(config.id.as_str(), "test-worker");
        assert_eq!(config.host, "10.0.0.1");
        assert_eq!(config.user, "admin");
        assert_eq!(config.identity_file, "/path/to/key");
        assert_eq!(config.total_slots, 32);
        assert_eq!(config.priority, 200);
        assert_eq!(config.tags.len(), 2);
        assert_eq!(config.tags[0], "tag1");
        assert_eq!(config.tags[1], "tag2");
    }

    #[test]
    fn test_worker_loading_zero_slots() {
        let _guard = test_guard!();
        init_test_logging();

        let temp_dir = TempDir::new().unwrap();
        let workers_path = temp_dir.path().join("workers.toml");

        let config_content = r#"
[[workers]]
id = "zero-slots"
host = "192.168.1.100"
total_slots = 0
"#;
        std::fs::write(&workers_path, config_content).unwrap();

        let config = load_workers_config(Some(&workers_path)).unwrap();
        assert_eq!(config.workers[0].total_slots, 0);
    }

    #[test]
    fn test_worker_loading_high_priority() {
        let _guard = test_guard!();
        init_test_logging();

        let temp_dir = TempDir::new().unwrap();
        let workers_path = temp_dir.path().join("workers.toml");

        let config_content = r#"
[[workers]]
id = "high-priority"
host = "192.168.1.100"
priority = 999999
"#;
        std::fs::write(&workers_path, config_content).unwrap();

        let config = load_workers_config(Some(&workers_path)).unwrap();
        assert_eq!(config.workers[0].priority, 999999);
    }

    #[test]
    fn config_dir_preference_matrix_matches_rch_cli() {
        // bd-9fgeu: identical rule to rch::config — existing XDG wins, legacy
        // native kept when it is the only one, fresh installs follow the docs.
        let xdg = Some(PathBuf::from("/home/u/.config/rch"));
        let native = Some(PathBuf::from(
            "/home/u/Library/Application Support/com.rch.rch",
        ));

        assert_eq!(
            resolve_config_dir_preference(xdg.clone(), true, native.clone(), true),
            xdg
        );
        assert_eq!(
            resolve_config_dir_preference(xdg.clone(), false, native.clone(), true),
            native
        );
        assert_eq!(
            resolve_config_dir_preference(xdg.clone(), false, native.clone(), false),
            xdg
        );
        assert_eq!(
            resolve_config_dir_preference(None, false, native.clone(), false),
            native
        );
    }
}