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