Skip to main content

rch_common/
types.rs

1//! Common types used across RCH components.
2
3use crate::{CompilationKind, toolchain::ToolchainInfo};
4use rand::RngExt;
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7use std::path::PathBuf;
8
9/// Unique identifier for a worker in the fleet.
10#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
11pub struct WorkerId(pub String);
12
13impl WorkerId {
14    pub fn new(id: impl Into<String>) -> Self {
15        Self(id.into())
16    }
17
18    pub fn as_str(&self) -> &str {
19        &self.0
20    }
21}
22
23impl std::fmt::Display for WorkerId {
24    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25        write!(f, "{}", self.0)
26    }
27}
28
29/// Status of a worker in the fleet.
30///
31/// State transitions:
32/// ```text
33/// HEALTHY ←→ DEGRADED (automatic based on response times)
34///    ↓           ↓
35///    ↓       UNREACHABLE (automatic on heartbeat failure)
36///    ↓
37/// DRAINING (via `rch workers drain`) - finishing current jobs
38///    ↓
39/// DRAINED (automatic when all jobs complete) - idle, ready to disable
40///    ↓
41/// DISABLED (via `rch workers disable`) - completely offline
42///
43/// Use `rch workers enable` to return from DRAINING/DRAINED/DISABLED → HEALTHY
44/// ```
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
46#[serde(rename_all = "snake_case")]
47pub enum WorkerStatus {
48    /// Worker is healthy and accepting jobs.
49    #[default]
50    Healthy,
51    /// Worker is responding slowly.
52    Degraded,
53    /// Worker failed to respond to heartbeat.
54    Unreachable,
55    /// Worker is not accepting new jobs (finishing current).
56    Draining,
57    /// Worker has finished draining (no active jobs, idle).
58    Drained,
59    /// Worker is manually disabled.
60    Disabled,
61}
62
63/// Circuit breaker state for a worker.
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
65#[serde(rename_all = "snake_case")]
66pub enum CircuitState {
67    /// Normal operation.
68    #[default]
69    Closed,
70    /// Circuit is open (short-circuit).
71    Open,
72    /// Circuit is half-open (probing).
73    HalfOpen,
74}
75
76/// Required runtime for command execution.
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default, JsonSchema)]
78#[serde(rename_all = "lowercase")]
79pub enum RequiredRuntime {
80    /// No specific runtime required (default).
81    #[default]
82    None,
83    /// Requires Rust toolchain.
84    Rust,
85    /// Requires Bun runtime.
86    Bun,
87    /// Requires Node.js runtime.
88    Node,
89    /// Requires the Nix package manager (nix binary + populated `/nix/store`).
90    Nix,
91    /// Requires the Go toolchain (`go` binary).
92    Go,
93    /// Requires the zig cross-compilation toolchain (`cargo-zigbuild` + `zig`).
94    Zig,
95}
96
97/// Per-command priority hint for worker selection.
98///
99/// This is an *input hint* from the caller (typically the hook) and should not
100/// change default behavior when omitted.
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default, JsonSchema)]
102#[serde(rename_all = "lowercase")]
103pub enum CommandPriority {
104    Low,
105    #[default]
106    Normal,
107    High,
108}
109
110impl std::fmt::Display for CommandPriority {
111    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112        let value = match self {
113            Self::Low => "low",
114            Self::Normal => "normal",
115            Self::High => "high",
116        };
117        write!(f, "{}", value)
118    }
119}
120
121impl std::str::FromStr for CommandPriority {
122    type Err = ();
123
124    fn from_str(s: &str) -> Result<Self, Self::Err> {
125        match s.trim().to_lowercase().as_str() {
126            "low" => Ok(Self::Low),
127            "normal" => Ok(Self::Normal),
128            "high" => Ok(Self::High),
129            _ => Err(()),
130        }
131    }
132}
133
134/// Worker selection request sent from hook to daemon.
135#[derive(Debug, Clone, Serialize, Deserialize)]
136pub struct SelectionRequest {
137    /// Project identifier (usually directory name or hash).
138    pub project: String,
139    /// Full command being executed (optional, for active build tracking).
140    #[serde(default, skip_serializing_if = "Option::is_none")]
141    pub command: Option<String>,
142    /// Priority hint for this request.
143    #[serde(default)]
144    pub command_priority: CommandPriority,
145    /// Estimated CPU cores needed for this compilation.
146    pub estimated_cores: u32,
147    /// Additional free GiB required on the worker's reported build filesystem.
148    /// A positive value is a hard admission budget, retained by the daemon for
149    /// this build's lifetime; zero leaves disk admission to the ordinary policy.
150    #[serde(default, skip_serializing_if = "disk_headroom_disabled")]
151    pub disk_headroom_gib: u32,
152    /// Preferred worker IDs (e.g., from project config).
153    #[serde(default)]
154    pub preferred_workers: Vec<WorkerId>,
155    /// Rust toolchain information for the project.
156    #[serde(default)]
157    pub toolchain: Option<ToolchainInfo>,
158    /// Required runtime for command execution.
159    #[serde(default)]
160    pub required_runtime: RequiredRuntime,
161    /// Classification decision latency in microseconds (for AGENTS.md compliance).
162    /// This tracks how long the 5-tier classification took on the hook side.
163    #[serde(default, skip_serializing_if = "Option::is_none")]
164    pub classification_duration_us: Option<u64>,
165    /// Job-mode admission (bd-g7rpy): set by `rch exec --job` only. When the
166    /// one-active-job-per-project-per-worker guard excludes every otherwise-
167    /// eligible worker, a job request may QUEUE on that exclusion instead of
168    /// failing over to local execution. Compilation requests never set it,
169    /// preserving their immediate NoAdmissibleWorkers behavior.
170    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
171    pub job_mode: bool,
172    /// Operator-declared named tools this work requires VERIFIED on the worker
173    /// (`rch exec --job --require-tool NAME`, or a project's
174    /// `jobs.required_tools`).
175    ///
176    /// Job mode only — the compilation classifier never sets it, so ordinary
177    /// offloaded builds keep their existing admission behavior exactly. Empty
178    /// means no gate; a name no worker has verified excludes every worker,
179    /// because the caller asked for the gate precisely because the job cannot
180    /// run without the tool.
181    #[serde(default, skip_serializing_if = "Vec::is_empty")]
182    pub required_tools: Vec<String>,
183    /// Process ID of the hook (for active build tracking).
184    #[serde(default, skip_serializing_if = "Option::is_none")]
185    pub hook_pid: Option<u32>,
186}
187
188fn disk_headroom_disabled(gib: &u32) -> bool {
189    *gib == 0
190}
191
192/// Reason for worker selection result.
193///
194/// Provides context when no worker is available, enabling informative
195/// fallback messages in the hook.
196#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
197#[serde(rename_all = "snake_case")]
198pub enum SelectionReason {
199    /// Worker assigned successfully.
200    Success,
201    /// No workers configured in workers.toml.
202    NoWorkersConfigured,
203    /// All workers are unreachable (failed health checks).
204    AllWorkersUnreachable,
205    /// All workers have circuits open (after repeated failures).
206    AllCircuitsOpen,
207    /// All workers are at capacity (no available slots).
208    AllWorkersBusy,
209    /// Workers were present but none passed selection health thresholds.
210    NoWorkersPassedHealth,
211    /// All candidate workers failed hard preflight checks.
212    AllWorkersFailedPreflight,
213    /// All candidate workers failed repo convergence checks (repos missing/stale/failed).
214    AllWorkersFailedConvergence,
215    /// Workers exist but admission was blocked by concrete capacity/preflight reasons.
216    NoAdmissibleWorkers(String),
217    /// No workers match required tags or preferences.
218    NoMatchingWorkers,
219    /// No workers have the required runtime (e.g., Bun, Node).
220    NoWorkersWithRuntime(String),
221    /// Internal error during selection.
222    SelectionError(String),
223    /// Worker assigned via affinity pinning (recent successful build).
224    AffinityPinned,
225    /// Worker assigned via last-success fallback (all others unavailable).
226    AffinityFallback,
227}
228
229/// Wire protocol version for daemon `/select-worker` responses.
230///
231/// This is intentionally separate from the broader CLI API envelope version:
232/// selection responses are emitted as a raw [`SelectionResponse`] on the hook
233/// hot path, so the client needs a small explicit compatibility marker.
234pub const SELECTION_RESPONSE_PROTOCOL_VERSION: u64 = 1;
235
236impl std::fmt::Display for SelectionReason {
237    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
238        match self {
239            Self::Success => write!(f, "worker assigned successfully"),
240            Self::NoWorkersConfigured => write!(f, "no workers configured"),
241            Self::AllWorkersUnreachable => write!(f, "all workers unreachable"),
242            Self::AllCircuitsOpen => write!(f, "all worker circuits open"),
243            Self::AllWorkersBusy => write!(f, "all workers at capacity"),
244            Self::NoWorkersPassedHealth => write!(f, "no workers passed health thresholds"),
245            Self::AllWorkersFailedPreflight => write!(f, "all workers failed preflight checks"),
246            Self::AllWorkersFailedConvergence => {
247                write!(f, "all workers failed repo convergence checks")
248            }
249            Self::NoAdmissibleWorkers(summary) => {
250                write!(f, "no admissible workers: {}", summary)
251            }
252            Self::NoMatchingWorkers => write!(f, "no matching workers found"),
253            Self::NoWorkersWithRuntime(rt) => write!(f, "no workers with {} installed", rt),
254            Self::SelectionError(e) => write!(f, "selection error: {}", e),
255            Self::AffinityPinned => write!(f, "worker assigned via affinity pinning"),
256            Self::AffinityFallback => write!(f, "worker assigned via last-success fallback"),
257        }
258    }
259}
260
261// ============================================================================
262// Worker Selection Strategy
263// ============================================================================
264
265/// Worker selection strategy determining how workers are chosen for jobs.
266#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
267#[serde(rename_all = "snake_case")]
268pub enum SelectionStrategy {
269    /// Legacy/manual control: prioritize worker.priority first, then break ties
270    /// using command-aware cache/speed hints.
271    Priority,
272    /// Select worker with highest SpeedScore.
273    /// Best for performance-critical builds with homogeneous workers.
274    Fastest,
275    /// Balance all factors: SpeedScore, load, health, cache affinity.
276    /// Default for general use across diverse worker pools.
277    #[default]
278    Balanced,
279    /// Prefer workers with warm caches for the project.
280    /// Best for incremental builds on large codebases.
281    CacheAffinity,
282    /// Weighted random selection favoring fast workers but ensuring fairness.
283    /// Prevents hot-spotting when many workers are available.
284    FairFastest,
285}
286
287impl std::fmt::Display for SelectionStrategy {
288    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
289        let name = match self {
290            Self::Priority => "priority",
291            Self::Fastest => "fastest",
292            Self::Balanced => "balanced",
293            Self::CacheAffinity => "cache_affinity",
294            Self::FairFastest => "fair_fastest",
295        };
296        write!(f, "{}", name)
297    }
298}
299
300impl std::str::FromStr for SelectionStrategy {
301    type Err = String;
302
303    fn from_str(s: &str) -> Result<Self, Self::Err> {
304        match s.trim().to_lowercase().as_str() {
305            "priority" => Ok(Self::Priority),
306            "fastest" => Ok(Self::Fastest),
307            "balanced" => Ok(Self::Balanced),
308            "cache_affinity" | "cache-affinity" | "cacheaffinity" => Ok(Self::CacheAffinity),
309            "fair_fastest" | "fair-fastest" | "fairfastest" => Ok(Self::FairFastest),
310            _ => Err(format!(
311                "unknown selection strategy '{}', expected one of: priority, fastest, balanced, cache_affinity, fair_fastest",
312                s
313            )),
314        }
315    }
316}
317
318/// Configuration for the worker selection algorithm.
319#[derive(Debug, Clone, Serialize, Deserialize)]
320pub struct SelectionConfig {
321    /// Selection strategy to use.
322    #[serde(default)]
323    pub strategy: SelectionStrategy,
324    /// Minimum success rate (0.0-1.0) for a worker to be considered.
325    #[serde(default = "default_min_success_rate")]
326    pub min_success_rate: f64,
327    /// Factor weights for the balanced strategy.
328    #[serde(default)]
329    pub weights: SelectionWeightConfig,
330    /// Fairness settings for fair_fastest strategy.
331    #[serde(default)]
332    pub fairness: FairnessConfig,
333    /// Cache affinity settings for project-to-worker pinning.
334    #[serde(default)]
335    pub affinity: AffinityConfig,
336
337    // Preflight health guards (bd-3eaa)
338    /// Maximum load-per-core threshold. Workers exceeding this are skipped.
339    /// Set to None to disable load-based filtering.
340    #[serde(default = "default_max_load_per_core")]
341    pub max_load_per_core: Option<f64>,
342    /// Minimum free disk space in GB. Workers below this are skipped.
343    /// Set to None to disable the free-space floor; per-slot disk derating still applies.
344    #[serde(default = "default_min_free_gb")]
345    pub min_free_gb: Option<f64>,
346    /// Disk budget in GiB per concurrent slot, after reserving `min_free_gb`.
347    /// Must be finite and positive. Unknown disk telemetry preserves configured slots.
348    #[serde(
349        default = "default_disk_gb_per_slot",
350        deserialize_with = "deserialize_disk_gb_per_slot"
351    )]
352    pub disk_gb_per_slot: f64,
353}
354
355impl Default for SelectionConfig {
356    fn default() -> Self {
357        Self {
358            strategy: SelectionStrategy::default(),
359            min_success_rate: default_min_success_rate(),
360            weights: SelectionWeightConfig::default(),
361            fairness: FairnessConfig::default(),
362            affinity: AffinityConfig::default(),
363            max_load_per_core: default_max_load_per_core(),
364            min_free_gb: default_min_free_gb(),
365            disk_gb_per_slot: default_disk_gb_per_slot(),
366        }
367    }
368}
369
370fn default_min_success_rate() -> f64 {
371    0.8
372}
373
374fn default_max_load_per_core() -> Option<f64> {
375    Some(2.0) // Skip workers with load/core > 2.0
376}
377
378fn default_min_free_gb() -> Option<f64> {
379    Some(10.0) // Skip workers with < 10 GB free
380}
381
382fn default_disk_gb_per_slot() -> f64 {
383    10.0
384}
385
386fn deserialize_disk_gb_per_slot<'de, D>(deserializer: D) -> Result<f64, D::Error>
387where
388    D: serde::Deserializer<'de>,
389{
390    let budget = f64::deserialize(deserializer)?;
391    if budget.is_finite() && budget > 0.0 {
392        Ok(budget)
393    } else {
394        Err(serde::de::Error::custom(
395            "disk_gb_per_slot must be finite and greater than zero",
396        ))
397    }
398}
399
400/// Weight configuration for the balanced selection strategy.
401#[derive(Debug, Clone, Serialize, Deserialize)]
402pub struct SelectionWeightConfig {
403    /// Weight for SpeedScore (0.0-1.0).
404    #[serde(default = "default_weight_speedscore")]
405    pub speedscore: f64,
406    /// Weight for available slots (0.0-1.0).
407    #[serde(default = "default_weight_slots")]
408    pub slots: f64,
409    /// Weight for health/success rate (0.0-1.0).
410    #[serde(default = "default_weight_health")]
411    pub health: f64,
412    /// Weight for cache affinity (0.0-1.0).
413    #[serde(default = "default_weight_cache")]
414    pub cache: f64,
415    /// Weight for network latency (0.0-1.0).
416    #[serde(default = "default_weight_network")]
417    pub network: f64,
418    /// Weight for worker priority (0.0-1.0).
419    #[serde(default = "default_weight_priority")]
420    pub priority: f64,
421    /// Weight for disk headroom (0.0-1.0); zero disables disk ranking.
422    #[serde(
423        default = "default_weight_disk",
424        deserialize_with = "deserialize_weight_disk"
425    )]
426    pub disk: f64,
427    /// Penalty multiplier for half-open circuit workers (0.0-1.0).
428    #[serde(default = "default_half_open_penalty")]
429    pub half_open_penalty: f64,
430}
431
432impl Default for SelectionWeightConfig {
433    fn default() -> Self {
434        Self {
435            speedscore: default_weight_speedscore(),
436            slots: default_weight_slots(),
437            health: default_weight_health(),
438            cache: default_weight_cache(),
439            network: default_weight_network(),
440            priority: default_weight_priority(),
441            disk: default_weight_disk(),
442            half_open_penalty: default_half_open_penalty(),
443        }
444    }
445}
446
447fn default_weight_speedscore() -> f64 {
448    0.5
449}
450fn default_weight_slots() -> f64 {
451    0.4
452}
453fn default_weight_health() -> f64 {
454    0.3
455}
456fn default_weight_cache() -> f64 {
457    0.2
458}
459fn default_weight_network() -> f64 {
460    0.1
461}
462fn default_weight_priority() -> f64 {
463    // Worker priority is a first-class selection factor: operators set high
464    // priority on preferred boxes (e.g. fast dedicated workers) and expect them
465    // to actually receive work. At the old 0.1 a top-priority worker gained at
466    // most +0.1 to its balanced score — too weak to overcome a warm-cache or
467    // lower-latency competitor, so the highest-priority workers could sit idle
468    // indefinitely. Load/slots still throttle a high-priority worker as it fills.
469    0.5
470}
471fn default_half_open_penalty() -> f64 {
472    0.5
473}
474
475fn default_weight_disk() -> f64 {
476    0.2
477}
478
479fn deserialize_weight_disk<'de, D>(deserializer: D) -> Result<f64, D::Error>
480where
481    D: serde::Deserializer<'de>,
482{
483    let weight = f64::deserialize(deserializer)?;
484    if weight.is_finite() && (0.0..=1.0).contains(&weight) {
485        Ok(weight)
486    } else {
487        Err(serde::de::Error::custom(
488            "disk weight must be finite and between zero and one",
489        ))
490    }
491}
492
493/// Fairness settings for the fair_fastest selection strategy.
494#[derive(Debug, Clone, Serialize, Deserialize)]
495pub struct FairnessConfig {
496    /// Lookback window in seconds for tracking recent selections.
497    #[serde(default = "default_fairness_lookback_secs")]
498    pub lookback_secs: u64,
499    /// Maximum consecutive selections for a single worker before penalty.
500    #[serde(default = "default_max_consecutive_selections")]
501    pub max_consecutive_selections: u32,
502}
503
504impl Default for FairnessConfig {
505    fn default() -> Self {
506        Self {
507            lookback_secs: default_fairness_lookback_secs(),
508            max_consecutive_selections: default_max_consecutive_selections(),
509        }
510    }
511}
512
513fn default_fairness_lookback_secs() -> u64 {
514    300 // 5 minutes
515}
516
517fn default_max_consecutive_selections() -> u32 {
518    3
519}
520
521/// Cache affinity settings for project-to-worker pinning.
522#[derive(Debug, Clone, Serialize, Deserialize)]
523pub struct AffinityConfig {
524    /// Enable affinity pinning (pin projects to last successful worker).
525    #[serde(default = "default_affinity_enabled")]
526    pub enabled: bool,
527    /// Time window in minutes to pin a project to its last successful worker.
528    /// After this window expires, normal selection resumes.
529    #[serde(default = "default_affinity_pin_minutes")]
530    pub pin_minutes: u64,
531    /// Enable last-success fallback when no workers match selection criteria.
532    /// If enabled, the daemon will attempt the last successful worker for a project
533    /// when all other workers are unavailable or fail selection.
534    #[serde(default = "default_last_success_fallback")]
535    pub enable_last_success_fallback: bool,
536    /// Minimum success rate for the last-success worker to be used as fallback.
537    /// Must be lower than min_success_rate to be meaningful as a fallback.
538    #[serde(default = "default_fallback_min_success_rate")]
539    pub fallback_min_success_rate: f64,
540}
541
542impl Default for AffinityConfig {
543    fn default() -> Self {
544        Self {
545            enabled: default_affinity_enabled(),
546            pin_minutes: default_affinity_pin_minutes(),
547            enable_last_success_fallback: default_last_success_fallback(),
548            fallback_min_success_rate: default_fallback_min_success_rate(),
549        }
550    }
551}
552
553fn default_affinity_enabled() -> bool {
554    true
555}
556
557fn default_affinity_pin_minutes() -> u64 {
558    60 // 1 hour default
559}
560
561fn default_last_success_fallback() -> bool {
562    true
563}
564
565fn default_fallback_min_success_rate() -> f64 {
566    0.5 // More lenient than normal min_success_rate (0.8)
567}
568
569/// Details about a selected worker for remote compilation.
570#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
571pub struct SelectedWorker {
572    /// Selected worker ID.
573    pub id: WorkerId,
574    /// Host address for SSH.
575    pub host: String,
576    /// SSH user.
577    pub user: String,
578    /// Path to SSH identity file.
579    pub identity_file: String,
580    /// Number of slots available on this worker after reservation.
581    pub slots_available: u32,
582    /// Worker's speed score (0-100).
583    pub speed_score: f64,
584    /// Operator-declared host OS (e.g. `windows`), if any. Propagated so the
585    /// hook can pick the right transport (Windows workers use `C:/rch` +
586    /// tar-over-ssh instead of the Unix rsync path). `None` for the historical
587    /// unlabelled workers. `#[serde(default)]` keeps old daemons/hooks
588    /// wire-compatible.
589    #[serde(default)]
590    pub declared_os: Option<String>,
591}
592
593/// Worker selection response from daemon to hook.
594#[derive(Debug, Clone, Serialize, Deserialize)]
595pub struct SelectionResponse {
596    /// Selected worker details, if available.
597    pub worker: Option<SelectedWorker>,
598    /// Reason for the selection result.
599    pub reason: SelectionReason,
600    /// Optional build ID assigned by the daemon (for active build tracking).
601    #[serde(default, skip_serializing_if = "Option::is_none")]
602    pub build_id: Option<u64>,
603    /// Optional per-worker selector diagnostics for machine-readable triage.
604    #[serde(default, skip_serializing_if = "Option::is_none")]
605    pub diagnostics: Option<SelectionDiagnostics>,
606}
607
608/// Final selector decision for a worker considered during routing.
609#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
610#[serde(rename_all = "snake_case")]
611pub enum WorkerSelectionDiagnosticDecision {
612    /// Worker passed hard gates and normal health threshold.
613    Allow,
614    /// Worker failed normal health threshold but passed fallback threshold.
615    FallbackCandidate,
616    /// Worker was denied by a hard gate or both health thresholds.
617    Deny,
618}
619
620/// Per-worker selector facts captured at worker-selection time.
621#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
622pub struct WorkerSelectionDiagnostic {
623    /// Worker ID.
624    pub worker_id: WorkerId,
625    /// Worker lifecycle/status label.
626    pub status: String,
627    /// Circuit breaker state label.
628    pub circuit_state: String,
629    /// Current normalized pressure state.
630    pub pressure_state: String,
631    /// Stable pressure reason code.
632    pub pressure_reason_code: String,
633    /// Rolling selector success rate, where available.
634    #[serde(skip_serializing_if = "Option::is_none")]
635    pub success_rate: Option<f64>,
636    /// Normal selection success-rate threshold.
637    pub min_success_rate: f64,
638    /// Last-success fallback success-rate threshold.
639    pub fallback_min_success_rate: f64,
640    /// Required runtime for this command.
641    pub required_runtime: RequiredRuntime,
642    /// Whether this worker has the required runtime.
643    pub runtime_available: bool,
644    /// Available slots at selection time.
645    pub available_slots: u32,
646    /// Total configured slots.
647    pub total_slots: u32,
648    /// Estimated slots requested by this command.
649    pub estimated_cores: u32,
650    /// Whether this worker was excluded because it already runs this project.
651    pub active_project_excluded: bool,
652    /// Final per-worker selector decision.
653    pub final_decision: WorkerSelectionDiagnosticDecision,
654    /// Human-readable final reason.
655    pub final_reason: String,
656    /// Stable machine-readable reasons collected for this worker.
657    pub reason_codes: Vec<String>,
658}
659
660/// Machine-readable worker selector diagnostics for a selection request.
661#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
662pub struct SelectionDiagnostics {
663    /// Required runtime for this command.
664    pub required_runtime: RequiredRuntime,
665    /// Estimated slots requested by this command.
666    pub estimated_cores: u32,
667    /// Normal success-rate threshold.
668    pub min_success_rate: f64,
669    /// Last-success fallback success-rate threshold.
670    pub fallback_min_success_rate: f64,
671    /// Count of workers excluded because they already run this project.
672    pub active_project_exclusion_count: usize,
673    /// One diagnostic entry per configured worker.
674    pub workers: Vec<WorkerSelectionDiagnostic>,
675}
676
677/// Request to release reserved worker slots.
678#[derive(Debug, Clone, Serialize, Deserialize)]
679pub struct ReleaseRequest {
680    /// ID of the worker to release slots on.
681    pub worker_id: WorkerId,
682    /// Number of slots to release.
683    pub slots: u32,
684    /// Optional build ID to mark complete.
685    #[serde(default, skip_serializing_if = "Option::is_none")]
686    pub build_id: Option<u64>,
687    /// Exact client wrapper identity associated with the admitted build.
688    #[serde(default, skip_serializing_if = "Option::is_none")]
689    pub local_wrapper_id: Option<String>,
690    /// Optional exit code for the build (used to finalize active build tracking).
691    #[serde(default, skip_serializing_if = "Option::is_none")]
692    pub exit_code: Option<i32>,
693    /// Optional total duration in milliseconds (pipeline or execution).
694    ///
695    /// If omitted, the daemon will compute duration from the active build's start time.
696    #[serde(default, skip_serializing_if = "Option::is_none")]
697    pub duration_ms: Option<u64>,
698    /// Optional bytes transferred during the pipeline (upload + artifact download).
699    #[serde(default, skip_serializing_if = "Option::is_none")]
700    pub bytes_transferred: Option<u64>,
701    /// Optional per-phase timing breakdown for the build pipeline.
702    #[serde(default, skip_serializing_if = "Option::is_none")]
703    pub timing: Option<CommandTimingBreakdown>,
704    /// The hook classified this non-zero exit as a worker fault (missing
705    /// toolchain or system library, CPU-capability signal, full disk), so the
706    /// daemon records no cache warmth for it (review of GH #81).
707    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
708    pub worker_fault: bool,
709    /// The failed remote command reported exhausted disk space or quota.
710    /// After matching the durable build owner, the daemon temporarily bypasses
711    /// this worker until fresh recovery probes establish disk headroom.
712    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
713    pub worker_disk_full: bool,
714    /// Actual remote source and output roots used by the failed attempt.
715    /// Recovery must measure these filesystems as well as configured roots.
716    #[serde(default, skip_serializing_if = "Vec::is_empty")]
717    pub worker_disk_roots: Vec<String>,
718}
719
720/// Build execution phase for daemon heartbeat tracking.
721#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
722#[serde(rename_all = "snake_case")]
723pub enum BuildHeartbeatPhase {
724    /// Uploading sources/dependencies to the worker.
725    SyncUp,
726    /// Running the remote compilation/test command.
727    Execute,
728    /// Downloading build artifacts from the worker.
729    SyncDown,
730    /// Build is completing or finalizing.
731    Finalize,
732}
733
734/// Request to update liveness/progress for an active build.
735#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
736pub struct BuildHeartbeatRequest {
737    /// Active build identifier assigned by the daemon.
738    pub build_id: u64,
739    /// Worker executing the build.
740    pub worker_id: WorkerId,
741    /// Hook process ID sending the heartbeat.
742    #[serde(default, skip_serializing_if = "Option::is_none")]
743    pub hook_pid: Option<u32>,
744    /// Client-minted wrapper identity for local durable-lease correlation.
745    #[serde(default, skip_serializing_if = "Option::is_none")]
746    pub local_wrapper_id: Option<String>,
747    /// Remote file containing the process-group leader PID for cancellation.
748    #[serde(default, skip_serializing_if = "Option::is_none")]
749    pub remote_pgid_file: Option<String>,
750    /// Current build execution phase.
751    pub phase: BuildHeartbeatPhase,
752    /// Optional human-readable progress detail.
753    #[serde(default, skip_serializing_if = "Option::is_none")]
754    pub detail: Option<String>,
755    /// Optional monotonic progress counter.
756    ///
757    /// The hook increments this when it observes meaningful progress
758    /// (phase transitions, new output, or richer progress signals).
759    #[serde(default, skip_serializing_if = "Option::is_none")]
760    pub progress_counter: Option<u64>,
761    /// Optional progress estimate in [0,100].
762    #[serde(default, skip_serializing_if = "Option::is_none")]
763    pub progress_percent: Option<f64>,
764}
765
766/// Configuration for a remote worker.
767#[derive(Debug, Clone, Serialize, Deserialize)]
768pub struct WorkerConfig {
769    /// Unique identifier for this worker.
770    pub id: WorkerId,
771    /// SSH hostname or IP address.
772    pub host: String,
773    /// SSH username.
774    pub user: String,
775    /// Path to SSH private key.
776    pub identity_file: String,
777    /// Total CPU slots available on this worker.
778    pub total_slots: u32,
779    /// Priority for worker selection (higher = preferred).
780    #[serde(default = "default_priority")]
781    pub priority: u32,
782    /// Optional tags for filtering.
783    ///
784    /// Mostly descriptive, with one reserved form: `os:<name>` (see
785    /// [`crate::declared_os`]) is a hard admission gate, written in
786    /// `workers.toml` as `os = "<name>"`.
787    #[serde(default)]
788    pub tags: Vec<String>,
789    /// Operator-declared named tool probes for this worker, written in
790    /// `workers.toml` as
791    /// `tools = [{ name = "clang", command = ["clang", "--version"] }]`.
792    ///
793    /// Unlike a tag, which is an unverified naming convention, each entry is
794    /// VERIFIED by running its fixed argv on the worker as the configured user;
795    /// only a zero exit makes the tool present. That is what lets
796    /// `--require-tool` gate selection on evidence instead of on a promise.
797    #[serde(default, skip_serializing_if = "Vec::is_empty")]
798    pub tools: Vec<WorkerToolProbe>,
799}
800
801/// One operator-declared tool probe as it appears in `workers.toml`.
802///
803/// Kept as plain configuration data; [`crate::capability_probe::NamedToolProbe`]
804/// is the validated form, and the conversion is where a malformed name is
805/// refused.
806#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
807pub struct WorkerToolProbe {
808    /// The name `--require-tool` and `jobs.required_tools` refer to.
809    pub name: String,
810    /// The exact argv to run. Zero exit = present; anything else = absent.
811    pub command: Vec<String>,
812}
813
814fn default_priority() -> u32 {
815    100
816}
817
818/// Tag prefix reserved for the operator-declared host OS.
819pub const OS_TAG_PREFIX: &str = "os:";
820
821/// The host OS an operator declared for a worker, from its tags.
822///
823/// Written in `workers.toml` as `os = "windows"` and normalized into the
824/// reserved `os:windows` tag on load, so it rides the existing tag vector
825/// through every path that already carries a [`WorkerConfig`].
826///
827/// Declaring it makes the worker **exclusive**: selection admits it only for
828/// commands that require that OS, so a Windows box cannot quietly absorb a
829/// `cargo check` dispatched from Linux and return wrong-platform artifacts.
830/// Workers without the tag — every historical worker — keep taking anything.
831#[must_use]
832pub fn declared_os(tags: &[String]) -> Option<String> {
833    // `find` over the mapped values, not `find_map` over the tags: a malformed
834    // `os:` entry must not mask a valid declaration later in the list, because
835    // failing open here is precisely the "Windows worker silently takes Linux
836    // jobs" outcome the gate exists to prevent.
837    tags.iter()
838        .filter_map(|tag| tag.strip_prefix(OS_TAG_PREFIX))
839        .map(|os| os.trim().to_ascii_lowercase())
840        .find(|os| !os.is_empty())
841}
842
843/// Build the reserved tag for a declared OS.
844#[must_use]
845pub fn os_tag(os: &str) -> String {
846    format!("{OS_TAG_PREFIX}{}", os.trim().to_ascii_lowercase())
847}
848
849impl Default for WorkerConfig {
850    fn default() -> Self {
851        Self {
852            id: WorkerId::new("default-worker"),
853            host: "localhost".to_string(),
854            user: "user".to_string(),
855            identity_file: "~/.ssh/id_rsa".to_string(),
856            total_slots: 4,
857            priority: default_priority(),
858            tags: Vec::new(),
859            tools: Vec::new(),
860        }
861    }
862}
863
864/// Runtime capabilities detected on a worker.
865///
866/// These are probed during health checks and cached for routing decisions.
867/// Commands requiring specific runtimes (e.g., `bun test`) can be routed
868/// only to workers with the corresponding capability.
869#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
870pub struct WorkerCapabilities {
871    /// Rust compiler version (from `rustc --version`).
872    #[serde(default, skip_serializing_if = "Option::is_none")]
873    pub rustc_version: Option<String>,
874    /// Installed rustup toolchains, including their host triple when rustup
875    /// reports one (for example `nightly-2026-07-05-x86_64-unknown-linux-gnu`).
876    #[serde(default, skip_serializing_if = "Vec::is_empty")]
877    pub rustup_toolchains: Vec<String>,
878    /// Installed rustup components as `<toolchain>:<component>` facts. Component
879    /// names are normalized by removing only the probed host-triple suffix, so
880    /// `clippy-preview` can never satisfy a `clippy` requirement.
881    #[serde(default, skip_serializing_if = "Vec::is_empty")]
882    pub rustup_components: Vec<String>,
883    /// Non-fatal diagnostics gathered while probing (for example a tool binary
884    /// that had to be resolved from a well-known fallback location because the
885    /// caller's PATH was minimal). Empty in the common case; clients may
886    /// surface these so "no facts" is distinguishable from "facts show
887    /// absence" (bd-deft5).
888    #[serde(default, skip_serializing_if = "Vec::is_empty")]
889    pub probe_warnings: Vec<String>,
890    /// Bun runtime version (from `bun --version`).
891    #[serde(default, skip_serializing_if = "Option::is_none")]
892    pub bun_version: Option<String>,
893    /// Node.js version (from `node --version`).
894    #[serde(default, skip_serializing_if = "Option::is_none")]
895    pub node_version: Option<String>,
896    /// npm version (from `npm --version`).
897    #[serde(default, skip_serializing_if = "Option::is_none")]
898    pub npm_version: Option<String>,
899    /// Nix version (from `nix --version`). Presence implies a usable nix binary
900    /// with an accompanying `/nix/store`, gating `nix build`/`nix develop -c`
901    /// routing to this worker.
902    #[serde(default, skip_serializing_if = "Option::is_none")]
903    pub nix_version: Option<String>,
904    /// Go toolchain version (from `go version`). Presence gates `go build`/
905    /// `go test`/`go vet` routing to this worker.
906    #[serde(default, skip_serializing_if = "Option::is_none")]
907    pub go_version: Option<String>,
908    /// Zig version (from `zig version`). `cargo zigbuild` shells out to `zig`
909    /// as the linker/C toolchain, so the bare `zig` binary is necessary but not
910    /// sufficient — see [`WorkerCapabilities::has_zig`].
911    #[serde(default, skip_serializing_if = "Option::is_none")]
912    pub zig_version: Option<String>,
913    /// cargo-zigbuild version (from `cargo-zigbuild --version`). Probed as the
914    /// hyphenated binary rather than `cargo zigbuild --version`, which the
915    /// subcommand's own parser rejects.
916    #[serde(default, skip_serializing_if = "Option::is_none")]
917    pub cargo_zigbuild_version: Option<String>,
918    /// x86-64 microarchitecture level (1..=4) parsed from `/proc/cpuinfo`
919    /// flags on the worker (bd-6qchz / bd-68hon item 4). `Some(2)` marks a
920    /// pre-AVX2 box (e.g. ovh-b's Ivy Bridge) whose build scripts SIGILL on
921    /// x86-64-v3 codegen; selection deprioritizes such workers proactively
922    /// while the reactive SIGILL quarantine remains the primary mechanism.
923    /// `None` on non-x86 workers or when the probe cannot read cpuinfo.
924    #[serde(default, skip_serializing_if = "Option::is_none")]
925    pub cpu_microarch_level: Option<u8>,
926    /// Operator-declared named tools whose probe exited ZERO on this worker.
927    ///
928    /// The list is evidence, not configuration: a name appears here only
929    /// because the worker ran the declared argv and it succeeded. Selection
930    /// gates `--require-tool` on this, which is the difference between a
931    /// verified capability and a tag somebody wrote by hand.
932    #[serde(default, skip_serializing_if = "Vec::is_empty")]
933    pub tools_present: Vec<String>,
934    /// Operator-declared named tools whose probe RAN and did not exit zero.
935    ///
936    /// Kept separate from "never declared" so an operator can tell a worker
937    /// that is missing a tool from a fleet that never probed for it — the two
938    /// have different fixes.
939    #[serde(default, skip_serializing_if = "Vec::is_empty")]
940    pub tools_absent: Vec<String>,
941
942    // Health metrics (bd-3eaa)
943    /// Number of CPU cores on the worker.
944    #[serde(default, skip_serializing_if = "Option::is_none")]
945    pub num_cpus: Option<u32>,
946    /// 1-minute load average.
947    #[serde(default, skip_serializing_if = "Option::is_none")]
948    pub load_avg_1: Option<f64>,
949    /// 5-minute load average.
950    #[serde(default, skip_serializing_if = "Option::is_none")]
951    pub load_avg_5: Option<f64>,
952    /// 15-minute load average.
953    #[serde(default, skip_serializing_if = "Option::is_none")]
954    pub load_avg_15: Option<f64>,
955    /// Free space in GB on the tightest mount a build touches: whichever of
956    /// the projects root, its alias and `/tmp` has the lowest free ratio.
957    /// Drives pressure classification (a full `/tmp` breaks scp/mktemp).
958    #[serde(default, skip_serializing_if = "Option::is_none")]
959    pub disk_free_gb: Option<f64>,
960    /// Total size in GB of the mount reported in `disk_free_gb`.
961    #[serde(default, skip_serializing_if = "Option::is_none")]
962    pub disk_total_gb: Option<f64>,
963    /// Free space in GB on the filesystem that holds build trees (the fuller
964    /// of the projects root and its alias; `/tmp` excluded). Sizes capacity:
965    /// slot derating, disk headroom and the free-space floor (GH #78).
966    /// `None` from an `rch-wkr` that predates the field.
967    #[serde(default, skip_serializing_if = "Option::is_none")]
968    pub build_disk_free_gb: Option<f64>,
969    /// Total size in GB of the mount reported in `build_disk_free_gb`.
970    #[serde(default, skip_serializing_if = "Option::is_none")]
971    pub build_disk_total_gb: Option<f64>,
972    /// Canonical path-topology preflight status (`/data/projects` + `/dp` alias).
973    ///
974    /// `Some(false)` indicates a hard preflight failure that should exclude this
975    /// worker from remote scheduling until a subsequent successful revalidation.
976    #[serde(default, skip_serializing_if = "Option::is_none")]
977    pub projects_root_ok: Option<bool>,
978    /// Machine-readable failure reason for path-topology preflight.
979    #[serde(default, skip_serializing_if = "Option::is_none")]
980    pub projects_root_issue: Option<String>,
981    /// Unix timestamp (ms) when topology preflight last executed.
982    #[serde(default, skip_serializing_if = "Option::is_none")]
983    pub projects_root_checked_at_unix_ms: Option<i64>,
984}
985
986impl WorkerCapabilities {
987    /// Create new empty capabilities.
988    pub fn new() -> Self {
989        Self::default()
990    }
991
992    /// Create mock capabilities with Rust installed.
993    ///
994    /// Used by mock transport to simulate a worker with Rust toolchain.
995    pub fn mock_with_rust() -> Self {
996        Self {
997            rustc_version: Some("1.85.0-nightly (mock)".to_string()),
998            projects_root_ok: Some(true),
999            ..Self::default()
1000        }
1001    }
1002
1003    /// Whether this is a known pre-x86-64-v3 (no AVX2) x86 worker — the class
1004    /// whose build-script/proc-macro binaries SIGILL on v3 codegen (bd-68hon).
1005    /// `None` (unknown/non-x86) is NOT pre-v3: only affirmative evidence
1006    /// deprioritizes a worker.
1007    pub fn is_pre_v3_x86(&self) -> bool {
1008        matches!(self.cpu_microarch_level, Some(1 | 2))
1009    }
1010
1011    /// Check if this worker has Bun installed.
1012    pub fn has_bun(&self) -> bool {
1013        self.bun_version.is_some()
1014    }
1015
1016    /// Check if this worker has Node.js installed.
1017    pub fn has_node(&self) -> bool {
1018        self.node_version.is_some()
1019    }
1020
1021    /// Check if this worker has Rust installed.
1022    pub fn has_rust(&self) -> bool {
1023        self.rustc_version.is_some()
1024    }
1025
1026    /// Check whether `component` is installed for `toolchain`.
1027    ///
1028    /// Rustup reports pinned toolchains with a host-triple suffix. The request
1029    /// carries the project pin without that suffix, so the owner half uses the
1030    /// same exact-or-`-`-boundary prefix rule as toolchain admission. The
1031    /// component half is exact.
1032    pub fn has_rustup_component(&self, toolchain: &str, component: &str) -> bool {
1033        let owner_prefix = format!("{toolchain}-");
1034        self.rustup_components.iter().any(|fact| {
1035            fact.split_once(':').is_some_and(|(owner, name)| {
1036                name == component && (owner == toolchain || owner.starts_with(&owner_prefix))
1037            })
1038        })
1039    }
1040
1041    /// Check if this worker has Nix installed (nix binary + `/nix/store`).
1042    pub fn has_nix(&self) -> bool {
1043        self.nix_version.is_some()
1044    }
1045
1046    /// Check if this worker has the Go toolchain installed.
1047    pub fn has_go(&self) -> bool {
1048        self.go_version.is_some()
1049    }
1050
1051    /// Check if this worker can run `cargo zigbuild` cross-compiles.
1052    ///
1053    /// Requires BOTH halves of the toolchain: the `cargo-zigbuild` cargo
1054    /// subcommand and the `zig` binary it drives as the linker. Either one
1055    /// alone fails at build time with an error the remote-result heuristics do
1056    /// not recognize as infrastructure (`error: no such command: 'zigbuild'` is
1057    /// not a rustup message), so the exit code would be surfaced verbatim
1058    /// instead of falling open to local. Gating both here keeps that failure
1059    /// out of the user's build.
1060    pub fn has_zig(&self) -> bool {
1061        self.zig_version.is_some() && self.cargo_zigbuild_version.is_some()
1062    }
1063
1064    /// Calculate load per core (1-minute load average / num_cpus).
1065    /// Returns None if metrics are unavailable.
1066    pub fn load_per_core(&self) -> Option<f64> {
1067        match (self.load_avg_1, self.num_cpus) {
1068            (Some(load), Some(cpus)) if cpus > 0 => Some(load / cpus as f64),
1069            _ => None,
1070        }
1071    }
1072
1073    /// Check if worker has high load (exceeds threshold).
1074    /// Returns None if metrics unavailable (fail-open).
1075    pub fn is_high_load(&self, max_load_per_core: f64) -> Option<bool> {
1076        self.load_per_core().map(|lpc| lpc > max_load_per_core)
1077    }
1078
1079    /// `(free_gb, total_gb)` of the filesystem that holds build trees.
1080    ///
1081    /// Capacity questions (how many builds fit, is the free-space floor met)
1082    /// are about that filesystem, not about a small tmpfs `/tmp` that happens
1083    /// to be the tightest mount. Falls back to the tightest-mount sample when
1084    /// the worker does not report a build-disk sample (older `rch-wkr`), which
1085    /// is the conservative pre-GH-#78 behaviour.
1086    pub fn build_disk_gb(&self) -> (Option<f64>, Option<f64>) {
1087        if self.build_disk_free_gb.is_some() {
1088            (self.build_disk_free_gb, self.build_disk_total_gb)
1089        } else {
1090            (self.disk_free_gb, self.disk_total_gb)
1091        }
1092    }
1093
1094    /// Check if the build disk is below the free-space threshold.
1095    /// Returns None if metrics unavailable (fail-open).
1096    pub fn is_low_disk(&self, min_free_gb: f64) -> Option<bool> {
1097        self.build_disk_gb().0.map(|free| free < min_free_gb)
1098    }
1099
1100    /// Check if canonical path-topology preflight is healthy.
1101    ///
1102    /// Returns `None` when probe data is unavailable (fail-open behavior).
1103    pub fn is_topology_healthy(&self) -> Option<bool> {
1104        self.projects_root_ok
1105    }
1106}
1107
1108/// Classify an x86-64 microarchitecture level (1..=4) from a `/proc/cpuinfo`
1109/// `flags` line (bd-6qchz).
1110///
1111/// Levels follow the psABI x86-64-v2/v3/v4 feature baselines, restricted to
1112/// flags as they appear in Linux cpuinfo. A CPU missing any flag of a level is
1113/// classified at the level below — e.g. ovh-b's Ivy Bridge E3-1245 V2 has AVX
1114/// but no `avx2`/`bmi2`/`fma`, so it classifies as 2 and its v3-codegen build
1115/// scripts SIGILL (the bd-68hon incident class).
1116#[must_use]
1117pub fn x86_64_microarch_level_from_flags(flags: &str) -> u8 {
1118    let set: std::collections::HashSet<&str> = flags.split_whitespace().collect();
1119    let has_all = |required: &[&str]| required.iter().all(|flag| set.contains(flag));
1120    // x86-64-v2: CMPXCHG16B, LAHF/SAHF, POPCNT, SSE3/SSSE3/SSE4.x.
1121    const V2: &[&str] = &["cx16", "lahf_lm", "popcnt", "sse4_1", "sse4_2", "ssse3"];
1122    // x86-64-v3: AVX/AVX2, BMI1/2, F16C, FMA, MOVBE, XSAVE (LZCNT is `abm`).
1123    const V3: &[&str] = &[
1124        "abm", "avx", "avx2", "bmi1", "bmi2", "f16c", "fma", "movbe", "xsave",
1125    ];
1126    // x86-64-v4: the AVX-512 F/BW/CD/DQ/VL baseline.
1127    const V4: &[&str] = &["avx512f", "avx512bw", "avx512cd", "avx512dq", "avx512vl"];
1128    if !has_all(V2) {
1129        return 1;
1130    }
1131    if !has_all(V3) {
1132        return 2;
1133    }
1134    if !has_all(V4) {
1135        return 3;
1136    }
1137    4
1138}
1139
1140/// Path topology configuration.
1141///
1142/// Overrides the default canonical and alias project roots used by
1143/// [`crate::path_topology::PathTopologyPolicy`].  This is useful on platforms
1144/// such as macOS where SIP prevents using `/data/projects` and the user must
1145/// choose a different root (e.g. `~/Projects`).
1146///
1147/// ```toml
1148/// [path_topology]
1149/// canonical_root = "/Users/me/Projects"
1150/// alias_root = "/Users/me/p"
1151/// ```
1152#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1153pub struct PathTopologyConfig {
1154    /// Canonical project root directory.
1155    /// Defaults to `/data/projects` when absent.
1156    #[serde(default)]
1157    pub canonical_root: Option<String>,
1158
1159    /// Alias (symlink) root that points at the canonical root.
1160    /// Defaults to `/dp` when absent.
1161    #[serde(default)]
1162    pub alias_root: Option<String>,
1163}
1164
1165impl PathTopologyConfig {
1166    /// Build a [`crate::path_topology::PathTopologyPolicy`] from this config,
1167    /// falling back to the compiled-in defaults for any field left unset.
1168    ///
1169    /// Empty strings are treated as unset (fall back to defaults).
1170    /// Tilde prefixes (`~/...`) are expanded to the user's home directory.
1171    pub fn to_policy(&self) -> crate::path_topology::PathTopologyPolicy {
1172        let canonical = self
1173            .canonical_root
1174            .as_deref()
1175            .filter(|s| !s.is_empty())
1176            .map(|s| shellexpand::tilde(s).into_owned())
1177            .unwrap_or_else(|| crate::path_topology::DEFAULT_CANONICAL_PROJECT_ROOT.to_string());
1178        let alias = self
1179            .alias_root
1180            .as_deref()
1181            .filter(|s| !s.is_empty())
1182            .map(|s| shellexpand::tilde(s).into_owned())
1183            .unwrap_or_else(|| crate::path_topology::DEFAULT_ALIAS_PROJECT_ROOT.to_string());
1184        crate::path_topology::PathTopologyPolicy::new(
1185            PathBuf::from(canonical),
1186            PathBuf::from(alias),
1187        )
1188    }
1189}
1190
1191/// RCH configuration.
1192#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1193pub struct RchConfig {
1194    #[serde(default)]
1195    pub general: GeneralConfig,
1196    #[serde(default)]
1197    pub compilation: CompilationConfig,
1198    #[serde(default)]
1199    pub transfer: TransferConfig,
1200    #[serde(default)]
1201    pub environment: EnvironmentConfig,
1202    #[serde(default)]
1203    pub circuit: CircuitBreakerConfig,
1204    #[serde(default)]
1205    pub output: OutputConfig,
1206    #[serde(default)]
1207    pub self_healing: SelfHealingConfig,
1208    #[serde(default)]
1209    pub self_test: SelfTestConfig,
1210    /// Worker selection algorithm configuration.
1211    #[serde(default)]
1212    pub selection: SelectionConfig,
1213    /// Execution allowlist configuration (bd-785w).
1214    #[serde(default)]
1215    pub execution: ExecutionConfig,
1216    /// Worker health alerting configuration (daemon).
1217    #[serde(default)]
1218    pub alerts: AlertsConfig,
1219    /// Fleet operation configuration (bd-rs7w.2).
1220    #[serde(default)]
1221    pub fleet: FleetConfig,
1222    /// Path topology overrides for project root directories.
1223    #[serde(default)]
1224    pub path_topology: PathTopologyConfig,
1225    /// Doctor / reliability subsystem configuration (verdict webhooks).
1226    #[serde(default)]
1227    pub doctor: DoctorConfig,
1228    /// Session-history remediation knobs: the central schema and default policy
1229    /// for temporary bypass, auto-rejoin, reconciliation, proof, incident
1230    /// ledger, build-root, pooled targets, telemetry freshness, log retention,
1231    /// disk pressure, and smoke defaults (bd-...remediation-ocv9i.17.1).
1232    #[serde(default)]
1233    pub remediation: crate::remediation_config::RemediationConfig,
1234    /// Layer 0 configuration pack knobs (bd-bqu38 / M-1 §149). Defaults OFF;
1235    /// injected as CARGO_PROFILE_* env vars into remote cargo builds.
1236    #[serde(default)]
1237    pub layer0: Layer0Config,
1238    /// Daemon status API over TCP for other machines on the tailnet
1239    /// (`[api]`, bd-2f5ms). Off unless `bind` is set.
1240    #[serde(default)]
1241    pub api: ApiConfig,
1242    /// Where the fleet dashboard lives (`[dashboard]`), for `rch web`.
1243    #[serde(default)]
1244    pub dashboard: DashboardConfig,
1245    /// Job-mode defaults (`[jobs]`), for `rch exec --job`.
1246    #[serde(default)]
1247    pub jobs: JobsConfig,
1248}
1249
1250/// Job-mode configuration (`[jobs]`).
1251#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1252pub struct JobsConfig {
1253    /// Named tools every job from this project requires a worker to have
1254    /// VERIFIED, as though each were passed with `--require-tool`.
1255    ///
1256    /// This is the project saying "my jobs cannot run on a worker without
1257    /// these", so it applies on top of any `--require-tool` given on the
1258    /// command line rather than being replaced by it. It affects job mode
1259    /// ONLY: ordinary offloaded compilation keeps its existing admission
1260    /// behavior, because a project-wide requirement that silently narrowed
1261    /// every build's worker pool would be a surprising way to lose the fleet.
1262    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1263    pub required_tools: Vec<String>,
1264}
1265
1266/// Daemon status API over TCP (`[api]`).
1267///
1268/// rchd's rich state (`/status`, `/workers/capabilities`) lives on a `0600`
1269/// Unix socket, which only the local user can read. This section opens the
1270/// same JSON on a TCP listener so agents and the fleet dashboard on OTHER
1271/// machines can ask a dispatcher "why are you local-only right now?" without
1272/// ssh. It is meant for a tailnet: the bind address must be loopback or a
1273/// Tailscale address (100.64.0.0/10, fd7a:115c:a1e0::/48) unless
1274/// `allow_any_addr` is set, and every status route requires the bearer token
1275/// unless `token` is unset AND `no_token` is explicitly true.
1276///
1277/// ```toml
1278/// [api]
1279/// bind = "tailscale"       # or "tailscale:9101", "100.68.51.94:9101", "127.0.0.1:9101"
1280/// token = "…"              # or token_file = "~/.config/rch/api.token"
1281/// ```
1282#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
1283#[serde(default)]
1284pub struct ApiConfig {
1285    /// Where to listen. `"tailscale"` resolves this machine's Tailscale IPv4
1286    /// at startup (default port 9101); `"tailscale:PORT"`, `"IP:PORT"` or
1287    /// `"[v6]:PORT"` are taken literally. Unset (empty) = API off.
1288    pub bind: String,
1289    /// Bearer token required on `/status` and `/workers/capabilities`.
1290    pub token: Option<String>,
1291    /// File holding the bearer token (trimmed). Takes precedence over `token`.
1292    pub token_file: Option<String>,
1293    /// Serve the status routes with NO token. Only honoured when no token is
1294    /// configured; must be set explicitly so an empty token is never an
1295    /// accidental open door.
1296    pub no_token: bool,
1297    /// Permit a bind address outside loopback and the Tailscale ranges.
1298    pub allow_any_addr: bool,
1299}
1300
1301/// Where the fleet dashboard is served (`[dashboard]`).
1302#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
1303#[serde(default)]
1304pub struct DashboardConfig {
1305    /// URL `rch web` opens, e.g. `https://rch-fleet.vercel.app`.
1306    pub url: Option<String>,
1307}
1308
1309/// Doctor reliability subsystem configuration.
1310///
1311/// Currently carries the verdict-transition webhook surface. Kept as its own
1312/// section (`[doctor]`) so future doctor knobs land here rather than bloating
1313/// the top-level config.
1314#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
1315pub struct DoctorConfig {
1316    /// Verdict-transition webhook destinations.
1317    #[serde(default)]
1318    pub webhooks: DoctorWebhooksConfig,
1319}
1320
1321/// Webhook notification surface for reliability verdict transitions.
1322///
1323/// Fires when `rch doctor --reliability --watch` observes a verdict change
1324/// (`Healthy → Degraded`, `Degraded → Failing`, etc.). Each endpoint selects
1325/// which transitions it cares about and how the payload is formatted.
1326#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1327pub struct DoctorWebhooksConfig {
1328    /// Named webhook destinations. Empty = no webhook dispatch.
1329    #[serde(default)]
1330    pub endpoints: Vec<DoctorWebhookEndpoint>,
1331    /// Maximum number of in-flight webhook deliveries. Bounds memory and
1332    /// outbound connection pressure: when the queue is full, a transition's
1333    /// delivery is dropped (and journaled) rather than growing unboundedly.
1334    /// Per-process, shared across all endpoints.
1335    #[serde(default = "default_webhook_max_inflight")]
1336    pub max_inflight: usize,
1337}
1338
1339// Manual `Default` so the in-code default matches the serde default
1340// (`#[derive(Default)]` would give `max_inflight = 0`, diverging from a
1341// from-TOML load that fills in 16).
1342impl Default for DoctorWebhooksConfig {
1343    fn default() -> Self {
1344        Self {
1345            endpoints: Vec::new(),
1346            max_inflight: default_webhook_max_inflight(),
1347        }
1348    }
1349}
1350
1351/// A single webhook destination for verdict transitions.
1352///
1353/// SECRETS ARE NEVER STORED HERE. Routing keys, bearer tokens, and signing
1354/// secrets are referenced by the *name* of an environment variable
1355/// (`*_env` fields) read at dispatch time. There is deliberately no
1356/// `secret` / `routing_key` / `bearer_token` / `password` field on this
1357/// struct (enforced by `test_no_inline_secret_fields`).
1358#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1359pub struct DoctorWebhookEndpoint {
1360    /// Operator-facing name (appears in logs and the audit trail).
1361    pub name: String,
1362    /// Destination URL.
1363    pub url: String,
1364    /// Payload format.
1365    #[serde(default)]
1366    pub format: DoctorWebhookFormat,
1367    /// Transition predicates that arm this endpoint. Empty = never fire.
1368    /// Supported: `healthy_to_degraded`, `degraded_to_failing`,
1369    /// `any_to_failing`, `any_to_degraded`, `failing_to_healthy`,
1370    /// `degraded_to_healthy`, `any_to_healthy`, `any_to_any`.
1371    #[serde(default)]
1372    pub on_transitions: Vec<String>,
1373    /// Maximum retry attempts after the first try fails.
1374    #[serde(default = "default_webhook_retry_max")]
1375    pub retry_max: u32,
1376    /// Base backoff between retries (milliseconds); doubles each attempt.
1377    #[serde(default = "default_webhook_retry_backoff_ms")]
1378    pub retry_backoff_ms: u64,
1379    /// Per-attempt request timeout (milliseconds).
1380    #[serde(default = "default_webhook_timeout_ms")]
1381    pub timeout_ms: u64,
1382    /// Per-endpoint kill switch.
1383    #[serde(default = "default_true")]
1384    pub enabled: bool,
1385    /// Name of the env var holding the PagerDuty Events API routing key.
1386    /// Required for `format = "pagerduty"`. Read at runtime, never stored.
1387    #[serde(default)]
1388    pub routing_key_env: Option<String>,
1389    /// Name of the env var holding a bearer token sent as
1390    /// `Authorization: Bearer <token>`. Read at runtime, never stored.
1391    #[serde(default)]
1392    pub bearer_token_env: Option<String>,
1393    /// Name of the env var holding an HMAC-SHA256 signing secret. When set,
1394    /// the body is signed and the signature sent as `X-RCH-Signature:
1395    /// sha256=<hex>`. Read at runtime, never stored.
1396    #[serde(default)]
1397    pub signing_secret_env: Option<String>,
1398}
1399
1400/// Built-in webhook payload formats.
1401#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
1402#[serde(rename_all = "snake_case")]
1403pub enum DoctorWebhookFormat {
1404    /// Opinionated RCH JSON schema (default).
1405    #[default]
1406    GenericJson,
1407    /// Slack Block Kit payload.
1408    Slack,
1409    /// PagerDuty Events API v2 payload.
1410    Pagerduty,
1411}
1412
1413fn default_webhook_max_inflight() -> usize {
1414    16
1415}
1416
1417fn default_webhook_retry_max() -> u32 {
1418    3
1419}
1420
1421fn default_webhook_retry_backoff_ms() -> u64 {
1422    200
1423}
1424
1425fn default_webhook_timeout_ms() -> u64 {
1426    5000
1427}
1428
1429/// Worker health alerting configuration.
1430#[derive(Debug, Clone, Serialize, Deserialize)]
1431pub struct AlertsConfig {
1432    /// Enable or disable alert generation in the daemon.
1433    #[serde(default = "default_true")]
1434    pub enabled: bool,
1435    /// Suppress duplicate alerts for this many seconds.
1436    #[serde(default = "default_alert_suppress_duplicates_secs")]
1437    pub suppress_duplicates_secs: u64,
1438    /// How long to keep a cleared alert visible (with state
1439    /// `cleared_pending_clean`) before removing it entirely. Prevents
1440    /// transient, self-healing circuit-breaker warnings from lingering on
1441    /// `rch status` long after the fleet returned to healthy (bd-3ogaz).
1442    #[serde(default = "default_alert_cleared_retention_secs")]
1443    pub cleared_retention_secs: u64,
1444    /// Webhook configuration for external notifications.
1445    #[serde(default)]
1446    pub webhook: Option<WebhookConfig>,
1447}
1448
1449/// Webhook configuration for alert dispatch.
1450#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1451pub struct WebhookConfig {
1452    /// Webhook endpoint URL (e.g., Slack/Discord webhook URL).
1453    pub url: Option<String>,
1454    /// Secret for HMAC-SHA256 signing (optional).
1455    #[serde(default)]
1456    pub secret: Option<String>,
1457    /// Timeout in seconds for webhook requests.
1458    #[serde(default = "default_webhook_timeout_secs")]
1459    pub timeout_secs: u64,
1460    /// Number of retries on failure.
1461    #[serde(default = "default_webhook_retry_count")]
1462    pub retry_count: u32,
1463    /// Events to send (empty = all events).
1464    /// Supported: worker_offline, worker_degraded, circuit_open, all_workers_offline
1465    #[serde(default)]
1466    pub events: Vec<String>,
1467}
1468
1469fn default_webhook_timeout_secs() -> u64 {
1470    5
1471}
1472
1473fn default_webhook_retry_count() -> u32 {
1474    3
1475}
1476
1477fn default_alert_suppress_duplicates_secs() -> u64 {
1478    300
1479}
1480
1481fn default_alert_cleared_retention_secs() -> u64 {
1482    300
1483}
1484
1485impl Default for AlertsConfig {
1486    fn default() -> Self {
1487        Self {
1488            enabled: true,
1489            suppress_duplicates_secs: default_alert_suppress_duplicates_secs(),
1490            cleared_retention_secs: default_alert_cleared_retention_secs(),
1491            webhook: None,
1492        }
1493    }
1494}
1495
1496/// Fleet operation configuration.
1497///
1498/// Controls timeouts, thresholds, and behavior for fleet management commands
1499/// like `rch fleet preflight`, `rch fleet status`, and `rch fleet deploy`.
1500#[derive(Debug, Clone, Serialize, Deserialize)]
1501pub struct FleetConfig {
1502    /// SSH connection timeout in seconds.
1503    #[serde(default = "default_fleet_ssh_connect_timeout_secs")]
1504    pub ssh_connect_timeout_secs: u64,
1505    /// SSH command execution timeout in seconds.
1506    #[serde(default = "default_fleet_ssh_command_timeout_secs")]
1507    pub ssh_command_timeout_secs: u64,
1508    /// Minimum required disk space in MB for worker health.
1509    #[serde(default = "default_fleet_min_disk_space_mb")]
1510    pub min_disk_space_mb: u64,
1511    /// Maximum acceptable load average for worker health.
1512    #[serde(default = "default_fleet_max_load_average")]
1513    pub max_load_average: f64,
1514    /// Maximum number of concurrent SSH connections.
1515    #[serde(default = "default_fleet_max_concurrent_workers")]
1516    pub max_concurrent_workers: usize,
1517    /// Number of retry attempts for transient failures.
1518    #[serde(default = "default_fleet_retry_count")]
1519    pub retry_count: u32,
1520    /// Delay between retries in milliseconds.
1521    #[serde(default = "default_fleet_retry_delay_ms")]
1522    pub retry_delay_ms: u64,
1523}
1524
1525fn default_fleet_ssh_connect_timeout_secs() -> u64 {
1526    10
1527}
1528
1529fn default_fleet_ssh_command_timeout_secs() -> u64 {
1530    30
1531}
1532
1533fn default_fleet_min_disk_space_mb() -> u64 {
1534    500
1535}
1536
1537fn default_fleet_max_load_average() -> f64 {
1538    10.0
1539}
1540
1541fn default_fleet_max_concurrent_workers() -> usize {
1542    10
1543}
1544
1545fn default_fleet_retry_count() -> u32 {
1546    2
1547}
1548
1549fn default_fleet_retry_delay_ms() -> u64 {
1550    1000
1551}
1552
1553impl Default for FleetConfig {
1554    fn default() -> Self {
1555        Self {
1556            ssh_connect_timeout_secs: default_fleet_ssh_connect_timeout_secs(),
1557            ssh_command_timeout_secs: default_fleet_ssh_command_timeout_secs(),
1558            min_disk_space_mb: default_fleet_min_disk_space_mb(),
1559            max_load_average: default_fleet_max_load_average(),
1560            max_concurrent_workers: default_fleet_max_concurrent_workers(),
1561            retry_count: default_fleet_retry_count(),
1562            retry_delay_ms: default_fleet_retry_delay_ms(),
1563        }
1564    }
1565}
1566
1567impl FleetConfig {
1568    /// Get SSH connect timeout as Duration.
1569    pub fn ssh_connect_timeout(&self) -> std::time::Duration {
1570        std::time::Duration::from_secs(self.ssh_connect_timeout_secs)
1571    }
1572
1573    /// Get SSH command timeout as Duration.
1574    pub fn ssh_command_timeout(&self) -> std::time::Duration {
1575        std::time::Duration::from_secs(self.ssh_command_timeout_secs)
1576    }
1577
1578    /// Get retry delay as Duration.
1579    pub fn retry_delay(&self) -> std::time::Duration {
1580        std::time::Duration::from_millis(self.retry_delay_ms)
1581    }
1582}
1583
1584/// Box-level role (bd-wywsj): what this MACHINE is for, so "never
1585/// build locally" is configuration rather than a per-call env var.
1586#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
1587#[serde(rename_all = "lowercase")]
1588pub enum BoxRole {
1589    /// Orchestrator box: offloadable builds default FAIL-CLOSED +
1590    /// queue (RCH_REQUIRE_REMOTE semantics) — a saturated fleet waits
1591    /// for a worker instead of repopulating local rustc. Explicit
1592    /// per-call env still overrides.
1593    Dispatcher,
1594    /// The box IS the compute: fail-open/local; `rch shim install`
1595    /// refuses here.
1596    Worker,
1597    /// Today's behavior (fully backward compatible).
1598    #[default]
1599    Hybrid,
1600}
1601
1602impl BoxRole {
1603    /// Stable lowercase token.
1604    #[must_use]
1605    pub fn as_str(self) -> &'static str {
1606        match self {
1607            BoxRole::Dispatcher => "dispatcher",
1608            BoxRole::Worker => "worker",
1609            BoxRole::Hybrid => "hybrid",
1610        }
1611    }
1612}
1613
1614#[derive(Debug, Clone, Serialize, Deserialize)]
1615pub struct GeneralConfig {
1616    /// Whether RCH is enabled.
1617    #[serde(default = "default_true")]
1618    pub enabled: bool,
1619    /// Box-level role (bd-wywsj): dispatcher boxes default fail-closed
1620    /// + queue for offloadable builds; worker boxes are the compute.
1621    #[serde(default)]
1622    pub role: BoxRole,
1623    /// Force local execution for this project (never offload), even if the command is classified.
1624    ///
1625    /// Intended for sensitive projects or cases where local state must be authoritative.
1626    #[serde(default)]
1627    pub force_local: bool,
1628    /// Force remote execution for this project (always attempt offload) when safe.
1629    ///
1630    /// This bypasses heuristic gating (e.g. confidence threshold overrides) but still respects
1631    /// structural safety checks and NEVER_INTERCEPT patterns.
1632    #[serde(default)]
1633    pub force_remote: bool,
1634    /// Log level (trace, debug, info, warn, error).
1635    #[serde(default = "default_log_level")]
1636    pub log_level: String,
1637    /// Path to Unix socket for daemon communication.
1638    #[serde(default = "default_socket_path")]
1639    pub socket_path: String,
1640}
1641
1642/// Environment variable passthrough configuration.
1643#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1644pub struct EnvironmentConfig {
1645    /// Allowlist of environment variables to forward to remote workers.
1646    #[serde(default)]
1647    pub allowlist: Vec<String>,
1648}
1649
1650impl Default for GeneralConfig {
1651    fn default() -> Self {
1652        Self {
1653            enabled: true,
1654            role: BoxRole::default(),
1655            force_local: false,
1656            force_remote: false,
1657            log_level: "info".to_string(),
1658            socket_path: default_socket_path(),
1659        }
1660    }
1661}
1662
1663/// Visibility level for hook output.
1664#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default, JsonSchema)]
1665#[serde(rename_all = "lowercase")]
1666pub enum OutputVisibility {
1667    #[default]
1668    None,
1669    Summary,
1670    Verbose,
1671}
1672
1673impl std::fmt::Display for OutputVisibility {
1674    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1675        let value = match self {
1676            OutputVisibility::None => "none",
1677            OutputVisibility::Summary => "summary",
1678            OutputVisibility::Verbose => "verbose",
1679        };
1680        write!(f, "{}", value)
1681    }
1682}
1683
1684impl std::str::FromStr for OutputVisibility {
1685    type Err = ();
1686
1687    fn from_str(s: &str) -> Result<Self, Self::Err> {
1688        match s.trim().to_lowercase().as_str() {
1689            "none" | "silent" | "quiet" => Ok(Self::None),
1690            "summary" | "short" => Ok(Self::Summary),
1691            "verbose" | "debug" => Ok(Self::Verbose),
1692            _ => Err(()),
1693        }
1694    }
1695}
1696
1697/// Color mode for remote command output.
1698///
1699/// Controls whether ANSI color codes are preserved when streaming
1700/// output from remote compilation commands.
1701#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
1702#[serde(rename_all = "lowercase")]
1703pub enum ColorMode {
1704    /// Force color output regardless of terminal detection.
1705    /// Sets CARGO_TERM_COLOR=always and similar environment variables.
1706    #[default]
1707    Always,
1708    /// Let the remote command detect terminal capabilities (may lose colors).
1709    Auto,
1710    /// Disable color output entirely.
1711    Never,
1712}
1713
1714impl std::fmt::Display for ColorMode {
1715    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1716        let value = match self {
1717            ColorMode::Always => "always",
1718            ColorMode::Auto => "auto",
1719            ColorMode::Never => "never",
1720        };
1721        write!(f, "{}", value)
1722    }
1723}
1724
1725impl std::str::FromStr for ColorMode {
1726    type Err = ();
1727
1728    fn from_str(s: &str) -> Result<Self, Self::Err> {
1729        match s.trim().to_lowercase().as_str() {
1730            "always" | "force" | "yes" | "true" => Ok(Self::Always),
1731            "auto" | "detect" => Ok(Self::Auto),
1732            "never" | "none" | "no" | "false" => Ok(Self::Never),
1733            _ => Err(()),
1734        }
1735    }
1736}
1737
1738fn default_color_mode() -> ColorMode {
1739    ColorMode::default()
1740}
1741
1742/// Hook output configuration.
1743#[derive(Debug, Clone, Serialize, Deserialize)]
1744pub struct OutputConfig {
1745    /// Output visibility level for hook messages.
1746    #[serde(default = "default_output_visibility")]
1747    pub visibility: OutputVisibility,
1748    /// Whether the first-run success message has been shown.
1749    #[serde(default)]
1750    pub first_run_complete: bool,
1751    /// Color mode for remote command output.
1752    /// Controls whether ANSI color codes are preserved in remote output.
1753    #[serde(default = "default_color_mode")]
1754    pub color_mode: ColorMode,
1755}
1756
1757impl Default for OutputConfig {
1758    fn default() -> Self {
1759        Self {
1760            visibility: OutputVisibility::None,
1761            first_run_complete: false,
1762            color_mode: ColorMode::default(),
1763        }
1764    }
1765}
1766
1767// ============================================================================
1768// Self-Healing Configuration
1769// ============================================================================
1770
1771fn default_autostart_cooldown_secs() -> u64 {
1772    30
1773}
1774
1775fn default_autostart_timeout_secs() -> u64 {
1776    3
1777}
1778
1779/// Log level for self-healing diagnostic output.
1780///
1781/// Used to filter `tracing` events emitted by the self-healing subsystem
1782/// (hook auto-start, daemon hook-install). Read from
1783/// `RCH_SELF_HEALING_LOG_LEVEL=debug|info|warn|error` (case-insensitive).
1784#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq)]
1785#[serde(rename_all = "lowercase")]
1786pub enum SelfHealingLogLevel {
1787    Debug,
1788    #[default]
1789    Info,
1790    Warn,
1791    Error,
1792}
1793
1794impl SelfHealingLogLevel {
1795    /// Parse a human-friendly level name. Returns `None` for unknown input.
1796    pub fn from_env_str(s: &str) -> Option<Self> {
1797        match s.trim().to_ascii_lowercase().as_str() {
1798            "debug" => Some(Self::Debug),
1799            "info" => Some(Self::Info),
1800            "warn" | "warning" => Some(Self::Warn),
1801            "error" => Some(Self::Error),
1802            _ => None,
1803        }
1804    }
1805}
1806
1807/// Self-healing behaviors for the hook and daemon.
1808#[derive(Debug, Clone, Serialize, Deserialize)]
1809pub struct SelfHealingConfig {
1810    /// Whether the hook should attempt to auto-start the daemon.
1811    #[serde(default = "default_true")]
1812    pub hook_starts_daemon: bool,
1813    /// Whether the daemon should auto-install Claude Code hooks on startup.
1814    #[serde(default = "default_true")]
1815    pub daemon_installs_hooks: bool,
1816    /// Cooldown between auto-start attempts in seconds.
1817    #[serde(default = "default_autostart_cooldown_secs")]
1818    pub auto_start_cooldown_secs: u64,
1819    /// Time to wait for the daemon socket after spawning in seconds.
1820    /// Also aliased as `daemon_start_timeout` for backwards compatibility.
1821    #[serde(
1822        default = "default_autostart_timeout_secs",
1823        alias = "daemon_start_timeout"
1824    )]
1825    pub auto_start_timeout_secs: u64,
1826    /// Log level for self-healing diagnostic events. Default: info.
1827    /// Override via `RCH_SELF_HEALING_LOG_LEVEL=debug|info|warn|error`.
1828    #[serde(default)]
1829    pub self_healing_log_level: SelfHealingLogLevel,
1830}
1831
1832impl Default for SelfHealingConfig {
1833    fn default() -> Self {
1834        Self {
1835            hook_starts_daemon: default_true(),
1836            daemon_installs_hooks: default_true(),
1837            auto_start_cooldown_secs: default_autostart_cooldown_secs(),
1838            auto_start_timeout_secs: default_autostart_timeout_secs(),
1839            self_healing_log_level: SelfHealingLogLevel::default(),
1840        }
1841    }
1842}
1843
1844impl SelfHealingConfig {
1845    /// Apply environment variable overrides to this config.
1846    ///
1847    /// Supported environment variables:
1848    /// - `RCH_NO_SELF_HEALING=1` - Master switch to disable all self-healing
1849    /// - `RCH_HOOK_STARTS_DAEMON=0|1` - Control hook auto-starting daemon
1850    /// - `RCH_DAEMON_INSTALLS_HOOKS=0|1` - Control daemon auto-installing hooks
1851    /// - `RCH_AUTO_START_TIMEOUT_SECS=<seconds>` - Max wait for daemon start
1852    /// - `RCH_AUTO_START_COOLDOWN_SECS=<seconds>` - Min time between auto-starts
1853    pub fn with_env_overrides(mut self) -> Self {
1854        // Master disable switch
1855        if let Ok(val) = std::env::var("RCH_NO_SELF_HEALING")
1856            && (val == "1" || val.eq_ignore_ascii_case("true"))
1857        {
1858            self.hook_starts_daemon = false;
1859            self.daemon_installs_hooks = false;
1860            return self;
1861        }
1862
1863        // Individual toggles
1864        if let Ok(val) = std::env::var("RCH_HOOK_STARTS_DAEMON") {
1865            self.hook_starts_daemon = val != "0" && !val.eq_ignore_ascii_case("false");
1866        }
1867        if let Ok(val) = std::env::var("RCH_DAEMON_INSTALLS_HOOKS") {
1868            self.daemon_installs_hooks = val != "0" && !val.eq_ignore_ascii_case("false");
1869        }
1870
1871        // Numeric settings
1872        if let Ok(val) = std::env::var("RCH_AUTO_START_TIMEOUT_SECS")
1873            && let Ok(secs) = val.parse()
1874        {
1875            self.auto_start_timeout_secs = secs;
1876        }
1877        if let Ok(val) = std::env::var("RCH_AUTO_START_COOLDOWN_SECS")
1878            && let Ok(secs) = val.parse()
1879        {
1880            self.auto_start_cooldown_secs = secs;
1881        }
1882        // br-4zf3p: log-level override.
1883        if let Ok(val) = std::env::var("RCH_SELF_HEALING_LOG_LEVEL") {
1884            if let Some(level) = SelfHealingLogLevel::from_env_str(&val) {
1885                self.self_healing_log_level = level;
1886            } else {
1887                tracing::warn!(
1888                    target: "rch::self_healing",
1889                    invalid = %val,
1890                    "RCH_SELF_HEALING_LOG_LEVEL has invalid value; using default=info"
1891                );
1892            }
1893        }
1894
1895        self
1896    }
1897}
1898
1899// ============================================================================
1900// Self-Test Configuration
1901// ============================================================================
1902
1903/// Action to take when a scheduled self-test fails.
1904#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
1905#[serde(rename_all = "snake_case")]
1906pub enum SelfTestFailureAction {
1907    /// Only emit an alert/log entry.
1908    #[default]
1909    Alert,
1910    /// Disable the failing worker automatically.
1911    DisableWorker,
1912    /// Alert and disable the worker.
1913    AlertAndDisable,
1914}
1915
1916/// Which workers to include in self-test runs.
1917#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1918#[serde(untagged)]
1919pub enum SelfTestWorkers {
1920    /// Special value "all" (or a single worker id string).
1921    All(String),
1922    /// Explicit worker list.
1923    List(Vec<WorkerId>),
1924}
1925
1926impl Default for SelfTestWorkers {
1927    fn default() -> Self {
1928        Self::All("all".to_string())
1929    }
1930}
1931
1932impl SelfTestWorkers {
1933    /// Resolve to an explicit list if configured, or None to indicate "all".
1934    pub fn resolve(&self) -> Option<Vec<WorkerId>> {
1935        match self {
1936            SelfTestWorkers::All(value) => {
1937                if value.eq_ignore_ascii_case("all") {
1938                    None
1939                } else {
1940                    Some(vec![WorkerId::new(value.clone())])
1941                }
1942            }
1943            SelfTestWorkers::List(list) => Some(list.clone()),
1944        }
1945    }
1946}
1947
1948fn default_self_test_retry_count() -> u32 {
1949    3
1950}
1951
1952fn default_self_test_retry_delay() -> String {
1953    "5m".to_string()
1954}
1955
1956fn default_self_test_enabled() -> bool {
1957    false
1958}
1959
1960/// Self-test scheduling and behavior configuration.
1961#[derive(Debug, Clone, Serialize, Deserialize)]
1962pub struct SelfTestConfig {
1963    /// Enable scheduled self-tests.
1964    #[serde(default = "default_self_test_enabled")]
1965    pub enabled: bool,
1966    /// Cron schedule (e.g., "0 3 * * *").
1967    #[serde(default)]
1968    pub schedule: Option<String>,
1969    /// Interval duration (e.g., "24h").
1970    #[serde(default)]
1971    pub interval: Option<String>,
1972    /// Which workers to test (default: "all").
1973    #[serde(default)]
1974    pub workers: SelfTestWorkers,
1975    /// Action on failure.
1976    #[serde(default)]
1977    pub on_failure: SelfTestFailureAction,
1978    /// Retry count for failed tests.
1979    #[serde(default = "default_self_test_retry_count")]
1980    pub retry_count: u32,
1981    /// Delay between retries.
1982    #[serde(default = "default_self_test_retry_delay")]
1983    pub retry_delay: String,
1984}
1985
1986impl Default for SelfTestConfig {
1987    fn default() -> Self {
1988        Self {
1989            enabled: default_self_test_enabled(),
1990            schedule: None,
1991            interval: None,
1992            workers: SelfTestWorkers::default(),
1993            on_failure: SelfTestFailureAction::default(),
1994            retry_count: default_self_test_retry_count(),
1995            retry_delay: default_self_test_retry_delay(),
1996        }
1997    }
1998}
1999
2000/// Circuit breaker configuration.
2001#[derive(Debug, Clone, Serialize, Deserialize)]
2002pub struct CircuitBreakerConfig {
2003    /// Consecutive failures to open circuit.
2004    #[serde(default = "default_circuit_failure_threshold")]
2005    pub failure_threshold: u32,
2006    /// Consecutive successes to close circuit.
2007    #[serde(default = "default_circuit_success_threshold")]
2008    pub success_threshold: u32,
2009    /// Error rate threshold (0.0-1.0) to open circuit.
2010    #[serde(default = "default_circuit_error_rate_threshold")]
2011    pub error_rate_threshold: f64,
2012    /// Rolling window size in seconds.
2013    #[serde(default = "default_circuit_window_secs")]
2014    pub window_secs: u64,
2015    /// Cooldown duration before half-open (seconds).
2016    #[serde(default = "default_circuit_open_cooldown_secs")]
2017    pub open_cooldown_secs: u64,
2018    /// Max concurrent probes in half-open.
2019    #[serde(default = "default_circuit_half_open_max_probes")]
2020    pub half_open_max_probes: u32,
2021    /// Consecutive *command-class* failures to open the circuit.
2022    ///
2023    /// Command-class evidence is an operation of the same shape as dispatched
2024    /// work — a remote binary that must run to completion (the telemetry poll,
2025    /// or a health probe whose session connected but whose command never
2026    /// finished). It is tracked separately from the plain liveness probe
2027    /// because a host under fork exhaustion or swap thrash keeps answering
2028    /// `echo` over a warm connection while every real command times out;
2029    /// interleaved liveness successes would otherwise keep resetting
2030    /// `failure_threshold` and the breaker would never trip.
2031    #[serde(default = "default_circuit_command_failure_threshold")]
2032    pub command_failure_threshold: u32,
2033    /// Upper bound (seconds) for the open cooldown after repeated reopens.
2034    ///
2035    /// Each Open -> HalfOpen -> Open cycle without an intervening Closed
2036    /// doubles the cooldown (`open_cooldown_secs`, x2, x4, ...) up to this
2037    /// cap, so a flapping worker converges to Open instead of being
2038    /// re-admitted every cooldown. Set equal to `open_cooldown_secs` to
2039    /// disable the backoff.
2040    #[serde(default = "default_circuit_open_cooldown_max_secs")]
2041    pub open_cooldown_max_secs: u64,
2042}
2043
2044impl Default for CircuitBreakerConfig {
2045    fn default() -> Self {
2046        Self {
2047            failure_threshold: default_circuit_failure_threshold(),
2048            success_threshold: default_circuit_success_threshold(),
2049            error_rate_threshold: default_circuit_error_rate_threshold(),
2050            window_secs: default_circuit_window_secs(),
2051            open_cooldown_secs: default_circuit_open_cooldown_secs(),
2052            half_open_max_probes: default_circuit_half_open_max_probes(),
2053            command_failure_threshold: default_circuit_command_failure_threshold(),
2054            open_cooldown_max_secs: default_circuit_open_cooldown_max_secs(),
2055        }
2056    }
2057}
2058
2059impl CircuitBreakerConfig {
2060    /// Effective cooldown (ms) for the given reopen streak, with exponential
2061    /// backoff capped at `open_cooldown_max_secs`. `reopen_streak` counts
2062    /// Open transitions since the circuit last closed (1 = first open).
2063    pub fn cooldown_ms_for_streak(&self, reopen_streak: u32) -> u64 {
2064        let base_ms = self.open_cooldown_secs.saturating_mul(1000);
2065        let cap_ms = self
2066            .open_cooldown_max_secs
2067            .saturating_mul(1000)
2068            .max(base_ms);
2069        // Exponent bounded so the shift cannot overflow; the cap clamps anyway.
2070        let exponent = reopen_streak.saturating_sub(1).min(16);
2071        base_ms.saturating_mul(1u64 << exponent).min(cap_ms)
2072    }
2073}
2074
2075/// Circuit breaker statistics for tracking state transitions.
2076///
2077/// Maintains a rolling window of successes and failures to determine
2078/// when the circuit should open, close, or enter half-open state.
2079#[derive(Debug, Clone, Default)]
2080pub struct CircuitStats {
2081    /// Current circuit state.
2082    state: CircuitState,
2083    /// Consecutive failure count (reset on success).
2084    consecutive_failures: u32,
2085    /// Consecutive success count in half-open state (reset on failure).
2086    consecutive_successes: u32,
2087    /// Total successes in the current rolling window.
2088    window_successes: u32,
2089    /// Total failures in the current rolling window.
2090    window_failures: u32,
2091    /// Timestamp when circuit entered Open state (epoch millis).
2092    opened_at: Option<u64>,
2093    /// Timestamp of last state change (epoch millis).
2094    last_state_change: u64,
2095    /// Current active probes in half-open state.
2096    active_probes: u32,
2097    /// Consecutive command-class failures (telemetry poll exhaustion, probe
2098    /// sessions that connected but never completed). Reset only by a
2099    /// command-class success or a circuit close — NOT by a liveness success,
2100    /// which is the whole point (see `CircuitBreakerConfig::command_failure_threshold`).
2101    consecutive_command_failures: u32,
2102    /// Number of Open transitions since the circuit last closed. Drives the
2103    /// cooldown backoff; 0 while Closed-since-recovery.
2104    reopen_streak: u32,
2105    /// Recent health check results (true=success, false=failure).
2106    /// Used for history visualization in status display.
2107    recent_results: Vec<bool>,
2108}
2109
2110/// Maximum number of recent results to keep for history visualization.
2111const CIRCUIT_HISTORY_SIZE: usize = 10;
2112
2113impl CircuitStats {
2114    /// Create new circuit stats in the closed state.
2115    pub fn new() -> Self {
2116        Self {
2117            state: CircuitState::Closed,
2118            consecutive_failures: 0,
2119            consecutive_successes: 0,
2120            window_successes: 0,
2121            window_failures: 0,
2122            opened_at: None,
2123            last_state_change: Self::now_millis(),
2124            active_probes: 0,
2125            consecutive_command_failures: 0,
2126            reopen_streak: 0,
2127            recent_results: Vec::with_capacity(CIRCUIT_HISTORY_SIZE),
2128        }
2129    }
2130
2131    /// Consecutive command-class failures observed since the last
2132    /// command-class success (or circuit close).
2133    pub fn consecutive_command_failures(&self) -> u32 {
2134        self.consecutive_command_failures
2135    }
2136
2137    /// Open transitions since the circuit last closed (0 when it has not
2138    /// opened since recovery). Exposed for diagnostics.
2139    pub fn reopen_streak(&self) -> u32 {
2140        self.reopen_streak
2141    }
2142
2143    /// Cooldown currently in force (ms), including reopen backoff.
2144    fn effective_cooldown_ms(&self, config: &CircuitBreakerConfig) -> u64 {
2145        config.cooldown_ms_for_streak(self.reopen_streak.max(1))
2146    }
2147
2148    /// Get the current circuit state.
2149    pub fn state(&self) -> CircuitState {
2150        self.state
2151    }
2152
2153    /// Get the timestamp when the circuit opened (if open).
2154    pub fn opened_at(&self) -> Option<u64> {
2155        self.opened_at
2156    }
2157
2158    /// Get the timestamp of the last state change.
2159    pub fn last_state_change(&self) -> u64 {
2160        self.last_state_change
2161    }
2162
2163    /// Get the consecutive failure count.
2164    pub fn consecutive_failures(&self) -> u32 {
2165        self.consecutive_failures
2166    }
2167
2168    /// Get the error rate in the current window (0.0-1.0).
2169    ///
2170    /// Computed over the bounded recent-results window (the last
2171    /// `CIRCUIT_HISTORY_SIZE` health checks) rather than the unbounded lifetime
2172    /// `window_successes`/`window_failures` counters. A long-lived daemon polling
2173    /// distant workers accumulates occasional transient failures over days; with a
2174    /// lifetime ratio a currently-healthy worker could stay gated (circuit kept
2175    /// open, depressed health score) until the daemon was restarted. A recency
2176    /// window lets the rate self-heal as fresh successes age out old failures.
2177    pub fn error_rate(&self) -> f64 {
2178        if self.recent_results.is_empty() {
2179            return 0.0;
2180        }
2181        let failures = self.recent_results.iter().filter(|&&ok| !ok).count();
2182        failures as f64 / self.recent_results.len() as f64
2183    }
2184
2185    /// Record a successful operation.
2186    ///
2187    /// In closed state: resets consecutive failures, increments window successes.
2188    /// In half-open state: increments consecutive successes.
2189    pub fn record_success(&mut self) {
2190        self.window_successes += 1;
2191        self.consecutive_failures = 0;
2192        self.push_result(true);
2193
2194        if self.state == CircuitState::HalfOpen {
2195            self.consecutive_successes += 1;
2196            if self.active_probes > 0 {
2197                self.active_probes -= 1;
2198            }
2199        }
2200    }
2201
2202    /// Record a failed operation.
2203    ///
2204    /// Increments consecutive failures and window failures.
2205    /// In half-open state, resets consecutive successes.
2206    pub fn record_failure(&mut self) {
2207        self.window_failures += 1;
2208        self.consecutive_failures += 1;
2209        self.push_result(false);
2210
2211        if self.state == CircuitState::HalfOpen {
2212            self.consecutive_successes = 0;
2213            if self.active_probes > 0 {
2214                self.active_probes -= 1;
2215            }
2216        }
2217    }
2218
2219    /// Check if the circuit should open based on config thresholds.
2220    ///
2221    /// Returns true if:
2222    /// - Consecutive failures exceed threshold, OR
2223    /// - Error rate exceeds threshold (with minimum sample size)
2224    pub fn should_open(&self, config: &CircuitBreakerConfig) -> bool {
2225        if self.state != CircuitState::Closed {
2226            return false;
2227        }
2228
2229        // Open if consecutive failures exceed threshold
2230        if self.consecutive_failures >= config.failure_threshold {
2231            return true;
2232        }
2233
2234        // Open if error rate exceeds threshold (with a minimum sample size).
2235        // Counts samples in the bounded recent-results window so the gate
2236        // reflects recent behavior, matching error_rate() above.
2237        if self.recent_results.len() >= 5 && self.error_rate() >= config.error_rate_threshold {
2238            return true;
2239        }
2240
2241        false
2242    }
2243
2244    /// Check if the circuit should transition to half-open.
2245    ///
2246    /// Returns true if the circuit is open and the cooldown period has elapsed.
2247    pub fn should_half_open(&self, config: &CircuitBreakerConfig) -> bool {
2248        if self.state != CircuitState::Open {
2249            return false;
2250        }
2251
2252        let now = Self::now_millis();
2253        let cooldown_ms = self.effective_cooldown_ms(config);
2254
2255        if let Some(opened_at) = self.opened_at {
2256            now.saturating_sub(opened_at) >= cooldown_ms
2257        } else {
2258            false
2259        }
2260    }
2261
2262    /// Check if the circuit should close.
2263    ///
2264    /// Returns true if in half-open state, consecutive successes meet or
2265    /// exceed the success threshold, AND no command-class failure is
2266    /// outstanding. A worker whose last real command timed out is not
2267    /// recovered no matter how many liveness probes it answers; it stays
2268    /// HalfOpen (degraded, probe-limited) until a command-class success
2269    /// clears the evidence.
2270    pub fn should_close(&self, config: &CircuitBreakerConfig) -> bool {
2271        if self.state != CircuitState::HalfOpen {
2272            return false;
2273        }
2274
2275        self.consecutive_successes >= config.success_threshold
2276            && self.consecutive_command_failures == 0
2277    }
2278
2279    /// Check if a probe request can be made in half-open state.
2280    ///
2281    /// Returns true if active probes are below the maximum allowed.
2282    pub fn can_probe(&self, config: &CircuitBreakerConfig) -> bool {
2283        if self.state != CircuitState::HalfOpen {
2284            return false;
2285        }
2286
2287        self.active_probes < config.half_open_max_probes
2288    }
2289
2290    /// Start a probe request in half-open state.
2291    ///
2292    /// Returns true if the probe was started, false if already at max probes.
2293    pub fn start_probe(&mut self, config: &CircuitBreakerConfig) -> bool {
2294        if !self.can_probe(config) {
2295            return false;
2296        }
2297        self.active_probes += 1;
2298        true
2299    }
2300
2301    /// Transition the circuit to open state.
2302    pub fn open(&mut self) {
2303        if self.state != CircuitState::Open {
2304            self.state = CircuitState::Open;
2305            self.opened_at = Some(Self::now_millis());
2306            self.last_state_change = Self::now_millis();
2307            self.consecutive_successes = 0;
2308            self.active_probes = 0;
2309            // Every open without an intervening close lengthens the next
2310            // cooldown (see `CircuitBreakerConfig::cooldown_ms_for_streak`).
2311            self.reopen_streak = self.reopen_streak.saturating_add(1);
2312        }
2313    }
2314
2315    /// Transition the circuit to half-open state.
2316    pub fn half_open(&mut self) {
2317        if self.state != CircuitState::HalfOpen {
2318            self.state = CircuitState::HalfOpen;
2319            self.last_state_change = Self::now_millis();
2320            self.consecutive_successes = 0;
2321            self.active_probes = 0;
2322        }
2323    }
2324
2325    /// Transition the circuit to closed state.
2326    pub fn close(&mut self) {
2327        if self.state != CircuitState::Closed {
2328            self.state = CircuitState::Closed;
2329            self.last_state_change = Self::now_millis();
2330            self.opened_at = None;
2331            self.consecutive_failures = 0;
2332            self.consecutive_successes = 0;
2333            self.active_probes = 0;
2334            self.consecutive_command_failures = 0;
2335            self.reopen_streak = 0;
2336            // Reset the window on close, INCLUDING the recent-results history
2337            // that error_rate() now reads. Otherwise a freshly-recovered circuit
2338            // would still compute a high error rate from the pre-failure samples
2339            // and immediately re-open (flapping). Matches the original intent of
2340            // resetting the error-rate inputs when the circuit recovers.
2341            self.window_successes = 0;
2342            self.window_failures = 0;
2343            self.recent_results.clear();
2344        }
2345    }
2346
2347    /// Reset the rolling window counters.
2348    ///
2349    /// Called periodically to ensure the window reflects recent activity.
2350    /// Also clears the recent-results history that `error_rate()` is computed
2351    /// from, so a reset truly zeroes the observed error rate.
2352    pub fn reset_window(&mut self) {
2353        self.window_successes = 0;
2354        self.window_failures = 0;
2355        self.recent_results.clear();
2356    }
2357
2358    /// Get recent health check results for history visualization.
2359    ///
2360    /// Returns a slice of recent results (true=success, false=failure),
2361    /// with the most recent result at the end.
2362    pub fn recent_results(&self) -> &[bool] {
2363        &self.recent_results
2364    }
2365
2366    /// Calculate seconds remaining until circuit auto-transitions to half-open.
2367    ///
2368    /// Returns None if circuit is not open or cooldown has already elapsed.
2369    pub fn recovery_remaining_secs(&self, config: &CircuitBreakerConfig) -> Option<u64> {
2370        if self.state != CircuitState::Open {
2371            return None;
2372        }
2373
2374        let now = Self::now_millis();
2375        let cooldown_ms = self.effective_cooldown_ms(config);
2376
2377        if let Some(opened_at) = self.opened_at {
2378            let elapsed_ms = now.saturating_sub(opened_at);
2379            if elapsed_ms < cooldown_ms {
2380                return Some((cooldown_ms - elapsed_ms) / 1000);
2381            }
2382        }
2383        None
2384    }
2385
2386    /// Push a result to the history, maintaining the maximum size.
2387    fn push_result(&mut self, success: bool) {
2388        if self.recent_results.len() >= CIRCUIT_HISTORY_SIZE {
2389            self.recent_results.remove(0);
2390        }
2391        self.recent_results.push(success);
2392    }
2393
2394    fn now_millis() -> u64 {
2395        std::time::SystemTime::now()
2396            .duration_since(std::time::UNIX_EPOCH)
2397            .map(|d| d.as_millis() as u64)
2398            .unwrap_or(0)
2399    }
2400
2401    /// Drive the circuit through a single health-check outcome and return the
2402    /// resulting [`CircuitState`].
2403    ///
2404    /// This is the single, self-contained transition engine shared by every
2405    /// circuit consumer (the daemon health monitor via
2406    /// `WorkerState::record_health_check`, and the diagnostic `WorkerHealth`
2407    /// panel via `WorkerHealth::observe`). Keeping the transition logic in ONE
2408    /// place is what makes `WorkerState.circuit` (which selection reads) and the
2409    /// diagnostic `WorkerHealth.circuit` agree.
2410    ///
2411    /// Behaviour:
2412    /// - On a **healthy** outcome: if the circuit is Open and its cooldown has
2413    ///   elapsed it first transitions Open → HalfOpen *before* crediting the
2414    ///   success, so recovery needs exactly `success_threshold` clean probes
2415    ///   (crediting a success against an Open circuit would be lost). Then the
2416    ///   success is recorded and the circuit closes once the threshold is met.
2417    /// - On an **unhealthy** outcome: the failure is recorded, the circuit opens
2418    ///   if the closed-state open condition is met, and a HalfOpen probe failure
2419    ///   reopens the circuit — UNLESS the failure was `transient` (a retryable
2420    ///   transport blip that survived the in-check retries). A transient
2421    ///   half-open failure neither reopens nor resets the cooldown, so a single
2422    ///   network hiccup during recovery cannot bounce a worker back to Open.
2423    /// - After either branch, an Open circuit past its cooldown is nudged to
2424    ///   HalfOpen so probing resumes on the next poll even for a still-failing
2425    ///   worker.
2426    pub fn apply_health_outcome(
2427        &mut self,
2428        healthy: bool,
2429        transient: bool,
2430        config: &CircuitBreakerConfig,
2431    ) -> CircuitState {
2432        if healthy {
2433            // Transition to half-open BEFORE crediting the success so the probe
2434            // counts toward recovery. record_success() only increments the
2435            // consecutive-success counter while in HalfOpen.
2436            if self.state == CircuitState::Open && self.should_half_open(config) {
2437                self.half_open();
2438            }
2439            self.record_success();
2440            if self.should_close(config) {
2441                self.close();
2442            }
2443        } else {
2444            let was_half_open = self.state == CircuitState::HalfOpen;
2445            self.record_failure();
2446            if self.should_open(config) {
2447                self.open();
2448            } else if was_half_open && !transient {
2449                // A real (non-transient) probe failure in half-open reopens the
2450                // circuit and restarts the cooldown. A transient failure is
2451                // ignored so a network blip can't undo an in-progress recovery.
2452                self.open();
2453            }
2454        }
2455
2456        // Even for a still-failing worker, resume probing once the cooldown
2457        // elapses so a recovered worker is retried promptly.
2458        if self.state == CircuitState::Open && self.should_half_open(config) {
2459            self.half_open();
2460        }
2461
2462        self.state
2463    }
2464
2465    /// Drive the circuit through a single *command-class* outcome and return
2466    /// the resulting [`CircuitState`].
2467    ///
2468    /// Command-class evidence comes from an operation of the same shape as
2469    /// dispatched work: a remote binary that must run to completion (the
2470    /// telemetry poll, or a health probe whose SSH session connected but whose
2471    /// command never finished). It is the signal the plain liveness probe
2472    /// cannot provide — a host under fork exhaustion or swap thrash keeps
2473    /// answering `echo` over a warm connection while every real command hangs,
2474    /// and on that evidence alone the breaker would happily re-admit it.
2475    ///
2476    /// Behaviour:
2477    /// - **Success**: clears the outstanding command-failure count and then
2478    ///   counts as an ordinary healthy outcome (may advance Open -> HalfOpen ->
2479    ///   Closed exactly like a liveness success).
2480    /// - **Failure**: increments the command-failure count and records a plain
2481    ///   failure. The circuit opens when either the ordinary open condition or
2482    ///   `command_failure_threshold` is met. In HalfOpen a command failure
2483    ///   ALWAYS reopens — there is no transient exemption, because "connected
2484    ///   but the command did not complete" is precisely the condition the
2485    ///   half-open trial exists to detect. While any command failure is
2486    ///   outstanding, [`Self::should_close`] refuses to close on liveness
2487    ///   successes alone.
2488    pub fn apply_command_outcome(
2489        &mut self,
2490        success: bool,
2491        config: &CircuitBreakerConfig,
2492    ) -> CircuitState {
2493        if success {
2494            self.consecutive_command_failures = 0;
2495            return self.apply_health_outcome(true, false, config);
2496        }
2497
2498        self.consecutive_command_failures = self.consecutive_command_failures.saturating_add(1);
2499        let was_half_open = self.state == CircuitState::HalfOpen;
2500        self.record_failure();
2501        let threshold = config.command_failure_threshold.max(1);
2502        if was_half_open
2503            || self.should_open(config)
2504            || (self.state == CircuitState::Closed
2505                && self.consecutive_command_failures >= threshold)
2506        {
2507            self.open();
2508        }
2509
2510        if self.state == CircuitState::Open && self.should_half_open(config) {
2511            self.half_open();
2512        }
2513
2514        self.state
2515    }
2516}
2517
2518#[derive(Debug, Clone, Serialize, Deserialize)]
2519pub struct CompilationConfig {
2520    /// Minimum confidence score to intercept (0.0-1.0).
2521    #[serde(default = "default_confidence")]
2522    pub confidence_threshold: f64,
2523    /// Skip interception if estimated local time < this (ms).
2524    #[serde(default = "default_min_local_time")]
2525    pub min_local_time_ms: u64,
2526    /// Minimum expected speedup ratio (local_time / remote_time) to offload.
2527    /// If predicted speedup < threshold, run locally. Default: 1.2 (20% faster).
2528    /// Set to 1.0 to always offload when other criteria are met.
2529    #[serde(default = "default_speedup_threshold")]
2530    pub remote_speedup_threshold: f64,
2531    /// Default slot estimate for build commands (cargo build, gcc, etc.).
2532    #[serde(default = "default_build_slots")]
2533    pub build_slots: u32,
2534    /// Default slot estimate for test commands (cargo test, nextest).
2535    /// Tests typically use more parallelism than builds.
2536    #[serde(default = "default_test_slots")]
2537    pub test_slots: u32,
2538    /// Default slot estimate for check/lint commands (cargo check, clippy).
2539    /// These are typically faster and use fewer resources.
2540    #[serde(default = "default_check_slots")]
2541    pub check_slots: u32,
2542    /// Per-build additional free-space budget on the worker's reported build
2543    /// filesystem, in GiB. Include expected output growth and a safety margin.
2544    /// Zero (default) disables this explicit budget. Positive budgets require
2545    /// a fresh disk observation and are held in durable daemon ownership until
2546    /// completion. They are admission accounting, not filesystem quotas.
2547    #[serde(default)]
2548    pub disk_headroom_gib: u32,
2549    /// Timeout in seconds for build commands.
2550    /// Build commands (cargo build, gcc, etc.) typically complete faster than tests.
2551    #[serde(default = "default_build_timeout")]
2552    pub build_timeout_sec: u64,
2553    /// Timeout in seconds for test commands.
2554    /// Test commands often need longer timeouts due to test suite execution time.
2555    #[serde(default = "default_test_timeout")]
2556    pub test_timeout_sec: u64,
2557    /// Timeout in seconds for bun commands (bun test, bun typecheck).
2558    /// Bun has known issues where its internal --timeout flag doesn't work for
2559    /// CPU-bound hangs, so we use a shorter external timeout by default.
2560    #[serde(default = "default_bun_timeout")]
2561    pub bun_timeout_sec: u64,
2562    /// Whether to wrap remote commands with external timeout protection.
2563    /// This prevents runaway/stuck processes from consuming worker slots indefinitely.
2564    /// Default: true. Set to false to disable timeout wrapping entirely.
2565    #[serde(default = "default_external_timeout_enabled")]
2566    pub external_timeout_enabled: bool,
2567    /// Whether a remote build FAILURE may fall back to LOCAL execution on the
2568    /// orchestrator once every eligible remote worker has been exhausted.
2569    ///
2570    /// On a remote failure the hook first retries the build on a *different,
2571    /// higher-capacity* worker (see `run_exec`'s worker-fallback loop). Local
2572    /// execution runs the heavy compile on the orchestrator that coordinates the
2573    /// whole fleet, so it is a genuine last resort and can flood that box. This
2574    /// flag gates it. Default `true` preserves the historical fail-open behavior
2575    /// (local only when no worker can serve); set to `false` on an orchestrator
2576    /// to refuse local fallback and fail the build closed instead. `force_remote`
2577    /// / proof mode / `RCH_REQUIRE_REMOTE` still override this by refusing local
2578    /// unconditionally.
2579    #[serde(default = "default_allow_local_fallback")]
2580    pub allow_local_fallback: bool,
2581    /// Per-job rustc parallelism cap applied on the WORKER (issue #49).
2582    ///
2583    /// `total_slots` bounds concurrent *jobs* per worker, but cargo defaults
2584    /// `-j` to the worker's `nproc`, so one offloaded `cargo test --workspace`
2585    /// forks `nproc` rustc regardless of slots and can swap-thrash a
2586    /// RAM-light box. This policy injects `CARGO_BUILD_JOBS` into the remote
2587    /// build environment; see [`RemoteBuildJobs`] for the modes. It never
2588    /// overrides a `CARGO_BUILD_JOBS` the worker session already carries, an
2589    /// inline `CARGO_BUILD_JOBS=N` or `-j N` in the command, or a project
2590    /// `.cargo/config.toml` `[build] jobs` — explicit intent always wins.
2591    #[serde(default)]
2592    pub remote_build_jobs: RemoteBuildJobs,
2593}
2594
2595/// How rch derives the `CARGO_BUILD_JOBS` it injects into a remote build.
2596///
2597/// - `auto` (default): computed on the worker from its live `nproc` and
2598///   total RAM as `clamp(ram_gib / 8, 2, min(nproc, 8))` — budgeting roughly
2599///   8 GiB of RAM per concurrent rustc leaves headroom for two to three
2600///   concurrent jobs at a realistic per-rustc peak of ~3 GiB.
2601/// - `off`: inject nothing (historical behavior; cargo uses `nproc`).
2602/// - `<n>`: inject a fixed job count fleet-wide.
2603///
2604/// In every mode an explicitly set `CARGO_BUILD_JOBS` on the worker (for
2605/// example from `/etc/environment`) or in the command is left untouched.
2606#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2607pub enum RemoteBuildJobs {
2608    /// Derive from the worker's cores and RAM at execution time.
2609    #[default]
2610    Auto,
2611    /// Do not inject `CARGO_BUILD_JOBS`.
2612    Off,
2613    /// Inject a fixed job count (must be >= 1).
2614    Fixed(u32),
2615}
2616
2617impl RemoteBuildJobs {
2618    /// Parse the config/CLI spelling: `auto`, `off`, or a positive integer.
2619    pub fn parse(value: &str) -> Result<Self, String> {
2620        let trimmed = value.trim();
2621        match trimmed.to_ascii_lowercase().as_str() {
2622            "auto" => Ok(Self::Auto),
2623            "off" | "none" | "disabled" => Ok(Self::Off),
2624            _ => match trimmed.parse::<u32>() {
2625                Ok(0) => Err(
2626                    "remote_build_jobs must be >= 1 (cargo rejects `-j 0`); use `off` to disable"
2627                        .to_string(),
2628                ),
2629                Ok(n) => Ok(Self::Fixed(n)),
2630                Err(_) => Err(format!(
2631                    "'{trimmed}' is not a valid remote_build_jobs value (expected `auto`, `off`, or a positive integer)"
2632                )),
2633            },
2634        }
2635    }
2636}
2637
2638impl std::fmt::Display for RemoteBuildJobs {
2639    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2640        match self {
2641            Self::Auto => f.write_str("auto"),
2642            Self::Off => f.write_str("off"),
2643            Self::Fixed(n) => write!(f, "{n}"),
2644        }
2645    }
2646}
2647
2648impl std::str::FromStr for RemoteBuildJobs {
2649    type Err = String;
2650
2651    fn from_str(value: &str) -> Result<Self, Self::Err> {
2652        Self::parse(value)
2653    }
2654}
2655
2656impl Serialize for RemoteBuildJobs {
2657    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2658        match self {
2659            Self::Auto => serializer.serialize_str("auto"),
2660            Self::Off => serializer.serialize_str("off"),
2661            Self::Fixed(n) => serializer.serialize_u32(*n),
2662        }
2663    }
2664}
2665
2666impl<'de> Deserialize<'de> for RemoteBuildJobs {
2667    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2668        #[derive(Deserialize)]
2669        #[serde(untagged)]
2670        enum Raw {
2671            Count(u64),
2672            Spelling(String),
2673        }
2674        match Raw::deserialize(deserializer)? {
2675            Raw::Count(n) => {
2676                let n = u32::try_from(n).map_err(|_| {
2677                    serde::de::Error::custom(format!("remote_build_jobs {n} is out of range"))
2678                })?;
2679                Self::parse(&n.to_string()).map_err(serde::de::Error::custom)
2680            }
2681            Raw::Spelling(s) => Self::parse(&s).map_err(serde::de::Error::custom),
2682        }
2683    }
2684}
2685
2686impl Default for CompilationConfig {
2687    fn default() -> Self {
2688        Self {
2689            confidence_threshold: 0.85,
2690            min_local_time_ms: 2000,
2691            remote_speedup_threshold: default_speedup_threshold(),
2692            build_slots: default_build_slots(),
2693            test_slots: default_test_slots(),
2694            check_slots: default_check_slots(),
2695            disk_headroom_gib: 0,
2696            build_timeout_sec: default_build_timeout(),
2697            test_timeout_sec: default_test_timeout(),
2698            bun_timeout_sec: default_bun_timeout(),
2699            external_timeout_enabled: default_external_timeout_enabled(),
2700            allow_local_fallback: default_allow_local_fallback(),
2701            remote_build_jobs: RemoteBuildJobs::default(),
2702        }
2703    }
2704}
2705
2706fn default_build_slots() -> u32 {
2707    4
2708}
2709
2710fn default_test_slots() -> u32 {
2711    8
2712}
2713
2714fn default_check_slots() -> u32 {
2715    2
2716}
2717
2718/// Default build timeout: 5 minutes (300 seconds).
2719/// Most builds complete well within this time.
2720fn default_build_timeout() -> u64 {
2721    300
2722}
2723
2724/// Default test timeout: 30 minutes (1800 seconds).
2725/// Test suites often take significantly longer than builds.
2726fn default_test_timeout() -> u64 {
2727    1800
2728}
2729
2730/// Default bun timeout: 10 minutes (600 seconds).
2731/// Bun's internal --timeout flag doesn't work for CPU-bound hangs,
2732/// so we use a shorter external timeout to prevent zombies.
2733fn default_bun_timeout() -> u64 {
2734    600
2735}
2736
2737/// Default: external timeout protection is enabled.
2738fn default_external_timeout_enabled() -> bool {
2739    true
2740}
2741
2742/// Default: permit last-resort local fallback after remote workers are
2743/// exhausted. Set `compilation.allow_local_fallback = false` to fail closed and
2744/// keep heavy compiles off the orchestrator entirely.
2745fn default_allow_local_fallback() -> bool {
2746    true
2747}
2748
2749impl CompilationConfig {
2750    /// Returns the appropriate external timeout for the given compilation kind.
2751    ///
2752    /// - Bun commands get the shorter bun_timeout (to protect against known hang issues)
2753    /// - Test commands get the longer test_timeout
2754    /// - All other commands (builds, checks, clippy) get the build_timeout
2755    pub fn timeout_for_kind(&self, kind: Option<CompilationKind>) -> std::time::Duration {
2756        let secs = match kind {
2757            // Bun has known issues where internal timeout doesn't work for CPU hangs
2758            Some(CompilationKind::BunTest) | Some(CompilationKind::BunTypecheck) => {
2759                self.bun_timeout_sec
2760            }
2761            // Other test commands use the standard test timeout
2762            Some(CompilationKind::CargoTest) | Some(CompilationKind::CargoNextest) => {
2763                self.test_timeout_sec
2764            }
2765            // Nix derivation builds can take a long time (fetch + compile large
2766            // closures); give them the generous test-timeout bucket rather than
2767            // the short build timeout so legitimate builds are not killed early.
2768            Some(CompilationKind::NixBuild) => self.test_timeout_sec,
2769            // Go test suites are long-running like cargo test; give them the
2770            // test bucket rather than the short build timeout.
2771            Some(CompilationKind::GoTest) => self.test_timeout_sec,
2772            // Builds, checks, clippy, and unknown use build timeout
2773            _ => self.build_timeout_sec,
2774        };
2775        std::time::Duration::from_secs(secs)
2776    }
2777
2778    /// Returns whether external timeout wrapping is enabled.
2779    pub fn external_timeout_enabled(&self) -> bool {
2780        self.external_timeout_enabled
2781    }
2782}
2783
2784/// Version of the Layer 0 configuration pack schema (bd-bqu38 / M-1 §149).
2785///
2786/// Bump when a knob is added, removed, or its meaning changes; consumers
2787/// record the version alongside emitted baselines so regressions are
2788/// attributable to a specific pack revision.
2789pub const LAYER0_PACK_VERSION: &str = "1";
2790
2791/// Layer 0 configuration pack knobs (bd-bqu38).
2792///
2793/// Every knob defaults to OFF and toggles independently — the kill/rollback
2794/// contract from the master plan (§149: removed from defaults if it regresses
2795/// representative p95, output equivalence, debugger behavior, or
2796/// compatibility). Knobs are injected into remote cargo builds as
2797/// `CARGO_PROFILE_*` environment variables, so enabling one never mutates any
2798/// user-owned `.cargo/config.toml`.
2799#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
2800#[serde(default)]
2801pub struct Layer0Config {
2802    /// Master switch: nothing is injected unless this is on.
2803    pub enabled: bool,
2804    /// `profile.release.lto = "thin"` via `CARGO_PROFILE_RELEASE_LTO=thin`.
2805    pub release_lto_thin: bool,
2806    /// `profile.release.codegen-units = 1` via
2807    /// `CARGO_PROFILE_RELEASE_CODEGEN_UNITS=1`.
2808    pub release_codegen_units_1: bool,
2809}
2810
2811impl Layer0Config {
2812    /// Environment pairs to inject into a remote cargo build.
2813    ///
2814    /// Empty unless [`Self::enabled`] — the master switch gates every knob so
2815    /// an operator can disable the whole pack with one key. Order is stable
2816    /// (declaration order) for deterministic emission and test assertions.
2817    #[must_use]
2818    pub fn active_env(&self) -> Vec<(&'static str, &'static str)> {
2819        if !self.enabled {
2820            return Vec::new();
2821        }
2822        let mut env = Vec::new();
2823        if self.release_lto_thin {
2824            env.push(("CARGO_PROFILE_RELEASE_LTO", "thin"));
2825        }
2826        if self.release_codegen_units_1 {
2827            env.push(("CARGO_PROFILE_RELEASE_CODEGEN_UNITS", "1"));
2828        }
2829        env
2830    }
2831}
2832
2833#[derive(Debug, Clone, Serialize, Deserialize)]
2834pub struct TransferConfig {
2835    /// zstd compression level (1-19).
2836    #[serde(default = "default_compression")]
2837    pub compression_level: u32,
2838    /// Patterns to exclude from transfer.
2839    #[serde(default = "default_excludes")]
2840    pub exclude_patterns: Vec<String>,
2841    /// SSH keepalive interval in seconds (`ssh -o ServerAliveInterval=<N>`).
2842    ///
2843    /// When unset, build transfers use 15 seconds. Zero defers to OpenSSH configuration.
2844    #[serde(default, skip_serializing_if = "Option::is_none")]
2845    pub ssh_server_alive_interval_secs: Option<u64>,
2846    /// SSH ControlPersist idle timeout in seconds (`ssh -o ControlPersist=<N>s`).
2847    ///
2848    /// - Unset preserves OpenSSH defaults (ControlPersist enabled by default via mux).
2849    /// - `0` disables persistence (`ControlPersist=no`).
2850    #[serde(default, skip_serializing_if = "Option::is_none")]
2851    pub ssh_control_persist_secs: Option<u64>,
2852    /// Staging base on the worker for the transfer paths that do NOT mirror
2853    /// the client's project layout: `--clean-overlay` roots, Windows workers,
2854    /// and `rch cache warm`. Must be an absolute path; defaults to
2855    /// [`default_remote_base`] (`/data/tmp/rch`).
2856    ///
2857    /// An ordinary `rch exec` does not use this: it mirrors the project under
2858    /// the worker's canonical root (`[path_topology] canonical_root`), and the
2859    /// pooled Cargo target store rides along inside that mirror. To move
2860    /// pooled stores onto another filesystem, set
2861    /// `[remediation.pooled_target] store_base` (issue #64).
2862    #[serde(default = "default_remote_base")]
2863    pub remote_base: String,
2864    /// Per-attempt timeout for source synchronization, in milliseconds.
2865    ///
2866    /// This is deliberately separate from remote compilation and artifact-return
2867    /// timeouts. When unset, RCH derives a conservative timeout from the source
2868    /// payload size (30 seconds plus one second per MiB, capped at one hour).
2869    #[serde(default, skip_serializing_if = "Option::is_none")]
2870    pub sync_timeout_ms: Option<u64>,
2871    /// Silence-based stall timeout for source synchronization, in seconds
2872    /// (issue #59).
2873    ///
2874    /// Aborts a source sync when rsync emits NO output at all — no progress
2875    /// refresh, no stats, no itemized line — for this long. This is deliberately
2876    /// far tighter than the wall-clock `sync_timeout_ms` cap (which scales with
2877    /// payload size up to an hour): a large first-time sync keeps refreshing its
2878    /// progress line and is never killed, while a dead channel or wedged rsync
2879    /// is detected within this window instead of holding the reservation until
2880    /// the wall-clock cap. On a stall the hook releases the worker and re-enters
2881    /// selection excluding it. `0` disables silence detection.
2882    #[serde(default = "default_source_sync_silence_timeout_secs")]
2883    pub source_sync_silence_timeout_secs: u64,
2884    /// Retry policy for transient network errors during transfer.
2885    #[serde(default)]
2886    pub retry: RetryConfig,
2887    /// Verify artifact integrity using blake3 hashes after transfer (bd-377q).
2888    ///
2889    /// When enabled, computes blake3 hashes of key artifacts (binaries, test outputs)
2890    /// on the worker after build, then verifies them locally after download.
2891    /// Disabled by default to avoid extra overhead.
2892    #[serde(default)]
2893    pub verify_artifacts: bool,
2894    /// Maximum file size (bytes) for artifact verification (bd-377q).
2895    ///
2896    /// Files larger than this limit are skipped during verification to avoid
2897    /// excessive I/O. Defaults to 100MB.
2898    #[serde(default = "default_verify_max_size")]
2899    pub verify_max_size_bytes: u64,
2900
2901    // =========================================================================
2902    // Transfer Optimization (bd-3hho)
2903    // =========================================================================
2904    /// Maximum transfer size in MB before skipping remote execution.
2905    ///
2906    /// When set, runs `rsync --dry-run --stats` to estimate transfer size.
2907    /// If the estimated size exceeds this threshold, remote offload is skipped
2908    /// and the command runs locally. Set to `None` (default) to disable.
2909    #[serde(default, skip_serializing_if = "Option::is_none")]
2910    pub max_transfer_mb: Option<u64>,
2911
2912    /// Maximum estimated transfer time in milliseconds before skipping remote.
2913    ///
2914    /// Uses `estimated_bandwidth_bps` (or measured link speed) to calculate
2915    /// expected transfer time. If it exceeds this threshold, remote offload
2916    /// is skipped. Set to `None` (default) to disable.
2917    #[serde(default, skip_serializing_if = "Option::is_none")]
2918    pub max_transfer_time_ms: Option<u64>,
2919
2920    /// Bandwidth limit for rsync in KB/s.
2921    ///
2922    /// Passed as `rsync --bwlimit=<N>` to limit transfer speed and prevent
2923    /// network saturation. Set to `None` or `0` (default) for unlimited.
2924    #[serde(default, skip_serializing_if = "Option::is_none")]
2925    pub bwlimit_kbps: Option<u64>,
2926
2927    /// Explicit rsync binary for every local transfer (issue #66).
2928    ///
2929    /// Unset (the default) lets rch pick: the PATH `rsync` when it is a
2930    /// modern (3.1+) rsync, otherwise a modern rsync from the well-known
2931    /// Homebrew/MacPorts locations, otherwise the PATH binary driven with the
2932    /// openrsync/2.6.9-compatible argv. Set this to force one binary
2933    /// (`~` is expanded; a bare name is looked up on PATH). The
2934    /// `RCH_RSYNC_BIN` environment variable overrides this setting.
2935    #[serde(default, skip_serializing_if = "Option::is_none")]
2936    pub rsync_bin: Option<String>,
2937
2938    /// Estimated link bandwidth in bytes per second.
2939    ///
2940    /// Used for transfer time estimation when `max_transfer_time_ms` is set.
2941    /// If not provided, defaults to 10 MB/s (10485760 bytes/sec).
2942    #[serde(default, skip_serializing_if = "Option::is_none")]
2943    pub estimated_bandwidth_bps: Option<u64>,
2944
2945    // =========================================================================
2946    // Adaptive Compression (bd-243w)
2947    // =========================================================================
2948    /// Enable adaptive zstd compression based on transfer size (bd-243w).
2949    ///
2950    /// When enabled, automatically selects compression level based on estimated
2951    /// payload size:
2952    /// - < 10MB: level 1 (fast, minimal compression)
2953    /// - 10-200MB: level 3 (balanced, default)
2954    /// - > 200MB: level 7 (slower, better compression)
2955    ///
2956    /// When disabled (default), uses the fixed `compression_level` setting.
2957    #[serde(default)]
2958    pub adaptive_compression: bool,
2959
2960    /// Minimum compression level for adaptive mode (bd-243w).
2961    ///
2962    /// Even in adaptive mode, compression level won't go below this.
2963    /// Defaults to 1.
2964    #[serde(default = "default_min_compression")]
2965    pub min_compression_level: u32,
2966
2967    /// Maximum compression level for adaptive mode (bd-243w).
2968    ///
2969    /// Even in adaptive mode, compression level won't exceed this.
2970    /// Defaults to 9 (avoids CPU-intensive levels 10+).
2971    #[serde(default = "default_max_compression")]
2972    pub max_compression_level: u32,
2973}
2974
2975impl Default for TransferConfig {
2976    fn default() -> Self {
2977        Self {
2978            compression_level: 3,
2979            exclude_patterns: default_excludes(),
2980            ssh_server_alive_interval_secs: None,
2981            ssh_control_persist_secs: None,
2982            remote_base: default_remote_base(),
2983            sync_timeout_ms: None,
2984            source_sync_silence_timeout_secs: default_source_sync_silence_timeout_secs(),
2985            retry: RetryConfig::default(),
2986            verify_artifacts: false,
2987            verify_max_size_bytes: default_verify_max_size(),
2988            // Transfer optimization (bd-3hho)
2989            max_transfer_mb: None,
2990            max_transfer_time_ms: None,
2991            bwlimit_kbps: None,
2992            rsync_bin: None,
2993            estimated_bandwidth_bps: None,
2994            // Adaptive compression (bd-243w)
2995            adaptive_compression: false,
2996            min_compression_level: default_min_compression(),
2997            max_compression_level: default_max_compression(),
2998        }
2999    }
3000}
3001
3002impl TransferConfig {
3003    /// Smallest accepted explicit source-sync timeout (one second).
3004    pub const MIN_SYNC_TIMEOUT_MS: u64 = 1_000;
3005    /// Largest accepted explicit or derived source-sync timeout (one hour).
3006    pub const MAX_SYNC_TIMEOUT_MS: u64 = 3_600_000;
3007    /// Fixed floor used by the payload-aware default policy.
3008    pub const DEFAULT_SYNC_TIMEOUT_FLOOR_MS: u64 = 30_000;
3009    const DEFAULT_SYNC_BYTES_PER_SECOND: u64 = 1024 * 1024;
3010
3011    /// Whether an explicit source-sync timeout is within the supported range.
3012    #[must_use]
3013    pub fn valid_sync_timeout_ms(value: u64) -> bool {
3014        (Self::MIN_SYNC_TIMEOUT_MS..=Self::MAX_SYNC_TIMEOUT_MS).contains(&value)
3015    }
3016
3017    /// Resolve the per-attempt source-sync timeout for an exact payload size.
3018    ///
3019    /// Explicit configuration wins. Otherwise the default grants 30 seconds of
3020    /// setup time plus one second per MiB at a conservative 1 MiB/s floor. This
3021    /// prevents a cold, large pinned tree from inheriting the old fixed 30-second
3022    /// ceiling while still bounding every individual attempt.
3023    #[must_use]
3024    pub fn sync_timeout_for_payload(&self, payload_bytes: u64) -> std::time::Duration {
3025        let timeout_ms = self
3026            .sync_timeout_ms
3027            .filter(|value| Self::valid_sync_timeout_ms(*value))
3028            .unwrap_or_else(|| {
3029                let transfer_seconds = payload_bytes
3030                    .saturating_add(Self::DEFAULT_SYNC_BYTES_PER_SECOND - 1)
3031                    / Self::DEFAULT_SYNC_BYTES_PER_SECOND;
3032                Self::DEFAULT_SYNC_TIMEOUT_FLOOR_MS
3033                    .saturating_add(transfer_seconds.saturating_mul(1_000))
3034                    .min(Self::MAX_SYNC_TIMEOUT_MS)
3035            });
3036        std::time::Duration::from_millis(timeout_ms)
3037    }
3038
3039    /// Select compression level based on estimated transfer size (bd-243w).
3040    ///
3041    /// When adaptive compression is enabled, selects an appropriate level
3042    /// based on payload size:
3043    /// - < 10MB: level 1 (fast, minimal compression)
3044    /// - 10-200MB: level 3 (balanced)
3045    /// - > 200MB: level 7 (better compression)
3046    ///
3047    /// The result is clamped between `min_compression_level` and `max_compression_level`.
3048    ///
3049    /// When adaptive compression is disabled, returns the fixed `compression_level`.
3050    pub fn select_compression_level(&self, estimated_bytes: Option<u64>) -> u32 {
3051        if !self.adaptive_compression {
3052            return self.compression_level;
3053        }
3054
3055        let Some(bytes) = estimated_bytes else {
3056            // No estimate available, use default
3057            return self.compression_level;
3058        };
3059
3060        // Size thresholds
3061        const SMALL_THRESHOLD: u64 = 10_000_000; // 10 MB (decimal)
3062        const LARGE_THRESHOLD: u64 = 200_000_000; // 200 MB (decimal)
3063
3064        let level = if bytes < SMALL_THRESHOLD {
3065            1 // Fast compression for small payloads
3066        } else if bytes < LARGE_THRESHOLD {
3067            3 // Balanced for medium payloads
3068        } else {
3069            7 // Better compression for large payloads
3070        };
3071
3072        // Clamp to configured bounds
3073        level.clamp(self.min_compression_level, self.max_compression_level)
3074    }
3075}
3076
3077// =============================================================================
3078// Execution Configuration (bd-785w)
3079// =============================================================================
3080
3081/// Default allowlist of commands that can be executed remotely.
3082/// Aligned with the classifier's supported CompilationKind values.
3083/// Command bases of every compilation kind rch knows how to offload.
3084///
3085/// This is the built-in `execution.allowlist`. It is also what a persisted,
3086/// explicit allowlist is compared against: a config file written before a tool
3087/// family was added (Go, Nix, TypeScript, ...) silently keeps that family local,
3088/// and the only symptom is a `[RCH] local (... not in execution.allowlist)` line
3089/// (issue #51). `ExecutionConfig::missing_builtin_bases` surfaces the gap.
3090#[rustfmt::skip]
3091pub const BUILTIN_EXECUTION_BASES: &[&str] = &[
3092    // Rust
3093    "cargo",
3094    "rustc",
3095    // cargo-nextest
3096    "nextest",
3097    // C/C++
3098    "gcc",
3099    "g++",
3100    "clang",
3101    "clang++",
3102    "cc",
3103    "c++",
3104    // Build systems
3105    "make",
3106    "cmake",
3107    "ninja",
3108    "meson",
3109    // Bun
3110    "bun",
3111    // Nix (covers both `nix build` and the legacy `nix-build`)
3112    "nix",
3113    // Go
3114    "go",
3115    // TypeScript (covers both `tsc` and `npx tsc`; command_base is "tsc")
3116    "tsc",
3117];
3118
3119fn default_execution_allowlist() -> Vec<String> {
3120    BUILTIN_EXECUTION_BASES
3121        .iter()
3122        .map(|base| (*base).to_string())
3123        .collect()
3124}
3125
3126/// Execution allowlist configuration for remote builds (bd-785w).
3127///
3128/// Controls which command base names are permitted for remote execution.
3129/// Commands not in the allowlist will fail-open to local execution.
3130#[derive(Debug, Clone, Serialize, Deserialize)]
3131pub struct ExecutionConfig {
3132    /// Allowlist of command base names permitted for remote execution.
3133    ///
3134    /// Examples: "cargo", "rustc", "gcc", "bun"
3135    ///
3136    /// If a classified compilation command's base name is not in this list,
3137    /// RCH will fail-open to local execution with a clear reason.
3138    ///
3139    /// An empty allowlist disables all remote execution (local only).
3140    #[serde(default = "default_execution_allowlist")]
3141    pub allowlist: Vec<String>,
3142}
3143
3144impl Default for ExecutionConfig {
3145    fn default() -> Self {
3146        Self {
3147            allowlist: default_execution_allowlist(),
3148        }
3149    }
3150}
3151
3152impl ExecutionConfig {
3153    /// Check if a command base name is allowed for remote execution.
3154    pub fn is_allowed(&self, command_base: &str) -> bool {
3155        self.allowlist
3156            .iter()
3157            .any(|allowed| allowed.eq_ignore_ascii_case(command_base))
3158    }
3159
3160    /// Built-in compilation tool bases that this allowlist does NOT admit.
3161    ///
3162    /// Empty for the default allowlist. Non-empty means some command family rch
3163    /// classifies as compilation will always fall open to local execution on
3164    /// this box — usually because the config file predates that family.
3165    pub fn missing_builtin_bases(&self) -> Vec<&'static str> {
3166        BUILTIN_EXECUTION_BASES
3167            .iter()
3168            .copied()
3169            .filter(|base| !self.is_allowed(base))
3170            .collect()
3171    }
3172}
3173
3174// =============================================================================
3175// Retry Configuration (bd-x1ek)
3176// =============================================================================
3177
3178fn default_retry_max_attempts() -> u32 {
3179    3
3180}
3181
3182fn default_retry_base_delay_ms() -> u64 {
3183    100
3184}
3185
3186fn default_retry_max_delay_ms() -> u64 {
3187    5000
3188}
3189
3190fn default_retry_jitter_factor() -> f64 {
3191    0.1
3192}
3193
3194fn default_retry_total_timeout_ms() -> u64 {
3195    30000
3196}
3197
3198/// Configuration for retry behavior on transient errors.
3199///
3200/// Used by rsync and SSH operations to recover from transient network failures
3201/// without blocking too long or retrying non-recoverable errors.
3202#[derive(Debug, Clone, Serialize, Deserialize)]
3203pub struct RetryConfig {
3204    /// Maximum number of retry attempts (1 = no retries, just initial attempt).
3205    #[serde(default = "default_retry_max_attempts")]
3206    pub max_attempts: u32,
3207
3208    /// Initial delay between retries in milliseconds.
3209    #[serde(default = "default_retry_base_delay_ms")]
3210    pub base_delay_ms: u64,
3211
3212    /// Maximum delay between retries in milliseconds (caps exponential backoff).
3213    #[serde(default = "default_retry_max_delay_ms")]
3214    pub max_delay_ms: u64,
3215
3216    /// Jitter factor (0.0 - 1.0) to randomize delay.
3217    /// A value of 0.1 means ±10% randomization.
3218    #[serde(default = "default_retry_jitter_factor")]
3219    pub jitter_factor: f64,
3220
3221    /// Total timeout for all retry attempts in milliseconds.
3222    /// After this, retries stop even if max_attempts not reached.
3223    #[serde(default = "default_retry_total_timeout_ms")]
3224    pub total_timeout_ms: u64,
3225}
3226
3227impl Default for RetryConfig {
3228    fn default() -> Self {
3229        Self {
3230            max_attempts: default_retry_max_attempts(),
3231            base_delay_ms: default_retry_base_delay_ms(),
3232            max_delay_ms: default_retry_max_delay_ms(),
3233            jitter_factor: default_retry_jitter_factor(),
3234            total_timeout_ms: default_retry_total_timeout_ms(),
3235        }
3236    }
3237}
3238
3239impl RetryConfig {
3240    /// Create a config that disables retries (single attempt only).
3241    pub fn no_retry() -> Self {
3242        Self {
3243            max_attempts: 1,
3244            ..Default::default()
3245        }
3246    }
3247
3248    /// Calculate delay for a given attempt number (0-indexed).
3249    ///
3250    /// Uses exponential backoff with optional jitter.
3251    pub fn delay_for_attempt(&self, attempt: u32) -> std::time::Duration {
3252        if attempt == 0 {
3253            return std::time::Duration::ZERO;
3254        }
3255
3256        // Exponential backoff: base * 2^attempt
3257        let base = self.base_delay_ms as f64;
3258        let delay = base * (2.0_f64.powi(attempt as i32 - 1));
3259        let capped = delay.min(self.max_delay_ms as f64);
3260
3261        // Apply jitter: delay ± (delay * jitter_factor)
3262        let jittered = if self.jitter_factor > 0.0 {
3263            let jitter_range = capped * self.jitter_factor;
3264            let jitter = (rand::rng().random::<f64>() * 2.0 - 1.0) * jitter_range;
3265            (capped + jitter).max(0.0)
3266        } else {
3267            capped
3268        };
3269
3270        std::time::Duration::from_millis(jittered as u64)
3271    }
3272
3273    /// Check if we should retry given elapsed time since start.
3274    pub fn should_retry(&self, attempt: u32, elapsed: std::time::Duration) -> bool {
3275        if attempt >= self.max_attempts {
3276            return false;
3277        }
3278        elapsed.as_millis() < self.total_timeout_ms as u128
3279    }
3280}
3281
3282/// Default source-sync silence timeout (issue #59): two minutes without a
3283/// single byte of rsync output means a dead channel or wedged rsync, not a
3284/// large transfer (progress2 refreshes its line continuously while bytes
3285/// flow, and each refresh counts as forward progress).
3286fn default_source_sync_silence_timeout_secs() -> u64 {
3287    120
3288}
3289
3290/// Default remote base path for project transfers.
3291///
3292/// Rooted under `/data/tmp` (the fleet-standard managed ephemeral-build zone)
3293/// rather than `/tmp`: on the Linux workers `/tmp` is a RAM-backed tmpfs, so
3294/// dispatched build artifacts placed there consume RAM and evade the disk-GC
3295/// (sbh / datatmp-janitor) that watches `/data/tmp`. Keeping the remote base in
3296/// the managed zone lets those reapers reclaim orphaned build trees. Must agree
3297/// with the rchd cache-cleanup and reclaim `remote_base` defaults.
3298pub fn default_remote_base() -> String {
3299    "/data/tmp/rch".to_string()
3300}
3301
3302/// Validate and normalize a remote base path.
3303/// Returns an error if the path is not absolute or contains traversal sequences.
3304pub fn validate_remote_base(path: &str) -> Result<String, String> {
3305    // Expand tilde for user convenience
3306    let expanded = shellexpand::tilde(path).into_owned();
3307
3308    // Check for absolute path
3309    if !expanded.starts_with('/') {
3310        return Err(format!(
3311            "remote_base must be an absolute path, got: {}",
3312            path
3313        ));
3314    }
3315
3316    // Check for path traversal attempts
3317    if expanded.contains("..") {
3318        return Err(format!(
3319            "remote_base must not contain path traversal (..): {}",
3320            path
3321        ));
3322    }
3323
3324    // Normalize: remove trailing slashes
3325    let normalized = expanded.trim_end_matches('/').to_string();
3326
3327    // Safety checks
3328    if normalized.is_empty() || normalized == "/" {
3329        return Err("remote_base cannot be the root directory (safety restriction)".to_string());
3330    }
3331
3332    // Enforce at least 2 levels deep (e.g. /tmp/rch, /home/user/rch)
3333    // /tmp -> depth 1 (unsafe for recursive delete)
3334    // /tmp/rch -> depth 2 (safe)
3335    let components: Vec<&str> = normalized.split('/').filter(|c| !c.is_empty()).collect();
3336    if components.len() < 2 {
3337        return Err(format!(
3338            "remote_base must be at least 2 levels deep (e.g. /tmp/rch), got: {}",
3339            normalized
3340        ));
3341    }
3342
3343    Ok(normalized)
3344}
3345
3346fn default_circuit_failure_threshold() -> u32 {
3347    3
3348}
3349
3350fn default_circuit_success_threshold() -> u32 {
3351    2
3352}
3353
3354fn default_circuit_error_rate_threshold() -> f64 {
3355    0.5
3356}
3357
3358fn default_circuit_window_secs() -> u64 {
3359    60
3360}
3361
3362fn default_circuit_open_cooldown_secs() -> u64 {
3363    30
3364}
3365
3366fn default_circuit_half_open_max_probes() -> u32 {
3367    1
3368}
3369
3370fn default_circuit_command_failure_threshold() -> u32 {
3371    2
3372}
3373
3374fn default_circuit_open_cooldown_max_secs() -> u64 {
3375    // 30s base doubled four times: 30, 60, 120, 240, 480.
3376    480
3377}
3378
3379fn default_true() -> bool {
3380    true
3381}
3382
3383fn default_log_level() -> String {
3384    "info".to_string()
3385}
3386
3387pub fn default_socket_path() -> String {
3388    // Prefer XDG_RUNTIME_DIR if available (per-user runtime directory).
3389    if let Ok(runtime_dir) = std::env::var("XDG_RUNTIME_DIR")
3390        && !runtime_dir.trim().is_empty()
3391    {
3392        let path = PathBuf::from(runtime_dir).join("rch.sock");
3393        return path.to_string_lossy().to_string();
3394    }
3395
3396    // Fallback to ~/.cache/rch/rch.sock (persistent across reboots).
3397    if let Some(cache_dir) = dirs::cache_dir() {
3398        let rch_cache = cache_dir.join("rch");
3399        let _ = std::fs::create_dir_all(&rch_cache);
3400        return rch_cache.join("rch.sock").to_string_lossy().to_string();
3401    }
3402
3403    // Last resort: /tmp/rch.sock
3404    "/tmp/rch.sock".to_string()
3405}
3406
3407#[allow(dead_code)]
3408fn default_output_visibility() -> OutputVisibility {
3409    OutputVisibility::None
3410}
3411
3412fn default_confidence() -> f64 {
3413    0.85
3414}
3415
3416fn default_min_local_time() -> u64 {
3417    2000
3418}
3419
3420/// Default speedup threshold: 1.2 (require 20% speedup to offload).
3421/// This is conservative to avoid offloading builds that would be only
3422/// marginally faster remotely when accounting for transfer overhead.
3423fn default_speedup_threshold() -> f64 {
3424    1.2
3425}
3426
3427fn default_compression() -> u32 {
3428    3
3429}
3430
3431/// Default maximum file size for artifact verification (100MB).
3432fn default_verify_max_size() -> u64 {
3433    100 * 1024 * 1024 // 100MB
3434}
3435
3436/// Default minimum compression level for adaptive mode.
3437fn default_min_compression() -> u32 {
3438    1
3439}
3440
3441/// Default maximum compression level for adaptive mode.
3442fn default_max_compression() -> u32 {
3443    9
3444}
3445
3446fn default_excludes() -> Vec<String> {
3447    vec![
3448        // Rust build artifacts
3449        "target/".to_string(),
3450        "*.rlib".to_string(),
3451        "*.rmeta".to_string(),
3452        // Git metadata is large, often permission-sensitive on workers, and
3453        // a partial `.git/` tree is not reliable for build scripts anyway.
3454        ".git/".to_string(),
3455        // Node.js / Bun dependencies (massive, reinstalled on worker)
3456        "node_modules/".to_string(),
3457        // Bun cache and runtime files
3458        ".bun/".to_string(),
3459        // npm / pnpm caches
3460        ".npm/".to_string(),
3461        ".pnpm-store/".to_string(),
3462        // Common build output directories
3463        "dist/".to_string(),
3464        "build/".to_string(),
3465        // Framework-specific caches
3466        ".next/".to_string(),
3467        ".nuxt/".to_string(),
3468        ".turbo/".to_string(),
3469        ".parcel-cache/".to_string(),
3470        // Beads runtime state (local issue DB + lock/temp files); not needed remotely.
3471        ".beads/".to_string(),
3472        // Local diagnostic runs may contain host-specific symlinks and are not build inputs.
3473        ".doctor/".to_string(),
3474        // Coverage reports (generated during tests)
3475        "coverage/".to_string(),
3476        ".nyc_output/".to_string(),
3477        // Credentials and secrets (must never be transferred to workers)
3478        ".cargo/credentials".to_string(),
3479        ".cargo/credentials.toml".to_string(),
3480        ".env".to_string(),
3481        ".env.*".to_string(),
3482        "*.pem".to_string(),
3483        "*.key".to_string(),
3484        "credentials.json".to_string(),
3485        "secrets.json".to_string(),
3486        "secrets.yaml".to_string(),
3487        "secrets.yml".to_string(),
3488        "secrets.toml".to_string(),
3489        "secrets.env".to_string(),
3490        "secrets.txt".to_string(),
3491        "secrets.conf".to_string(),
3492        "secrets.cfg".to_string(),
3493        "secrets.properties".to_string(),
3494        "secrets.xml".to_string(),
3495        // The classes above were already covered. These are the ones
3496        // RABS's E027 source-capture seed set denies
3497        // (rabs-sandbox/src/source_capture.rs) that this list did not,
3498        // so the two halves of the product now agree about what a
3499        // secret is. Two components disagreeing on that is the kind of
3500        // gap nobody notices until one of them is the path that ran.
3501        //
3502        // rsync patterns without a `/` match a basename at any depth,
3503        // so these cover nested copies too — a key checked into a
3504        // fixtures directory is excluded exactly like one at the root.
3505        //
3506        // SSH private keys. The public halves (.pub) are deliberately
3507        // not excluded: they are not secret and some builds read them.
3508        "id_rsa".to_string(),
3509        "id_ed25519".to_string(),
3510        "id_ecdsa".to_string(),
3511        "id_dsa".to_string(),
3512        // Key/certificate container formats (*.pem and *.key are above).
3513        "*.p12".to_string(),
3514        "*.pfx".to_string(),
3515        "*.keystore".to_string(),
3516        "*.jks".to_string(),
3517        // Machine credentials and cloud/container config that carries
3518        // long-lived tokens.
3519        ".netrc".to_string(),
3520        "_netrc".to_string(),
3521        ".aws/credentials".to_string(),
3522        ".docker/config.json".to_string(),
3523        // Package-registry auth tokens. These sit in project roots far
3524        // more often than the key formats above and are the likeliest
3525        // real leak in a normal repo.
3526        ".npmrc".to_string(),
3527        ".pypirc".to_string(),
3528        // GnuPG private keyring.
3529        "secring.*".to_string(),
3530    ]
3531}
3532
3533// ============================================================================
3534// Build History Types
3535// ============================================================================
3536
3537/// Location where a build was executed.
3538#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
3539#[serde(rename_all = "snake_case")]
3540pub enum BuildLocation {
3541    /// Build executed locally.
3542    #[default]
3543    Local,
3544    /// Build executed on a remote worker.
3545    Remote,
3546}
3547
3548/// Worker health snapshot captured when a cancellation completes.
3549#[derive(Debug, Clone, Serialize, Deserialize)]
3550pub struct BuildCancellationWorkerHealth {
3551    /// Worker status at cancellation completion.
3552    pub status: String,
3553    /// Worker speed score at cancellation completion.
3554    pub speed_score: f64,
3555    /// Slots currently used on the worker.
3556    pub used_slots: u32,
3557    /// Slots currently available on the worker.
3558    pub available_slots: u32,
3559    /// Normalized pressure state.
3560    pub pressure_state: String,
3561    /// Stable pressure reason code.
3562    pub pressure_reason_code: String,
3563}
3564
3565/// Structured cancellation metadata attached to cancelled build records.
3566#[derive(Debug, Clone, Serialize, Deserialize)]
3567pub struct BuildCancellationMetadata {
3568    /// Stable cancellation operation identifier.
3569    pub operation_id: String,
3570    /// Cancellation origin (for example `user`, `timeout`).
3571    pub origin: String,
3572    /// Stable reason code for cancellation.
3573    pub reason_code: String,
3574    /// Ordered cancellation state path.
3575    #[serde(default)]
3576    pub decision_path: Vec<String>,
3577    /// Highest escalation stage reached (`term`, `remote_kill`, `sigkill`).
3578    pub escalation_stage: String,
3579    /// Number of escalation transitions taken.
3580    pub escalation_count: u32,
3581    /// Whether remote kill was attempted.
3582    pub remote_kill_attempted: bool,
3583    /// Whether cleanup completed successfully.
3584    pub cleanup_ok: bool,
3585    /// Whether active build history was successfully claimed/cancelled.
3586    pub history_cancelled: bool,
3587    /// Final cancellation state.
3588    pub final_state: String,
3589    /// Worker health snapshot at completion.
3590    #[serde(default, skip_serializing_if = "Option::is_none")]
3591    pub worker_health: Option<BuildCancellationWorkerHealth>,
3592}
3593
3594/// Record of a completed build.
3595#[derive(Debug, Clone, Serialize, Deserialize)]
3596pub struct BuildRecord {
3597    /// Unique build identifier.
3598    pub id: u64,
3599    /// When the build started (ISO 8601 timestamp).
3600    pub started_at: String,
3601    /// When the build completed (ISO 8601 timestamp).
3602    pub completed_at: String,
3603    /// Project identifier (usually directory name or hash).
3604    pub project_id: String,
3605    /// Worker that executed the build (None if local).
3606    pub worker_id: Option<String>,
3607    /// Full command executed.
3608    pub command: String,
3609    /// Exit code (0 = success).
3610    pub exit_code: i32,
3611    /// Duration in milliseconds.
3612    pub duration_ms: u64,
3613    /// Build location (local or remote).
3614    pub location: BuildLocation,
3615    /// Bytes transferred (if remote).
3616    pub bytes_transferred: Option<u64>,
3617    /// Optional timing breakdown for the pipeline.
3618    #[serde(default)]
3619    pub timing: Option<CommandTimingBreakdown>,
3620    /// Structured cancellation metadata for cancelled builds.
3621    #[serde(default, skip_serializing_if = "Option::is_none")]
3622    pub cancellation: Option<BuildCancellationMetadata>,
3623}
3624
3625/// Input payload for recording a completed build.
3626#[derive(Debug, Clone, Serialize, Deserialize)]
3627pub struct BuildRecordInput {
3628    /// When the build started (ISO 8601 timestamp).
3629    pub started_at: String,
3630    /// When the build completed (ISO 8601 timestamp).
3631    pub completed_at: String,
3632    /// Project identifier (usually directory name or hash).
3633    pub project_id: String,
3634    /// Worker that executed the build (None if local).
3635    pub worker_id: Option<String>,
3636    /// Full command executed.
3637    pub command: String,
3638    /// Exit code (0 = success).
3639    pub exit_code: i32,
3640    /// Duration in milliseconds.
3641    pub duration_ms: u64,
3642    /// Build location (local or remote).
3643    pub location: BuildLocation,
3644    /// Bytes transferred (if remote).
3645    pub bytes_transferred: Option<u64>,
3646    /// Optional timing breakdown for the pipeline.
3647    #[serde(default)]
3648    pub timing: Option<CommandTimingBreakdown>,
3649    /// Structured cancellation metadata for cancelled builds.
3650    #[serde(default, skip_serializing_if = "Option::is_none")]
3651    pub cancellation: Option<BuildCancellationMetadata>,
3652}
3653
3654impl BuildRecordInput {
3655    /// Convert input payload into a build record with a supplied ID.
3656    pub fn into_record(self, id: u64) -> BuildRecord {
3657        BuildRecord {
3658            id,
3659            started_at: self.started_at,
3660            completed_at: self.completed_at,
3661            project_id: self.project_id,
3662            worker_id: self.worker_id,
3663            command: self.command,
3664            exit_code: self.exit_code,
3665            duration_ms: self.duration_ms,
3666            location: self.location,
3667            bytes_transferred: self.bytes_transferred,
3668            timing: self.timing,
3669            cancellation: self.cancellation,
3670        }
3671    }
3672}
3673
3674/// Aggregate terminal-command statistics for build history.
3675///
3676/// These counts do not infer whether compilation completed before a failing
3677/// test or interrupted command. The denominator includes every stored record.
3678#[derive(Debug, Clone, Default, Serialize, Deserialize)]
3679pub struct BuildStats {
3680    /// Total number of builds in history.
3681    pub total_builds: usize,
3682    /// Number of successfully completed commands (exit_code == 0).
3683    pub success_count: usize,
3684    /// Number of unsuccessful commands, including interruption (exit_code != 0).
3685    pub failure_count: usize,
3686    /// Number of remote builds.
3687    pub remote_count: usize,
3688    /// Number of local builds.
3689    pub local_count: usize,
3690    /// Average build duration in milliseconds.
3691    pub avg_duration_ms: u64,
3692}
3693
3694/// Saved time statistics from remote builds.
3695///
3696/// Tracks estimated time savings from offloading builds to remote workers.
3697/// Estimates are only produced from an observed local baseline; without one the
3698/// stats carry measured remote durations with `estimate_basis = "none"` and
3699/// zero estimated savings rather than a fabricated speedup factor.
3700#[derive(Debug, Clone, Default, Serialize, Deserialize)]
3701pub struct SavedTimeStats {
3702    /// Total time spent on remote builds (milliseconds).
3703    pub total_remote_duration_ms: u64,
3704    /// Estimated total time if those builds ran locally (milliseconds).
3705    /// Zero when no local baseline exists.
3706    pub estimated_local_duration_ms: u64,
3707    /// Time saved by offloading (milliseconds).
3708    /// Computed as max(0, estimated_local - remote); zero without a baseline.
3709    pub time_saved_ms: u64,
3710    /// Number of remote builds included in calculation.
3711    pub builds_counted: usize,
3712    /// Average speedup factor (local_estimate / remote_duration).
3713    /// A value of 2.0 means remote builds are ~2x faster than local.
3714    /// Zero when the estimate basis is "none".
3715    pub avg_speedup: f64,
3716    /// Total time saved today (milliseconds).
3717    pub today_saved_ms: u64,
3718    /// Total time saved this week (milliseconds).
3719    pub week_saved_ms: u64,
3720    /// How the local-time estimate was derived: "observed_local_mean" when
3721    /// successful local builds back the baseline, "none" otherwise.
3722    #[serde(default)]
3723    pub estimate_basis: String,
3724    /// Number of successful local builds backing the baseline (0 for "none").
3725    #[serde(default)]
3726    pub local_baseline_builds: usize,
3727}
3728
3729// ============================================================================
3730// Compilation Timing and Metrics
3731// ============================================================================
3732
3733use std::collections::VecDeque;
3734use std::time::{Duration, Instant};
3735
3736/// Breakdown of timing for each compilation phase.
3737#[derive(Debug, Clone, Default, Serialize, Deserialize)]
3738pub struct CompilationTimingBreakdown {
3739    /// Time to sync source files to worker.
3740    #[serde(with = "duration_millis")]
3741    pub rsync_up: Duration,
3742    /// Time for cargo build on worker.
3743    #[serde(with = "duration_millis")]
3744    pub remote_build: Duration,
3745    /// Time to sync artifacts back.
3746    #[serde(with = "duration_millis")]
3747    pub rsync_down: Duration,
3748    /// Total end-to-end latency.
3749    #[serde(with = "duration_millis")]
3750    pub total: Duration,
3751}
3752
3753/// Timing breakdown for a single command pipeline.
3754///
3755/// Uses optional durations so missing phases serialize as `null`.
3756#[derive(Debug, Clone, Default, Serialize, Deserialize)]
3757pub struct CommandTimingBreakdown {
3758    /// Time spent classifying the command.
3759    #[serde(with = "option_duration_millis")]
3760    pub classify: Option<Duration>,
3761    /// Time spent selecting a worker.
3762    #[serde(with = "option_duration_millis")]
3763    pub select: Option<Duration>,
3764    /// Time spent syncing source files to the worker.
3765    #[serde(with = "option_duration_millis")]
3766    pub sync_up: Option<Duration>,
3767    /// Time spent executing the remote command.
3768    #[serde(with = "option_duration_millis")]
3769    pub exec: Option<Duration>,
3770    /// Time spent syncing artifacts back.
3771    #[serde(with = "option_duration_millis")]
3772    pub sync_down: Option<Duration>,
3773    /// Time spent on cleanup (slot release, bookkeeping).
3774    #[serde(with = "option_duration_millis")]
3775    pub cleanup: Option<Duration>,
3776    /// Total end-to-end time for the pipeline.
3777    #[serde(with = "option_duration_millis")]
3778    pub total: Option<Duration>,
3779}
3780
3781mod duration_millis {
3782    use serde::{Deserialize, Deserializer, Serialize, Serializer};
3783    use std::time::Duration;
3784
3785    pub fn serialize<S>(duration: &Duration, serializer: S) -> Result<S::Ok, S::Error>
3786    where
3787        S: Serializer,
3788    {
3789        duration.as_millis().serialize(serializer)
3790    }
3791
3792    pub fn deserialize<'de, D>(deserializer: D) -> Result<Duration, D::Error>
3793    where
3794        D: Deserializer<'de>,
3795    {
3796        let millis = u64::deserialize(deserializer)?;
3797        Ok(Duration::from_millis(millis))
3798    }
3799}
3800
3801/// Comprehensive metrics for a single compilation.
3802#[derive(Debug, Clone, Serialize, Deserialize)]
3803pub struct CompilationMetrics {
3804    /// Project identifier (usually directory name or hash).
3805    pub project_id: String,
3806    /// Worker that performed the compilation.
3807    pub worker_id: String,
3808    /// When the compilation occurred.
3809    pub timestamp: chrono::DateTime<chrono::Utc>,
3810    /// Timing breakdown for each phase.
3811    pub timing: CompilationTimingBreakdown,
3812    /// Local build time for comparison (if available).
3813    #[serde(with = "option_duration_millis")]
3814    pub local_build_time: Option<Duration>,
3815    /// Speedup ratio (local_time / remote_time).
3816    pub speedup: Option<f64>,
3817    /// Number of files synced to worker.
3818    pub files_synced: u64,
3819    /// Total bytes transferred.
3820    pub bytes_transferred: u64,
3821    /// Exit code from compilation.
3822    pub exit_code: i32,
3823    /// Whether compilation succeeded.
3824    pub success: bool,
3825}
3826
3827mod option_duration_millis {
3828    use serde::{Deserialize, Deserializer, Serialize, Serializer};
3829    use std::time::Duration;
3830
3831    pub fn serialize<S>(duration: &Option<Duration>, serializer: S) -> Result<S::Ok, S::Error>
3832    where
3833        S: Serializer,
3834    {
3835        match duration {
3836            Some(d) => Some(d.as_millis() as u64).serialize(serializer),
3837            None => Option::<u64>::None.serialize(serializer),
3838        }
3839    }
3840
3841    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Duration>, D::Error>
3842    where
3843        D: Deserializer<'de>,
3844    {
3845        let opt: Option<u64> = Option::deserialize(deserializer)?;
3846        Ok(opt.map(Duration::from_millis))
3847    }
3848}
3849
3850impl CompilationMetrics {
3851    /// Calculate speedup based on local vs remote build time.
3852    pub fn calculate_speedup(&mut self) {
3853        if let Some(local) = self.local_build_time
3854            && self.timing.total.as_millis() > 0
3855        {
3856            self.speedup = Some(local.as_secs_f64() / self.timing.total.as_secs_f64());
3857        }
3858    }
3859
3860    /// Check if remote compilation was beneficial (faster than local).
3861    pub fn is_beneficial(&self) -> bool {
3862        self.speedup.map(|s| s > 1.0).unwrap_or(false)
3863    }
3864}
3865
3866impl Default for CompilationMetrics {
3867    fn default() -> Self {
3868        Self {
3869            project_id: String::new(),
3870            worker_id: String::new(),
3871            timestamp: chrono::Utc::now(),
3872            timing: CompilationTimingBreakdown::default(),
3873            local_build_time: None,
3874            speedup: None,
3875            files_synced: 0,
3876            bytes_transferred: 0,
3877            exit_code: 0,
3878            success: true,
3879        }
3880    }
3881}
3882
3883/// Timer for tracking compilation phases.
3884///
3885/// Use this to measure the duration of each phase of remote compilation.
3886///
3887/// # Example
3888/// ```ignore
3889/// let mut timer = CompilationTimer::new("my-project", "worker-1");
3890/// // ... rsync source files ...
3891/// timer.end_rsync_up();
3892/// // ... run cargo build ...
3893/// timer.end_remote_build();
3894/// // ... rsync artifacts back ...
3895/// timer.end_rsync_down();
3896/// let metrics = timer.finish(0, 100, 1_000_000);
3897/// ```
3898#[derive(Debug)]
3899pub struct CompilationTimer {
3900    project_id: String,
3901    worker_id: String,
3902    start: Instant,
3903    phase_start: Instant,
3904    rsync_up: Option<Duration>,
3905    remote_build: Option<Duration>,
3906    rsync_down: Option<Duration>,
3907}
3908
3909impl CompilationTimer {
3910    /// Create a new timer for a compilation.
3911    pub fn new(project_id: &str, worker_id: &str) -> Self {
3912        let now = Instant::now();
3913        Self {
3914            project_id: project_id.to_string(),
3915            worker_id: worker_id.to_string(),
3916            start: now,
3917            phase_start: now,
3918            rsync_up: None,
3919            remote_build: None,
3920            rsync_down: None,
3921        }
3922    }
3923
3924    /// Mark the end of the rsync upload phase.
3925    pub fn end_rsync_up(&mut self) {
3926        self.rsync_up = Some(self.phase_start.elapsed());
3927        self.phase_start = Instant::now();
3928        tracing::info!(
3929            rsync_up_ms = %self.rsync_up.unwrap().as_millis(),
3930            "TIMING: rsync_up completed"
3931        );
3932    }
3933
3934    /// Mark the end of the remote build phase.
3935    pub fn end_remote_build(&mut self) {
3936        self.remote_build = Some(self.phase_start.elapsed());
3937        self.phase_start = Instant::now();
3938        tracing::info!(
3939            remote_build_ms = %self.remote_build.unwrap().as_millis(),
3940            "TIMING: remote_build completed"
3941        );
3942    }
3943
3944    /// Mark the end of the rsync download phase.
3945    pub fn end_rsync_down(&mut self) {
3946        self.rsync_down = Some(self.phase_start.elapsed());
3947        tracing::info!(
3948            rsync_down_ms = %self.rsync_down.unwrap().as_millis(),
3949            "TIMING: rsync_down completed"
3950        );
3951    }
3952
3953    /// Finish timing and produce metrics.
3954    pub fn finish(self, exit_code: i32, files: u64, bytes: u64) -> CompilationMetrics {
3955        let total = self.start.elapsed();
3956        tracing::info!(
3957            total_ms = %total.as_millis(),
3958            exit_code = %exit_code,
3959            "TIMING: compilation completed"
3960        );
3961
3962        CompilationMetrics {
3963            project_id: self.project_id,
3964            worker_id: self.worker_id,
3965            timestamp: chrono::Utc::now(),
3966            timing: CompilationTimingBreakdown {
3967                rsync_up: self.rsync_up.unwrap_or_default(),
3968                remote_build: self.remote_build.unwrap_or_default(),
3969                rsync_down: self.rsync_down.unwrap_or_default(),
3970                total,
3971            },
3972            local_build_time: None,
3973            speedup: None,
3974            files_synced: files,
3975            bytes_transferred: bytes,
3976            exit_code,
3977            success: exit_code == 0,
3978        }
3979    }
3980}
3981
3982/// Aggregator for compilation metrics with statistics.
3983#[derive(Debug)]
3984pub struct MetricsAggregator {
3985    history: VecDeque<CompilationMetrics>,
3986    max_history: usize,
3987}
3988
3989impl MetricsAggregator {
3990    /// Create a new aggregator with a maximum history size.
3991    pub fn new(max_history: usize) -> Self {
3992        Self {
3993            history: VecDeque::with_capacity(max_history),
3994            max_history,
3995        }
3996    }
3997
3998    /// Record a new compilation's metrics.
3999    pub fn record(&mut self, metrics: CompilationMetrics) {
4000        if self.history.len() >= self.max_history {
4001            self.history.pop_front();
4002        }
4003        self.history.push_back(metrics);
4004    }
4005
4006    /// Get the average speedup across all recorded compilations.
4007    pub fn average_speedup(&self) -> Option<f64> {
4008        let speedups: Vec<f64> = self.history.iter().filter_map(|m| m.speedup).collect();
4009
4010        if speedups.is_empty() {
4011            None
4012        } else {
4013            Some(speedups.iter().sum::<f64>() / speedups.len() as f64)
4014        }
4015    }
4016
4017    /// Get the p50 (median) total compilation time.
4018    pub fn p50_total_time(&self) -> Option<Duration> {
4019        self.percentile_total_time(0.50)
4020    }
4021
4022    /// Get the p95 total compilation time.
4023    pub fn p95_total_time(&self) -> Option<Duration> {
4024        self.percentile_total_time(0.95)
4025    }
4026
4027    /// Get the p99 total compilation time.
4028    pub fn p99_total_time(&self) -> Option<Duration> {
4029        self.percentile_total_time(0.99)
4030    }
4031
4032    /// Get a percentile of total compilation times.
4033    ///
4034    /// Uses the "inclusive" percentile method (matching numpy.percentile, Excel PERCENTILE.INC):
4035    /// index = (n - 1) * percentile, where n is the number of samples.
4036    fn percentile_total_time(&self, percentile: f64) -> Option<Duration> {
4037        let mut times: Vec<_> = self.history.iter().map(|m| m.timing.total).collect();
4038
4039        if times.is_empty() {
4040            return None;
4041        }
4042
4043        times.sort();
4044        // Use inclusive percentile: index = (n - 1) * p
4045        // For p50 with 100 items: (99 * 0.50) = 49.5 -> 49 (true median position)
4046        // For p99 with 100 items: (99 * 0.99) = 98.01 -> 98
4047        let idx = (((times.len() - 1) as f64 * percentile).round() as usize).min(times.len() - 1);
4048        Some(times[idx])
4049    }
4050
4051    /// Get the success rate as a percentage.
4052    pub fn success_rate(&self) -> f64 {
4053        if self.history.is_empty() {
4054            return 100.0;
4055        }
4056        let successes = self.history.iter().filter(|m| m.success).count();
4057        (successes as f64 / self.history.len() as f64) * 100.0
4058    }
4059
4060    /// Get the number of recorded compilations.
4061    pub fn count(&self) -> usize {
4062        self.history.len()
4063    }
4064
4065    /// Get all recorded metrics.
4066    pub fn metrics(&self) -> &VecDeque<CompilationMetrics> {
4067        &self.history
4068    }
4069
4070    /// Clear all recorded metrics.
4071    pub fn clear(&mut self) {
4072        self.history.clear();
4073    }
4074}
4075
4076impl Default for MetricsAggregator {
4077    fn default() -> Self {
4078        Self::new(1000)
4079    }
4080}
4081
4082#[cfg(test)]
4083mod tests {
4084    use super::*;
4085    use crate::test_guard;
4086
4087    #[test]
4088    fn test_declared_os_reads_reserved_tag() {
4089        assert_eq!(
4090            declared_os(&["rust".to_string(), "os:windows".to_string()]),
4091            Some("windows".to_string())
4092        );
4093        assert_eq!(
4094            declared_os(&["os:WINDOWS".to_string()]),
4095            Some("windows".to_string())
4096        );
4097    }
4098
4099    #[test]
4100    fn test_declared_os_absent_for_ordinary_tags() {
4101        // Every historical worker: no reserved tag, so no exclusivity and the
4102        // worker stays a candidate for any job.
4103        assert_eq!(declared_os(&[]), None);
4104        assert_eq!(
4105            declared_os(&["rust".to_string(), "bun".to_string(), "go".to_string()]),
4106            None
4107        );
4108        // A malformed declaration must not silently fence the worker off.
4109        assert_eq!(declared_os(&["os:".to_string()]), None);
4110        assert_eq!(declared_os(&["os:  ".to_string()]), None);
4111    }
4112
4113    #[test]
4114    fn test_os_tag_roundtrips_through_declared_os() {
4115        for os in ["windows", "Darwin", " linux "] {
4116            let tag = os_tag(os);
4117            assert_eq!(
4118                declared_os(std::slice::from_ref(&tag)).as_deref(),
4119                Some(os.trim().to_ascii_lowercase().as_str())
4120            );
4121        }
4122    }
4123
4124    /// Verdict-webhook config must NEVER carry an inline secret. Operators
4125    /// reference secrets by env-var name (`*_env`); the resolved value is
4126    /// read at dispatch time and never persisted to the cache or config TOML.
4127    /// This guards against a future careless `pub secret: String` addition.
4128    #[test]
4129    fn test_no_inline_secret_fields() {
4130        let endpoint = DoctorWebhookEndpoint {
4131            name: "ops".to_string(),
4132            url: "https://example.com/hook".to_string(),
4133            format: DoctorWebhookFormat::Pagerduty,
4134            on_transitions: vec!["any_to_failing".to_string()],
4135            retry_max: 3,
4136            retry_backoff_ms: 200,
4137            timeout_ms: 5000,
4138            enabled: true,
4139            routing_key_env: Some("RCH_PAGERDUTY_ROUTING_KEY".to_string()),
4140            bearer_token_env: Some("RCH_WEBHOOK_BEARER".to_string()),
4141            signing_secret_env: Some("RCH_WEBHOOK_HMAC".to_string()),
4142        };
4143        // Serialize to a JSON object and inspect the *keys*. The forbidden
4144        // field names must be entirely absent; only `*_env` references survive.
4145        let value = serde_json::to_value(&endpoint).unwrap();
4146        let obj = value.as_object().expect("endpoint serializes to an object");
4147        for forbidden in ["secret", "routing_key", "bearer_token", "password", "token"] {
4148            assert!(
4149                !obj.contains_key(forbidden),
4150                "endpoint config must not expose an inline `{forbidden}` field"
4151            );
4152        }
4153        assert!(obj.contains_key("routing_key_env"));
4154        assert!(obj.contains_key("bearer_token_env"));
4155        assert!(obj.contains_key("signing_secret_env"));
4156    }
4157
4158    #[test]
4159    fn test_webhook_format_toml_spelling() {
4160        // The config TOML uses snake_case spellings. TOML documents are tables
4161        // at the root, so a bare enum cannot be (de)serialized standalone —
4162        // verify the wire spelling through a `format = "..."` table field, the
4163        // shape it actually appears in within the config.
4164        #[derive(serde::Serialize, serde::Deserialize, PartialEq, Debug)]
4165        struct FormatWrap {
4166            format: DoctorWebhookFormat,
4167        }
4168        let rendered = toml::to_string(&FormatWrap {
4169            format: DoctorWebhookFormat::GenericJson,
4170        })
4171        .unwrap();
4172        assert!(
4173            rendered.contains("format = \"generic_json\""),
4174            "unexpected TOML: {rendered}"
4175        );
4176        let slack: FormatWrap = toml::from_str("format = \"slack\"").unwrap();
4177        assert_eq!(slack.format, DoctorWebhookFormat::Slack);
4178        let pd: FormatWrap = toml::from_str("format = \"pagerduty\"").unwrap();
4179        assert_eq!(pd.format, DoctorWebhookFormat::Pagerduty);
4180    }
4181
4182    #[test]
4183    fn test_doctor_webhooks_defaults() {
4184        let cfg = DoctorWebhooksConfig::default();
4185        assert!(cfg.endpoints.is_empty());
4186        assert_eq!(cfg.max_inflight, 16);
4187        // RchConfig wires the section in with serde(default), so an empty
4188        // config still yields an empty (never-firing) webhook surface.
4189        let rch: RchConfig = toml::from_str("").unwrap();
4190        assert!(rch.doctor.webhooks.endpoints.is_empty());
4191    }
4192
4193    #[test]
4194    fn test_doctor_webhook_endpoint_parses_from_toml() {
4195        let toml_src = r#"
4196[doctor.webhooks]
4197max_inflight = 8
4198
4199[[doctor.webhooks.endpoints]]
4200name = "ops-slack"
4201url = "https://hooks.slack.com/services/T0/B0/x"
4202format = "slack"
4203on_transitions = ["healthy_to_degraded", "any_to_failing"]
4204retry_max = 2
4205"#;
4206        let cfg: RchConfig = toml::from_str(toml_src).unwrap();
4207        assert_eq!(cfg.doctor.webhooks.max_inflight, 8);
4208        assert_eq!(cfg.doctor.webhooks.endpoints.len(), 1);
4209        let ep = &cfg.doctor.webhooks.endpoints[0];
4210        assert_eq!(ep.name, "ops-slack");
4211        assert_eq!(ep.format, DoctorWebhookFormat::Slack);
4212        assert_eq!(ep.on_transitions.len(), 2);
4213        assert_eq!(ep.retry_max, 2);
4214        // Defaults filled in for omitted fields.
4215        assert_eq!(ep.retry_backoff_ms, 200);
4216        assert_eq!(ep.timeout_ms, 5000);
4217        assert!(ep.enabled);
4218    }
4219
4220    fn assert_golden_json(
4221        actual: serde_json::Value,
4222        expected: &serde_json::Value,
4223        fixture_path: &str,
4224    ) {
4225        if &actual == expected {
4226            return;
4227        }
4228
4229        let actual_json = serde_json::to_string_pretty(&actual).expect("actual JSON renders");
4230        let expected_json = serde_json::to_string_pretty(expected).expect("expected JSON renders");
4231        assert_eq!(
4232            &actual,
4233            expected,
4234            "golden mismatch in {fixture_path}\n\
4235             expected_blake3={}\n\
4236             actual_blake3={}\n\
4237             bless path: review the semantic diff, update the fixture expected_* field, \
4238             and record both hashes in the Beads closeout.\n\
4239             expected:\n{expected_json}\n\
4240             actual:\n{actual_json}",
4241            blake3::hash(expected_json.as_bytes()),
4242            blake3::hash(actual_json.as_bytes())
4243        );
4244    }
4245
4246    #[test]
4247    fn test_circuit_state_default() {
4248        let _guard = test_guard!();
4249        assert_eq!(CircuitState::default(), CircuitState::Closed);
4250    }
4251
4252    #[test]
4253    fn test_circuit_config_defaults() {
4254        let _guard = test_guard!();
4255        let config = CircuitBreakerConfig::default();
4256        assert_eq!(config.failure_threshold, 3);
4257        assert_eq!(config.success_threshold, 2);
4258        assert_eq!(config.error_rate_threshold, 0.5);
4259        assert_eq!(config.window_secs, 60);
4260        assert_eq!(config.open_cooldown_secs, 30);
4261        assert_eq!(config.half_open_max_probes, 1);
4262    }
4263
4264    #[test]
4265    fn test_rch_config_has_circuit_defaults() {
4266        let _guard = test_guard!();
4267        let config = RchConfig::default();
4268        assert_eq!(config.circuit.failure_threshold, 3);
4269    }
4270
4271    #[test]
4272    fn test_circuit_config_serde_roundtrip() {
4273        let _guard = test_guard!();
4274        let config = CircuitBreakerConfig {
4275            failure_threshold: 5,
4276            success_threshold: 3,
4277            error_rate_threshold: 0.75,
4278            window_secs: 120,
4279            open_cooldown_secs: 45,
4280            half_open_max_probes: 2,
4281            command_failure_threshold: 4,
4282            open_cooldown_max_secs: 900,
4283        };
4284        let json = serde_json::to_string(&config).unwrap();
4285        let parsed: CircuitBreakerConfig = serde_json::from_str(&json).unwrap();
4286        assert_eq!(parsed.command_failure_threshold, 4);
4287        assert_eq!(parsed.open_cooldown_max_secs, 900);
4288        assert_eq!(parsed.failure_threshold, 5);
4289        assert_eq!(parsed.success_threshold, 3);
4290        assert_eq!(parsed.error_rate_threshold, 0.75);
4291        assert_eq!(parsed.window_secs, 120);
4292        assert_eq!(parsed.open_cooldown_secs, 45);
4293        assert_eq!(parsed.half_open_max_probes, 2);
4294    }
4295
4296    // ========================================================================
4297    // WorkerCapabilities Tests
4298    // ========================================================================
4299
4300    #[test]
4301    fn test_worker_capabilities_default() {
4302        let _guard = test_guard!();
4303        let caps = WorkerCapabilities::default();
4304        assert!(caps.rustc_version.is_none());
4305        assert!(caps.rustup_toolchains.is_empty());
4306        assert!(caps.rustup_components.is_empty());
4307        assert!(caps.bun_version.is_none());
4308        assert!(caps.node_version.is_none());
4309        assert!(caps.npm_version.is_none());
4310        assert!(caps.projects_root_ok.is_none());
4311        assert!(caps.projects_root_issue.is_none());
4312        assert!(caps.projects_root_checked_at_unix_ms.is_none());
4313    }
4314
4315    #[test]
4316    fn test_worker_capabilities_new() {
4317        let _guard = test_guard!();
4318        let caps = WorkerCapabilities::new();
4319        assert!(caps.rustc_version.is_none());
4320        assert!(!caps.has_rust());
4321        assert!(!caps.has_bun());
4322        assert!(!caps.has_node());
4323        assert!(caps.is_topology_healthy().is_none());
4324    }
4325
4326    #[test]
4327    fn test_worker_capabilities_has_rust() {
4328        let _guard = test_guard!();
4329        let mut caps = WorkerCapabilities::new();
4330        assert!(!caps.has_rust());
4331
4332        caps.rustc_version = Some("rustc 1.76.0 (07dca489a 2024-02-04)".to_string());
4333        assert!(caps.has_rust());
4334    }
4335
4336    #[test]
4337    fn test_worker_capabilities_components_are_toolchain_scoped_and_exact() {
4338        let _guard = test_guard!();
4339        let caps = WorkerCapabilities {
4340            rustup_components: vec![
4341                "stable-x86_64-unknown-linux-gnu:clippy".to_string(),
4342                "nightly-2026-07-05-x86_64-unknown-linux-gnu:rustfmt".to_string(),
4343                "beta-x86_64-unknown-linux-gnu:clippy-preview".to_string(),
4344            ],
4345            ..Default::default()
4346        };
4347
4348        assert!(caps.has_rustup_component("stable", "clippy"));
4349        assert!(caps.has_rustup_component("nightly-2026-07-05", "rustfmt"));
4350        assert!(!caps.has_rustup_component("nightly-2026-07-05", "clippy"));
4351        assert!(!caps.has_rustup_component("beta", "clippy"));
4352        assert!(!caps.has_rustup_component("nightly-2026-07-0", "rustfmt"));
4353    }
4354
4355    #[test]
4356    fn test_worker_capabilities_has_bun() {
4357        let _guard = test_guard!();
4358        let mut caps = WorkerCapabilities::new();
4359        assert!(!caps.has_bun());
4360
4361        caps.bun_version = Some("1.0.25".to_string());
4362        assert!(caps.has_bun());
4363    }
4364
4365    #[test]
4366    fn test_worker_capabilities_has_nix() {
4367        let _guard = test_guard!();
4368        let mut caps = WorkerCapabilities::new();
4369        assert!(!caps.has_nix());
4370
4371        caps.nix_version = Some("nix (Nix) 2.24.9".to_string());
4372        assert!(caps.has_nix());
4373    }
4374
4375    #[test]
4376    fn test_worker_capabilities_has_zig_requires_both_halves() {
4377        let _guard = test_guard!();
4378        let mut caps = WorkerCapabilities::new();
4379        assert!(!caps.has_zig());
4380
4381        // `zig` alone cannot run `cargo zigbuild` — cargo would report
4382        // `no such command: 'zigbuild'`.
4383        caps.zig_version = Some("0.14.1".to_string());
4384        assert!(!caps.has_zig());
4385
4386        // cargo-zigbuild alone cannot link — it shells out to `zig cc`.
4387        caps.zig_version = None;
4388        caps.cargo_zigbuild_version = Some("cargo-zigbuild 0.23.0".to_string());
4389        assert!(!caps.has_zig());
4390
4391        caps.zig_version = Some("0.14.1".to_string());
4392        assert!(caps.has_zig());
4393    }
4394
4395    #[test]
4396    fn test_nix_build_uses_generous_timeout() {
4397        let _guard = test_guard!();
4398        let cfg = CompilationConfig::default();
4399        // Nix builds get the long test-timeout bucket, not the short build timeout.
4400        assert_eq!(
4401            cfg.timeout_for_kind(Some(CompilationKind::NixBuild)),
4402            std::time::Duration::from_secs(cfg.test_timeout_sec)
4403        );
4404    }
4405
4406    #[test]
4407    fn test_job_uses_build_timeout_bucket() {
4408        let _guard = test_guard!();
4409        // Jobs (explicit `rch exec --job`) reuse the standard build-timeout
4410        // bucket, so `RCH_BUILD_TIMEOUT_SEC` governs them without new config.
4411        let cfg = CompilationConfig::default();
4412        assert_eq!(
4413            cfg.timeout_for_kind(Some(CompilationKind::Job)),
4414            std::time::Duration::from_secs(cfg.build_timeout_sec)
4415        );
4416    }
4417
4418    #[test]
4419    fn test_layer0_disabled_by_default_and_env_gated() {
4420        let _guard = test_guard!();
4421        let cfg = Layer0Config::default();
4422        assert!(!cfg.enabled);
4423        // Master switch off ⇒ nothing injects even with knobs on.
4424        let knobs_on = Layer0Config {
4425            enabled: false,
4426            release_lto_thin: true,
4427            release_codegen_units_1: true,
4428        };
4429        assert!(cfg.active_env().is_empty());
4430        assert!(knobs_on.active_env().is_empty());
4431    }
4432
4433    #[test]
4434    fn test_layer0_knobs_emit_stable_env_pairs() {
4435        let _guard = test_guard!();
4436        let lto_only = Layer0Config {
4437            enabled: true,
4438            release_lto_thin: true,
4439            release_codegen_units_1: false,
4440        };
4441        assert_eq!(
4442            lto_only.active_env(),
4443            vec![("CARGO_PROFILE_RELEASE_LTO", "thin")]
4444        );
4445        let both = Layer0Config {
4446            enabled: true,
4447            release_lto_thin: true,
4448            release_codegen_units_1: true,
4449        };
4450        assert_eq!(
4451            both.active_env(),
4452            vec![
4453                ("CARGO_PROFILE_RELEASE_LTO", "thin"),
4454                ("CARGO_PROFILE_RELEASE_CODEGEN_UNITS", "1"),
4455            ],
4456            "emission order must stay stable for deterministic baselines"
4457        );
4458    }
4459
4460    #[test]
4461    fn test_layer0_pack_version_is_recorded() {
4462        let _guard = test_guard!();
4463        // Baselines record the pack version; it must exist and be non-empty.
4464        assert!(!LAYER0_PACK_VERSION.is_empty());
4465    }
4466    #[test]
4467    fn test_default_allowlist_includes_nix() {
4468        let _guard = test_guard!();
4469        let cfg = ExecutionConfig::default();
4470        assert!(cfg.is_allowed("nix"));
4471    }
4472
4473    #[test]
4474    fn test_worker_capabilities_has_node() {
4475        let _guard = test_guard!();
4476        let mut caps = WorkerCapabilities::new();
4477        assert!(!caps.has_node());
4478
4479        caps.node_version = Some("v20.11.0".to_string());
4480        assert!(caps.has_node());
4481    }
4482
4483    #[test]
4484    fn test_worker_capabilities_multiple_runtimes() {
4485        let _guard = test_guard!();
4486        let caps = WorkerCapabilities {
4487            rustc_version: Some("rustc 1.76.0".to_string()),
4488            bun_version: Some("1.0.25".to_string()),
4489            node_version: Some("v20.11.0".to_string()),
4490            npm_version: Some("10.2.4".to_string()),
4491            ..Default::default()
4492        };
4493
4494        assert!(caps.has_rust());
4495        assert!(caps.has_bun());
4496        assert!(caps.has_node());
4497    }
4498
4499    #[test]
4500    fn test_worker_capabilities_serialization_empty() {
4501        let _guard = test_guard!();
4502        let caps = WorkerCapabilities::new();
4503        let json = serde_json::to_string(&caps).unwrap();
4504        // Empty capabilities should serialize to {}
4505        assert_eq!(json, "{}");
4506
4507        // And deserialize back correctly
4508        let parsed: WorkerCapabilities = serde_json::from_str(&json).unwrap();
4509        assert!(!parsed.has_rust());
4510        assert!(!parsed.has_bun());
4511        assert!(!parsed.has_node());
4512    }
4513
4514    #[test]
4515    fn test_worker_capabilities_serialization_with_versions() {
4516        let _guard = test_guard!();
4517        let caps = WorkerCapabilities {
4518            rustc_version: Some("rustc 1.76.0-nightly".to_string()),
4519            bun_version: Some("1.0.25".to_string()),
4520            node_version: None,
4521            npm_version: None,
4522            ..Default::default()
4523        };
4524
4525        let json = serde_json::to_string(&caps).unwrap();
4526        assert!(json.contains("rustc_version"));
4527        assert!(json.contains("rustc 1.76.0-nightly"));
4528        assert!(json.contains("bun_version"));
4529        assert!(json.contains("1.0.25"));
4530        // None fields should be skipped
4531        assert!(!json.contains("node_version"));
4532        assert!(!json.contains("npm_version"));
4533
4534        let parsed: WorkerCapabilities = serde_json::from_str(&json).unwrap();
4535        assert!(parsed.has_rust());
4536        assert!(parsed.has_bun());
4537        assert!(!parsed.has_node());
4538    }
4539
4540    #[test]
4541    fn test_worker_capabilities_deserialization_partial() {
4542        let _guard = test_guard!();
4543        // Deserialize JSON with only some fields
4544        let json = r#"{"bun_version": "1.0.0"}"#;
4545        let caps: WorkerCapabilities = serde_json::from_str(json).unwrap();
4546
4547        assert!(!caps.has_rust());
4548        assert!(caps.has_bun());
4549        assert!(!caps.has_node());
4550        assert_eq!(caps.bun_version, Some("1.0.0".to_string()));
4551    }
4552
4553    #[test]
4554    fn test_worker_capabilities_clone() {
4555        let _guard = test_guard!();
4556        let caps = WorkerCapabilities {
4557            rustc_version: Some("1.76.0".to_string()),
4558            bun_version: None,
4559            node_version: Some("v20".to_string()),
4560            npm_version: None,
4561            projects_root_ok: Some(false),
4562            projects_root_issue: Some("alias_missing".to_string()),
4563            projects_root_checked_at_unix_ms: Some(123),
4564            ..Default::default()
4565        };
4566
4567        let cloned = caps.clone();
4568        assert_eq!(cloned.rustc_version, caps.rustc_version);
4569        assert_eq!(cloned.bun_version, caps.bun_version);
4570        assert_eq!(cloned.node_version, caps.node_version);
4571        assert_eq!(cloned.npm_version, caps.npm_version);
4572        assert_eq!(cloned.projects_root_ok, caps.projects_root_ok);
4573        assert_eq!(cloned.projects_root_issue, caps.projects_root_issue);
4574        assert_eq!(
4575            cloned.projects_root_checked_at_unix_ms,
4576            caps.projects_root_checked_at_unix_ms
4577        );
4578    }
4579
4580    #[test]
4581    fn test_worker_capabilities_topology_health_helper() {
4582        let _guard = test_guard!();
4583        let mut caps = WorkerCapabilities::new();
4584        assert_eq!(caps.is_topology_healthy(), None);
4585
4586        caps.projects_root_ok = Some(true);
4587        assert_eq!(caps.is_topology_healthy(), Some(true));
4588
4589        caps.projects_root_ok = Some(false);
4590        assert_eq!(caps.is_topology_healthy(), Some(false));
4591    }
4592
4593    #[test]
4594    fn test_selection_reason_serialization() {
4595        let _guard = test_guard!();
4596        // Test that all variants serialize to snake_case
4597        assert_eq!(
4598            serde_json::to_string(&SelectionReason::Success).unwrap(),
4599            "\"success\""
4600        );
4601        assert_eq!(
4602            serde_json::to_string(&SelectionReason::NoWorkersConfigured).unwrap(),
4603            "\"no_workers_configured\""
4604        );
4605        assert_eq!(
4606            serde_json::to_string(&SelectionReason::AllWorkersUnreachable).unwrap(),
4607            "\"all_workers_unreachable\""
4608        );
4609        assert_eq!(
4610            serde_json::to_string(&SelectionReason::AllCircuitsOpen).unwrap(),
4611            "\"all_circuits_open\""
4612        );
4613        assert_eq!(
4614            serde_json::to_string(&SelectionReason::AllWorkersBusy).unwrap(),
4615            "\"all_workers_busy\""
4616        );
4617        assert_eq!(
4618            serde_json::to_string(&SelectionReason::NoWorkersPassedHealth).unwrap(),
4619            "\"no_workers_passed_health\""
4620        );
4621        assert_eq!(
4622            serde_json::to_string(&SelectionReason::AllWorkersFailedPreflight).unwrap(),
4623            "\"all_workers_failed_preflight\""
4624        );
4625        assert_eq!(
4626            serde_json::to_string(&SelectionReason::AllWorkersFailedConvergence).unwrap(),
4627            "\"all_workers_failed_convergence\""
4628        );
4629        assert_eq!(
4630            serde_json::to_string(&SelectionReason::NoAdmissibleWorkers(
4631                "critical_pressure=1,insufficient_slots=1".to_string()
4632            ))
4633            .unwrap(),
4634            "{\"no_admissible_workers\":\"critical_pressure=1,insufficient_slots=1\"}"
4635        );
4636        assert_eq!(
4637            serde_json::to_string(&SelectionReason::NoMatchingWorkers).unwrap(),
4638            "\"no_matching_workers\""
4639        );
4640    }
4641
4642    #[test]
4643    fn test_selection_reason_with_error() {
4644        let _guard = test_guard!();
4645        let reason = SelectionReason::SelectionError("test error".to_string());
4646        let json = serde_json::to_string(&reason).unwrap();
4647        assert!(json.contains("selection_error"));
4648        assert!(json.contains("test error"));
4649    }
4650
4651    #[test]
4652    fn test_selection_reason_deserialization() {
4653        let _guard = test_guard!();
4654        assert_eq!(
4655            serde_json::from_str::<SelectionReason>("\"success\"").unwrap(),
4656            SelectionReason::Success
4657        );
4658        assert_eq!(
4659            serde_json::from_str::<SelectionReason>("\"all_workers_busy\"").unwrap(),
4660            SelectionReason::AllWorkersBusy
4661        );
4662        assert_eq!(
4663            serde_json::from_str::<SelectionReason>("\"no_workers_passed_health\"").unwrap(),
4664            SelectionReason::NoWorkersPassedHealth
4665        );
4666        assert_eq!(
4667            serde_json::from_str::<SelectionReason>("\"all_workers_failed_preflight\"").unwrap(),
4668            SelectionReason::AllWorkersFailedPreflight
4669        );
4670        assert_eq!(
4671            serde_json::from_str::<SelectionReason>("\"all_workers_failed_convergence\"").unwrap(),
4672            SelectionReason::AllWorkersFailedConvergence
4673        );
4674        assert_eq!(
4675            serde_json::from_str::<SelectionReason>(
4676                "{\"no_admissible_workers\":\"critical_pressure=1\"}"
4677            )
4678            .unwrap(),
4679            SelectionReason::NoAdmissibleWorkers("critical_pressure=1".to_string())
4680        );
4681    }
4682
4683    #[test]
4684    fn test_selection_reason_display() {
4685        let _guard = test_guard!();
4686        assert_eq!(
4687            SelectionReason::Success.to_string(),
4688            "worker assigned successfully"
4689        );
4690        assert_eq!(
4691            SelectionReason::NoWorkersConfigured.to_string(),
4692            "no workers configured"
4693        );
4694        assert_eq!(
4695            SelectionReason::AllWorkersUnreachable.to_string(),
4696            "all workers unreachable"
4697        );
4698        assert_eq!(
4699            SelectionReason::AllWorkersBusy.to_string(),
4700            "all workers at capacity"
4701        );
4702        assert_eq!(
4703            SelectionReason::NoWorkersPassedHealth.to_string(),
4704            "no workers passed health thresholds"
4705        );
4706        assert_eq!(
4707            SelectionReason::AllWorkersFailedPreflight.to_string(),
4708            "all workers failed preflight checks"
4709        );
4710        assert_eq!(
4711            SelectionReason::AllWorkersFailedConvergence.to_string(),
4712            "all workers failed repo convergence checks"
4713        );
4714        assert_eq!(
4715            SelectionReason::NoAdmissibleWorkers(
4716                "critical_pressure=1,insufficient_slots=1".to_string()
4717            )
4718            .to_string(),
4719            "no admissible workers: critical_pressure=1,insufficient_slots=1"
4720        );
4721        assert_eq!(
4722            SelectionReason::SelectionError("oops".to_string()).to_string(),
4723            "selection error: oops"
4724        );
4725    }
4726
4727    #[test]
4728    fn test_selection_response_with_worker() {
4729        let _guard = test_guard!();
4730        let response = SelectionResponse {
4731            worker: Some(SelectedWorker {
4732                id: WorkerId::new("test"),
4733                host: "localhost".to_string(),
4734                user: "user".to_string(),
4735                identity_file: "~/.ssh/id_rsa".to_string(),
4736                slots_available: 8,
4737                speed_score: 75.0,
4738                declared_os: None,
4739            }),
4740            reason: SelectionReason::Success,
4741            build_id: None,
4742            diagnostics: None,
4743        };
4744
4745        let json = serde_json::to_string(&response).unwrap();
4746        assert!(json.contains("\"reason\":\"success\""));
4747        assert!(json.contains("\"id\":\"test\""));
4748    }
4749
4750    #[test]
4751    fn test_selection_response_without_worker() {
4752        let _guard = test_guard!();
4753        let response = SelectionResponse {
4754            worker: None,
4755            reason: SelectionReason::AllWorkersBusy,
4756            build_id: None,
4757            diagnostics: None,
4758        };
4759
4760        let json = serde_json::to_string(&response).unwrap();
4761        assert!(json.contains("\"worker\":null"));
4762        assert!(json.contains("\"reason\":\"all_workers_busy\""));
4763    }
4764
4765    #[test]
4766    fn golden_selection_response_with_no_workers_passed_health_diagnostics() {
4767        let _guard = test_guard!();
4768        const FIXTURE_PATH: &str =
4769            "../../tests/goldens/ft_4tp7g/selection_diagnostics_no_workers_passed_health.json";
4770        let fixture: serde_json::Value = serde_json::from_str(include_str!(
4771            "../../tests/goldens/ft_4tp7g/selection_diagnostics_no_workers_passed_health.json"
4772        ))
4773        .expect("selection diagnostics golden fixture parses");
4774        assert_eq!(
4775            fixture["schema_version"],
4776            "rch.golden.selection_diagnostics.v1"
4777        );
4778
4779        let response = SelectionResponse {
4780            worker: None,
4781            reason: SelectionReason::NoWorkersPassedHealth,
4782            build_id: None,
4783            diagnostics: Some(SelectionDiagnostics {
4784                required_runtime: RequiredRuntime::Rust,
4785                estimated_cores: 2,
4786                min_success_rate: 0.8,
4787                fallback_min_success_rate: 0.5,
4788                active_project_exclusion_count: 0,
4789                workers: vec![WorkerSelectionDiagnostic {
4790                    worker_id: WorkerId::new("fixture-worker"),
4791                    status: "healthy".to_string(),
4792                    circuit_state: "closed".to_string(),
4793                    pressure_state: "healthy".to_string(),
4794                    pressure_reason_code: "pressure.ok".to_string(),
4795                    success_rate: Some(0.2),
4796                    min_success_rate: 0.8,
4797                    fallback_min_success_rate: 0.5,
4798                    required_runtime: RequiredRuntime::Rust,
4799                    runtime_available: true,
4800                    available_slots: 8,
4801                    total_slots: 8,
4802                    estimated_cores: 2,
4803                    active_project_excluded: false,
4804                    final_decision: WorkerSelectionDiagnosticDecision::Deny,
4805                    final_reason: "success_rate 0.20 < fallback 0.50".to_string(),
4806                    reason_codes: vec![
4807                        "health.below_min_success_rate".to_string(),
4808                        "health.below_fallback_min_success_rate".to_string(),
4809                    ],
4810                }],
4811            }),
4812        };
4813
4814        assert_golden_json(
4815            serde_json::to_value(&response).expect("response serializes"),
4816            &fixture["expected_response"],
4817            FIXTURE_PATH,
4818        );
4819    }
4820
4821    #[test]
4822    fn test_selection_response_roundtrip() {
4823        let _guard = test_guard!();
4824        let original = SelectionResponse {
4825            worker: Some(SelectedWorker {
4826                id: WorkerId::new("worker-1"),
4827                host: "192.168.1.100".to_string(),
4828                user: "ubuntu".to_string(),
4829                identity_file: "/path/to/key".to_string(),
4830                slots_available: 16,
4831                speed_score: 90.5,
4832                declared_os: None,
4833            }),
4834            reason: SelectionReason::Success,
4835            build_id: None,
4836            diagnostics: None,
4837        };
4838
4839        let json = serde_json::to_string(&original).unwrap();
4840        let parsed: SelectionResponse = serde_json::from_str(&json).unwrap();
4841
4842        assert!(parsed.worker.is_some());
4843        let worker = parsed.worker.unwrap();
4844        assert_eq!(worker.id.as_str(), "worker-1");
4845        assert_eq!(worker.host, "192.168.1.100");
4846        assert_eq!(worker.slots_available, 16);
4847        assert_eq!(parsed.reason, SelectionReason::Success);
4848    }
4849
4850    #[test]
4851    fn test_build_heartbeat_phase_roundtrip() {
4852        let _guard = test_guard!();
4853        let json = serde_json::to_string(&BuildHeartbeatPhase::SyncUp).unwrap();
4854        assert_eq!(json, "\"sync_up\"");
4855        let parsed: BuildHeartbeatPhase = serde_json::from_str(&json).unwrap();
4856        assert_eq!(parsed, BuildHeartbeatPhase::SyncUp);
4857    }
4858
4859    #[test]
4860    fn test_build_heartbeat_request_roundtrip() {
4861        let _guard = test_guard!();
4862        let request = BuildHeartbeatRequest {
4863            build_id: 42,
4864            worker_id: WorkerId::new("worker-a"),
4865            hook_pid: Some(12345),
4866            local_wrapper_id: Some("wrapper-abc123".to_string()),
4867            remote_pgid_file: Some("/tmp/rch/project/hash/.rch-run/42.pgid".to_string()),
4868            phase: BuildHeartbeatPhase::Execute,
4869            detail: Some("Compiling crates".to_string()),
4870            progress_counter: Some(7),
4871            progress_percent: Some(42.5),
4872        };
4873
4874        let json = serde_json::to_string(&request).unwrap();
4875        let parsed: BuildHeartbeatRequest = serde_json::from_str(&json).unwrap();
4876        assert_eq!(parsed.build_id, 42);
4877        assert_eq!(parsed.worker_id.as_str(), "worker-a");
4878        assert_eq!(
4879            parsed.remote_pgid_file,
4880            Some("/tmp/rch/project/hash/.rch-run/42.pgid".to_string())
4881        );
4882        assert_eq!(parsed.phase, BuildHeartbeatPhase::Execute);
4883        assert_eq!(parsed.progress_counter, Some(7));
4884        assert_eq!(parsed.progress_percent, Some(42.5));
4885    }
4886
4887    // CircuitStats tests
4888
4889    #[test]
4890    fn test_circuit_stats_new() {
4891        let _guard = test_guard!();
4892        let stats = CircuitStats::new();
4893        assert_eq!(stats.state(), CircuitState::Closed);
4894        assert_eq!(stats.consecutive_failures(), 0);
4895        assert_eq!(stats.error_rate(), 0.0);
4896        assert!(stats.opened_at().is_none());
4897    }
4898
4899    #[test]
4900    fn test_circuit_stats_record_success() {
4901        let _guard = test_guard!();
4902        let mut stats = CircuitStats::new();
4903        stats.record_success();
4904        stats.record_success();
4905        assert_eq!(stats.error_rate(), 0.0);
4906        assert_eq!(stats.consecutive_failures(), 0);
4907    }
4908
4909    #[test]
4910    fn test_circuit_stats_record_failure() {
4911        let _guard = test_guard!();
4912        let mut stats = CircuitStats::new();
4913        stats.record_failure();
4914        stats.record_failure();
4915        assert_eq!(stats.consecutive_failures(), 2);
4916        assert_eq!(stats.error_rate(), 1.0); // 2 failures, 0 successes
4917    }
4918
4919    #[test]
4920    fn test_circuit_stats_error_rate() {
4921        let _guard = test_guard!();
4922        let mut stats = CircuitStats::new();
4923        stats.record_success();
4924        stats.record_success();
4925        stats.record_failure();
4926        // 1 failure / 3 total = 0.333...
4927        assert!((stats.error_rate() - 0.333).abs() < 0.01);
4928    }
4929
4930    #[test]
4931    fn test_circuit_stats_should_open_consecutive_failures() {
4932        let _guard = test_guard!();
4933        let mut stats = CircuitStats::new();
4934        let config = CircuitBreakerConfig::default(); // threshold = 3
4935
4936        stats.record_failure();
4937        assert!(!stats.should_open(&config));
4938
4939        stats.record_failure();
4940        assert!(!stats.should_open(&config));
4941
4942        stats.record_failure();
4943        assert!(stats.should_open(&config)); // 3 consecutive failures
4944    }
4945
4946    #[test]
4947    fn test_circuit_stats_should_open_error_rate() {
4948        let _guard = test_guard!();
4949        let mut stats = CircuitStats::new();
4950        let config = CircuitBreakerConfig {
4951            error_rate_threshold: 0.5,
4952            ..Default::default()
4953        };
4954
4955        // Need at least 5 samples
4956        stats.record_success();
4957        stats.record_success();
4958        stats.record_failure();
4959        stats.record_failure();
4960        assert!(!stats.should_open(&config)); // Only 4 samples
4961
4962        stats.record_failure(); // 5 samples: 2 success, 3 failures = 60% error rate
4963        assert!(stats.should_open(&config));
4964    }
4965
4966    #[test]
4967    fn test_circuit_close_clears_recent_results_no_flap() {
4968        let _guard = test_guard!();
4969        // Regression: error_rate() is computed over recent_results, so close()
4970        // must clear that history or a recovered circuit immediately re-opens
4971        // on stale pre-failure samples (flapping).
4972        let mut stats = CircuitStats::new();
4973        let config = CircuitBreakerConfig {
4974            error_rate_threshold: 0.5,
4975            ..Default::default()
4976        };
4977        for _ in 0..6 {
4978            stats.record_failure();
4979        }
4980        assert!(stats.should_open(&config));
4981        stats.open();
4982        // Recover via half-open probes, then close.
4983        stats.half_open();
4984        stats.record_success();
4985        stats.record_success();
4986        stats.close();
4987        // Error rate must be reset and the circuit must NOT immediately re-open.
4988        assert_eq!(stats.error_rate(), 0.0);
4989        assert!(!stats.should_open(&config));
4990    }
4991
4992    #[test]
4993    fn test_apply_health_outcome_opens_on_failure_threshold() {
4994        let _guard = test_guard!();
4995        // failure_threshold=3: three unhealthy outcomes open the circuit.
4996        let config = CircuitBreakerConfig {
4997            failure_threshold: 3,
4998            open_cooldown_secs: 300,
4999            ..Default::default()
5000        };
5001        let mut stats = CircuitStats::new();
5002        assert_eq!(
5003            stats.apply_health_outcome(false, false, &config),
5004            CircuitState::Closed
5005        );
5006        assert_eq!(
5007            stats.apply_health_outcome(false, false, &config),
5008            CircuitState::Closed
5009        );
5010        assert_eq!(
5011            stats.apply_health_outcome(false, false, &config),
5012            CircuitState::Open
5013        );
5014    }
5015
5016    #[test]
5017    fn test_apply_health_outcome_half_open_two_probe_recovery() {
5018        let _guard = test_guard!();
5019        // success_threshold=2: recovery from Open needs exactly two clean probes.
5020        // open_cooldown_secs=0 makes should_half_open() true immediately, so the
5021        // engine's trailing nudge leaves an opened circuit already in HalfOpen —
5022        // exactly the state a real daemon would be in on the next poll once the
5023        // cooldown had elapsed. From HalfOpen the engine credits successes.
5024        let config = CircuitBreakerConfig {
5025            failure_threshold: 3,
5026            success_threshold: 2,
5027            open_cooldown_secs: 0,
5028            ..Default::default()
5029        };
5030        let mut stats = CircuitStats::new();
5031        for _ in 0..3 {
5032            stats.apply_health_outcome(false, false, &config);
5033        }
5034        // With a 0s cooldown the engine nudges Open -> HalfOpen immediately.
5035        assert_eq!(stats.state(), CircuitState::HalfOpen);
5036
5037        // First healthy probe in half-open: one success credited, not yet closed.
5038        let after_first = stats.apply_health_outcome(true, false, &config);
5039        assert_eq!(after_first, CircuitState::HalfOpen);
5040
5041        // Second healthy probe: threshold met -> Closed.
5042        let after_second = stats.apply_health_outcome(true, false, &config);
5043        assert_eq!(after_second, CircuitState::Closed);
5044    }
5045
5046    #[test]
5047    fn test_apply_health_outcome_transient_half_open_does_not_reopen() {
5048        let _guard = test_guard!();
5049        // A transient failure while half-open must NOT reset the recovery streak
5050        // — a network blip can't undo an in-progress recovery.
5051        let config = CircuitBreakerConfig {
5052            failure_threshold: 3,
5053            success_threshold: 2,
5054            open_cooldown_secs: 0,
5055            ..Default::default()
5056        };
5057        let mut stats = CircuitStats::new();
5058        for _ in 0..3 {
5059            stats.apply_health_outcome(false, false, &config);
5060        }
5061        // 0s cooldown -> already nudged to HalfOpen.
5062        assert_eq!(stats.state(), CircuitState::HalfOpen);
5063
5064        // One clean probe (1 of 2 needed).
5065        assert_eq!(
5066            stats.apply_health_outcome(true, false, &config),
5067            CircuitState::HalfOpen
5068        );
5069
5070        // Transient failure in half-open: stays HalfOpen (does NOT reopen the
5071        // circuit or restart the cooldown). The key contrast with a real failure
5072        // is that the circuit does not drop back to Open — probing continues in
5073        // place, so recovery resumes immediately on the next clean probes rather
5074        // than waiting out a fresh cooldown.
5075        let after_transient = stats.apply_health_outcome(false, true, &config);
5076        assert_eq!(after_transient, CircuitState::HalfOpen);
5077
5078        // Recovery still completes from half-open with the required clean probes.
5079        assert_eq!(
5080            stats.apply_health_outcome(true, false, &config),
5081            CircuitState::HalfOpen
5082        );
5083        assert_eq!(
5084            stats.apply_health_outcome(true, false, &config),
5085            CircuitState::Closed
5086        );
5087    }
5088
5089    #[test]
5090    fn test_apply_health_outcome_real_vs_transient_half_open_failure() {
5091        let _guard = test_guard!();
5092        // With a positive cooldown the difference is directly observable: a REAL
5093        // half-open failure reopens the circuit (state -> Open, must wait out the
5094        // cooldown again), whereas a TRANSIENT half-open failure keeps it in
5095        // HalfOpen so recovery continues without a fresh cooldown.
5096        //
5097        // Manually drive to HalfOpen (open() + half_open()) so the positive
5098        // cooldown doesn't force a real wallclock wait to reach half-open.
5099        let config = CircuitBreakerConfig {
5100            failure_threshold: 3,
5101            success_threshold: 2,
5102            open_cooldown_secs: 300,
5103            ..Default::default()
5104        };
5105
5106        // Real failure path.
5107        let mut real = CircuitStats::new();
5108        real.open();
5109        real.half_open();
5110        assert_eq!(real.state(), CircuitState::HalfOpen);
5111        let after_real = real.apply_health_outcome(false, false, &config);
5112        assert_eq!(
5113            after_real,
5114            CircuitState::Open,
5115            "a real half-open failure must reopen the circuit"
5116        );
5117
5118        // Transient failure path (same starting state).
5119        let mut transient = CircuitStats::new();
5120        transient.open();
5121        transient.half_open();
5122        assert_eq!(transient.state(), CircuitState::HalfOpen);
5123        let after_transient = transient.apply_health_outcome(false, true, &config);
5124        assert_eq!(
5125            after_transient,
5126            CircuitState::HalfOpen,
5127            "a transient half-open failure must NOT reopen the circuit"
5128        );
5129    }
5130
5131    /// Issue #48 regression: a worker whose liveness probe (`echo` over a warm
5132    /// session) keeps succeeding while every real command times out must NOT
5133    /// be re-admitted. Liveness successes alone cannot close a half-open
5134    /// circuit while command-class evidence is outstanding.
5135    #[test]
5136    fn test_command_failure_blocks_half_open_close_on_liveness_successes() {
5137        let _guard = test_guard!();
5138        let config = CircuitBreakerConfig {
5139            failure_threshold: 3,
5140            success_threshold: 2,
5141            open_cooldown_secs: 0,
5142            command_failure_threshold: 2,
5143            ..Default::default()
5144        };
5145        let mut stats = CircuitStats::new();
5146        stats.open();
5147        stats.half_open();
5148
5149        // The half-open trial: a real command hangs on the worker.
5150        assert_eq!(
5151            stats.apply_command_outcome(false, &config),
5152            CircuitState::HalfOpen,
5153            "cooldown 0: reopen then immediately half-open again"
5154        );
5155        assert_eq!(stats.consecutive_command_failures(), 1);
5156
5157        // Liveness keeps answering — many times over.
5158        for _ in 0..10 {
5159            assert_eq!(
5160                stats.apply_health_outcome(true, false, &config),
5161                CircuitState::HalfOpen,
5162                "liveness successes must not close the circuit while a command failure is outstanding"
5163            );
5164        }
5165
5166        // Only a command-class success clears the evidence and recovers.
5167        assert_eq!(
5168            stats.apply_command_outcome(true, &config),
5169            CircuitState::Closed
5170        );
5171        assert_eq!(stats.consecutive_command_failures(), 0);
5172        assert_eq!(stats.reopen_streak(), 0);
5173    }
5174
5175    /// Issue #48: interleaved liveness successes reset `failure_threshold`, so
5176    /// command failures need their own threshold to open a Closed circuit.
5177    #[test]
5178    fn test_command_failures_open_closed_circuit_despite_liveness_successes() {
5179        let _guard = test_guard!();
5180        let config = CircuitBreakerConfig {
5181            failure_threshold: 3,
5182            command_failure_threshold: 2,
5183            open_cooldown_secs: 300,
5184            ..Default::default()
5185        };
5186        let mut stats = CircuitStats::new();
5187
5188        assert_eq!(
5189            stats.apply_command_outcome(false, &config),
5190            CircuitState::Closed
5191        );
5192        // Two liveness successes in between: consecutive_failures is reset...
5193        stats.apply_health_outcome(true, false, &config);
5194        stats.apply_health_outcome(true, false, &config);
5195        assert_eq!(stats.consecutive_failures(), 0);
5196        // ...but the command-failure count is not, and the second one opens.
5197        assert_eq!(
5198            stats.apply_command_outcome(false, &config),
5199            CircuitState::Open
5200        );
5201        assert_eq!(stats.reopen_streak(), 1);
5202    }
5203
5204    /// A command failure in HalfOpen always reopens: "connected but the
5205    /// command never completed" is exactly what the trial exists to detect,
5206    /// so there is no transient exemption on this channel.
5207    #[test]
5208    fn test_command_failure_in_half_open_always_reopens() {
5209        let _guard = test_guard!();
5210        let config = CircuitBreakerConfig {
5211            open_cooldown_secs: 300,
5212            ..Default::default()
5213        };
5214        let mut stats = CircuitStats::new();
5215        stats.open();
5216        stats.half_open();
5217        assert_eq!(
5218            stats.apply_command_outcome(false, &config),
5219            CircuitState::Open
5220        );
5221        assert_eq!(stats.reopen_streak(), 2);
5222    }
5223
5224    /// Repeated Open -> HalfOpen -> Open cycles lengthen the cooldown
5225    /// (exponential, capped) so a flapping worker converges to Open instead of
5226    /// being re-admitted on every base cooldown.
5227    #[test]
5228    fn test_reopen_streak_backs_off_cooldown_until_cap() {
5229        let _guard = test_guard!();
5230        let config = CircuitBreakerConfig {
5231            open_cooldown_secs: 30,
5232            open_cooldown_max_secs: 100,
5233            ..Default::default()
5234        };
5235        assert_eq!(config.cooldown_ms_for_streak(0), 30_000);
5236        assert_eq!(config.cooldown_ms_for_streak(1), 30_000);
5237        assert_eq!(config.cooldown_ms_for_streak(2), 60_000);
5238        assert_eq!(config.cooldown_ms_for_streak(3), 100_000, "capped");
5239        assert_eq!(config.cooldown_ms_for_streak(40), 100_000, "no overflow");
5240
5241        // A cap below the base never shortens the base cooldown.
5242        let inverted = CircuitBreakerConfig {
5243            open_cooldown_secs: 30,
5244            open_cooldown_max_secs: 5,
5245            ..Default::default()
5246        };
5247        assert_eq!(inverted.cooldown_ms_for_streak(3), 30_000);
5248
5249        // The streak is observable through recovery_remaining_secs: after two
5250        // opens the remaining cooldown exceeds the base.
5251        let mut stats = CircuitStats::new();
5252        stats.open();
5253        stats.half_open();
5254        stats.open();
5255        assert_eq!(stats.reopen_streak(), 2);
5256        let remaining = stats.recovery_remaining_secs(&config).unwrap();
5257        assert!(
5258            remaining > 30 && remaining <= 60,
5259            "second open should wait ~60s, got {remaining}"
5260        );
5261
5262        // Closing resets the streak, so the next open starts from the base.
5263        stats.close();
5264        assert_eq!(stats.reopen_streak(), 0);
5265        stats.open();
5266        assert!(stats.recovery_remaining_secs(&config).unwrap() <= 30);
5267    }
5268
5269    #[test]
5270    fn test_circuit_stats_success_resets_consecutive_failures() {
5271        let _guard = test_guard!();
5272        let mut stats = CircuitStats::new();
5273        stats.record_failure();
5274        stats.record_failure();
5275        assert_eq!(stats.consecutive_failures(), 2);
5276
5277        stats.record_success();
5278        assert_eq!(stats.consecutive_failures(), 0);
5279    }
5280
5281    #[test]
5282    fn test_circuit_stats_open_transition() {
5283        let _guard = test_guard!();
5284        let mut stats = CircuitStats::new();
5285        stats.open();
5286
5287        assert_eq!(stats.state(), CircuitState::Open);
5288        assert!(stats.opened_at().is_some());
5289    }
5290
5291    #[test]
5292    fn test_circuit_stats_half_open_transition() {
5293        let _guard = test_guard!();
5294        let mut stats = CircuitStats::new();
5295        stats.open();
5296        stats.half_open();
5297
5298        assert_eq!(stats.state(), CircuitState::HalfOpen);
5299    }
5300
5301    #[test]
5302    fn test_circuit_stats_close_transition() {
5303        let _guard = test_guard!();
5304        let mut stats = CircuitStats::new();
5305        stats.open();
5306        stats.half_open();
5307        stats.close();
5308
5309        assert_eq!(stats.state(), CircuitState::Closed);
5310        assert!(stats.opened_at().is_none());
5311        assert_eq!(stats.consecutive_failures(), 0);
5312    }
5313
5314    #[test]
5315    fn test_circuit_stats_should_close() {
5316        let _guard = test_guard!();
5317        let mut stats = CircuitStats::new();
5318        let config = CircuitBreakerConfig {
5319            success_threshold: 2,
5320            ..Default::default()
5321        };
5322
5323        stats.open();
5324        stats.half_open();
5325
5326        assert!(!stats.should_close(&config)); // 0 successes
5327
5328        stats.record_success();
5329        assert!(!stats.should_close(&config)); // 1 success
5330
5331        stats.record_success();
5332        assert!(stats.should_close(&config)); // 2 successes
5333    }
5334
5335    #[test]
5336    fn test_circuit_stats_can_probe() {
5337        let _guard = test_guard!();
5338        let mut stats = CircuitStats::new();
5339        let config = CircuitBreakerConfig {
5340            half_open_max_probes: 1,
5341            ..Default::default()
5342        };
5343
5344        // Can't probe when closed
5345        assert!(!stats.can_probe(&config));
5346
5347        stats.open();
5348        // Can't probe when open
5349        assert!(!stats.can_probe(&config));
5350
5351        stats.half_open();
5352        // Can probe when half-open
5353        assert!(stats.can_probe(&config));
5354
5355        // Start a probe
5356        assert!(stats.start_probe(&config));
5357        // Can't start another probe
5358        assert!(!stats.can_probe(&config));
5359        assert!(!stats.start_probe(&config));
5360    }
5361
5362    #[test]
5363    fn test_circuit_stats_probe_completion() {
5364        let _guard = test_guard!();
5365        let mut stats = CircuitStats::new();
5366        let config = CircuitBreakerConfig {
5367            half_open_max_probes: 1,
5368            ..Default::default()
5369        };
5370
5371        stats.open();
5372        stats.half_open();
5373        stats.start_probe(&config);
5374
5375        // Probe completes with success
5376        stats.record_success();
5377
5378        // Can start another probe
5379        assert!(stats.can_probe(&config));
5380    }
5381
5382    #[test]
5383    fn test_circuit_stats_failure_in_half_open() {
5384        let _guard = test_guard!();
5385        let mut stats = CircuitStats::new();
5386        let config = CircuitBreakerConfig {
5387            success_threshold: 2,
5388            ..Default::default()
5389        };
5390
5391        stats.open();
5392        stats.half_open();
5393
5394        stats.record_success();
5395        assert_eq!(stats.consecutive_failures(), 0);
5396
5397        // Failure resets consecutive successes
5398        stats.record_failure();
5399        assert!(!stats.should_close(&config));
5400
5401        // Need 2 more successes
5402        stats.record_success();
5403        stats.record_success();
5404        assert!(stats.should_close(&config));
5405    }
5406
5407    #[test]
5408    fn test_circuit_stats_reset_window() {
5409        let _guard = test_guard!();
5410        let mut stats = CircuitStats::new();
5411        stats.record_success();
5412        stats.record_failure();
5413
5414        assert!(stats.error_rate() > 0.0);
5415
5416        stats.reset_window();
5417        assert_eq!(stats.error_rate(), 0.0);
5418    }
5419
5420    #[test]
5421    fn test_circuit_state_transitions_are_deterministic() {
5422        let _guard = test_guard!();
5423        let config = CircuitBreakerConfig::default();
5424        let mut stats = CircuitStats::new();
5425
5426        // Start closed
5427        assert_eq!(stats.state(), CircuitState::Closed);
5428
5429        // Cause failures to open
5430        for _ in 0..3 {
5431            stats.record_failure();
5432        }
5433        assert!(stats.should_open(&config));
5434        stats.open();
5435        assert_eq!(stats.state(), CircuitState::Open);
5436
5437        // Transition to half-open after cooldown would be checked
5438        stats.half_open();
5439        assert_eq!(stats.state(), CircuitState::HalfOpen);
5440
5441        // Successes to close
5442        for _ in 0..2 {
5443            stats.record_success();
5444        }
5445        assert!(stats.should_close(&config));
5446        stats.close();
5447        assert_eq!(stats.state(), CircuitState::Closed);
5448    }
5449
5450    // ========================================================================
5451    // Compilation Timing Tests
5452    // ========================================================================
5453
5454    fn make_test_metrics(
5455        speedup: Option<f64>,
5456        total_secs: u64,
5457        success: bool,
5458    ) -> CompilationMetrics {
5459        CompilationMetrics {
5460            project_id: "test-project".to_string(),
5461            worker_id: "worker-1".to_string(),
5462            timestamp: chrono::Utc::now(),
5463            timing: CompilationTimingBreakdown {
5464                rsync_up: Duration::from_millis(100),
5465                remote_build: Duration::from_millis(800),
5466                rsync_down: Duration::from_millis(100),
5467                total: Duration::from_secs(total_secs),
5468            },
5469            local_build_time: speedup.map(|s| Duration::from_secs_f64(total_secs as f64 * s)),
5470            speedup,
5471            files_synced: 100,
5472            bytes_transferred: 1_000_000,
5473            exit_code: if success { 0 } else { 1 },
5474            success,
5475        }
5476    }
5477
5478    #[test]
5479    fn test_compilation_timing_breakdown_default() {
5480        let _guard = test_guard!();
5481        let timing = CompilationTimingBreakdown::default();
5482        assert_eq!(timing.rsync_up, Duration::ZERO);
5483        assert_eq!(timing.remote_build, Duration::ZERO);
5484        assert_eq!(timing.rsync_down, Duration::ZERO);
5485        assert_eq!(timing.total, Duration::ZERO);
5486    }
5487
5488    #[test]
5489    fn test_compilation_timing_breakdown_serialization() {
5490        let _guard = test_guard!();
5491        let timing = CompilationTimingBreakdown {
5492            rsync_up: Duration::from_millis(100),
5493            remote_build: Duration::from_millis(2000),
5494            rsync_down: Duration::from_millis(50),
5495            total: Duration::from_millis(2150),
5496        };
5497
5498        let json = serde_json::to_string(&timing).unwrap();
5499        assert!(json.contains("100")); // rsync_up
5500        assert!(json.contains("2000")); // remote_build
5501        assert!(json.contains("50")); // rsync_down
5502        assert!(json.contains("2150")); // total
5503
5504        let parsed: CompilationTimingBreakdown = serde_json::from_str(&json).unwrap();
5505        assert_eq!(parsed.rsync_up, timing.rsync_up);
5506        assert_eq!(parsed.remote_build, timing.remote_build);
5507        assert_eq!(parsed.rsync_down, timing.rsync_down);
5508        assert_eq!(parsed.total, timing.total);
5509    }
5510
5511    #[test]
5512    fn test_command_timing_breakdown_serialization() {
5513        let _guard = test_guard!();
5514        let timing = CommandTimingBreakdown {
5515            classify: Some(Duration::from_millis(2)),
5516            select: None,
5517            sync_up: Some(Duration::from_millis(120)),
5518            exec: Some(Duration::from_millis(900)),
5519            sync_down: None,
5520            cleanup: Some(Duration::from_millis(5)),
5521            total: Some(Duration::from_millis(1027)),
5522        };
5523
5524        let json = serde_json::to_string(&timing).unwrap();
5525        assert!(json.contains("\"classify\":2"));
5526        assert!(json.contains("\"select\":null"));
5527        assert!(json.contains("\"sync_up\":120"));
5528        assert!(json.contains("\"exec\":900"));
5529        assert!(json.contains("\"sync_down\":null"));
5530        assert!(json.contains("\"cleanup\":5"));
5531        assert!(json.contains("\"total\":1027"));
5532
5533        let parsed: CommandTimingBreakdown = serde_json::from_str(&json).unwrap();
5534        assert_eq!(parsed.classify, timing.classify);
5535        assert_eq!(parsed.select, timing.select);
5536        assert_eq!(parsed.sync_up, timing.sync_up);
5537        assert_eq!(parsed.exec, timing.exec);
5538        assert_eq!(parsed.sync_down, timing.sync_down);
5539        assert_eq!(parsed.cleanup, timing.cleanup);
5540        assert_eq!(parsed.total, timing.total);
5541    }
5542
5543    #[test]
5544    fn test_compilation_metrics_calculate_speedup() {
5545        let _guard = test_guard!();
5546        let mut metrics = CompilationMetrics {
5547            timing: CompilationTimingBreakdown {
5548                total: Duration::from_secs(10),
5549                ..Default::default()
5550            },
5551            local_build_time: Some(Duration::from_secs(30)),
5552            ..Default::default()
5553        };
5554
5555        metrics.calculate_speedup();
5556
5557        assert!(metrics.speedup.is_some());
5558        let speedup = metrics.speedup.unwrap();
5559        assert!(
5560            (speedup - 3.0).abs() < 0.01,
5561            "Expected 3.0x speedup, got {}",
5562            speedup
5563        );
5564    }
5565
5566    #[test]
5567    fn test_compilation_metrics_is_beneficial() {
5568        let _guard = test_guard!();
5569        let mut metrics = CompilationMetrics::default();
5570
5571        // No speedup calculated
5572        assert!(!metrics.is_beneficial());
5573
5574        // Speedup > 1 is beneficial
5575        metrics.speedup = Some(1.5);
5576        assert!(metrics.is_beneficial());
5577
5578        // Speedup < 1 is not beneficial
5579        metrics.speedup = Some(0.8);
5580        assert!(!metrics.is_beneficial());
5581
5582        // Speedup = 1 is not beneficial (exactly same speed)
5583        metrics.speedup = Some(1.0);
5584        assert!(!metrics.is_beneficial());
5585    }
5586
5587    #[test]
5588    fn test_compilation_metrics_serialization() {
5589        let _guard = test_guard!();
5590        let metrics = make_test_metrics(Some(2.5), 10, true);
5591        let json = serde_json::to_string(&metrics).unwrap();
5592
5593        assert!(json.contains("test-project"));
5594        assert!(json.contains("worker-1"));
5595        assert!(json.contains("2.5")); // speedup
5596
5597        let parsed: CompilationMetrics = serde_json::from_str(&json).unwrap();
5598        assert_eq!(parsed.project_id, "test-project");
5599        assert_eq!(parsed.worker_id, "worker-1");
5600        assert!(parsed.success);
5601    }
5602
5603    #[test]
5604    fn test_compilation_timer_new() {
5605        let _guard = test_guard!();
5606        let timer = CompilationTimer::new("my-project", "my-worker");
5607        assert_eq!(timer.project_id, "my-project");
5608        assert_eq!(timer.worker_id, "my-worker");
5609        assert!(timer.rsync_up.is_none());
5610        assert!(timer.remote_build.is_none());
5611        assert!(timer.rsync_down.is_none());
5612    }
5613
5614    #[test]
5615    fn test_compilation_timer_phases() {
5616        let _guard = test_guard!();
5617        let mut timer = CompilationTimer::new("test", "worker");
5618
5619        // Simulate rsync up
5620        std::thread::sleep(Duration::from_millis(5));
5621        timer.end_rsync_up();
5622        assert!(timer.rsync_up.is_some());
5623        assert!(timer.rsync_up.unwrap() >= Duration::from_millis(5));
5624
5625        // Simulate remote build
5626        std::thread::sleep(Duration::from_millis(10));
5627        timer.end_remote_build();
5628        assert!(timer.remote_build.is_some());
5629        assert!(timer.remote_build.unwrap() >= Duration::from_millis(10));
5630
5631        // Simulate rsync down
5632        std::thread::sleep(Duration::from_millis(5));
5633        timer.end_rsync_down();
5634        assert!(timer.rsync_down.is_some());
5635        assert!(timer.rsync_down.unwrap() >= Duration::from_millis(5));
5636
5637        // Finish
5638        let metrics = timer.finish(0, 50, 500_000);
5639        assert_eq!(metrics.project_id, "test");
5640        assert_eq!(metrics.worker_id, "worker");
5641        assert!(metrics.success);
5642        assert!(metrics.timing.total >= Duration::from_millis(20));
5643        assert_eq!(metrics.files_synced, 50);
5644        assert_eq!(metrics.bytes_transferred, 500_000);
5645    }
5646
5647    #[test]
5648    fn test_metrics_aggregator_new() {
5649        let _guard = test_guard!();
5650        let agg = MetricsAggregator::new(100);
5651        assert_eq!(agg.count(), 0);
5652        assert!(agg.average_speedup().is_none());
5653    }
5654
5655    #[test]
5656    fn test_metrics_aggregator_record() {
5657        let _guard = test_guard!();
5658        let mut agg = MetricsAggregator::new(3);
5659
5660        // Record first metric
5661        agg.record(make_test_metrics(Some(2.0), 10, true));
5662        assert_eq!(agg.count(), 1);
5663
5664        // Record up to max
5665        agg.record(make_test_metrics(Some(3.0), 20, true));
5666        agg.record(make_test_metrics(Some(4.0), 30, true));
5667        assert_eq!(agg.count(), 3);
5668
5669        // Exceed max should drop oldest
5670        agg.record(make_test_metrics(Some(5.0), 40, true));
5671        assert_eq!(agg.count(), 3);
5672    }
5673
5674    #[test]
5675    fn test_metrics_aggregator_average_speedup() {
5676        let _guard = test_guard!();
5677        let mut agg = MetricsAggregator::new(100);
5678
5679        // Empty case
5680        assert!(agg.average_speedup().is_none());
5681
5682        // Add metrics with speedups 1, 2, 3, 4, 5 -> average = 3
5683        for i in 1..=5 {
5684            agg.record(make_test_metrics(Some(i as f64), 10, true));
5685        }
5686
5687        let avg = agg.average_speedup().unwrap();
5688        assert!((avg - 3.0).abs() < 0.01, "Expected 3.0, got {}", avg);
5689    }
5690
5691    #[test]
5692    fn test_metrics_aggregator_average_speedup_with_none() {
5693        let _guard = test_guard!();
5694        let mut agg = MetricsAggregator::new(100);
5695
5696        // Mix of Some and None speedups
5697        agg.record(make_test_metrics(Some(2.0), 10, true));
5698        agg.record(make_test_metrics(None, 10, true)); // No speedup
5699        agg.record(make_test_metrics(Some(4.0), 10, true));
5700
5701        // Average should only consider metrics with speedup
5702        let avg = agg.average_speedup().unwrap();
5703        assert!((avg - 3.0).abs() < 0.01, "Expected 3.0, got {}", avg);
5704    }
5705
5706    #[test]
5707    fn test_metrics_aggregator_percentiles() {
5708        let _guard = test_guard!();
5709        let mut agg = MetricsAggregator::new(100);
5710
5711        // Add metrics with total times 1s, 2s, 3s, ..., 10s
5712        for i in 1..=10 {
5713            agg.record(make_test_metrics(Some(1.0), i, true));
5714        }
5715
5716        // p50 (median) should be around 5s
5717        let p50 = agg.p50_total_time().unwrap();
5718        assert!(p50 >= Duration::from_secs(5) && p50 <= Duration::from_secs(6));
5719
5720        // p95 should be around 9s or 10s
5721        let p95 = agg.p95_total_time().unwrap();
5722        assert!(p95 >= Duration::from_secs(9) && p95 <= Duration::from_secs(10));
5723
5724        // p99 should be 10s
5725        let p99 = agg.p99_total_time().unwrap();
5726        assert!(p99 >= Duration::from_secs(9));
5727    }
5728
5729    #[test]
5730    fn test_metrics_aggregator_success_rate() {
5731        let _guard = test_guard!();
5732        let mut agg = MetricsAggregator::new(100);
5733
5734        // Empty case
5735        assert_eq!(agg.success_rate(), 100.0);
5736
5737        // All successful
5738        agg.record(make_test_metrics(Some(1.0), 10, true));
5739        agg.record(make_test_metrics(Some(1.0), 10, true));
5740        assert_eq!(agg.success_rate(), 100.0);
5741
5742        // Add a failure (2 success, 1 failure = 66.67%)
5743        agg.record(make_test_metrics(Some(1.0), 10, false));
5744        let rate = agg.success_rate();
5745        assert!((rate - 66.67).abs() < 1.0, "Expected ~66.67%, got {}", rate);
5746    }
5747
5748    #[test]
5749    fn test_metrics_aggregator_clear() {
5750        let _guard = test_guard!();
5751        let mut agg = MetricsAggregator::new(100);
5752        agg.record(make_test_metrics(Some(1.0), 10, true));
5753        agg.record(make_test_metrics(Some(2.0), 20, true));
5754
5755        assert_eq!(agg.count(), 2);
5756
5757        agg.clear();
5758        assert_eq!(agg.count(), 0);
5759        assert!(agg.average_speedup().is_none());
5760    }
5761
5762    // CompilationConfig timeout tests
5763
5764    #[test]
5765    fn test_remote_build_jobs_parse_display_and_serde() {
5766        let _guard = test_guard!();
5767        assert_eq!(RemoteBuildJobs::default(), RemoteBuildJobs::Auto);
5768        for (spelling, expected) in [
5769            ("auto", RemoteBuildJobs::Auto),
5770            (" AUTO ", RemoteBuildJobs::Auto),
5771            ("off", RemoteBuildJobs::Off),
5772            ("none", RemoteBuildJobs::Off),
5773            ("4", RemoteBuildJobs::Fixed(4)),
5774        ] {
5775            assert_eq!(
5776                RemoteBuildJobs::parse(spelling).unwrap(),
5777                expected,
5778                "{spelling}"
5779            );
5780        }
5781        assert!(RemoteBuildJobs::parse("0").is_err(), "cargo rejects -j 0");
5782        assert!(RemoteBuildJobs::parse("many").is_err());
5783        assert_eq!(RemoteBuildJobs::Fixed(4).to_string(), "4");
5784        assert_eq!(RemoteBuildJobs::Off.to_string(), "off");
5785
5786        // TOML accepts both the string spellings and a bare integer, and an
5787        // absent key keeps the default.
5788        #[derive(Deserialize)]
5789        struct Wrap {
5790            compilation: CompilationConfig,
5791        }
5792        let parsed: Wrap = toml::from_str("[compilation]\nremote_build_jobs = \"off\"\n").unwrap();
5793        assert_eq!(parsed.compilation.remote_build_jobs, RemoteBuildJobs::Off);
5794        let parsed: Wrap = toml::from_str("[compilation]\nremote_build_jobs = 6\n").unwrap();
5795        assert_eq!(
5796            parsed.compilation.remote_build_jobs,
5797            RemoteBuildJobs::Fixed(6)
5798        );
5799        let parsed: Wrap = toml::from_str("[compilation]\nbuild_slots = 4\n").unwrap();
5800        assert_eq!(parsed.compilation.remote_build_jobs, RemoteBuildJobs::Auto);
5801        assert!(toml::from_str::<Wrap>("[compilation]\nremote_build_jobs = 0\n").is_err());
5802
5803        // Serialization round-trips through the same spellings.
5804        let json = serde_json::to_string(&RemoteBuildJobs::Fixed(3)).unwrap();
5805        assert_eq!(json, "3");
5806        assert_eq!(
5807            serde_json::to_string(&RemoteBuildJobs::Auto).unwrap(),
5808            "\"auto\""
5809        );
5810        let back: RemoteBuildJobs = serde_json::from_str("\"auto\"").unwrap();
5811        assert_eq!(back, RemoteBuildJobs::Auto);
5812    }
5813
5814    #[test]
5815    fn test_compilation_config_default_timeouts() {
5816        let _guard = test_guard!();
5817        let config = CompilationConfig::default();
5818        // Default build timeout: 5 minutes
5819        assert_eq!(config.build_timeout_sec, 300);
5820        // Default test timeout: 30 minutes
5821        assert_eq!(config.test_timeout_sec, 1800);
5822    }
5823
5824    #[test]
5825    fn test_compilation_config_timeout_for_test_kinds() {
5826        let _guard = test_guard!();
5827        let config = CompilationConfig::default();
5828
5829        // Test commands should get test_timeout_sec
5830        assert_eq!(
5831            config.timeout_for_kind(Some(crate::CompilationKind::CargoTest)),
5832            std::time::Duration::from_secs(1800)
5833        );
5834        assert_eq!(
5835            config.timeout_for_kind(Some(crate::CompilationKind::CargoNextest)),
5836            std::time::Duration::from_secs(1800)
5837        );
5838        assert_eq!(
5839            config.timeout_for_kind(Some(crate::CompilationKind::BunTest)),
5840            std::time::Duration::from_secs(config.bun_timeout_sec)
5841        );
5842    }
5843
5844    #[test]
5845    fn test_compilation_config_timeout_for_build_kinds() {
5846        let _guard = test_guard!();
5847        let config = CompilationConfig::default();
5848
5849        // Build/check commands should get build_timeout_sec
5850        assert_eq!(
5851            config.timeout_for_kind(Some(crate::CompilationKind::CargoBuild)),
5852            std::time::Duration::from_secs(300)
5853        );
5854        assert_eq!(
5855            config.timeout_for_kind(Some(crate::CompilationKind::CargoCheck)),
5856            std::time::Duration::from_secs(300)
5857        );
5858        assert_eq!(
5859            config.timeout_for_kind(Some(crate::CompilationKind::CargoClippy)),
5860            std::time::Duration::from_secs(300)
5861        );
5862        assert_eq!(
5863            config.timeout_for_kind(None),
5864            std::time::Duration::from_secs(300)
5865        );
5866    }
5867
5868    #[test]
5869    fn test_compilation_config_custom_timeouts() {
5870        let _guard = test_guard!();
5871        let config = CompilationConfig {
5872            build_timeout_sec: 600, // 10 minutes
5873            test_timeout_sec: 3600, // 1 hour
5874            ..Default::default()
5875        };
5876
5877        assert_eq!(
5878            config.timeout_for_kind(Some(crate::CompilationKind::CargoBuild)),
5879            std::time::Duration::from_secs(600)
5880        );
5881        assert_eq!(
5882            config.timeout_for_kind(Some(crate::CompilationKind::CargoTest)),
5883            std::time::Duration::from_secs(3600)
5884        );
5885    }
5886
5887    #[test]
5888    fn test_compilation_config_speedup_threshold_default() {
5889        let _guard = test_guard!();
5890        let config = CompilationConfig::default();
5891        // Default speedup threshold: 1.2 (20% faster required)
5892        assert!((config.remote_speedup_threshold - 1.2).abs() < 0.001);
5893    }
5894
5895    #[test]
5896    fn test_compilation_config_speedup_threshold_custom() {
5897        let _guard = test_guard!();
5898        let config = CompilationConfig {
5899            remote_speedup_threshold: 1.5, // Require 50% faster
5900            ..Default::default()
5901        };
5902        assert!((config.remote_speedup_threshold - 1.5).abs() < 0.001);
5903    }
5904
5905    #[test]
5906    fn test_compilation_config_speedup_threshold_no_minimum() {
5907        let _guard = test_guard!();
5908        // Setting to 1.0 means "always offload when other criteria met"
5909        let config = CompilationConfig {
5910            remote_speedup_threshold: 1.0,
5911            ..Default::default()
5912        };
5913        assert!((config.remote_speedup_threshold - 1.0).abs() < 0.001);
5914    }
5915
5916    #[test]
5917    fn test_compilation_config_min_local_time_ms_default() {
5918        let _guard = test_guard!();
5919        let config = CompilationConfig::default();
5920        // Default min_local_time_ms: 2000ms
5921        assert_eq!(config.min_local_time_ms, 2000);
5922    }
5923
5924    #[test]
5925    fn test_compilation_config_serde_roundtrip_speedup_threshold() {
5926        let _guard = test_guard!();
5927        let config = CompilationConfig {
5928            remote_speedup_threshold: 2.5,
5929            min_local_time_ms: 5000,
5930            ..Default::default()
5931        };
5932        let json = serde_json::to_string(&config).unwrap();
5933        let parsed: CompilationConfig = serde_json::from_str(&json).unwrap();
5934        assert!((parsed.remote_speedup_threshold - 2.5).abs() < 0.001);
5935        assert_eq!(parsed.min_local_time_ms, 5000);
5936    }
5937
5938    // ========================================================================
5939    // validate_remote_base Tests
5940    // ========================================================================
5941
5942    #[test]
5943    fn test_validate_remote_base_absolute_path() {
5944        let _guard = test_guard!();
5945        assert_eq!(validate_remote_base("/tmp/rch").unwrap(), "/tmp/rch");
5946        assert_eq!(
5947            validate_remote_base("/var/rch-builds").unwrap(),
5948            "/var/rch-builds"
5949        );
5950        assert_eq!(
5951            validate_remote_base("/home/builder/.rch").unwrap(),
5952            "/home/builder/.rch"
5953        );
5954    }
5955
5956    #[test]
5957    fn test_validate_remote_base_tilde_expansion() {
5958        let _guard = test_guard!();
5959        // Tilde expansion should work
5960        let result = validate_remote_base("~/rch");
5961        assert!(result.is_ok());
5962        let path = result.unwrap();
5963        assert!(
5964            path.starts_with('/'),
5965            "Path should be absolute after expansion: {}",
5966            path
5967        );
5968        assert!(!path.contains('~'), "Tilde should be expanded: {}", path);
5969    }
5970
5971    #[test]
5972    fn test_validate_remote_base_rejects_relative_path() {
5973        let _guard = test_guard!();
5974        let result = validate_remote_base("tmp/rch");
5975        assert!(result.is_err());
5976        assert!(result.unwrap_err().contains("absolute path"));
5977    }
5978
5979    #[test]
5980    fn test_validate_remote_base_rejects_path_traversal() {
5981        let _guard = test_guard!();
5982        let result = validate_remote_base("/tmp/../etc/rch");
5983        assert!(result.is_err());
5984        assert!(result.unwrap_err().contains("path traversal"));
5985
5986        let result = validate_remote_base("/tmp/rch/../other");
5987        assert!(result.is_err());
5988        assert!(result.unwrap_err().contains("path traversal"));
5989    }
5990
5991    #[test]
5992    fn test_validate_remote_base_normalizes_trailing_slash() {
5993        let _guard = test_guard!();
5994        assert_eq!(validate_remote_base("/tmp/rch/").unwrap(), "/tmp/rch");
5995        assert_eq!(validate_remote_base("/tmp/rch///").unwrap(), "/tmp/rch");
5996    }
5997
5998    #[test]
5999    fn test_validate_remote_base_root_path() {
6000        let _guard = test_guard!();
6001        // Root path should be rejected
6002        let result = validate_remote_base("/");
6003        assert!(result.is_err());
6004        assert!(result.unwrap_err().contains("root directory"));
6005    }
6006
6007    #[test]
6008    fn test_validate_remote_base_rejects_top_level() {
6009        let _guard = test_guard!();
6010        // Top-level directories should be rejected (depth 1)
6011        let result = validate_remote_base("/tmp");
6012        assert!(result.is_err());
6013        assert!(result.unwrap_err().contains("at least 2 levels deep"));
6014
6015        let result = validate_remote_base("/home");
6016        assert!(result.is_err());
6017
6018        // Depth 2 should be allowed
6019        assert_eq!(validate_remote_base("/tmp/rch").unwrap(), "/tmp/rch");
6020    }
6021
6022    #[test]
6023    fn test_default_remote_base() {
6024        let _guard = test_guard!();
6025        assert_eq!(default_remote_base(), "/data/tmp/rch");
6026    }
6027
6028    #[test]
6029    fn test_transfer_config_default_has_remote_base() {
6030        let _guard = test_guard!();
6031        let config = TransferConfig::default();
6032        assert_eq!(config.remote_base, "/data/tmp/rch");
6033    }
6034
6035    #[test]
6036    fn test_source_sync_timeout_validation_boundaries() {
6037        let _guard = test_guard!();
6038        assert!(!TransferConfig::valid_sync_timeout_ms(0));
6039        assert!(!TransferConfig::valid_sync_timeout_ms(999));
6040        assert!(TransferConfig::valid_sync_timeout_ms(1_000));
6041        assert!(TransferConfig::valid_sync_timeout_ms(3_600_000));
6042        assert!(!TransferConfig::valid_sync_timeout_ms(3_600_001));
6043    }
6044
6045    #[test]
6046    fn test_source_sync_timeout_is_explicit_or_payload_aware() {
6047        let _guard = test_guard!();
6048        let default = TransferConfig::default();
6049        assert_eq!(
6050            default.sync_timeout_for_payload(0),
6051            std::time::Duration::from_millis(30_000)
6052        );
6053        assert_eq!(
6054            default.sync_timeout_for_payload(10 * 1024 * 1024),
6055            std::time::Duration::from_millis(40_000)
6056        );
6057        assert_eq!(
6058            default.sync_timeout_for_payload(u64::MAX),
6059            std::time::Duration::from_millis(3_600_000)
6060        );
6061
6062        let explicit = TransferConfig {
6063            sync_timeout_ms: Some(120_000),
6064            ..TransferConfig::default()
6065        };
6066        assert_eq!(
6067            explicit.sync_timeout_for_payload(u64::MAX),
6068            std::time::Duration::from_millis(120_000)
6069        );
6070    }
6071
6072    // ========================================================================
6073    // RetryConfig Tests (bd-x1ek)
6074    // ========================================================================
6075
6076    #[test]
6077    fn test_retry_config_default() {
6078        let _guard = test_guard!();
6079        let config = RetryConfig::default();
6080        assert_eq!(config.max_attempts, 3);
6081        assert_eq!(config.base_delay_ms, 100);
6082        assert_eq!(config.max_delay_ms, 5000);
6083        assert_eq!(config.jitter_factor, 0.1);
6084        assert_eq!(config.total_timeout_ms, 30000);
6085    }
6086
6087    #[test]
6088    fn test_retry_config_no_retry() {
6089        let _guard = test_guard!();
6090        let config = RetryConfig::no_retry();
6091        assert_eq!(config.max_attempts, 1);
6092    }
6093
6094    #[test]
6095    fn test_retry_config_delay_for_attempt_zero() {
6096        let _guard = test_guard!();
6097        let config = RetryConfig::default();
6098        assert_eq!(config.delay_for_attempt(0), std::time::Duration::ZERO);
6099    }
6100
6101    #[test]
6102    fn test_retry_config_delay_for_attempt_exponential() {
6103        let _guard = test_guard!();
6104        let config = RetryConfig {
6105            base_delay_ms: 100,
6106            max_delay_ms: 10000,
6107            jitter_factor: 0.0, // No jitter for deterministic test
6108            ..Default::default()
6109        };
6110
6111        // attempt 1: 100 * 2^0 = 100ms
6112        assert_eq!(
6113            config.delay_for_attempt(1),
6114            std::time::Duration::from_millis(100)
6115        );
6116        // attempt 2: 100 * 2^1 = 200ms
6117        assert_eq!(
6118            config.delay_for_attempt(2),
6119            std::time::Duration::from_millis(200)
6120        );
6121        // attempt 3: 100 * 2^2 = 400ms
6122        assert_eq!(
6123            config.delay_for_attempt(3),
6124            std::time::Duration::from_millis(400)
6125        );
6126    }
6127
6128    #[test]
6129    fn test_retry_config_delay_capped_at_max() {
6130        let _guard = test_guard!();
6131        let config = RetryConfig {
6132            base_delay_ms: 1000,
6133            max_delay_ms: 2000,
6134            jitter_factor: 0.0,
6135            ..Default::default()
6136        };
6137
6138        // attempt 2: 1000 * 2^1 = 2000ms (at cap)
6139        assert_eq!(
6140            config.delay_for_attempt(2),
6141            std::time::Duration::from_millis(2000)
6142        );
6143        // attempt 3: 1000 * 2^2 = 4000ms, capped to 2000ms
6144        assert_eq!(
6145            config.delay_for_attempt(3),
6146            std::time::Duration::from_millis(2000)
6147        );
6148    }
6149
6150    #[test]
6151    fn test_retry_config_random_jitter_stays_within_bounds() {
6152        let _guard = test_guard!();
6153        let config = RetryConfig {
6154            base_delay_ms: 100,
6155            max_delay_ms: 200,
6156            jitter_factor: 0.25,
6157            ..Default::default()
6158        };
6159
6160        // Jitter applies after the exponential delay is capped. Exercise the
6161        // real RNG without requiring any particular random value or sequence.
6162        for (attempt, minimum_ms, maximum_ms) in [(1, 75, 125), (3, 150, 250)] {
6163            for _ in 0..128 {
6164                let delay = config.delay_for_attempt(attempt);
6165                assert!(delay >= std::time::Duration::from_millis(minimum_ms));
6166                assert!(delay <= std::time::Duration::from_millis(maximum_ms));
6167            }
6168        }
6169    }
6170
6171    #[test]
6172    fn test_retry_config_should_retry() {
6173        let _guard = test_guard!();
6174        let config = RetryConfig {
6175            max_attempts: 3,
6176            total_timeout_ms: 1000,
6177            ..Default::default()
6178        };
6179
6180        // Before max attempts and within timeout
6181        assert!(config.should_retry(0, std::time::Duration::from_millis(0)));
6182        assert!(config.should_retry(1, std::time::Duration::from_millis(500)));
6183        assert!(config.should_retry(2, std::time::Duration::from_millis(900)));
6184
6185        // At max attempts
6186        assert!(!config.should_retry(3, std::time::Duration::from_millis(0)));
6187
6188        // Past timeout
6189        assert!(!config.should_retry(1, std::time::Duration::from_millis(1001)));
6190    }
6191
6192    #[test]
6193    fn test_retry_config_serde_roundtrip() {
6194        let _guard = test_guard!();
6195        let config = RetryConfig {
6196            max_attempts: 5,
6197            base_delay_ms: 200,
6198            max_delay_ms: 8000,
6199            jitter_factor: 0.2,
6200            total_timeout_ms: 60000,
6201        };
6202        let json = serde_json::to_string(&config).unwrap();
6203        let parsed: RetryConfig = serde_json::from_str(&json).unwrap();
6204        assert_eq!(parsed.max_attempts, 5);
6205        assert_eq!(parsed.base_delay_ms, 200);
6206        assert_eq!(parsed.max_delay_ms, 8000);
6207        assert_eq!(parsed.jitter_factor, 0.2);
6208        assert_eq!(parsed.total_timeout_ms, 60000);
6209    }
6210
6211    #[test]
6212    fn test_transfer_config_includes_retry() {
6213        let _guard = test_guard!();
6214        let config = TransferConfig::default();
6215        assert_eq!(config.retry.max_attempts, 3);
6216    }
6217
6218    // =========================================================================
6219    // ExecutionConfig Tests (bd-785w)
6220    // =========================================================================
6221
6222    #[test]
6223    fn test_execution_config_default_allowlist() {
6224        let _guard = test_guard!();
6225        let config = ExecutionConfig::default();
6226        // All supported compilers should be in the default allowlist
6227        assert!(config.is_allowed("cargo"));
6228        assert!(config.is_allowed("rustc"));
6229        assert!(config.is_allowed("gcc"));
6230        assert!(config.is_allowed("g++"));
6231        assert!(config.is_allowed("clang"));
6232        assert!(config.is_allowed("clang++"));
6233        assert!(config.is_allowed("make"));
6234        assert!(config.is_allowed("cmake"));
6235        assert!(config.is_allowed("ninja"));
6236        assert!(config.is_allowed("meson"));
6237        assert!(config.is_allowed("bun"));
6238        assert!(config.is_allowed("nextest"));
6239        assert!(config.is_allowed("cc"));
6240        assert!(config.is_allowed("c++"));
6241    }
6242
6243    #[test]
6244    fn test_execution_config_is_allowed_case_insensitive() {
6245        let _guard = test_guard!();
6246        let config = ExecutionConfig::default();
6247        // Should be case-insensitive
6248        assert!(config.is_allowed("CARGO"));
6249        assert!(config.is_allowed("Cargo"));
6250        assert!(config.is_allowed("GCC"));
6251        assert!(config.is_allowed("Gcc"));
6252    }
6253
6254    #[test]
6255    fn test_execution_config_is_not_allowed() {
6256        let _guard = test_guard!();
6257        let config = ExecutionConfig::default();
6258        // Unknown commands should not be allowed
6259        assert!(!config.is_allowed("python"));
6260        assert!(!config.is_allowed("npm"));
6261        assert!(!config.is_allowed(""));
6262        // `go` and `tsc` ARE allowed now that Go/TypeScript are offload targets.
6263        // If they were missing from the allowlist the hook would fail open to
6264        // LOCAL execution — classification would look correct while every build
6265        // silently ran on the orchestrator.
6266        assert!(config.is_allowed("go"));
6267        assert!(config.is_allowed("tsc"));
6268    }
6269
6270    #[test]
6271    fn test_execution_config_empty_allowlist() {
6272        let _guard = test_guard!();
6273        let config = ExecutionConfig { allowlist: vec![] };
6274        // Empty allowlist should block everything
6275        assert!(!config.is_allowed("cargo"));
6276        assert!(!config.is_allowed("gcc"));
6277    }
6278
6279    #[test]
6280    fn test_execution_config_custom_allowlist() {
6281        let _guard = test_guard!();
6282        let config = ExecutionConfig {
6283            allowlist: vec!["cargo".to_string(), "custom_tool".to_string()],
6284        };
6285        assert!(config.is_allowed("cargo"));
6286        assert!(config.is_allowed("custom_tool"));
6287        assert!(!config.is_allowed("gcc"));
6288    }
6289
6290    #[test]
6291    fn test_execution_config_serde() {
6292        let _guard = test_guard!();
6293        let config = ExecutionConfig {
6294            allowlist: vec!["cargo".to_string(), "rustc".to_string()],
6295        };
6296        let json = serde_json::to_string(&config).unwrap();
6297        let parsed: ExecutionConfig = serde_json::from_str(&json).unwrap();
6298        assert_eq!(parsed.allowlist, config.allowlist);
6299    }
6300
6301    #[test]
6302    fn test_rch_config_includes_execution() {
6303        let _guard = test_guard!();
6304        let config = RchConfig::default();
6305        // RchConfig should include ExecutionConfig with default allowlist
6306        assert!(config.execution.is_allowed("cargo"));
6307    }
6308
6309    // ========================================================================
6310    // Adaptive Compression Tests (bd-243w)
6311    // ========================================================================
6312
6313    #[test]
6314    fn test_adaptive_compression_disabled_by_default() {
6315        let _guard = test_guard!();
6316        let config = TransferConfig::default();
6317        assert!(!config.adaptive_compression);
6318        // Should use fixed level when disabled
6319        assert_eq!(config.select_compression_level(Some(1_000_000)), 3);
6320        assert_eq!(config.select_compression_level(Some(500_000_000)), 3);
6321    }
6322
6323    #[test]
6324    fn test_adaptive_compression_small_payload() {
6325        let _guard = test_guard!();
6326        let config = TransferConfig {
6327            adaptive_compression: true,
6328            ..Default::default()
6329        };
6330        // < 10MB should use level 1
6331        assert_eq!(config.select_compression_level(Some(0)), 1);
6332        assert_eq!(config.select_compression_level(Some(1_000_000)), 1); // 1MB
6333        assert_eq!(config.select_compression_level(Some(9_999_999)), 1); // ~10MB
6334    }
6335
6336    #[test]
6337    fn test_adaptive_compression_medium_payload() {
6338        let _guard = test_guard!();
6339        let config = TransferConfig {
6340            adaptive_compression: true,
6341            ..Default::default()
6342        };
6343        // 10-200MB should use level 3
6344        assert_eq!(config.select_compression_level(Some(10_000_000)), 3); // 10MB
6345        assert_eq!(config.select_compression_level(Some(100_000_000)), 3); // 100MB
6346        assert_eq!(config.select_compression_level(Some(199_999_999)), 3); // ~200MB
6347    }
6348
6349    #[test]
6350    fn test_adaptive_compression_large_payload() {
6351        let _guard = test_guard!();
6352        let config = TransferConfig {
6353            adaptive_compression: true,
6354            ..Default::default()
6355        };
6356        // > 200MB should use level 7
6357        assert_eq!(config.select_compression_level(Some(200_000_000)), 7); // 200MB
6358        assert_eq!(config.select_compression_level(Some(500_000_000)), 7); // 500MB
6359        assert_eq!(config.select_compression_level(Some(1_000_000_000)), 7); // 1GB
6360    }
6361
6362    #[test]
6363    fn test_adaptive_compression_no_estimate() {
6364        let _guard = test_guard!();
6365        let config = TransferConfig {
6366            adaptive_compression: true,
6367            compression_level: 5,
6368            ..Default::default()
6369        };
6370        // No estimate should fallback to default level
6371        assert_eq!(config.select_compression_level(None), 5);
6372    }
6373
6374    #[test]
6375    fn test_adaptive_compression_respects_min_level() {
6376        let _guard = test_guard!();
6377        let config = TransferConfig {
6378            adaptive_compression: true,
6379            min_compression_level: 3,
6380            ..Default::default()
6381        };
6382        // Small payload would want level 1, but min is 3
6383        assert_eq!(config.select_compression_level(Some(1_000_000)), 3);
6384    }
6385
6386    #[test]
6387    fn test_adaptive_compression_respects_max_level() {
6388        let _guard = test_guard!();
6389        let config = TransferConfig {
6390            adaptive_compression: true,
6391            max_compression_level: 5,
6392            ..Default::default()
6393        };
6394        // Large payload would want level 7, but max is 5
6395        assert_eq!(config.select_compression_level(Some(500_000_000)), 5);
6396    }
6397
6398    #[test]
6399    fn test_adaptive_compression_serde_roundtrip() {
6400        let _guard = test_guard!();
6401        let config = TransferConfig {
6402            adaptive_compression: true,
6403            min_compression_level: 2,
6404            max_compression_level: 8,
6405            ..Default::default()
6406        };
6407        let json = serde_json::to_string(&config).unwrap();
6408        let parsed: TransferConfig = serde_json::from_str(&json).unwrap();
6409        assert!(parsed.adaptive_compression);
6410        assert_eq!(parsed.min_compression_level, 2);
6411        assert_eq!(parsed.max_compression_level, 8);
6412    }
6413
6414    // -------------------------------------------------------------------------
6415    // Self-Healing Config Tests (bd-59kg)
6416    // -------------------------------------------------------------------------
6417
6418    #[test]
6419    fn test_self_healing_config_defaults() {
6420        let _guard = test_guard!();
6421        // TEST START: SelfHealingConfig::default() returns expected values
6422        let config = SelfHealingConfig::default();
6423
6424        // Both self-healing behaviors enabled by default
6425        assert!(
6426            config.hook_starts_daemon,
6427            "hook_starts_daemon should be true by default"
6428        );
6429        assert!(
6430            config.daemon_installs_hooks,
6431            "daemon_installs_hooks should be true by default"
6432        );
6433
6434        // Timing defaults
6435        assert_eq!(
6436            config.auto_start_cooldown_secs, 30,
6437            "auto_start_cooldown_secs should default to 30"
6438        );
6439        assert_eq!(
6440            config.auto_start_timeout_secs, 3,
6441            "auto_start_timeout_secs should default to 3"
6442        );
6443        // TEST PASS: SelfHealingConfig defaults
6444    }
6445
6446    #[test]
6447    fn test_self_healing_config_serde_full() {
6448        let _guard = test_guard!();
6449        // TEST START: Full SelfHealingConfig serialization/deserialization
6450        let config = SelfHealingConfig {
6451            hook_starts_daemon: false,
6452            daemon_installs_hooks: false,
6453            auto_start_cooldown_secs: 60,
6454            auto_start_timeout_secs: 10,
6455            self_healing_log_level: SelfHealingLogLevel::Debug,
6456        };
6457
6458        let json = serde_json::to_string(&config).unwrap();
6459        assert!(json.contains("\"hook_starts_daemon\":false"));
6460        assert!(json.contains("\"daemon_installs_hooks\":false"));
6461        assert!(json.contains("\"auto_start_cooldown_secs\":60"));
6462        assert!(json.contains("\"auto_start_timeout_secs\":10"));
6463        assert!(json.contains("\"self_healing_log_level\":\"debug\""));
6464
6465        let parsed: SelfHealingConfig = serde_json::from_str(&json).unwrap();
6466        assert!(!parsed.hook_starts_daemon);
6467        assert!(!parsed.daemon_installs_hooks);
6468        assert_eq!(parsed.auto_start_cooldown_secs, 60);
6469        assert_eq!(parsed.auto_start_timeout_secs, 10);
6470        assert_eq!(parsed.self_healing_log_level, SelfHealingLogLevel::Debug);
6471        // TEST PASS: Full SelfHealingConfig serde
6472    }
6473
6474    // br-4zf3p: Tests for the self_healing_log_level field.
6475
6476    #[test]
6477    fn test_self_healing_log_level_default_is_info() {
6478        // TEST START: SelfHealingLogLevel::default() == Info
6479        let level = SelfHealingLogLevel::default();
6480        assert_eq!(level, SelfHealingLogLevel::Info);
6481        // Also verify the SelfHealingConfig default surfaces it.
6482        let config = SelfHealingConfig::default();
6483        assert_eq!(
6484            config.self_healing_log_level,
6485            SelfHealingLogLevel::Info,
6486            "config default should be Info"
6487        );
6488        // TEST PASS
6489    }
6490
6491    #[test]
6492    fn test_self_healing_log_level_serializes_lowercase() {
6493        // TEST START: serde uses lowercase variants
6494        let json = serde_json::to_string(&SelfHealingLogLevel::Warn).unwrap();
6495        assert_eq!(json, "\"warn\"");
6496        let parsed: SelfHealingLogLevel = serde_json::from_str("\"error\"").unwrap();
6497        assert_eq!(parsed, SelfHealingLogLevel::Error);
6498        // TEST PASS
6499    }
6500
6501    #[test]
6502    fn test_self_healing_log_level_from_env_str_accepts_known() {
6503        // TEST START: from_env_str parses each level (case-insensitive) and aliases
6504        assert_eq!(
6505            SelfHealingLogLevel::from_env_str("debug"),
6506            Some(SelfHealingLogLevel::Debug)
6507        );
6508        assert_eq!(
6509            SelfHealingLogLevel::from_env_str("DEBUG"),
6510            Some(SelfHealingLogLevel::Debug)
6511        );
6512        assert_eq!(
6513            SelfHealingLogLevel::from_env_str("info"),
6514            Some(SelfHealingLogLevel::Info)
6515        );
6516        assert_eq!(
6517            SelfHealingLogLevel::from_env_str("warn"),
6518            Some(SelfHealingLogLevel::Warn)
6519        );
6520        assert_eq!(
6521            SelfHealingLogLevel::from_env_str("warning"),
6522            Some(SelfHealingLogLevel::Warn),
6523            "warning should map to Warn"
6524        );
6525        assert_eq!(
6526            SelfHealingLogLevel::from_env_str("error"),
6527            Some(SelfHealingLogLevel::Error)
6528        );
6529        // Whitespace tolerance
6530        assert_eq!(
6531            SelfHealingLogLevel::from_env_str("  debug  "),
6532            Some(SelfHealingLogLevel::Debug)
6533        );
6534        // TEST PASS
6535    }
6536
6537    #[test]
6538    fn test_self_healing_log_level_from_env_str_rejects_unknown() {
6539        // TEST START: unknown values return None (caller falls back to default)
6540        assert!(SelfHealingLogLevel::from_env_str("banana").is_none());
6541        assert!(SelfHealingLogLevel::from_env_str("").is_none());
6542        assert!(SelfHealingLogLevel::from_env_str("trace").is_none());
6543        // TEST PASS
6544    }
6545
6546    #[test]
6547    fn test_self_healing_config_serde_partial_uses_defaults() {
6548        let _guard = test_guard!();
6549        // TEST START: Partial TOML/JSON uses defaults for missing fields
6550        let json = r#"{"hook_starts_daemon": false}"#;
6551        let config: SelfHealingConfig = serde_json::from_str(json).unwrap();
6552
6553        assert!(
6554            !config.hook_starts_daemon,
6555            "Explicit false should be parsed"
6556        );
6557        assert!(
6558            config.daemon_installs_hooks,
6559            "Missing field should use default (true)"
6560        );
6561        assert_eq!(
6562            config.auto_start_cooldown_secs, 30,
6563            "Missing field should use default (30)"
6564        );
6565        assert_eq!(
6566            config.auto_start_timeout_secs, 3,
6567            "Missing field should use default (3)"
6568        );
6569        // TEST PASS: Partial SelfHealingConfig uses defaults
6570    }
6571
6572    #[test]
6573    fn test_self_healing_config_toml_with_alias() {
6574        let _guard = test_guard!();
6575        // TEST START: daemon_start_timeout alias works for auto_start_timeout_secs
6576        let toml_str = r#"
6577            hook_starts_daemon = true
6578            daemon_installs_hooks = false
6579            auto_start_cooldown_secs = 45
6580            daemon_start_timeout = 7
6581        "#;
6582
6583        let config: SelfHealingConfig = toml::from_str(toml_str).unwrap();
6584        assert!(config.hook_starts_daemon);
6585        assert!(!config.daemon_installs_hooks);
6586        assert_eq!(config.auto_start_cooldown_secs, 45);
6587        assert_eq!(
6588            config.auto_start_timeout_secs, 7,
6589            "daemon_start_timeout alias should set auto_start_timeout_secs"
6590        );
6591        // TEST PASS: TOML alias works
6592    }
6593
6594    #[allow(unsafe_code)]
6595    mod self_healing_env_override_tests {
6596        use super::*;
6597        use crate::config::env_test_lock;
6598
6599        fn env_guard() -> std::sync::MutexGuard<'static, ()> {
6600            env_test_lock()
6601        }
6602
6603        fn set_env(key: &str, value: &str) {
6604            // SAFETY: Tests are serialized with env_guard().
6605            unsafe { std::env::set_var(key, value) };
6606        }
6607
6608        fn remove_env(key: &str) {
6609            // SAFETY: Tests are serialized with env_guard().
6610            unsafe { std::env::remove_var(key) };
6611        }
6612
6613        struct EnvVarGuard {
6614            key: &'static str,
6615            old: Option<String>,
6616        }
6617
6618        impl EnvVarGuard {
6619            fn set(key: &'static str, value: &str) -> Self {
6620                let old = std::env::var(key).ok();
6621                set_env(key, value);
6622                Self { key, old }
6623            }
6624        }
6625
6626        impl Drop for EnvVarGuard {
6627            fn drop(&mut self) {
6628                if let Some(old) = &self.old {
6629                    set_env(self.key, old);
6630                } else {
6631                    remove_env(self.key);
6632                }
6633            }
6634        }
6635
6636        #[test]
6637        fn test_self_healing_config_with_env_overrides_master_disable() {
6638            let _guard = test_guard!();
6639            let _guard = env_guard();
6640
6641            let _no_self_healing = EnvVarGuard::set("RCH_NO_SELF_HEALING", "1");
6642            let _hook_starts_daemon = EnvVarGuard::set("RCH_HOOK_STARTS_DAEMON", "1");
6643            let _daemon_installs_hooks = EnvVarGuard::set("RCH_DAEMON_INSTALLS_HOOKS", "1");
6644            let _cooldown = EnvVarGuard::set("RCH_AUTO_START_COOLDOWN_SECS", "99");
6645            let _timeout = EnvVarGuard::set("RCH_AUTO_START_TIMEOUT_SECS", "99");
6646
6647            let config = SelfHealingConfig::default().with_env_overrides();
6648            assert!(
6649                !config.hook_starts_daemon,
6650                "RCH_NO_SELF_HEALING should disable hook auto-start"
6651            );
6652            assert!(
6653                !config.daemon_installs_hooks,
6654                "RCH_NO_SELF_HEALING should disable daemon hook installation"
6655            );
6656
6657            // Master disable returns early; numeric overrides should not apply.
6658            assert_eq!(config.auto_start_cooldown_secs, 30);
6659            assert_eq!(config.auto_start_timeout_secs, 3);
6660        }
6661
6662        #[test]
6663        fn test_self_healing_config_with_env_overrides_toggles_and_numbers() {
6664            let _guard = test_guard!();
6665            let _guard = env_guard();
6666
6667            let _hook_starts_daemon = EnvVarGuard::set("RCH_HOOK_STARTS_DAEMON", "0");
6668            let _daemon_installs_hooks = EnvVarGuard::set("RCH_DAEMON_INSTALLS_HOOKS", "false");
6669            let _cooldown = EnvVarGuard::set("RCH_AUTO_START_COOLDOWN_SECS", "45");
6670            let _timeout = EnvVarGuard::set("RCH_AUTO_START_TIMEOUT_SECS", "7");
6671
6672            let config = SelfHealingConfig::default().with_env_overrides();
6673            assert!(!config.hook_starts_daemon);
6674            assert!(!config.daemon_installs_hooks);
6675            assert_eq!(config.auto_start_cooldown_secs, 45);
6676            assert_eq!(config.auto_start_timeout_secs, 7);
6677        }
6678
6679        #[test]
6680        fn test_self_healing_config_with_env_overrides_invalid_numbers_ignored() {
6681            let _guard = test_guard!();
6682            let _guard = env_guard();
6683
6684            let _cooldown = EnvVarGuard::set("RCH_AUTO_START_COOLDOWN_SECS", "not-a-number");
6685            let _timeout = EnvVarGuard::set("RCH_AUTO_START_TIMEOUT_SECS", "nope");
6686
6687            let config = SelfHealingConfig::default().with_env_overrides();
6688            assert_eq!(config.auto_start_cooldown_secs, 30);
6689            assert_eq!(config.auto_start_timeout_secs, 3);
6690        }
6691    }
6692
6693    // -------------------------------------------------------------------------
6694    // Preflight Health Guard Tests (bd-3eaa)
6695    // -------------------------------------------------------------------------
6696
6697    #[test]
6698    fn test_load_per_core_calculation() {
6699        let _guard = test_guard!();
6700        let mut caps = WorkerCapabilities::new();
6701        // No metrics -> None
6702        assert!(caps.load_per_core().is_none());
6703
6704        // Only load, no cpus -> None
6705        caps.load_avg_1 = Some(4.0);
6706        assert!(caps.load_per_core().is_none());
6707
6708        // Both available
6709        caps.num_cpus = Some(4);
6710        assert_eq!(caps.load_per_core(), Some(1.0)); // 4.0 / 4 = 1.0
6711
6712        // High load
6713        caps.load_avg_1 = Some(16.0);
6714        assert_eq!(caps.load_per_core(), Some(4.0)); // 16.0 / 4 = 4.0
6715    }
6716
6717    #[test]
6718    fn test_is_high_load() {
6719        let _guard = test_guard!();
6720        let mut caps = WorkerCapabilities::new();
6721        caps.load_avg_1 = Some(8.0);
6722        caps.num_cpus = Some(4);
6723        // load_per_core = 2.0
6724
6725        // Below threshold
6726        assert_eq!(caps.is_high_load(3.0), Some(false));
6727        // At threshold
6728        assert_eq!(caps.is_high_load(2.0), Some(false)); // equal is OK
6729        // Above threshold
6730        assert_eq!(caps.is_high_load(1.5), Some(true));
6731
6732        // No metrics -> None (fail-open)
6733        caps.load_avg_1 = None;
6734        assert!(caps.is_high_load(1.0).is_none());
6735    }
6736
6737    #[test]
6738    fn test_is_low_disk() {
6739        let _guard = test_guard!();
6740        let mut caps = WorkerCapabilities::new();
6741        caps.disk_free_gb = Some(15.0);
6742
6743        // Above threshold
6744        assert_eq!(caps.is_low_disk(10.0), Some(false));
6745        // At threshold
6746        assert_eq!(caps.is_low_disk(15.0), Some(false)); // equal is OK
6747        // Below threshold
6748        assert_eq!(caps.is_low_disk(20.0), Some(true));
6749
6750        // No metrics -> None (fail-open)
6751        caps.disk_free_gb = None;
6752        assert!(caps.is_low_disk(10.0).is_none());
6753    }
6754
6755    #[test]
6756    fn low_disk_judges_the_build_disk_not_a_small_tmpfs() {
6757        let _guard = test_guard!();
6758        // GH #78: a 16 GB tmpfs /tmp is the tightest mount by ratio, but the
6759        // build trees live on a roomy data disk.
6760        let mut caps = WorkerCapabilities::new();
6761        caps.disk_free_gb = Some(8.0);
6762        caps.disk_total_gb = Some(15.5);
6763        caps.build_disk_free_gb = Some(1700.0);
6764        caps.build_disk_total_gb = Some(1900.0);
6765        assert_eq!(caps.build_disk_gb(), (Some(1700.0), Some(1900.0)));
6766        assert_eq!(caps.is_low_disk(10.0), Some(false));
6767
6768        // A full build disk is low even when /tmp is roomy.
6769        caps.build_disk_free_gb = Some(4.0);
6770        assert_eq!(caps.is_low_disk(10.0), Some(true));
6771
6772        // An older rch-wkr without the build sample keeps the old behaviour.
6773        caps.build_disk_free_gb = None;
6774        caps.build_disk_total_gb = None;
6775        assert_eq!(caps.build_disk_gb(), (Some(8.0), Some(15.5)));
6776        assert_eq!(caps.is_low_disk(10.0), Some(true));
6777    }
6778
6779    #[test]
6780    fn build_disk_sample_is_optional_on_the_wire() {
6781        let _guard = test_guard!();
6782        let old: WorkerCapabilities =
6783            serde_json::from_str(r#"{"disk_free_gb":13.9,"disk_total_gb":15.5}"#).unwrap();
6784        assert_eq!(old.build_disk_free_gb, None);
6785        assert_eq!(old.build_disk_gb(), (Some(13.9), Some(15.5)));
6786
6787        let new: WorkerCapabilities = serde_json::from_str(
6788            r#"{"disk_free_gb":13.9,"disk_total_gb":15.5,"build_disk_free_gb":1700.0,"build_disk_total_gb":1900.0}"#,
6789        )
6790        .unwrap();
6791        assert_eq!(new.build_disk_gb(), (Some(1700.0), Some(1900.0)));
6792        let json = serde_json::to_string(&new).unwrap();
6793        assert!(json.contains("\"build_disk_free_gb\":1700.0"), "{json}");
6794    }
6795
6796    #[test]
6797    fn test_selection_config_preflight_defaults() {
6798        let _guard = test_guard!();
6799        let config = SelectionConfig::default();
6800        // Default thresholds
6801        assert_eq!(config.max_load_per_core, Some(2.0));
6802        assert_eq!(config.min_free_gb, Some(10.0));
6803        assert_eq!(config.disk_gb_per_slot, 10.0);
6804    }
6805
6806    #[test]
6807    fn test_selection_config_preflight_serde() {
6808        let _guard = test_guard!();
6809        let config = SelectionConfig {
6810            max_load_per_core: Some(3.5),
6811            min_free_gb: Some(25.0),
6812            disk_gb_per_slot: 0.83,
6813            ..Default::default()
6814        };
6815        let json = serde_json::to_string(&config).unwrap();
6816        let parsed: SelectionConfig = serde_json::from_str(&json).unwrap();
6817        assert_eq!(parsed.max_load_per_core, Some(3.5));
6818        assert_eq!(parsed.min_free_gb, Some(25.0));
6819        assert_eq!(parsed.disk_gb_per_slot, 0.83);
6820    }
6821
6822    #[test]
6823    fn test_selection_disk_slot_budget_validation() {
6824        let _guard = test_guard!();
6825        for value in ["0.0", "-1.0", "nan", "inf", "-inf"] {
6826            let result = toml::from_str::<SelectionConfig>(&format!("disk_gb_per_slot = {value}"));
6827            assert!(result.is_err(), "invalid disk slot budget {value}");
6828        }
6829        let default: SelectionConfig = toml::from_str("").unwrap();
6830        assert_eq!(default.disk_gb_per_slot, 10.0);
6831    }
6832
6833    #[test]
6834    fn test_selection_disk_weight_validation_and_roundtrip() {
6835        for value in ["-0.1", "1.1", "nan", "inf", "-inf"] {
6836            assert!(toml::from_str::<SelectionWeightConfig>(&format!("disk = {value}")).is_err());
6837        }
6838        for value in [0.0, 0.2, 1.0] {
6839            let weights: SelectionWeightConfig =
6840                toml::from_str(&format!("disk = {value}")).unwrap();
6841            assert_eq!(weights.disk, value);
6842            let roundtrip: SelectionWeightConfig =
6843                serde_json::from_str(&serde_json::to_string(&weights).unwrap()).unwrap();
6844            assert_eq!(roundtrip.disk, value);
6845        }
6846        let defaults: SelectionWeightConfig = toml::from_str("").unwrap();
6847        assert_eq!(defaults.disk, 0.2);
6848    }
6849
6850    #[test]
6851    fn test_worker_capabilities_health_metrics_serde() {
6852        let _guard = test_guard!();
6853        let caps = WorkerCapabilities {
6854            num_cpus: Some(8),
6855            load_avg_1: Some(1.5),
6856            load_avg_5: Some(2.0),
6857            load_avg_15: Some(1.8),
6858            disk_free_gb: Some(50.5),
6859            disk_total_gb: Some(100.0),
6860            ..Default::default()
6861        };
6862        let json = serde_json::to_string(&caps).unwrap();
6863        let parsed: WorkerCapabilities = serde_json::from_str(&json).unwrap();
6864        assert_eq!(parsed.num_cpus, Some(8));
6865        assert_eq!(parsed.load_avg_1, Some(1.5));
6866        assert_eq!(parsed.disk_free_gb, Some(50.5));
6867    }
6868
6869    #[test]
6870    fn microarch_level_classifies_ivy_bridge_as_v2() {
6871        // Abbreviated real flag set from ovh-b (Xeon E3-1245 V2, Ivy Bridge):
6872        // AVX present, but no avx2/bmi/fma — the bd-68hon SIGILL class.
6873        let ivy = "fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov \
6874                   pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx rdtscp lm \
6875                   constant_tsc pni pclmulqdq ssse3 cx16 sse4_1 sse4_2 x2apic \
6876                   popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm";
6877        assert_eq!(x86_64_microarch_level_from_flags(ivy), 2);
6878    }
6879
6880    #[test]
6881    fn microarch_level_classifies_v3_and_v4() {
6882        let v3 = "cx16 lahf_lm popcnt sse4_1 sse4_2 ssse3 abm avx avx2 bmi1 bmi2 \
6883                  f16c fma movbe xsave";
6884        assert_eq!(x86_64_microarch_level_from_flags(v3), 3);
6885
6886        let v4 = format!("{v3} avx512f avx512bw avx512cd avx512dq avx512vl");
6887        assert_eq!(x86_64_microarch_level_from_flags(&v4), 4);
6888    }
6889
6890    #[test]
6891    fn microarch_level_v1_for_ancient_or_empty_flags() {
6892        assert_eq!(x86_64_microarch_level_from_flags(""), 1);
6893        assert_eq!(x86_64_microarch_level_from_flags("fpu mmx sse sse2"), 1);
6894    }
6895
6896    #[test]
6897    fn pre_v3_predicate_only_fires_on_affirmative_evidence() {
6898        let mut caps = WorkerCapabilities::new();
6899        assert!(!caps.is_pre_v3_x86(), "unknown must not deprioritize");
6900        caps.cpu_microarch_level = Some(2);
6901        assert!(caps.is_pre_v3_x86());
6902        caps.cpu_microarch_level = Some(3);
6903        assert!(!caps.is_pre_v3_x86());
6904    }
6905}