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        // Agent/session state, not ordinary compilation inputs (issue #109).
3530        // Directory-only basenames cover nested copies, not similarly named
3531        // files or directories. .beads/ also covers .beads/.br_recovery/.
3532        ".beads/".to_string(),
3533        ".ntm/".to_string(),
3534        ".beads-recovery/".to_string(),
3535        // Do not exclude scratch/, data/, artifacts/ or project configuration:
3536        // they may contain required build inputs. .rchignore adds project-local
3537        // exclusions; an explicit exclude_patterns list replaces these defaults.
3538        // Local diagnostic runs may contain host-specific symlinks and are not build inputs.
3539        ".doctor/".to_string(),
3540        // Coverage reports (generated during tests)
3541        "coverage/".to_string(),
3542        ".nyc_output/".to_string(),
3543        // Credentials and secrets (must never be transferred to workers)
3544        ".cargo/credentials".to_string(),
3545        ".cargo/credentials.toml".to_string(),
3546        ".env".to_string(),
3547        ".env.*".to_string(),
3548        "*.pem".to_string(),
3549        "*.key".to_string(),
3550        "credentials.json".to_string(),
3551        "secrets.json".to_string(),
3552        "secrets.yaml".to_string(),
3553        "secrets.yml".to_string(),
3554        "secrets.toml".to_string(),
3555        "secrets.env".to_string(),
3556        "secrets.txt".to_string(),
3557        "secrets.conf".to_string(),
3558        "secrets.cfg".to_string(),
3559        "secrets.properties".to_string(),
3560        "secrets.xml".to_string(),
3561        // The classes above were already covered. These are the ones
3562        // RABS's E027 source-capture seed set denies
3563        // (rabs-sandbox/src/source_capture.rs) that this list did not,
3564        // so the two halves of the product now agree about what a
3565        // secret is. Two components disagreeing on that is the kind of
3566        // gap nobody notices until one of them is the path that ran.
3567        //
3568        // rsync patterns without a `/` match a basename at any depth,
3569        // so these cover nested copies too — a key checked into a
3570        // fixtures directory is excluded exactly like one at the root.
3571        //
3572        // SSH private keys. The public halves (.pub) are deliberately
3573        // not excluded: they are not secret and some builds read them.
3574        "id_rsa".to_string(),
3575        "id_ed25519".to_string(),
3576        "id_ecdsa".to_string(),
3577        "id_dsa".to_string(),
3578        // Key/certificate container formats (*.pem and *.key are above).
3579        "*.p12".to_string(),
3580        "*.pfx".to_string(),
3581        "*.keystore".to_string(),
3582        "*.jks".to_string(),
3583        // Machine credentials and cloud/container config that carries
3584        // long-lived tokens.
3585        ".netrc".to_string(),
3586        "_netrc".to_string(),
3587        ".aws/credentials".to_string(),
3588        ".docker/config.json".to_string(),
3589        // Package-registry auth tokens. These sit in project roots far
3590        // more often than the key formats above and are the likeliest
3591        // real leak in a normal repo.
3592        ".npmrc".to_string(),
3593        ".pypirc".to_string(),
3594        // GnuPG private keyring.
3595        "secring.*".to_string(),
3596    ]
3597}
3598
3599// ============================================================================
3600// Build History Types
3601// ============================================================================
3602
3603/// Location where a build was executed.
3604#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
3605#[serde(rename_all = "snake_case")]
3606pub enum BuildLocation {
3607    /// Build executed locally.
3608    #[default]
3609    Local,
3610    /// Build executed on a remote worker.
3611    Remote,
3612}
3613
3614/// Worker health snapshot captured when a cancellation completes.
3615#[derive(Debug, Clone, Serialize, Deserialize)]
3616pub struct BuildCancellationWorkerHealth {
3617    /// Worker status at cancellation completion.
3618    pub status: String,
3619    /// Worker speed score at cancellation completion.
3620    pub speed_score: f64,
3621    /// Slots currently used on the worker.
3622    pub used_slots: u32,
3623    /// Slots currently available on the worker.
3624    pub available_slots: u32,
3625    /// Normalized pressure state.
3626    pub pressure_state: String,
3627    /// Stable pressure reason code.
3628    pub pressure_reason_code: String,
3629}
3630
3631/// Structured cancellation metadata attached to cancelled build records.
3632#[derive(Debug, Clone, Serialize, Deserialize)]
3633pub struct BuildCancellationMetadata {
3634    /// Stable cancellation operation identifier.
3635    pub operation_id: String,
3636    /// Cancellation origin (for example `user`, `timeout`).
3637    pub origin: String,
3638    /// Stable reason code for cancellation.
3639    pub reason_code: String,
3640    /// Ordered cancellation state path.
3641    #[serde(default)]
3642    pub decision_path: Vec<String>,
3643    /// Highest escalation stage reached (`term`, `remote_kill`, `sigkill`).
3644    pub escalation_stage: String,
3645    /// Number of escalation transitions taken.
3646    pub escalation_count: u32,
3647    /// Whether remote kill was attempted.
3648    pub remote_kill_attempted: bool,
3649    /// Whether cleanup completed successfully.
3650    pub cleanup_ok: bool,
3651    /// Whether active build history was successfully claimed/cancelled.
3652    pub history_cancelled: bool,
3653    /// Final cancellation state.
3654    pub final_state: String,
3655    /// Worker health snapshot at completion.
3656    #[serde(default, skip_serializing_if = "Option::is_none")]
3657    pub worker_health: Option<BuildCancellationWorkerHealth>,
3658}
3659
3660/// Record of a completed build.
3661#[derive(Debug, Clone, Serialize, Deserialize)]
3662pub struct BuildRecord {
3663    /// Unique build identifier.
3664    pub id: u64,
3665    /// When the build started (ISO 8601 timestamp).
3666    pub started_at: String,
3667    /// When the build completed (ISO 8601 timestamp).
3668    pub completed_at: String,
3669    /// Project identifier (usually directory name or hash).
3670    pub project_id: String,
3671    /// Worker that executed the build (None if local).
3672    pub worker_id: Option<String>,
3673    /// Full command executed.
3674    pub command: String,
3675    /// Exit code (0 = success).
3676    pub exit_code: i32,
3677    /// Duration in milliseconds.
3678    pub duration_ms: u64,
3679    /// Build location (local or remote).
3680    pub location: BuildLocation,
3681    /// Bytes transferred (if remote).
3682    pub bytes_transferred: Option<u64>,
3683    /// Optional timing breakdown for the pipeline.
3684    #[serde(default)]
3685    pub timing: Option<CommandTimingBreakdown>,
3686    /// Structured cancellation metadata for cancelled builds.
3687    #[serde(default, skip_serializing_if = "Option::is_none")]
3688    pub cancellation: Option<BuildCancellationMetadata>,
3689}
3690
3691/// Input payload for recording a completed build.
3692#[derive(Debug, Clone, Serialize, Deserialize)]
3693pub struct BuildRecordInput {
3694    /// When the build started (ISO 8601 timestamp).
3695    pub started_at: String,
3696    /// When the build completed (ISO 8601 timestamp).
3697    pub completed_at: String,
3698    /// Project identifier (usually directory name or hash).
3699    pub project_id: String,
3700    /// Worker that executed the build (None if local).
3701    pub worker_id: Option<String>,
3702    /// Full command executed.
3703    pub command: String,
3704    /// Exit code (0 = success).
3705    pub exit_code: i32,
3706    /// Duration in milliseconds.
3707    pub duration_ms: u64,
3708    /// Build location (local or remote).
3709    pub location: BuildLocation,
3710    /// Bytes transferred (if remote).
3711    pub bytes_transferred: Option<u64>,
3712    /// Optional timing breakdown for the pipeline.
3713    #[serde(default)]
3714    pub timing: Option<CommandTimingBreakdown>,
3715    /// Structured cancellation metadata for cancelled builds.
3716    #[serde(default, skip_serializing_if = "Option::is_none")]
3717    pub cancellation: Option<BuildCancellationMetadata>,
3718}
3719
3720impl BuildRecordInput {
3721    /// Convert input payload into a build record with a supplied ID.
3722    pub fn into_record(self, id: u64) -> BuildRecord {
3723        BuildRecord {
3724            id,
3725            started_at: self.started_at,
3726            completed_at: self.completed_at,
3727            project_id: self.project_id,
3728            worker_id: self.worker_id,
3729            command: self.command,
3730            exit_code: self.exit_code,
3731            duration_ms: self.duration_ms,
3732            location: self.location,
3733            bytes_transferred: self.bytes_transferred,
3734            timing: self.timing,
3735            cancellation: self.cancellation,
3736        }
3737    }
3738}
3739
3740/// Aggregate terminal-command statistics for build history.
3741///
3742/// These counts do not infer whether compilation completed before a failing
3743/// test or interrupted command. The denominator includes every stored record.
3744#[derive(Debug, Clone, Default, Serialize, Deserialize)]
3745pub struct BuildStats {
3746    /// Total number of builds in history.
3747    pub total_builds: usize,
3748    /// Number of successfully completed commands (exit_code == 0).
3749    pub success_count: usize,
3750    /// Number of unsuccessful commands, including interruption (exit_code != 0).
3751    pub failure_count: usize,
3752    /// Number of remote builds.
3753    pub remote_count: usize,
3754    /// Number of local builds.
3755    pub local_count: usize,
3756    /// Average build duration in milliseconds.
3757    pub avg_duration_ms: u64,
3758}
3759
3760/// Saved time statistics from remote builds.
3761///
3762/// Tracks estimated time savings from offloading builds to remote workers.
3763/// Estimates are only produced from an observed local baseline; without one the
3764/// stats carry measured remote durations with `estimate_basis = "none"` and
3765/// zero estimated savings rather than a fabricated speedup factor.
3766#[derive(Debug, Clone, Default, Serialize, Deserialize)]
3767pub struct SavedTimeStats {
3768    /// Total time spent on remote builds (milliseconds).
3769    pub total_remote_duration_ms: u64,
3770    /// Estimated total time if those builds ran locally (milliseconds).
3771    /// Zero when no local baseline exists.
3772    pub estimated_local_duration_ms: u64,
3773    /// Time saved by offloading (milliseconds).
3774    /// Computed as max(0, estimated_local - remote); zero without a baseline.
3775    pub time_saved_ms: u64,
3776    /// Number of remote builds included in calculation.
3777    pub builds_counted: usize,
3778    /// Average speedup factor (local_estimate / remote_duration).
3779    /// A value of 2.0 means remote builds are ~2x faster than local.
3780    /// Zero when the estimate basis is "none".
3781    pub avg_speedup: f64,
3782    /// Total time saved today (milliseconds).
3783    pub today_saved_ms: u64,
3784    /// Total time saved this week (milliseconds).
3785    pub week_saved_ms: u64,
3786    /// How the local-time estimate was derived: "observed_local_mean" when
3787    /// successful local builds back the baseline, "none" otherwise.
3788    #[serde(default)]
3789    pub estimate_basis: String,
3790    /// Number of successful local builds backing the baseline (0 for "none").
3791    #[serde(default)]
3792    pub local_baseline_builds: usize,
3793}
3794
3795// ============================================================================
3796// Compilation Timing and Metrics
3797// ============================================================================
3798
3799use std::collections::VecDeque;
3800use std::time::{Duration, Instant};
3801
3802/// Breakdown of timing for each compilation phase.
3803#[derive(Debug, Clone, Default, Serialize, Deserialize)]
3804pub struct CompilationTimingBreakdown {
3805    /// Time to sync source files to worker.
3806    #[serde(with = "duration_millis")]
3807    pub rsync_up: Duration,
3808    /// Time for cargo build on worker.
3809    #[serde(with = "duration_millis")]
3810    pub remote_build: Duration,
3811    /// Time to sync artifacts back.
3812    #[serde(with = "duration_millis")]
3813    pub rsync_down: Duration,
3814    /// Total end-to-end latency.
3815    #[serde(with = "duration_millis")]
3816    pub total: Duration,
3817}
3818
3819/// Timing breakdown for a single command pipeline.
3820///
3821/// Uses optional durations so missing phases serialize as `null`.
3822#[derive(Debug, Clone, Default, Serialize, Deserialize)]
3823pub struct CommandTimingBreakdown {
3824    /// Time spent classifying the command.
3825    #[serde(with = "option_duration_millis")]
3826    pub classify: Option<Duration>,
3827    /// Time spent selecting a worker.
3828    #[serde(with = "option_duration_millis")]
3829    pub select: Option<Duration>,
3830    /// Time spent syncing source files to the worker.
3831    #[serde(with = "option_duration_millis")]
3832    pub sync_up: Option<Duration>,
3833    /// Time spent executing the remote command.
3834    #[serde(with = "option_duration_millis")]
3835    pub exec: Option<Duration>,
3836    /// Time spent syncing artifacts back.
3837    #[serde(with = "option_duration_millis")]
3838    pub sync_down: Option<Duration>,
3839    /// Time spent on cleanup (slot release, bookkeeping).
3840    #[serde(with = "option_duration_millis")]
3841    pub cleanup: Option<Duration>,
3842    /// Total end-to-end time for the pipeline.
3843    #[serde(with = "option_duration_millis")]
3844    pub total: Option<Duration>,
3845}
3846
3847mod duration_millis {
3848    use serde::{Deserialize, Deserializer, Serialize, Serializer};
3849    use std::time::Duration;
3850
3851    pub fn serialize<S>(duration: &Duration, serializer: S) -> Result<S::Ok, S::Error>
3852    where
3853        S: Serializer,
3854    {
3855        duration.as_millis().serialize(serializer)
3856    }
3857
3858    pub fn deserialize<'de, D>(deserializer: D) -> Result<Duration, D::Error>
3859    where
3860        D: Deserializer<'de>,
3861    {
3862        let millis = u64::deserialize(deserializer)?;
3863        Ok(Duration::from_millis(millis))
3864    }
3865}
3866
3867/// Comprehensive metrics for a single compilation.
3868#[derive(Debug, Clone, Serialize, Deserialize)]
3869pub struct CompilationMetrics {
3870    /// Project identifier (usually directory name or hash).
3871    pub project_id: String,
3872    /// Worker that performed the compilation.
3873    pub worker_id: String,
3874    /// When the compilation occurred.
3875    pub timestamp: chrono::DateTime<chrono::Utc>,
3876    /// Timing breakdown for each phase.
3877    pub timing: CompilationTimingBreakdown,
3878    /// Local build time for comparison (if available).
3879    #[serde(with = "option_duration_millis")]
3880    pub local_build_time: Option<Duration>,
3881    /// Speedup ratio (local_time / remote_time).
3882    pub speedup: Option<f64>,
3883    /// Number of files synced to worker.
3884    pub files_synced: u64,
3885    /// Total bytes transferred.
3886    pub bytes_transferred: u64,
3887    /// Exit code from compilation.
3888    pub exit_code: i32,
3889    /// Whether compilation succeeded.
3890    pub success: bool,
3891}
3892
3893mod option_duration_millis {
3894    use serde::{Deserialize, Deserializer, Serialize, Serializer};
3895    use std::time::Duration;
3896
3897    pub fn serialize<S>(duration: &Option<Duration>, serializer: S) -> Result<S::Ok, S::Error>
3898    where
3899        S: Serializer,
3900    {
3901        match duration {
3902            Some(d) => Some(d.as_millis() as u64).serialize(serializer),
3903            None => Option::<u64>::None.serialize(serializer),
3904        }
3905    }
3906
3907    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Duration>, D::Error>
3908    where
3909        D: Deserializer<'de>,
3910    {
3911        let opt: Option<u64> = Option::deserialize(deserializer)?;
3912        Ok(opt.map(Duration::from_millis))
3913    }
3914}
3915
3916impl CompilationMetrics {
3917    /// Calculate speedup based on local vs remote build time.
3918    pub fn calculate_speedup(&mut self) {
3919        if let Some(local) = self.local_build_time
3920            && self.timing.total.as_millis() > 0
3921        {
3922            self.speedup = Some(local.as_secs_f64() / self.timing.total.as_secs_f64());
3923        }
3924    }
3925
3926    /// Check if remote compilation was beneficial (faster than local).
3927    pub fn is_beneficial(&self) -> bool {
3928        self.speedup.map(|s| s > 1.0).unwrap_or(false)
3929    }
3930}
3931
3932impl Default for CompilationMetrics {
3933    fn default() -> Self {
3934        Self {
3935            project_id: String::new(),
3936            worker_id: String::new(),
3937            timestamp: chrono::Utc::now(),
3938            timing: CompilationTimingBreakdown::default(),
3939            local_build_time: None,
3940            speedup: None,
3941            files_synced: 0,
3942            bytes_transferred: 0,
3943            exit_code: 0,
3944            success: true,
3945        }
3946    }
3947}
3948
3949/// Timer for tracking compilation phases.
3950///
3951/// Use this to measure the duration of each phase of remote compilation.
3952///
3953/// # Example
3954/// ```ignore
3955/// let mut timer = CompilationTimer::new("my-project", "worker-1");
3956/// // ... rsync source files ...
3957/// timer.end_rsync_up();
3958/// // ... run cargo build ...
3959/// timer.end_remote_build();
3960/// // ... rsync artifacts back ...
3961/// timer.end_rsync_down();
3962/// let metrics = timer.finish(0, 100, 1_000_000);
3963/// ```
3964#[derive(Debug)]
3965pub struct CompilationTimer {
3966    project_id: String,
3967    worker_id: String,
3968    start: Instant,
3969    phase_start: Instant,
3970    rsync_up: Option<Duration>,
3971    remote_build: Option<Duration>,
3972    rsync_down: Option<Duration>,
3973}
3974
3975impl CompilationTimer {
3976    /// Create a new timer for a compilation.
3977    pub fn new(project_id: &str, worker_id: &str) -> Self {
3978        let now = Instant::now();
3979        Self {
3980            project_id: project_id.to_string(),
3981            worker_id: worker_id.to_string(),
3982            start: now,
3983            phase_start: now,
3984            rsync_up: None,
3985            remote_build: None,
3986            rsync_down: None,
3987        }
3988    }
3989
3990    /// Mark the end of the rsync upload phase.
3991    pub fn end_rsync_up(&mut self) {
3992        self.rsync_up = Some(self.phase_start.elapsed());
3993        self.phase_start = Instant::now();
3994        tracing::info!(
3995            rsync_up_ms = %self.rsync_up.unwrap().as_millis(),
3996            "TIMING: rsync_up completed"
3997        );
3998    }
3999
4000    /// Mark the end of the remote build phase.
4001    pub fn end_remote_build(&mut self) {
4002        self.remote_build = Some(self.phase_start.elapsed());
4003        self.phase_start = Instant::now();
4004        tracing::info!(
4005            remote_build_ms = %self.remote_build.unwrap().as_millis(),
4006            "TIMING: remote_build completed"
4007        );
4008    }
4009
4010    /// Mark the end of the rsync download phase.
4011    pub fn end_rsync_down(&mut self) {
4012        self.rsync_down = Some(self.phase_start.elapsed());
4013        tracing::info!(
4014            rsync_down_ms = %self.rsync_down.unwrap().as_millis(),
4015            "TIMING: rsync_down completed"
4016        );
4017    }
4018
4019    /// Finish timing and produce metrics.
4020    pub fn finish(self, exit_code: i32, files: u64, bytes: u64) -> CompilationMetrics {
4021        let total = self.start.elapsed();
4022        tracing::info!(
4023            total_ms = %total.as_millis(),
4024            exit_code = %exit_code,
4025            "TIMING: compilation completed"
4026        );
4027
4028        CompilationMetrics {
4029            project_id: self.project_id,
4030            worker_id: self.worker_id,
4031            timestamp: chrono::Utc::now(),
4032            timing: CompilationTimingBreakdown {
4033                rsync_up: self.rsync_up.unwrap_or_default(),
4034                remote_build: self.remote_build.unwrap_or_default(),
4035                rsync_down: self.rsync_down.unwrap_or_default(),
4036                total,
4037            },
4038            local_build_time: None,
4039            speedup: None,
4040            files_synced: files,
4041            bytes_transferred: bytes,
4042            exit_code,
4043            success: exit_code == 0,
4044        }
4045    }
4046}
4047
4048/// Aggregator for compilation metrics with statistics.
4049#[derive(Debug)]
4050pub struct MetricsAggregator {
4051    history: VecDeque<CompilationMetrics>,
4052    max_history: usize,
4053}
4054
4055impl MetricsAggregator {
4056    /// Create a new aggregator with a maximum history size.
4057    pub fn new(max_history: usize) -> Self {
4058        Self {
4059            history: VecDeque::with_capacity(max_history),
4060            max_history,
4061        }
4062    }
4063
4064    /// Record a new compilation's metrics.
4065    pub fn record(&mut self, metrics: CompilationMetrics) {
4066        if self.history.len() >= self.max_history {
4067            self.history.pop_front();
4068        }
4069        self.history.push_back(metrics);
4070    }
4071
4072    /// Get the average speedup across all recorded compilations.
4073    pub fn average_speedup(&self) -> Option<f64> {
4074        let speedups: Vec<f64> = self.history.iter().filter_map(|m| m.speedup).collect();
4075
4076        if speedups.is_empty() {
4077            None
4078        } else {
4079            Some(speedups.iter().sum::<f64>() / speedups.len() as f64)
4080        }
4081    }
4082
4083    /// Get the p50 (median) total compilation time.
4084    pub fn p50_total_time(&self) -> Option<Duration> {
4085        self.percentile_total_time(0.50)
4086    }
4087
4088    /// Get the p95 total compilation time.
4089    pub fn p95_total_time(&self) -> Option<Duration> {
4090        self.percentile_total_time(0.95)
4091    }
4092
4093    /// Get the p99 total compilation time.
4094    pub fn p99_total_time(&self) -> Option<Duration> {
4095        self.percentile_total_time(0.99)
4096    }
4097
4098    /// Get a percentile of total compilation times.
4099    ///
4100    /// Uses the "inclusive" percentile method (matching numpy.percentile, Excel PERCENTILE.INC):
4101    /// index = (n - 1) * percentile, where n is the number of samples.
4102    fn percentile_total_time(&self, percentile: f64) -> Option<Duration> {
4103        let mut times: Vec<_> = self.history.iter().map(|m| m.timing.total).collect();
4104
4105        if times.is_empty() {
4106            return None;
4107        }
4108
4109        times.sort();
4110        // Use inclusive percentile: index = (n - 1) * p
4111        // For p50 with 100 items: (99 * 0.50) = 49.5 -> 49 (true median position)
4112        // For p99 with 100 items: (99 * 0.99) = 98.01 -> 98
4113        let idx = (((times.len() - 1) as f64 * percentile).round() as usize).min(times.len() - 1);
4114        Some(times[idx])
4115    }
4116
4117    /// Get the success rate as a percentage.
4118    pub fn success_rate(&self) -> f64 {
4119        if self.history.is_empty() {
4120            return 100.0;
4121        }
4122        let successes = self.history.iter().filter(|m| m.success).count();
4123        (successes as f64 / self.history.len() as f64) * 100.0
4124    }
4125
4126    /// Get the number of recorded compilations.
4127    pub fn count(&self) -> usize {
4128        self.history.len()
4129    }
4130
4131    /// Get all recorded metrics.
4132    pub fn metrics(&self) -> &VecDeque<CompilationMetrics> {
4133        &self.history
4134    }
4135
4136    /// Clear all recorded metrics.
4137    pub fn clear(&mut self) {
4138        self.history.clear();
4139    }
4140}
4141
4142impl Default for MetricsAggregator {
4143    fn default() -> Self {
4144        Self::new(1000)
4145    }
4146}
4147
4148#[cfg(test)]
4149mod tests {
4150    use super::*;
4151    use crate::test_guard;
4152
4153    #[test]
4154    fn test_declared_os_reads_reserved_tag() {
4155        assert_eq!(
4156            declared_os(&["rust".to_string(), "os:windows".to_string()]),
4157            Some("windows".to_string())
4158        );
4159        assert_eq!(
4160            declared_os(&["os:WINDOWS".to_string()]),
4161            Some("windows".to_string())
4162        );
4163    }
4164
4165    #[test]
4166    fn test_declared_os_absent_for_ordinary_tags() {
4167        // Every historical worker: no reserved tag, so no exclusivity and the
4168        // worker stays a candidate for any job.
4169        assert_eq!(declared_os(&[]), None);
4170        assert_eq!(
4171            declared_os(&["rust".to_string(), "bun".to_string(), "go".to_string()]),
4172            None
4173        );
4174        // A malformed declaration must not silently fence the worker off.
4175        assert_eq!(declared_os(&["os:".to_string()]), None);
4176        assert_eq!(declared_os(&["os:  ".to_string()]), None);
4177    }
4178
4179    #[test]
4180    fn test_os_tag_roundtrips_through_declared_os() {
4181        for os in ["windows", "Darwin", " linux "] {
4182            let tag = os_tag(os);
4183            assert_eq!(
4184                declared_os(std::slice::from_ref(&tag)).as_deref(),
4185                Some(os.trim().to_ascii_lowercase().as_str())
4186            );
4187        }
4188    }
4189
4190    /// Verdict-webhook config must NEVER carry an inline secret. Operators
4191    /// reference secrets by env-var name (`*_env`); the resolved value is
4192    /// read at dispatch time and never persisted to the cache or config TOML.
4193    /// This guards against a future careless `pub secret: String` addition.
4194    #[test]
4195    fn test_no_inline_secret_fields() {
4196        let endpoint = DoctorWebhookEndpoint {
4197            name: "ops".to_string(),
4198            url: "https://example.com/hook".to_string(),
4199            format: DoctorWebhookFormat::Pagerduty,
4200            on_transitions: vec!["any_to_failing".to_string()],
4201            retry_max: 3,
4202            retry_backoff_ms: 200,
4203            timeout_ms: 5000,
4204            enabled: true,
4205            routing_key_env: Some("RCH_PAGERDUTY_ROUTING_KEY".to_string()),
4206            bearer_token_env: Some("RCH_WEBHOOK_BEARER".to_string()),
4207            signing_secret_env: Some("RCH_WEBHOOK_HMAC".to_string()),
4208        };
4209        // Serialize to a JSON object and inspect the *keys*. The forbidden
4210        // field names must be entirely absent; only `*_env` references survive.
4211        let value = serde_json::to_value(&endpoint).unwrap();
4212        let obj = value.as_object().expect("endpoint serializes to an object");
4213        for forbidden in ["secret", "routing_key", "bearer_token", "password", "token"] {
4214            assert!(
4215                !obj.contains_key(forbidden),
4216                "endpoint config must not expose an inline `{forbidden}` field"
4217            );
4218        }
4219        assert!(obj.contains_key("routing_key_env"));
4220        assert!(obj.contains_key("bearer_token_env"));
4221        assert!(obj.contains_key("signing_secret_env"));
4222    }
4223
4224    #[test]
4225    fn test_webhook_format_toml_spelling() {
4226        // The config TOML uses snake_case spellings. TOML documents are tables
4227        // at the root, so a bare enum cannot be (de)serialized standalone —
4228        // verify the wire spelling through a `format = "..."` table field, the
4229        // shape it actually appears in within the config.
4230        #[derive(serde::Serialize, serde::Deserialize, PartialEq, Debug)]
4231        struct FormatWrap {
4232            format: DoctorWebhookFormat,
4233        }
4234        let rendered = toml::to_string(&FormatWrap {
4235            format: DoctorWebhookFormat::GenericJson,
4236        })
4237        .unwrap();
4238        assert!(
4239            rendered.contains("format = \"generic_json\""),
4240            "unexpected TOML: {rendered}"
4241        );
4242        let slack: FormatWrap = toml::from_str("format = \"slack\"").unwrap();
4243        assert_eq!(slack.format, DoctorWebhookFormat::Slack);
4244        let pd: FormatWrap = toml::from_str("format = \"pagerduty\"").unwrap();
4245        assert_eq!(pd.format, DoctorWebhookFormat::Pagerduty);
4246    }
4247
4248    #[test]
4249    fn test_doctor_webhooks_defaults() {
4250        let cfg = DoctorWebhooksConfig::default();
4251        assert!(cfg.endpoints.is_empty());
4252        assert_eq!(cfg.max_inflight, 16);
4253        // RchConfig wires the section in with serde(default), so an empty
4254        // config still yields an empty (never-firing) webhook surface.
4255        let rch: RchConfig = toml::from_str("").unwrap();
4256        assert!(rch.doctor.webhooks.endpoints.is_empty());
4257    }
4258
4259    #[test]
4260    fn test_doctor_webhook_endpoint_parses_from_toml() {
4261        let toml_src = r#"
4262[doctor.webhooks]
4263max_inflight = 8
4264
4265[[doctor.webhooks.endpoints]]
4266name = "ops-slack"
4267url = "https://hooks.slack.com/services/T0/B0/x"
4268format = "slack"
4269on_transitions = ["healthy_to_degraded", "any_to_failing"]
4270retry_max = 2
4271"#;
4272        let cfg: RchConfig = toml::from_str(toml_src).unwrap();
4273        assert_eq!(cfg.doctor.webhooks.max_inflight, 8);
4274        assert_eq!(cfg.doctor.webhooks.endpoints.len(), 1);
4275        let ep = &cfg.doctor.webhooks.endpoints[0];
4276        assert_eq!(ep.name, "ops-slack");
4277        assert_eq!(ep.format, DoctorWebhookFormat::Slack);
4278        assert_eq!(ep.on_transitions.len(), 2);
4279        assert_eq!(ep.retry_max, 2);
4280        // Defaults filled in for omitted fields.
4281        assert_eq!(ep.retry_backoff_ms, 200);
4282        assert_eq!(ep.timeout_ms, 5000);
4283        assert!(ep.enabled);
4284    }
4285
4286    fn assert_golden_json(
4287        actual: serde_json::Value,
4288        expected: &serde_json::Value,
4289        fixture_path: &str,
4290    ) {
4291        if &actual == expected {
4292            return;
4293        }
4294
4295        let actual_json = serde_json::to_string_pretty(&actual).expect("actual JSON renders");
4296        let expected_json = serde_json::to_string_pretty(expected).expect("expected JSON renders");
4297        assert_eq!(
4298            &actual,
4299            expected,
4300            "golden mismatch in {fixture_path}\n\
4301             expected_blake3={}\n\
4302             actual_blake3={}\n\
4303             bless path: review the semantic diff, update the fixture expected_* field, \
4304             and record both hashes in the Beads closeout.\n\
4305             expected:\n{expected_json}\n\
4306             actual:\n{actual_json}",
4307            blake3::hash(expected_json.as_bytes()),
4308            blake3::hash(actual_json.as_bytes())
4309        );
4310    }
4311
4312    #[test]
4313    fn test_circuit_state_default() {
4314        let _guard = test_guard!();
4315        assert_eq!(CircuitState::default(), CircuitState::Closed);
4316    }
4317
4318    #[test]
4319    fn test_circuit_config_defaults() {
4320        let _guard = test_guard!();
4321        let config = CircuitBreakerConfig::default();
4322        assert_eq!(config.failure_threshold, 3);
4323        assert_eq!(config.success_threshold, 2);
4324        assert_eq!(config.error_rate_threshold, 0.5);
4325        assert_eq!(config.window_secs, 60);
4326        assert_eq!(config.open_cooldown_secs, 30);
4327        assert_eq!(config.half_open_max_probes, 1);
4328    }
4329
4330    #[test]
4331    fn test_rch_config_has_circuit_defaults() {
4332        let _guard = test_guard!();
4333        let config = RchConfig::default();
4334        assert_eq!(config.circuit.failure_threshold, 3);
4335    }
4336
4337    #[test]
4338    fn test_circuit_config_serde_roundtrip() {
4339        let _guard = test_guard!();
4340        let config = CircuitBreakerConfig {
4341            failure_threshold: 5,
4342            success_threshold: 3,
4343            error_rate_threshold: 0.75,
4344            window_secs: 120,
4345            open_cooldown_secs: 45,
4346            half_open_max_probes: 2,
4347            command_failure_threshold: 4,
4348            open_cooldown_max_secs: 900,
4349        };
4350        let json = serde_json::to_string(&config).unwrap();
4351        let parsed: CircuitBreakerConfig = serde_json::from_str(&json).unwrap();
4352        assert_eq!(parsed.command_failure_threshold, 4);
4353        assert_eq!(parsed.open_cooldown_max_secs, 900);
4354        assert_eq!(parsed.failure_threshold, 5);
4355        assert_eq!(parsed.success_threshold, 3);
4356        assert_eq!(parsed.error_rate_threshold, 0.75);
4357        assert_eq!(parsed.window_secs, 120);
4358        assert_eq!(parsed.open_cooldown_secs, 45);
4359        assert_eq!(parsed.half_open_max_probes, 2);
4360    }
4361
4362    // ========================================================================
4363    // WorkerCapabilities Tests
4364    // ========================================================================
4365
4366    #[test]
4367    fn test_worker_capabilities_default() {
4368        let _guard = test_guard!();
4369        let caps = WorkerCapabilities::default();
4370        assert!(caps.rustc_version.is_none());
4371        assert!(caps.rustup_toolchains.is_empty());
4372        assert!(caps.rustup_components.is_empty());
4373        assert!(caps.bun_version.is_none());
4374        assert!(caps.node_version.is_none());
4375        assert!(caps.npm_version.is_none());
4376        assert!(caps.projects_root_ok.is_none());
4377        assert!(caps.projects_root_issue.is_none());
4378        assert!(caps.projects_root_checked_at_unix_ms.is_none());
4379    }
4380
4381    #[test]
4382    fn test_worker_capabilities_new() {
4383        let _guard = test_guard!();
4384        let caps = WorkerCapabilities::new();
4385        assert!(caps.rustc_version.is_none());
4386        assert!(!caps.has_rust());
4387        assert!(!caps.has_bun());
4388        assert!(!caps.has_node());
4389        assert!(caps.is_topology_healthy().is_none());
4390    }
4391
4392    #[test]
4393    fn test_worker_capabilities_has_rust() {
4394        let _guard = test_guard!();
4395        let mut caps = WorkerCapabilities::new();
4396        assert!(!caps.has_rust());
4397
4398        caps.rustc_version = Some("rustc 1.76.0 (07dca489a 2024-02-04)".to_string());
4399        assert!(caps.has_rust());
4400    }
4401
4402    #[test]
4403    fn test_worker_capabilities_components_are_toolchain_scoped_and_exact() {
4404        let _guard = test_guard!();
4405        let caps = WorkerCapabilities {
4406            rustup_components: vec![
4407                "stable-x86_64-unknown-linux-gnu:clippy".to_string(),
4408                "nightly-2026-07-05-x86_64-unknown-linux-gnu:rustfmt".to_string(),
4409                "beta-x86_64-unknown-linux-gnu:clippy-preview".to_string(),
4410            ],
4411            ..Default::default()
4412        };
4413
4414        assert!(caps.has_rustup_component("stable", "clippy"));
4415        assert!(caps.has_rustup_component("nightly-2026-07-05", "rustfmt"));
4416        assert!(!caps.has_rustup_component("nightly-2026-07-05", "clippy"));
4417        assert!(!caps.has_rustup_component("beta", "clippy"));
4418        assert!(!caps.has_rustup_component("nightly-2026-07-0", "rustfmt"));
4419    }
4420
4421    #[test]
4422    fn test_worker_capabilities_has_bun() {
4423        let _guard = test_guard!();
4424        let mut caps = WorkerCapabilities::new();
4425        assert!(!caps.has_bun());
4426
4427        caps.bun_version = Some("1.0.25".to_string());
4428        assert!(caps.has_bun());
4429    }
4430
4431    #[test]
4432    fn test_worker_capabilities_has_nix() {
4433        let _guard = test_guard!();
4434        let mut caps = WorkerCapabilities::new();
4435        assert!(!caps.has_nix());
4436
4437        caps.nix_version = Some("nix (Nix) 2.24.9".to_string());
4438        assert!(caps.has_nix());
4439    }
4440
4441    #[test]
4442    fn test_worker_capabilities_has_zig_requires_both_halves() {
4443        let _guard = test_guard!();
4444        let mut caps = WorkerCapabilities::new();
4445        assert!(!caps.has_zig());
4446
4447        // `zig` alone cannot run `cargo zigbuild` — cargo would report
4448        // `no such command: 'zigbuild'`.
4449        caps.zig_version = Some("0.14.1".to_string());
4450        assert!(!caps.has_zig());
4451
4452        // cargo-zigbuild alone cannot link — it shells out to `zig cc`.
4453        caps.zig_version = None;
4454        caps.cargo_zigbuild_version = Some("cargo-zigbuild 0.23.0".to_string());
4455        assert!(!caps.has_zig());
4456
4457        caps.zig_version = Some("0.14.1".to_string());
4458        assert!(caps.has_zig());
4459    }
4460
4461    #[test]
4462    fn test_nix_build_uses_generous_timeout() {
4463        let _guard = test_guard!();
4464        let cfg = CompilationConfig::default();
4465        // Nix builds get the long test-timeout bucket, not the short build timeout.
4466        assert_eq!(
4467            cfg.timeout_for_kind(Some(CompilationKind::NixBuild)),
4468            std::time::Duration::from_secs(cfg.test_timeout_sec)
4469        );
4470    }
4471
4472    #[test]
4473    fn test_job_uses_build_timeout_bucket() {
4474        let _guard = test_guard!();
4475        // Jobs (explicit `rch exec --job`) reuse the standard build-timeout
4476        // bucket, so `RCH_BUILD_TIMEOUT_SEC` governs them without new config.
4477        let cfg = CompilationConfig::default();
4478        assert_eq!(
4479            cfg.timeout_for_kind(Some(CompilationKind::Job)),
4480            std::time::Duration::from_secs(cfg.build_timeout_sec)
4481        );
4482    }
4483
4484    #[test]
4485    fn test_layer0_disabled_by_default_and_env_gated() {
4486        let _guard = test_guard!();
4487        let cfg = Layer0Config::default();
4488        assert!(!cfg.enabled);
4489        // Master switch off ⇒ nothing injects even with knobs on.
4490        let knobs_on = Layer0Config {
4491            enabled: false,
4492            release_lto_thin: true,
4493            release_codegen_units_1: true,
4494            debug_line_tables_only: true,
4495        };
4496        assert!(cfg.active_env().is_empty());
4497        assert!(knobs_on.active_env().is_empty());
4498    }
4499
4500    #[test]
4501    fn test_layer0_knobs_emit_stable_env_pairs() {
4502        let _guard = test_guard!();
4503        let lto_only = Layer0Config {
4504            enabled: true,
4505            release_lto_thin: true,
4506            ..Layer0Config::default()
4507        };
4508        assert_eq!(
4509            lto_only.active_env(),
4510            vec![("CARGO_PROFILE_RELEASE_LTO", "thin")]
4511        );
4512        let debug_only = Layer0Config {
4513            enabled: true,
4514            debug_line_tables_only: true,
4515            ..Layer0Config::default()
4516        };
4517        assert_eq!(
4518            debug_only.active_env(),
4519            vec![
4520                ("CARGO_PROFILE_DEV_DEBUG", "line-tables-only"),
4521                ("CARGO_PROFILE_TEST_DEBUG", "line-tables-only"),
4522            ]
4523        );
4524        let all = Layer0Config {
4525            enabled: true,
4526            release_lto_thin: true,
4527            release_codegen_units_1: true,
4528            debug_line_tables_only: true,
4529        };
4530        assert_eq!(
4531            all.active_env(),
4532            vec![
4533                ("CARGO_PROFILE_RELEASE_LTO", "thin"),
4534                ("CARGO_PROFILE_RELEASE_CODEGEN_UNITS", "1"),
4535                ("CARGO_PROFILE_DEV_DEBUG", "line-tables-only"),
4536                ("CARGO_PROFILE_TEST_DEBUG", "line-tables-only"),
4537            ],
4538            "emission order must stay stable for deterministic baselines"
4539        );
4540    }
4541
4542    #[test]
4543    fn test_layer0_pack_version_is_recorded() {
4544        let _guard = test_guard!();
4545        // Baselines record the pack version; it must exist and be non-empty.
4546        assert!(!LAYER0_PACK_VERSION.is_empty());
4547    }
4548    #[test]
4549    fn test_default_allowlist_includes_nix() {
4550        let _guard = test_guard!();
4551        let cfg = ExecutionConfig::default();
4552        assert!(cfg.is_allowed("nix"));
4553    }
4554
4555    #[test]
4556    fn test_worker_capabilities_has_node() {
4557        let _guard = test_guard!();
4558        let mut caps = WorkerCapabilities::new();
4559        assert!(!caps.has_node());
4560
4561        caps.node_version = Some("v20.11.0".to_string());
4562        assert!(caps.has_node());
4563    }
4564
4565    #[test]
4566    fn test_worker_capabilities_multiple_runtimes() {
4567        let _guard = test_guard!();
4568        let caps = WorkerCapabilities {
4569            rustc_version: Some("rustc 1.76.0".to_string()),
4570            bun_version: Some("1.0.25".to_string()),
4571            node_version: Some("v20.11.0".to_string()),
4572            npm_version: Some("10.2.4".to_string()),
4573            ..Default::default()
4574        };
4575
4576        assert!(caps.has_rust());
4577        assert!(caps.has_bun());
4578        assert!(caps.has_node());
4579    }
4580
4581    #[test]
4582    fn test_worker_capabilities_serialization_empty() {
4583        let _guard = test_guard!();
4584        let caps = WorkerCapabilities::new();
4585        let json = serde_json::to_string(&caps).unwrap();
4586        // Empty capabilities should serialize to {}
4587        assert_eq!(json, "{}");
4588
4589        // And deserialize back correctly
4590        let parsed: WorkerCapabilities = serde_json::from_str(&json).unwrap();
4591        assert!(!parsed.has_rust());
4592        assert!(!parsed.has_bun());
4593        assert!(!parsed.has_node());
4594    }
4595
4596    #[test]
4597    fn test_worker_capabilities_serialization_with_versions() {
4598        let _guard = test_guard!();
4599        let caps = WorkerCapabilities {
4600            rustc_version: Some("rustc 1.76.0-nightly".to_string()),
4601            bun_version: Some("1.0.25".to_string()),
4602            node_version: None,
4603            npm_version: None,
4604            ..Default::default()
4605        };
4606
4607        let json = serde_json::to_string(&caps).unwrap();
4608        assert!(json.contains("rustc_version"));
4609        assert!(json.contains("rustc 1.76.0-nightly"));
4610        assert!(json.contains("bun_version"));
4611        assert!(json.contains("1.0.25"));
4612        // None fields should be skipped
4613        assert!(!json.contains("node_version"));
4614        assert!(!json.contains("npm_version"));
4615
4616        let parsed: WorkerCapabilities = serde_json::from_str(&json).unwrap();
4617        assert!(parsed.has_rust());
4618        assert!(parsed.has_bun());
4619        assert!(!parsed.has_node());
4620    }
4621
4622    #[test]
4623    fn test_worker_capabilities_deserialization_partial() {
4624        let _guard = test_guard!();
4625        // Deserialize JSON with only some fields
4626        let json = r#"{"bun_version": "1.0.0"}"#;
4627        let caps: WorkerCapabilities = serde_json::from_str(json).unwrap();
4628
4629        assert!(!caps.has_rust());
4630        assert!(caps.has_bun());
4631        assert!(!caps.has_node());
4632        assert_eq!(caps.bun_version, Some("1.0.0".to_string()));
4633    }
4634
4635    #[test]
4636    fn test_worker_capabilities_clone() {
4637        let _guard = test_guard!();
4638        let caps = WorkerCapabilities {
4639            rustc_version: Some("1.76.0".to_string()),
4640            bun_version: None,
4641            node_version: Some("v20".to_string()),
4642            npm_version: None,
4643            projects_root_ok: Some(false),
4644            projects_root_issue: Some("alias_missing".to_string()),
4645            projects_root_checked_at_unix_ms: Some(123),
4646            ..Default::default()
4647        };
4648
4649        let cloned = caps.clone();
4650        assert_eq!(cloned.rustc_version, caps.rustc_version);
4651        assert_eq!(cloned.bun_version, caps.bun_version);
4652        assert_eq!(cloned.node_version, caps.node_version);
4653        assert_eq!(cloned.npm_version, caps.npm_version);
4654        assert_eq!(cloned.projects_root_ok, caps.projects_root_ok);
4655        assert_eq!(cloned.projects_root_issue, caps.projects_root_issue);
4656        assert_eq!(
4657            cloned.projects_root_checked_at_unix_ms,
4658            caps.projects_root_checked_at_unix_ms
4659        );
4660    }
4661
4662    #[test]
4663    fn test_worker_capabilities_topology_health_helper() {
4664        let _guard = test_guard!();
4665        let mut caps = WorkerCapabilities::new();
4666        assert_eq!(caps.is_topology_healthy(), None);
4667
4668        caps.projects_root_ok = Some(true);
4669        assert_eq!(caps.is_topology_healthy(), Some(true));
4670
4671        caps.projects_root_ok = Some(false);
4672        assert_eq!(caps.is_topology_healthy(), Some(false));
4673    }
4674
4675    #[test]
4676    fn test_selection_reason_serialization() {
4677        let _guard = test_guard!();
4678        // Test that all variants serialize to snake_case
4679        assert_eq!(
4680            serde_json::to_string(&SelectionReason::Success).unwrap(),
4681            "\"success\""
4682        );
4683        assert_eq!(
4684            serde_json::to_string(&SelectionReason::NoWorkersConfigured).unwrap(),
4685            "\"no_workers_configured\""
4686        );
4687        assert_eq!(
4688            serde_json::to_string(&SelectionReason::AllWorkersUnreachable).unwrap(),
4689            "\"all_workers_unreachable\""
4690        );
4691        assert_eq!(
4692            serde_json::to_string(&SelectionReason::AllCircuitsOpen).unwrap(),
4693            "\"all_circuits_open\""
4694        );
4695        assert_eq!(
4696            serde_json::to_string(&SelectionReason::AllWorkersBusy).unwrap(),
4697            "\"all_workers_busy\""
4698        );
4699        assert_eq!(
4700            serde_json::to_string(&SelectionReason::NoWorkersPassedHealth).unwrap(),
4701            "\"no_workers_passed_health\""
4702        );
4703        assert_eq!(
4704            serde_json::to_string(&SelectionReason::AllWorkersFailedPreflight).unwrap(),
4705            "\"all_workers_failed_preflight\""
4706        );
4707        assert_eq!(
4708            serde_json::to_string(&SelectionReason::AllWorkersFailedConvergence).unwrap(),
4709            "\"all_workers_failed_convergence\""
4710        );
4711        assert_eq!(
4712            serde_json::to_string(&SelectionReason::NoAdmissibleWorkers(
4713                "critical_pressure=1,insufficient_slots=1".to_string()
4714            ))
4715            .unwrap(),
4716            "{\"no_admissible_workers\":\"critical_pressure=1,insufficient_slots=1\"}"
4717        );
4718        assert_eq!(
4719            serde_json::to_string(&SelectionReason::NoMatchingWorkers).unwrap(),
4720            "\"no_matching_workers\""
4721        );
4722    }
4723
4724    #[test]
4725    fn test_selection_reason_with_error() {
4726        let _guard = test_guard!();
4727        let reason = SelectionReason::SelectionError("test error".to_string());
4728        let json = serde_json::to_string(&reason).unwrap();
4729        assert!(json.contains("selection_error"));
4730        assert!(json.contains("test error"));
4731    }
4732
4733    #[test]
4734    fn test_selection_reason_deserialization() {
4735        let _guard = test_guard!();
4736        assert_eq!(
4737            serde_json::from_str::<SelectionReason>("\"success\"").unwrap(),
4738            SelectionReason::Success
4739        );
4740        assert_eq!(
4741            serde_json::from_str::<SelectionReason>("\"all_workers_busy\"").unwrap(),
4742            SelectionReason::AllWorkersBusy
4743        );
4744        assert_eq!(
4745            serde_json::from_str::<SelectionReason>("\"no_workers_passed_health\"").unwrap(),
4746            SelectionReason::NoWorkersPassedHealth
4747        );
4748        assert_eq!(
4749            serde_json::from_str::<SelectionReason>("\"all_workers_failed_preflight\"").unwrap(),
4750            SelectionReason::AllWorkersFailedPreflight
4751        );
4752        assert_eq!(
4753            serde_json::from_str::<SelectionReason>("\"all_workers_failed_convergence\"").unwrap(),
4754            SelectionReason::AllWorkersFailedConvergence
4755        );
4756        assert_eq!(
4757            serde_json::from_str::<SelectionReason>(
4758                "{\"no_admissible_workers\":\"critical_pressure=1\"}"
4759            )
4760            .unwrap(),
4761            SelectionReason::NoAdmissibleWorkers("critical_pressure=1".to_string())
4762        );
4763    }
4764
4765    #[test]
4766    fn test_selection_reason_display() {
4767        let _guard = test_guard!();
4768        assert_eq!(
4769            SelectionReason::Success.to_string(),
4770            "worker assigned successfully"
4771        );
4772        assert_eq!(
4773            SelectionReason::NoWorkersConfigured.to_string(),
4774            "no workers configured"
4775        );
4776        assert_eq!(
4777            SelectionReason::AllWorkersUnreachable.to_string(),
4778            "all workers unreachable"
4779        );
4780        assert_eq!(
4781            SelectionReason::AllWorkersBusy.to_string(),
4782            "all workers at capacity"
4783        );
4784        assert_eq!(
4785            SelectionReason::NoWorkersPassedHealth.to_string(),
4786            "no workers passed health thresholds"
4787        );
4788        assert_eq!(
4789            SelectionReason::AllWorkersFailedPreflight.to_string(),
4790            "all workers failed preflight checks"
4791        );
4792        assert_eq!(
4793            SelectionReason::AllWorkersFailedConvergence.to_string(),
4794            "all workers failed repo convergence checks"
4795        );
4796        assert_eq!(
4797            SelectionReason::NoAdmissibleWorkers(
4798                "critical_pressure=1,insufficient_slots=1".to_string()
4799            )
4800            .to_string(),
4801            "no admissible workers: critical_pressure=1,insufficient_slots=1"
4802        );
4803        assert_eq!(
4804            SelectionReason::SelectionError("oops".to_string()).to_string(),
4805            "selection error: oops"
4806        );
4807    }
4808
4809    #[test]
4810    fn test_selection_response_with_worker() {
4811        let _guard = test_guard!();
4812        let response = SelectionResponse {
4813            worker: Some(SelectedWorker {
4814                id: WorkerId::new("test"),
4815                host: "localhost".to_string(),
4816                user: "user".to_string(),
4817                identity_file: "~/.ssh/id_rsa".to_string(),
4818                slots_available: 8,
4819                speed_score: 75.0,
4820                declared_os: None,
4821            }),
4822            reason: SelectionReason::Success,
4823            build_id: None,
4824            diagnostics: None,
4825        };
4826
4827        let json = serde_json::to_string(&response).unwrap();
4828        assert!(json.contains("\"reason\":\"success\""));
4829        assert!(json.contains("\"id\":\"test\""));
4830    }
4831
4832    #[test]
4833    fn test_selection_response_without_worker() {
4834        let _guard = test_guard!();
4835        let response = SelectionResponse {
4836            worker: None,
4837            reason: SelectionReason::AllWorkersBusy,
4838            build_id: None,
4839            diagnostics: None,
4840        };
4841
4842        let json = serde_json::to_string(&response).unwrap();
4843        assert!(json.contains("\"worker\":null"));
4844        assert!(json.contains("\"reason\":\"all_workers_busy\""));
4845    }
4846
4847    #[test]
4848    fn golden_selection_response_with_no_workers_passed_health_diagnostics() {
4849        let _guard = test_guard!();
4850        const FIXTURE_PATH: &str =
4851            "../../tests/goldens/ft_4tp7g/selection_diagnostics_no_workers_passed_health.json";
4852        let fixture: serde_json::Value = serde_json::from_str(include_str!(
4853            "../../tests/goldens/ft_4tp7g/selection_diagnostics_no_workers_passed_health.json"
4854        ))
4855        .expect("selection diagnostics golden fixture parses");
4856        assert_eq!(
4857            fixture["schema_version"],
4858            "rch.golden.selection_diagnostics.v1"
4859        );
4860
4861        let response = SelectionResponse {
4862            worker: None,
4863            reason: SelectionReason::NoWorkersPassedHealth,
4864            build_id: None,
4865            diagnostics: Some(SelectionDiagnostics {
4866                required_runtime: RequiredRuntime::Rust,
4867                estimated_cores: 2,
4868                min_success_rate: 0.8,
4869                fallback_min_success_rate: 0.5,
4870                active_project_exclusion_count: 0,
4871                workers: vec![WorkerSelectionDiagnostic {
4872                    worker_id: WorkerId::new("fixture-worker"),
4873                    status: "healthy".to_string(),
4874                    circuit_state: "closed".to_string(),
4875                    pressure_state: "healthy".to_string(),
4876                    pressure_reason_code: "pressure.ok".to_string(),
4877                    success_rate: Some(0.2),
4878                    min_success_rate: 0.8,
4879                    fallback_min_success_rate: 0.5,
4880                    required_runtime: RequiredRuntime::Rust,
4881                    runtime_available: true,
4882                    available_slots: 8,
4883                    total_slots: 8,
4884                    estimated_cores: 2,
4885                    active_project_excluded: false,
4886                    final_decision: WorkerSelectionDiagnosticDecision::Deny,
4887                    final_reason: "success_rate 0.20 < fallback 0.50".to_string(),
4888                    reason_codes: vec![
4889                        "health.below_min_success_rate".to_string(),
4890                        "health.below_fallback_min_success_rate".to_string(),
4891                    ],
4892                }],
4893            }),
4894        };
4895
4896        assert_golden_json(
4897            serde_json::to_value(&response).expect("response serializes"),
4898            &fixture["expected_response"],
4899            FIXTURE_PATH,
4900        );
4901    }
4902
4903    #[test]
4904    fn test_selection_response_roundtrip() {
4905        let _guard = test_guard!();
4906        let original = SelectionResponse {
4907            worker: Some(SelectedWorker {
4908                id: WorkerId::new("worker-1"),
4909                host: "192.168.1.100".to_string(),
4910                user: "ubuntu".to_string(),
4911                identity_file: "/path/to/key".to_string(),
4912                slots_available: 16,
4913                speed_score: 90.5,
4914                declared_os: None,
4915            }),
4916            reason: SelectionReason::Success,
4917            build_id: None,
4918            diagnostics: None,
4919        };
4920
4921        let json = serde_json::to_string(&original).unwrap();
4922        let parsed: SelectionResponse = serde_json::from_str(&json).unwrap();
4923
4924        assert!(parsed.worker.is_some());
4925        let worker = parsed.worker.unwrap();
4926        assert_eq!(worker.id.as_str(), "worker-1");
4927        assert_eq!(worker.host, "192.168.1.100");
4928        assert_eq!(worker.slots_available, 16);
4929        assert_eq!(parsed.reason, SelectionReason::Success);
4930    }
4931
4932    #[test]
4933    fn test_build_heartbeat_phase_roundtrip() {
4934        let _guard = test_guard!();
4935        let json = serde_json::to_string(&BuildHeartbeatPhase::SyncUp).unwrap();
4936        assert_eq!(json, "\"sync_up\"");
4937        let parsed: BuildHeartbeatPhase = serde_json::from_str(&json).unwrap();
4938        assert_eq!(parsed, BuildHeartbeatPhase::SyncUp);
4939    }
4940
4941    #[test]
4942    fn test_build_heartbeat_request_roundtrip() {
4943        let _guard = test_guard!();
4944        let request = BuildHeartbeatRequest {
4945            build_id: 42,
4946            worker_id: WorkerId::new("worker-a"),
4947            hook_pid: Some(12345),
4948            local_wrapper_id: Some("wrapper-abc123".to_string()),
4949            remote_pgid_file: Some("/tmp/rch/project/hash/.rch-run/42.pgid".to_string()),
4950            phase: BuildHeartbeatPhase::Execute,
4951            detail: Some("Compiling crates".to_string()),
4952            progress_counter: Some(7),
4953            progress_percent: Some(42.5),
4954        };
4955
4956        let json = serde_json::to_string(&request).unwrap();
4957        let parsed: BuildHeartbeatRequest = serde_json::from_str(&json).unwrap();
4958        assert_eq!(parsed.build_id, 42);
4959        assert_eq!(parsed.worker_id.as_str(), "worker-a");
4960        assert_eq!(
4961            parsed.remote_pgid_file,
4962            Some("/tmp/rch/project/hash/.rch-run/42.pgid".to_string())
4963        );
4964        assert_eq!(parsed.phase, BuildHeartbeatPhase::Execute);
4965        assert_eq!(parsed.progress_counter, Some(7));
4966        assert_eq!(parsed.progress_percent, Some(42.5));
4967    }
4968
4969    // CircuitStats tests
4970
4971    #[test]
4972    fn test_circuit_stats_new() {
4973        let _guard = test_guard!();
4974        let stats = CircuitStats::new();
4975        assert_eq!(stats.state(), CircuitState::Closed);
4976        assert_eq!(stats.consecutive_failures(), 0);
4977        assert_eq!(stats.error_rate(), 0.0);
4978        assert!(stats.opened_at().is_none());
4979    }
4980
4981    #[test]
4982    fn test_circuit_stats_record_success() {
4983        let _guard = test_guard!();
4984        let mut stats = CircuitStats::new();
4985        stats.record_success();
4986        stats.record_success();
4987        assert_eq!(stats.error_rate(), 0.0);
4988        assert_eq!(stats.consecutive_failures(), 0);
4989    }
4990
4991    #[test]
4992    fn test_circuit_stats_record_failure() {
4993        let _guard = test_guard!();
4994        let mut stats = CircuitStats::new();
4995        stats.record_failure();
4996        stats.record_failure();
4997        assert_eq!(stats.consecutive_failures(), 2);
4998        assert_eq!(stats.error_rate(), 1.0); // 2 failures, 0 successes
4999    }
5000
5001    #[test]
5002    fn test_circuit_stats_error_rate() {
5003        let _guard = test_guard!();
5004        let mut stats = CircuitStats::new();
5005        stats.record_success();
5006        stats.record_success();
5007        stats.record_failure();
5008        // 1 failure / 3 total = 0.333...
5009        assert!((stats.error_rate() - 0.333).abs() < 0.01);
5010    }
5011
5012    #[test]
5013    fn test_circuit_stats_should_open_consecutive_failures() {
5014        let _guard = test_guard!();
5015        let mut stats = CircuitStats::new();
5016        let config = CircuitBreakerConfig::default(); // threshold = 3
5017
5018        stats.record_failure();
5019        assert!(!stats.should_open(&config));
5020
5021        stats.record_failure();
5022        assert!(!stats.should_open(&config));
5023
5024        stats.record_failure();
5025        assert!(stats.should_open(&config)); // 3 consecutive failures
5026    }
5027
5028    #[test]
5029    fn test_circuit_stats_should_open_error_rate() {
5030        let _guard = test_guard!();
5031        let mut stats = CircuitStats::new();
5032        let config = CircuitBreakerConfig {
5033            error_rate_threshold: 0.5,
5034            ..Default::default()
5035        };
5036
5037        // Need at least 5 samples
5038        stats.record_success();
5039        stats.record_success();
5040        stats.record_failure();
5041        stats.record_failure();
5042        assert!(!stats.should_open(&config)); // Only 4 samples
5043
5044        stats.record_failure(); // 5 samples: 2 success, 3 failures = 60% error rate
5045        assert!(stats.should_open(&config));
5046    }
5047
5048    #[test]
5049    fn test_circuit_close_clears_recent_results_no_flap() {
5050        let _guard = test_guard!();
5051        // Regression: error_rate() is computed over recent_results, so close()
5052        // must clear that history or a recovered circuit immediately re-opens
5053        // on stale pre-failure samples (flapping).
5054        let mut stats = CircuitStats::new();
5055        let config = CircuitBreakerConfig {
5056            error_rate_threshold: 0.5,
5057            ..Default::default()
5058        };
5059        for _ in 0..6 {
5060            stats.record_failure();
5061        }
5062        assert!(stats.should_open(&config));
5063        stats.open();
5064        // Recover via half-open probes, then close.
5065        stats.half_open();
5066        stats.record_success();
5067        stats.record_success();
5068        stats.close();
5069        // Error rate must be reset and the circuit must NOT immediately re-open.
5070        assert_eq!(stats.error_rate(), 0.0);
5071        assert!(!stats.should_open(&config));
5072    }
5073
5074    #[test]
5075    fn test_apply_health_outcome_opens_on_failure_threshold() {
5076        let _guard = test_guard!();
5077        // failure_threshold=3: three unhealthy outcomes open the circuit.
5078        let config = CircuitBreakerConfig {
5079            failure_threshold: 3,
5080            open_cooldown_secs: 300,
5081            ..Default::default()
5082        };
5083        let mut stats = CircuitStats::new();
5084        assert_eq!(
5085            stats.apply_health_outcome(false, false, &config),
5086            CircuitState::Closed
5087        );
5088        assert_eq!(
5089            stats.apply_health_outcome(false, false, &config),
5090            CircuitState::Closed
5091        );
5092        assert_eq!(
5093            stats.apply_health_outcome(false, false, &config),
5094            CircuitState::Open
5095        );
5096    }
5097
5098    #[test]
5099    fn test_apply_health_outcome_half_open_two_probe_recovery() {
5100        let _guard = test_guard!();
5101        // success_threshold=2: recovery from Open needs exactly two clean probes.
5102        // open_cooldown_secs=0 makes should_half_open() true immediately, so the
5103        // engine's trailing nudge leaves an opened circuit already in HalfOpen —
5104        // exactly the state a real daemon would be in on the next poll once the
5105        // cooldown had elapsed. From HalfOpen the engine credits successes.
5106        let config = CircuitBreakerConfig {
5107            failure_threshold: 3,
5108            success_threshold: 2,
5109            open_cooldown_secs: 0,
5110            ..Default::default()
5111        };
5112        let mut stats = CircuitStats::new();
5113        for _ in 0..3 {
5114            stats.apply_health_outcome(false, false, &config);
5115        }
5116        // With a 0s cooldown the engine nudges Open -> HalfOpen immediately.
5117        assert_eq!(stats.state(), CircuitState::HalfOpen);
5118
5119        // First healthy probe in half-open: one success credited, not yet closed.
5120        let after_first = stats.apply_health_outcome(true, false, &config);
5121        assert_eq!(after_first, CircuitState::HalfOpen);
5122
5123        // Second healthy probe: threshold met -> Closed.
5124        let after_second = stats.apply_health_outcome(true, false, &config);
5125        assert_eq!(after_second, CircuitState::Closed);
5126    }
5127
5128    #[test]
5129    fn test_apply_health_outcome_transient_half_open_does_not_reopen() {
5130        let _guard = test_guard!();
5131        // A transient failure while half-open must NOT reset the recovery streak
5132        // — a network blip can't undo an in-progress recovery.
5133        let config = CircuitBreakerConfig {
5134            failure_threshold: 3,
5135            success_threshold: 2,
5136            open_cooldown_secs: 0,
5137            ..Default::default()
5138        };
5139        let mut stats = CircuitStats::new();
5140        for _ in 0..3 {
5141            stats.apply_health_outcome(false, false, &config);
5142        }
5143        // 0s cooldown -> already nudged to HalfOpen.
5144        assert_eq!(stats.state(), CircuitState::HalfOpen);
5145
5146        // One clean probe (1 of 2 needed).
5147        assert_eq!(
5148            stats.apply_health_outcome(true, false, &config),
5149            CircuitState::HalfOpen
5150        );
5151
5152        // Transient failure in half-open: stays HalfOpen (does NOT reopen the
5153        // circuit or restart the cooldown). The key contrast with a real failure
5154        // is that the circuit does not drop back to Open — probing continues in
5155        // place, so recovery resumes immediately on the next clean probes rather
5156        // than waiting out a fresh cooldown.
5157        let after_transient = stats.apply_health_outcome(false, true, &config);
5158        assert_eq!(after_transient, CircuitState::HalfOpen);
5159
5160        // Recovery still completes from half-open with the required clean probes.
5161        assert_eq!(
5162            stats.apply_health_outcome(true, false, &config),
5163            CircuitState::HalfOpen
5164        );
5165        assert_eq!(
5166            stats.apply_health_outcome(true, false, &config),
5167            CircuitState::Closed
5168        );
5169    }
5170
5171    #[test]
5172    fn test_apply_health_outcome_real_vs_transient_half_open_failure() {
5173        let _guard = test_guard!();
5174        // With a positive cooldown the difference is directly observable: a REAL
5175        // half-open failure reopens the circuit (state -> Open, must wait out the
5176        // cooldown again), whereas a TRANSIENT half-open failure keeps it in
5177        // HalfOpen so recovery continues without a fresh cooldown.
5178        //
5179        // Manually drive to HalfOpen (open() + half_open()) so the positive
5180        // cooldown doesn't force a real wallclock wait to reach half-open.
5181        let config = CircuitBreakerConfig {
5182            failure_threshold: 3,
5183            success_threshold: 2,
5184            open_cooldown_secs: 300,
5185            ..Default::default()
5186        };
5187
5188        // Real failure path.
5189        let mut real = CircuitStats::new();
5190        real.open();
5191        real.half_open();
5192        assert_eq!(real.state(), CircuitState::HalfOpen);
5193        let after_real = real.apply_health_outcome(false, false, &config);
5194        assert_eq!(
5195            after_real,
5196            CircuitState::Open,
5197            "a real half-open failure must reopen the circuit"
5198        );
5199
5200        // Transient failure path (same starting state).
5201        let mut transient = CircuitStats::new();
5202        transient.open();
5203        transient.half_open();
5204        assert_eq!(transient.state(), CircuitState::HalfOpen);
5205        let after_transient = transient.apply_health_outcome(false, true, &config);
5206        assert_eq!(
5207            after_transient,
5208            CircuitState::HalfOpen,
5209            "a transient half-open failure must NOT reopen the circuit"
5210        );
5211    }
5212
5213    /// Issue #48 regression: a worker whose liveness probe (`echo` over a warm
5214    /// session) keeps succeeding while every real command times out must NOT
5215    /// be re-admitted. Liveness successes alone cannot close a half-open
5216    /// circuit while command-class evidence is outstanding.
5217    #[test]
5218    fn test_command_failure_blocks_half_open_close_on_liveness_successes() {
5219        let _guard = test_guard!();
5220        let config = CircuitBreakerConfig {
5221            failure_threshold: 3,
5222            success_threshold: 2,
5223            open_cooldown_secs: 0,
5224            command_failure_threshold: 2,
5225            ..Default::default()
5226        };
5227        let mut stats = CircuitStats::new();
5228        stats.open();
5229        stats.half_open();
5230
5231        // The half-open trial: a real command hangs on the worker.
5232        assert_eq!(
5233            stats.apply_command_outcome(false, &config),
5234            CircuitState::HalfOpen,
5235            "cooldown 0: reopen then immediately half-open again"
5236        );
5237        assert_eq!(stats.consecutive_command_failures(), 1);
5238
5239        // Liveness keeps answering — many times over.
5240        for _ in 0..10 {
5241            assert_eq!(
5242                stats.apply_health_outcome(true, false, &config),
5243                CircuitState::HalfOpen,
5244                "liveness successes must not close the circuit while a command failure is outstanding"
5245            );
5246        }
5247
5248        // Only a command-class success clears the evidence and recovers.
5249        assert_eq!(
5250            stats.apply_command_outcome(true, &config),
5251            CircuitState::Closed
5252        );
5253        assert_eq!(stats.consecutive_command_failures(), 0);
5254        assert_eq!(stats.reopen_streak(), 0);
5255    }
5256
5257    /// Issue #48: interleaved liveness successes reset `failure_threshold`, so
5258    /// command failures need their own threshold to open a Closed circuit.
5259    #[test]
5260    fn test_command_failures_open_closed_circuit_despite_liveness_successes() {
5261        let _guard = test_guard!();
5262        let config = CircuitBreakerConfig {
5263            failure_threshold: 3,
5264            command_failure_threshold: 2,
5265            open_cooldown_secs: 300,
5266            ..Default::default()
5267        };
5268        let mut stats = CircuitStats::new();
5269
5270        assert_eq!(
5271            stats.apply_command_outcome(false, &config),
5272            CircuitState::Closed
5273        );
5274        // Two liveness successes in between: consecutive_failures is reset...
5275        stats.apply_health_outcome(true, false, &config);
5276        stats.apply_health_outcome(true, false, &config);
5277        assert_eq!(stats.consecutive_failures(), 0);
5278        // ...but the command-failure count is not, and the second one opens.
5279        assert_eq!(
5280            stats.apply_command_outcome(false, &config),
5281            CircuitState::Open
5282        );
5283        assert_eq!(stats.reopen_streak(), 1);
5284    }
5285
5286    /// A command failure in HalfOpen always reopens: "connected but the
5287    /// command never completed" is exactly what the trial exists to detect,
5288    /// so there is no transient exemption on this channel.
5289    #[test]
5290    fn test_command_failure_in_half_open_always_reopens() {
5291        let _guard = test_guard!();
5292        let config = CircuitBreakerConfig {
5293            open_cooldown_secs: 300,
5294            ..Default::default()
5295        };
5296        let mut stats = CircuitStats::new();
5297        stats.open();
5298        stats.half_open();
5299        assert_eq!(
5300            stats.apply_command_outcome(false, &config),
5301            CircuitState::Open
5302        );
5303        assert_eq!(stats.reopen_streak(), 2);
5304    }
5305
5306    /// Repeated Open -> HalfOpen -> Open cycles lengthen the cooldown
5307    /// (exponential, capped) so a flapping worker converges to Open instead of
5308    /// being re-admitted on every base cooldown.
5309    #[test]
5310    fn test_reopen_streak_backs_off_cooldown_until_cap() {
5311        let _guard = test_guard!();
5312        let config = CircuitBreakerConfig {
5313            open_cooldown_secs: 30,
5314            open_cooldown_max_secs: 100,
5315            ..Default::default()
5316        };
5317        assert_eq!(config.cooldown_ms_for_streak(0), 30_000);
5318        assert_eq!(config.cooldown_ms_for_streak(1), 30_000);
5319        assert_eq!(config.cooldown_ms_for_streak(2), 60_000);
5320        assert_eq!(config.cooldown_ms_for_streak(3), 100_000, "capped");
5321        assert_eq!(config.cooldown_ms_for_streak(40), 100_000, "no overflow");
5322
5323        // A cap below the base never shortens the base cooldown.
5324        let inverted = CircuitBreakerConfig {
5325            open_cooldown_secs: 30,
5326            open_cooldown_max_secs: 5,
5327            ..Default::default()
5328        };
5329        assert_eq!(inverted.cooldown_ms_for_streak(3), 30_000);
5330
5331        // The streak is observable through recovery_remaining_secs: after two
5332        // opens the remaining cooldown exceeds the base.
5333        let mut stats = CircuitStats::new();
5334        stats.open();
5335        stats.half_open();
5336        stats.open();
5337        assert_eq!(stats.reopen_streak(), 2);
5338        let remaining = stats.recovery_remaining_secs(&config).unwrap();
5339        assert!(
5340            remaining > 30 && remaining <= 60,
5341            "second open should wait ~60s, got {remaining}"
5342        );
5343
5344        // Closing resets the streak, so the next open starts from the base.
5345        stats.close();
5346        assert_eq!(stats.reopen_streak(), 0);
5347        stats.open();
5348        assert!(stats.recovery_remaining_secs(&config).unwrap() <= 30);
5349    }
5350
5351    #[test]
5352    fn test_circuit_stats_success_resets_consecutive_failures() {
5353        let _guard = test_guard!();
5354        let mut stats = CircuitStats::new();
5355        stats.record_failure();
5356        stats.record_failure();
5357        assert_eq!(stats.consecutive_failures(), 2);
5358
5359        stats.record_success();
5360        assert_eq!(stats.consecutive_failures(), 0);
5361    }
5362
5363    #[test]
5364    fn test_circuit_stats_open_transition() {
5365        let _guard = test_guard!();
5366        let mut stats = CircuitStats::new();
5367        stats.open();
5368
5369        assert_eq!(stats.state(), CircuitState::Open);
5370        assert!(stats.opened_at().is_some());
5371    }
5372
5373    #[test]
5374    fn test_circuit_stats_half_open_transition() {
5375        let _guard = test_guard!();
5376        let mut stats = CircuitStats::new();
5377        stats.open();
5378        stats.half_open();
5379
5380        assert_eq!(stats.state(), CircuitState::HalfOpen);
5381    }
5382
5383    #[test]
5384    fn test_circuit_stats_close_transition() {
5385        let _guard = test_guard!();
5386        let mut stats = CircuitStats::new();
5387        stats.open();
5388        stats.half_open();
5389        stats.close();
5390
5391        assert_eq!(stats.state(), CircuitState::Closed);
5392        assert!(stats.opened_at().is_none());
5393        assert_eq!(stats.consecutive_failures(), 0);
5394    }
5395
5396    #[test]
5397    fn test_circuit_stats_should_close() {
5398        let _guard = test_guard!();
5399        let mut stats = CircuitStats::new();
5400        let config = CircuitBreakerConfig {
5401            success_threshold: 2,
5402            ..Default::default()
5403        };
5404
5405        stats.open();
5406        stats.half_open();
5407
5408        assert!(!stats.should_close(&config)); // 0 successes
5409
5410        stats.record_success();
5411        assert!(!stats.should_close(&config)); // 1 success
5412
5413        stats.record_success();
5414        assert!(stats.should_close(&config)); // 2 successes
5415    }
5416
5417    #[test]
5418    fn test_circuit_stats_can_probe() {
5419        let _guard = test_guard!();
5420        let mut stats = CircuitStats::new();
5421        let config = CircuitBreakerConfig {
5422            half_open_max_probes: 1,
5423            ..Default::default()
5424        };
5425
5426        // Can't probe when closed
5427        assert!(!stats.can_probe(&config));
5428
5429        stats.open();
5430        // Can't probe when open
5431        assert!(!stats.can_probe(&config));
5432
5433        stats.half_open();
5434        // Can probe when half-open
5435        assert!(stats.can_probe(&config));
5436
5437        // Start a probe
5438        assert!(stats.start_probe(&config));
5439        // Can't start another probe
5440        assert!(!stats.can_probe(&config));
5441        assert!(!stats.start_probe(&config));
5442    }
5443
5444    #[test]
5445    fn test_circuit_stats_probe_completion() {
5446        let _guard = test_guard!();
5447        let mut stats = CircuitStats::new();
5448        let config = CircuitBreakerConfig {
5449            half_open_max_probes: 1,
5450            ..Default::default()
5451        };
5452
5453        stats.open();
5454        stats.half_open();
5455        stats.start_probe(&config);
5456
5457        // Probe completes with success
5458        stats.record_success();
5459
5460        // Can start another probe
5461        assert!(stats.can_probe(&config));
5462    }
5463
5464    #[test]
5465    fn test_circuit_stats_failure_in_half_open() {
5466        let _guard = test_guard!();
5467        let mut stats = CircuitStats::new();
5468        let config = CircuitBreakerConfig {
5469            success_threshold: 2,
5470            ..Default::default()
5471        };
5472
5473        stats.open();
5474        stats.half_open();
5475
5476        stats.record_success();
5477        assert_eq!(stats.consecutive_failures(), 0);
5478
5479        // Failure resets consecutive successes
5480        stats.record_failure();
5481        assert!(!stats.should_close(&config));
5482
5483        // Need 2 more successes
5484        stats.record_success();
5485        stats.record_success();
5486        assert!(stats.should_close(&config));
5487    }
5488
5489    #[test]
5490    fn test_circuit_stats_reset_window() {
5491        let _guard = test_guard!();
5492        let mut stats = CircuitStats::new();
5493        stats.record_success();
5494        stats.record_failure();
5495
5496        assert!(stats.error_rate() > 0.0);
5497
5498        stats.reset_window();
5499        assert_eq!(stats.error_rate(), 0.0);
5500    }
5501
5502    #[test]
5503    fn test_circuit_state_transitions_are_deterministic() {
5504        let _guard = test_guard!();
5505        let config = CircuitBreakerConfig::default();
5506        let mut stats = CircuitStats::new();
5507
5508        // Start closed
5509        assert_eq!(stats.state(), CircuitState::Closed);
5510
5511        // Cause failures to open
5512        for _ in 0..3 {
5513            stats.record_failure();
5514        }
5515        assert!(stats.should_open(&config));
5516        stats.open();
5517        assert_eq!(stats.state(), CircuitState::Open);
5518
5519        // Transition to half-open after cooldown would be checked
5520        stats.half_open();
5521        assert_eq!(stats.state(), CircuitState::HalfOpen);
5522
5523        // Successes to close
5524        for _ in 0..2 {
5525            stats.record_success();
5526        }
5527        assert!(stats.should_close(&config));
5528        stats.close();
5529        assert_eq!(stats.state(), CircuitState::Closed);
5530    }
5531
5532    // ========================================================================
5533    // Compilation Timing Tests
5534    // ========================================================================
5535
5536    fn make_test_metrics(
5537        speedup: Option<f64>,
5538        total_secs: u64,
5539        success: bool,
5540    ) -> CompilationMetrics {
5541        CompilationMetrics {
5542            project_id: "test-project".to_string(),
5543            worker_id: "worker-1".to_string(),
5544            timestamp: chrono::Utc::now(),
5545            timing: CompilationTimingBreakdown {
5546                rsync_up: Duration::from_millis(100),
5547                remote_build: Duration::from_millis(800),
5548                rsync_down: Duration::from_millis(100),
5549                total: Duration::from_secs(total_secs),
5550            },
5551            local_build_time: speedup.map(|s| Duration::from_secs_f64(total_secs as f64 * s)),
5552            speedup,
5553            files_synced: 100,
5554            bytes_transferred: 1_000_000,
5555            exit_code: if success { 0 } else { 1 },
5556            success,
5557        }
5558    }
5559
5560    #[test]
5561    fn test_compilation_timing_breakdown_default() {
5562        let _guard = test_guard!();
5563        let timing = CompilationTimingBreakdown::default();
5564        assert_eq!(timing.rsync_up, Duration::ZERO);
5565        assert_eq!(timing.remote_build, Duration::ZERO);
5566        assert_eq!(timing.rsync_down, Duration::ZERO);
5567        assert_eq!(timing.total, Duration::ZERO);
5568    }
5569
5570    #[test]
5571    fn test_compilation_timing_breakdown_serialization() {
5572        let _guard = test_guard!();
5573        let timing = CompilationTimingBreakdown {
5574            rsync_up: Duration::from_millis(100),
5575            remote_build: Duration::from_millis(2000),
5576            rsync_down: Duration::from_millis(50),
5577            total: Duration::from_millis(2150),
5578        };
5579
5580        let json = serde_json::to_string(&timing).unwrap();
5581        assert!(json.contains("100")); // rsync_up
5582        assert!(json.contains("2000")); // remote_build
5583        assert!(json.contains("50")); // rsync_down
5584        assert!(json.contains("2150")); // total
5585
5586        let parsed: CompilationTimingBreakdown = serde_json::from_str(&json).unwrap();
5587        assert_eq!(parsed.rsync_up, timing.rsync_up);
5588        assert_eq!(parsed.remote_build, timing.remote_build);
5589        assert_eq!(parsed.rsync_down, timing.rsync_down);
5590        assert_eq!(parsed.total, timing.total);
5591    }
5592
5593    #[test]
5594    fn test_command_timing_breakdown_serialization() {
5595        let _guard = test_guard!();
5596        let timing = CommandTimingBreakdown {
5597            classify: Some(Duration::from_millis(2)),
5598            select: None,
5599            sync_up: Some(Duration::from_millis(120)),
5600            exec: Some(Duration::from_millis(900)),
5601            sync_down: None,
5602            cleanup: Some(Duration::from_millis(5)),
5603            total: Some(Duration::from_millis(1027)),
5604        };
5605
5606        let json = serde_json::to_string(&timing).unwrap();
5607        assert!(json.contains("\"classify\":2"));
5608        assert!(json.contains("\"select\":null"));
5609        assert!(json.contains("\"sync_up\":120"));
5610        assert!(json.contains("\"exec\":900"));
5611        assert!(json.contains("\"sync_down\":null"));
5612        assert!(json.contains("\"cleanup\":5"));
5613        assert!(json.contains("\"total\":1027"));
5614
5615        let parsed: CommandTimingBreakdown = serde_json::from_str(&json).unwrap();
5616        assert_eq!(parsed.classify, timing.classify);
5617        assert_eq!(parsed.select, timing.select);
5618        assert_eq!(parsed.sync_up, timing.sync_up);
5619        assert_eq!(parsed.exec, timing.exec);
5620        assert_eq!(parsed.sync_down, timing.sync_down);
5621        assert_eq!(parsed.cleanup, timing.cleanup);
5622        assert_eq!(parsed.total, timing.total);
5623    }
5624
5625    #[test]
5626    fn test_compilation_metrics_calculate_speedup() {
5627        let _guard = test_guard!();
5628        let mut metrics = CompilationMetrics {
5629            timing: CompilationTimingBreakdown {
5630                total: Duration::from_secs(10),
5631                ..Default::default()
5632            },
5633            local_build_time: Some(Duration::from_secs(30)),
5634            ..Default::default()
5635        };
5636
5637        metrics.calculate_speedup();
5638
5639        assert!(metrics.speedup.is_some());
5640        let speedup = metrics.speedup.unwrap();
5641        assert!(
5642            (speedup - 3.0).abs() < 0.01,
5643            "Expected 3.0x speedup, got {}",
5644            speedup
5645        );
5646    }
5647
5648    #[test]
5649    fn test_compilation_metrics_is_beneficial() {
5650        let _guard = test_guard!();
5651        let mut metrics = CompilationMetrics::default();
5652
5653        // No speedup calculated
5654        assert!(!metrics.is_beneficial());
5655
5656        // Speedup > 1 is beneficial
5657        metrics.speedup = Some(1.5);
5658        assert!(metrics.is_beneficial());
5659
5660        // Speedup < 1 is not beneficial
5661        metrics.speedup = Some(0.8);
5662        assert!(!metrics.is_beneficial());
5663
5664        // Speedup = 1 is not beneficial (exactly same speed)
5665        metrics.speedup = Some(1.0);
5666        assert!(!metrics.is_beneficial());
5667    }
5668
5669    #[test]
5670    fn test_compilation_metrics_serialization() {
5671        let _guard = test_guard!();
5672        let metrics = make_test_metrics(Some(2.5), 10, true);
5673        let json = serde_json::to_string(&metrics).unwrap();
5674
5675        assert!(json.contains("test-project"));
5676        assert!(json.contains("worker-1"));
5677        assert!(json.contains("2.5")); // speedup
5678
5679        let parsed: CompilationMetrics = serde_json::from_str(&json).unwrap();
5680        assert_eq!(parsed.project_id, "test-project");
5681        assert_eq!(parsed.worker_id, "worker-1");
5682        assert!(parsed.success);
5683    }
5684
5685    #[test]
5686    fn test_compilation_timer_new() {
5687        let _guard = test_guard!();
5688        let timer = CompilationTimer::new("my-project", "my-worker");
5689        assert_eq!(timer.project_id, "my-project");
5690        assert_eq!(timer.worker_id, "my-worker");
5691        assert!(timer.rsync_up.is_none());
5692        assert!(timer.remote_build.is_none());
5693        assert!(timer.rsync_down.is_none());
5694    }
5695
5696    #[test]
5697    fn test_compilation_timer_phases() {
5698        let _guard = test_guard!();
5699        let mut timer = CompilationTimer::new("test", "worker");
5700
5701        // Simulate rsync up
5702        std::thread::sleep(Duration::from_millis(5));
5703        timer.end_rsync_up();
5704        assert!(timer.rsync_up.is_some());
5705        assert!(timer.rsync_up.unwrap() >= Duration::from_millis(5));
5706
5707        // Simulate remote build
5708        std::thread::sleep(Duration::from_millis(10));
5709        timer.end_remote_build();
5710        assert!(timer.remote_build.is_some());
5711        assert!(timer.remote_build.unwrap() >= Duration::from_millis(10));
5712
5713        // Simulate rsync down
5714        std::thread::sleep(Duration::from_millis(5));
5715        timer.end_rsync_down();
5716        assert!(timer.rsync_down.is_some());
5717        assert!(timer.rsync_down.unwrap() >= Duration::from_millis(5));
5718
5719        // Finish
5720        let metrics = timer.finish(0, 50, 500_000);
5721        assert_eq!(metrics.project_id, "test");
5722        assert_eq!(metrics.worker_id, "worker");
5723        assert!(metrics.success);
5724        assert!(metrics.timing.total >= Duration::from_millis(20));
5725        assert_eq!(metrics.files_synced, 50);
5726        assert_eq!(metrics.bytes_transferred, 500_000);
5727    }
5728
5729    #[test]
5730    fn test_metrics_aggregator_new() {
5731        let _guard = test_guard!();
5732        let agg = MetricsAggregator::new(100);
5733        assert_eq!(agg.count(), 0);
5734        assert!(agg.average_speedup().is_none());
5735    }
5736
5737    #[test]
5738    fn test_metrics_aggregator_record() {
5739        let _guard = test_guard!();
5740        let mut agg = MetricsAggregator::new(3);
5741
5742        // Record first metric
5743        agg.record(make_test_metrics(Some(2.0), 10, true));
5744        assert_eq!(agg.count(), 1);
5745
5746        // Record up to max
5747        agg.record(make_test_metrics(Some(3.0), 20, true));
5748        agg.record(make_test_metrics(Some(4.0), 30, true));
5749        assert_eq!(agg.count(), 3);
5750
5751        // Exceed max should drop oldest
5752        agg.record(make_test_metrics(Some(5.0), 40, true));
5753        assert_eq!(agg.count(), 3);
5754    }
5755
5756    #[test]
5757    fn test_metrics_aggregator_average_speedup() {
5758        let _guard = test_guard!();
5759        let mut agg = MetricsAggregator::new(100);
5760
5761        // Empty case
5762        assert!(agg.average_speedup().is_none());
5763
5764        // Add metrics with speedups 1, 2, 3, 4, 5 -> average = 3
5765        for i in 1..=5 {
5766            agg.record(make_test_metrics(Some(i as f64), 10, true));
5767        }
5768
5769        let avg = agg.average_speedup().unwrap();
5770        assert!((avg - 3.0).abs() < 0.01, "Expected 3.0, got {}", avg);
5771    }
5772
5773    #[test]
5774    fn test_metrics_aggregator_average_speedup_with_none() {
5775        let _guard = test_guard!();
5776        let mut agg = MetricsAggregator::new(100);
5777
5778        // Mix of Some and None speedups
5779        agg.record(make_test_metrics(Some(2.0), 10, true));
5780        agg.record(make_test_metrics(None, 10, true)); // No speedup
5781        agg.record(make_test_metrics(Some(4.0), 10, true));
5782
5783        // Average should only consider metrics with speedup
5784        let avg = agg.average_speedup().unwrap();
5785        assert!((avg - 3.0).abs() < 0.01, "Expected 3.0, got {}", avg);
5786    }
5787
5788    #[test]
5789    fn test_metrics_aggregator_percentiles() {
5790        let _guard = test_guard!();
5791        let mut agg = MetricsAggregator::new(100);
5792
5793        // Add metrics with total times 1s, 2s, 3s, ..., 10s
5794        for i in 1..=10 {
5795            agg.record(make_test_metrics(Some(1.0), i, true));
5796        }
5797
5798        // p50 (median) should be around 5s
5799        let p50 = agg.p50_total_time().unwrap();
5800        assert!(p50 >= Duration::from_secs(5) && p50 <= Duration::from_secs(6));
5801
5802        // p95 should be around 9s or 10s
5803        let p95 = agg.p95_total_time().unwrap();
5804        assert!(p95 >= Duration::from_secs(9) && p95 <= Duration::from_secs(10));
5805
5806        // p99 should be 10s
5807        let p99 = agg.p99_total_time().unwrap();
5808        assert!(p99 >= Duration::from_secs(9));
5809    }
5810
5811    #[test]
5812    fn test_metrics_aggregator_success_rate() {
5813        let _guard = test_guard!();
5814        let mut agg = MetricsAggregator::new(100);
5815
5816        // Empty case
5817        assert_eq!(agg.success_rate(), 100.0);
5818
5819        // All successful
5820        agg.record(make_test_metrics(Some(1.0), 10, true));
5821        agg.record(make_test_metrics(Some(1.0), 10, true));
5822        assert_eq!(agg.success_rate(), 100.0);
5823
5824        // Add a failure (2 success, 1 failure = 66.67%)
5825        agg.record(make_test_metrics(Some(1.0), 10, false));
5826        let rate = agg.success_rate();
5827        assert!((rate - 66.67).abs() < 1.0, "Expected ~66.67%, got {}", rate);
5828    }
5829
5830    #[test]
5831    fn test_metrics_aggregator_clear() {
5832        let _guard = test_guard!();
5833        let mut agg = MetricsAggregator::new(100);
5834        agg.record(make_test_metrics(Some(1.0), 10, true));
5835        agg.record(make_test_metrics(Some(2.0), 20, true));
5836
5837        assert_eq!(agg.count(), 2);
5838
5839        agg.clear();
5840        assert_eq!(agg.count(), 0);
5841        assert!(agg.average_speedup().is_none());
5842    }
5843
5844    // CompilationConfig timeout tests
5845
5846    #[test]
5847    fn test_remote_build_jobs_parse_display_and_serde() {
5848        let _guard = test_guard!();
5849        assert_eq!(RemoteBuildJobs::default(), RemoteBuildJobs::Auto);
5850        for (spelling, expected) in [
5851            ("auto", RemoteBuildJobs::Auto),
5852            (" AUTO ", RemoteBuildJobs::Auto),
5853            ("off", RemoteBuildJobs::Off),
5854            ("none", RemoteBuildJobs::Off),
5855            ("4", RemoteBuildJobs::Fixed(4)),
5856        ] {
5857            assert_eq!(
5858                RemoteBuildJobs::parse(spelling).unwrap(),
5859                expected,
5860                "{spelling}"
5861            );
5862        }
5863        assert!(RemoteBuildJobs::parse("0").is_err(), "cargo rejects -j 0");
5864        assert!(RemoteBuildJobs::parse("many").is_err());
5865        assert_eq!(RemoteBuildJobs::Fixed(4).to_string(), "4");
5866        assert_eq!(RemoteBuildJobs::Off.to_string(), "off");
5867
5868        // TOML accepts both the string spellings and a bare integer, and an
5869        // absent key keeps the default.
5870        #[derive(Deserialize)]
5871        struct Wrap {
5872            compilation: CompilationConfig,
5873        }
5874        let parsed: Wrap = toml::from_str("[compilation]\nremote_build_jobs = \"off\"\n").unwrap();
5875        assert_eq!(parsed.compilation.remote_build_jobs, RemoteBuildJobs::Off);
5876        let parsed: Wrap = toml::from_str("[compilation]\nremote_build_jobs = 6\n").unwrap();
5877        assert_eq!(
5878            parsed.compilation.remote_build_jobs,
5879            RemoteBuildJobs::Fixed(6)
5880        );
5881        let parsed: Wrap = toml::from_str("[compilation]\nbuild_slots = 4\n").unwrap();
5882        assert_eq!(parsed.compilation.remote_build_jobs, RemoteBuildJobs::Auto);
5883        assert!(toml::from_str::<Wrap>("[compilation]\nremote_build_jobs = 0\n").is_err());
5884
5885        // Serialization round-trips through the same spellings.
5886        let json = serde_json::to_string(&RemoteBuildJobs::Fixed(3)).unwrap();
5887        assert_eq!(json, "3");
5888        assert_eq!(
5889            serde_json::to_string(&RemoteBuildJobs::Auto).unwrap(),
5890            "\"auto\""
5891        );
5892        let back: RemoteBuildJobs = serde_json::from_str("\"auto\"").unwrap();
5893        assert_eq!(back, RemoteBuildJobs::Auto);
5894    }
5895
5896    #[test]
5897    fn test_compilation_config_default_timeouts() {
5898        let _guard = test_guard!();
5899        let config = CompilationConfig::default();
5900        // Default build timeout: 5 minutes
5901        assert_eq!(config.build_timeout_sec, 300);
5902        // Default test timeout: 30 minutes
5903        assert_eq!(config.test_timeout_sec, 1800);
5904    }
5905
5906    #[test]
5907    fn test_compilation_config_timeout_for_test_kinds() {
5908        let _guard = test_guard!();
5909        let config = CompilationConfig::default();
5910
5911        // Test commands should get test_timeout_sec
5912        assert_eq!(
5913            config.timeout_for_kind(Some(crate::CompilationKind::CargoTest)),
5914            std::time::Duration::from_secs(1800)
5915        );
5916        assert_eq!(
5917            config.timeout_for_kind(Some(crate::CompilationKind::CargoNextest)),
5918            std::time::Duration::from_secs(1800)
5919        );
5920        assert_eq!(
5921            config.timeout_for_kind(Some(crate::CompilationKind::BunTest)),
5922            std::time::Duration::from_secs(config.bun_timeout_sec)
5923        );
5924    }
5925
5926    #[test]
5927    fn test_compilation_config_timeout_for_build_kinds() {
5928        let _guard = test_guard!();
5929        let config = CompilationConfig::default();
5930
5931        // Build/check commands should get build_timeout_sec
5932        assert_eq!(
5933            config.timeout_for_kind(Some(crate::CompilationKind::CargoBuild)),
5934            std::time::Duration::from_secs(300)
5935        );
5936        assert_eq!(
5937            config.timeout_for_kind(Some(crate::CompilationKind::CargoCheck)),
5938            std::time::Duration::from_secs(300)
5939        );
5940        assert_eq!(
5941            config.timeout_for_kind(Some(crate::CompilationKind::CargoClippy)),
5942            std::time::Duration::from_secs(300)
5943        );
5944        assert_eq!(
5945            config.timeout_for_kind(None),
5946            std::time::Duration::from_secs(300)
5947        );
5948    }
5949
5950    #[test]
5951    fn test_compilation_config_custom_timeouts() {
5952        let _guard = test_guard!();
5953        let config = CompilationConfig {
5954            build_timeout_sec: 600, // 10 minutes
5955            test_timeout_sec: 3600, // 1 hour
5956            ..Default::default()
5957        };
5958
5959        assert_eq!(
5960            config.timeout_for_kind(Some(crate::CompilationKind::CargoBuild)),
5961            std::time::Duration::from_secs(600)
5962        );
5963        assert_eq!(
5964            config.timeout_for_kind(Some(crate::CompilationKind::CargoTest)),
5965            std::time::Duration::from_secs(3600)
5966        );
5967    }
5968
5969    #[test]
5970    fn test_compilation_config_speedup_threshold_default() {
5971        let _guard = test_guard!();
5972        let config = CompilationConfig::default();
5973        // Default speedup threshold: 1.2 (20% faster required)
5974        assert!((config.remote_speedup_threshold - 1.2).abs() < 0.001);
5975    }
5976
5977    #[test]
5978    fn test_compilation_config_speedup_threshold_custom() {
5979        let _guard = test_guard!();
5980        let config = CompilationConfig {
5981            remote_speedup_threshold: 1.5, // Require 50% faster
5982            ..Default::default()
5983        };
5984        assert!((config.remote_speedup_threshold - 1.5).abs() < 0.001);
5985    }
5986
5987    #[test]
5988    fn test_compilation_config_speedup_threshold_no_minimum() {
5989        let _guard = test_guard!();
5990        // Setting to 1.0 means "always offload when other criteria met"
5991        let config = CompilationConfig {
5992            remote_speedup_threshold: 1.0,
5993            ..Default::default()
5994        };
5995        assert!((config.remote_speedup_threshold - 1.0).abs() < 0.001);
5996    }
5997
5998    #[test]
5999    fn test_compilation_config_min_local_time_ms_default() {
6000        let _guard = test_guard!();
6001        let config = CompilationConfig::default();
6002        // Default min_local_time_ms: 2000ms
6003        assert_eq!(config.min_local_time_ms, 2000);
6004    }
6005
6006    #[test]
6007    fn test_compilation_config_serde_roundtrip_speedup_threshold() {
6008        let _guard = test_guard!();
6009        let config = CompilationConfig {
6010            remote_speedup_threshold: 2.5,
6011            min_local_time_ms: 5000,
6012            ..Default::default()
6013        };
6014        let json = serde_json::to_string(&config).unwrap();
6015        let parsed: CompilationConfig = serde_json::from_str(&json).unwrap();
6016        assert!((parsed.remote_speedup_threshold - 2.5).abs() < 0.001);
6017        assert_eq!(parsed.min_local_time_ms, 5000);
6018    }
6019
6020    // ========================================================================
6021    // validate_remote_base Tests
6022    // ========================================================================
6023
6024    #[test]
6025    fn test_validate_remote_base_absolute_path() {
6026        let _guard = test_guard!();
6027        assert_eq!(validate_remote_base("/tmp/rch").unwrap(), "/tmp/rch");
6028        assert_eq!(
6029            validate_remote_base("/var/rch-builds").unwrap(),
6030            "/var/rch-builds"
6031        );
6032        assert_eq!(
6033            validate_remote_base("/home/builder/.rch").unwrap(),
6034            "/home/builder/.rch"
6035        );
6036    }
6037
6038    #[test]
6039    fn test_validate_remote_base_tilde_expansion() {
6040        let _guard = test_guard!();
6041        // Tilde expansion should work
6042        let result = validate_remote_base("~/rch");
6043        assert!(result.is_ok());
6044        let path = result.unwrap();
6045        assert!(
6046            path.starts_with('/'),
6047            "Path should be absolute after expansion: {}",
6048            path
6049        );
6050        assert!(!path.contains('~'), "Tilde should be expanded: {}", path);
6051    }
6052
6053    #[test]
6054    fn test_validate_remote_base_rejects_relative_path() {
6055        let _guard = test_guard!();
6056        let result = validate_remote_base("tmp/rch");
6057        assert!(result.is_err());
6058        assert!(result.unwrap_err().contains("absolute path"));
6059    }
6060
6061    #[test]
6062    fn test_validate_remote_base_rejects_path_traversal() {
6063        let _guard = test_guard!();
6064        let result = validate_remote_base("/tmp/../etc/rch");
6065        assert!(result.is_err());
6066        assert!(result.unwrap_err().contains("path traversal"));
6067
6068        let result = validate_remote_base("/tmp/rch/../other");
6069        assert!(result.is_err());
6070        assert!(result.unwrap_err().contains("path traversal"));
6071    }
6072
6073    #[test]
6074    fn test_validate_remote_base_normalizes_trailing_slash() {
6075        let _guard = test_guard!();
6076        assert_eq!(validate_remote_base("/tmp/rch/").unwrap(), "/tmp/rch");
6077        assert_eq!(validate_remote_base("/tmp/rch///").unwrap(), "/tmp/rch");
6078    }
6079
6080    #[test]
6081    fn test_validate_remote_base_root_path() {
6082        let _guard = test_guard!();
6083        // Root path should be rejected
6084        let result = validate_remote_base("/");
6085        assert!(result.is_err());
6086        assert!(result.unwrap_err().contains("root directory"));
6087    }
6088
6089    #[test]
6090    fn test_validate_remote_base_rejects_top_level() {
6091        let _guard = test_guard!();
6092        // Top-level directories should be rejected (depth 1)
6093        let result = validate_remote_base("/tmp");
6094        assert!(result.is_err());
6095        assert!(result.unwrap_err().contains("at least 2 levels deep"));
6096
6097        let result = validate_remote_base("/home");
6098        assert!(result.is_err());
6099
6100        // Depth 2 should be allowed
6101        assert_eq!(validate_remote_base("/tmp/rch").unwrap(), "/tmp/rch");
6102    }
6103
6104    #[test]
6105    fn test_default_remote_base() {
6106        let _guard = test_guard!();
6107        assert_eq!(default_remote_base(), "/data/tmp/rch");
6108    }
6109
6110    #[test]
6111    fn test_transfer_config_default_has_remote_base() {
6112        let _guard = test_guard!();
6113        let config = TransferConfig::default();
6114        assert_eq!(config.remote_base, "/data/tmp/rch");
6115    }
6116
6117    #[test]
6118    fn test_source_sync_timeout_validation_boundaries() {
6119        let _guard = test_guard!();
6120        assert!(!TransferConfig::valid_sync_timeout_ms(0));
6121        assert!(!TransferConfig::valid_sync_timeout_ms(999));
6122        assert!(TransferConfig::valid_sync_timeout_ms(1_000));
6123        assert!(TransferConfig::valid_sync_timeout_ms(3_600_000));
6124        assert!(!TransferConfig::valid_sync_timeout_ms(3_600_001));
6125    }
6126
6127    #[test]
6128    fn test_source_sync_timeout_is_explicit_or_payload_aware() {
6129        let _guard = test_guard!();
6130        let default = TransferConfig::default();
6131        assert_eq!(
6132            default.sync_timeout_for_payload(0),
6133            std::time::Duration::from_millis(30_000)
6134        );
6135        assert_eq!(
6136            default.sync_timeout_for_payload(10 * 1024 * 1024),
6137            std::time::Duration::from_millis(40_000)
6138        );
6139        assert_eq!(
6140            default.sync_timeout_for_payload(u64::MAX),
6141            std::time::Duration::from_millis(3_600_000)
6142        );
6143
6144        let explicit = TransferConfig {
6145            sync_timeout_ms: Some(120_000),
6146            ..TransferConfig::default()
6147        };
6148        assert_eq!(
6149            explicit.sync_timeout_for_payload(u64::MAX),
6150            std::time::Duration::from_millis(120_000)
6151        );
6152    }
6153
6154    // ========================================================================
6155    // RetryConfig Tests (bd-x1ek)
6156    // ========================================================================
6157
6158    #[test]
6159    fn test_retry_config_default() {
6160        let _guard = test_guard!();
6161        let config = RetryConfig::default();
6162        assert_eq!(config.max_attempts, 3);
6163        assert_eq!(config.base_delay_ms, 100);
6164        assert_eq!(config.max_delay_ms, 5000);
6165        assert_eq!(config.jitter_factor, 0.1);
6166        assert_eq!(config.total_timeout_ms, 30000);
6167    }
6168
6169    #[test]
6170    fn test_retry_config_no_retry() {
6171        let _guard = test_guard!();
6172        let config = RetryConfig::no_retry();
6173        assert_eq!(config.max_attempts, 1);
6174    }
6175
6176    #[test]
6177    fn test_retry_config_delay_for_attempt_zero() {
6178        let _guard = test_guard!();
6179        let config = RetryConfig::default();
6180        assert_eq!(config.delay_for_attempt(0), std::time::Duration::ZERO);
6181    }
6182
6183    #[test]
6184    fn test_retry_config_delay_for_attempt_exponential() {
6185        let _guard = test_guard!();
6186        let config = RetryConfig {
6187            base_delay_ms: 100,
6188            max_delay_ms: 10000,
6189            jitter_factor: 0.0, // No jitter for deterministic test
6190            ..Default::default()
6191        };
6192
6193        // attempt 1: 100 * 2^0 = 100ms
6194        assert_eq!(
6195            config.delay_for_attempt(1),
6196            std::time::Duration::from_millis(100)
6197        );
6198        // attempt 2: 100 * 2^1 = 200ms
6199        assert_eq!(
6200            config.delay_for_attempt(2),
6201            std::time::Duration::from_millis(200)
6202        );
6203        // attempt 3: 100 * 2^2 = 400ms
6204        assert_eq!(
6205            config.delay_for_attempt(3),
6206            std::time::Duration::from_millis(400)
6207        );
6208    }
6209
6210    #[test]
6211    fn test_retry_config_delay_capped_at_max() {
6212        let _guard = test_guard!();
6213        let config = RetryConfig {
6214            base_delay_ms: 1000,
6215            max_delay_ms: 2000,
6216            jitter_factor: 0.0,
6217            ..Default::default()
6218        };
6219
6220        // attempt 2: 1000 * 2^1 = 2000ms (at cap)
6221        assert_eq!(
6222            config.delay_for_attempt(2),
6223            std::time::Duration::from_millis(2000)
6224        );
6225        // attempt 3: 1000 * 2^2 = 4000ms, capped to 2000ms
6226        assert_eq!(
6227            config.delay_for_attempt(3),
6228            std::time::Duration::from_millis(2000)
6229        );
6230    }
6231
6232    #[test]
6233    fn test_retry_config_random_jitter_stays_within_bounds() {
6234        let _guard = test_guard!();
6235        let config = RetryConfig {
6236            base_delay_ms: 100,
6237            max_delay_ms: 200,
6238            jitter_factor: 0.25,
6239            ..Default::default()
6240        };
6241
6242        // Jitter applies after the exponential delay is capped. Exercise the
6243        // real RNG without requiring any particular random value or sequence.
6244        for (attempt, minimum_ms, maximum_ms) in [(1, 75, 125), (3, 150, 250)] {
6245            for _ in 0..128 {
6246                let delay = config.delay_for_attempt(attempt);
6247                assert!(delay >= std::time::Duration::from_millis(minimum_ms));
6248                assert!(delay <= std::time::Duration::from_millis(maximum_ms));
6249            }
6250        }
6251    }
6252
6253    #[test]
6254    fn test_retry_config_should_retry() {
6255        let _guard = test_guard!();
6256        let config = RetryConfig {
6257            max_attempts: 3,
6258            total_timeout_ms: 1000,
6259            ..Default::default()
6260        };
6261
6262        // Before max attempts and within timeout
6263        assert!(config.should_retry(0, std::time::Duration::from_millis(0)));
6264        assert!(config.should_retry(1, std::time::Duration::from_millis(500)));
6265        assert!(config.should_retry(2, std::time::Duration::from_millis(900)));
6266
6267        // At max attempts
6268        assert!(!config.should_retry(3, std::time::Duration::from_millis(0)));
6269
6270        // Past timeout
6271        assert!(!config.should_retry(1, std::time::Duration::from_millis(1001)));
6272    }
6273
6274    #[test]
6275    fn test_retry_config_serde_roundtrip() {
6276        let _guard = test_guard!();
6277        let config = RetryConfig {
6278            max_attempts: 5,
6279            base_delay_ms: 200,
6280            max_delay_ms: 8000,
6281            jitter_factor: 0.2,
6282            total_timeout_ms: 60000,
6283        };
6284        let json = serde_json::to_string(&config).unwrap();
6285        let parsed: RetryConfig = serde_json::from_str(&json).unwrap();
6286        assert_eq!(parsed.max_attempts, 5);
6287        assert_eq!(parsed.base_delay_ms, 200);
6288        assert_eq!(parsed.max_delay_ms, 8000);
6289        assert_eq!(parsed.jitter_factor, 0.2);
6290        assert_eq!(parsed.total_timeout_ms, 60000);
6291    }
6292
6293    #[test]
6294    fn test_transfer_config_includes_retry() {
6295        let _guard = test_guard!();
6296        let config = TransferConfig::default();
6297        assert_eq!(config.retry.max_attempts, 3);
6298    }
6299
6300    // =========================================================================
6301    // ExecutionConfig Tests (bd-785w)
6302    // =========================================================================
6303
6304    #[test]
6305    fn test_execution_config_default_allowlist() {
6306        let _guard = test_guard!();
6307        let config = ExecutionConfig::default();
6308        // All supported compilers should be in the default allowlist
6309        assert!(config.is_allowed("cargo"));
6310        assert!(config.is_allowed("rustc"));
6311        assert!(config.is_allowed("gcc"));
6312        assert!(config.is_allowed("g++"));
6313        assert!(config.is_allowed("clang"));
6314        assert!(config.is_allowed("clang++"));
6315        assert!(config.is_allowed("make"));
6316        assert!(config.is_allowed("cmake"));
6317        assert!(config.is_allowed("ninja"));
6318        assert!(config.is_allowed("meson"));
6319        assert!(config.is_allowed("bun"));
6320        assert!(config.is_allowed("nextest"));
6321        assert!(config.is_allowed("cc"));
6322        assert!(config.is_allowed("c++"));
6323    }
6324
6325    #[test]
6326    fn test_execution_config_is_allowed_case_insensitive() {
6327        let _guard = test_guard!();
6328        let config = ExecutionConfig::default();
6329        // Should be case-insensitive
6330        assert!(config.is_allowed("CARGO"));
6331        assert!(config.is_allowed("Cargo"));
6332        assert!(config.is_allowed("GCC"));
6333        assert!(config.is_allowed("Gcc"));
6334    }
6335
6336    #[test]
6337    fn test_execution_config_is_not_allowed() {
6338        let _guard = test_guard!();
6339        let config = ExecutionConfig::default();
6340        // Unknown commands should not be allowed
6341        assert!(!config.is_allowed("python"));
6342        assert!(!config.is_allowed("npm"));
6343        assert!(!config.is_allowed(""));
6344        // `go` and `tsc` ARE allowed now that Go/TypeScript are offload targets.
6345        // If they were missing from the allowlist the hook would fail open to
6346        // LOCAL execution — classification would look correct while every build
6347        // silently ran on the orchestrator.
6348        assert!(config.is_allowed("go"));
6349        assert!(config.is_allowed("tsc"));
6350    }
6351
6352    #[test]
6353    fn test_execution_config_empty_allowlist() {
6354        let _guard = test_guard!();
6355        let config = ExecutionConfig { allowlist: vec![] };
6356        // Empty allowlist should block everything
6357        assert!(!config.is_allowed("cargo"));
6358        assert!(!config.is_allowed("gcc"));
6359    }
6360
6361    #[test]
6362    fn test_execution_config_custom_allowlist() {
6363        let _guard = test_guard!();
6364        let config = ExecutionConfig {
6365            allowlist: vec!["cargo".to_string(), "custom_tool".to_string()],
6366        };
6367        assert!(config.is_allowed("cargo"));
6368        assert!(config.is_allowed("custom_tool"));
6369        assert!(!config.is_allowed("gcc"));
6370    }
6371
6372    #[test]
6373    fn test_execution_config_serde() {
6374        let _guard = test_guard!();
6375        let config = ExecutionConfig {
6376            allowlist: vec!["cargo".to_string(), "rustc".to_string()],
6377        };
6378        let json = serde_json::to_string(&config).unwrap();
6379        let parsed: ExecutionConfig = serde_json::from_str(&json).unwrap();
6380        assert_eq!(parsed.allowlist, config.allowlist);
6381    }
6382
6383    #[test]
6384    fn test_rch_config_includes_execution() {
6385        let _guard = test_guard!();
6386        let config = RchConfig::default();
6387        // RchConfig should include ExecutionConfig with default allowlist
6388        assert!(config.execution.is_allowed("cargo"));
6389    }
6390
6391    // ========================================================================
6392    // Adaptive Compression Tests (bd-243w)
6393    // ========================================================================
6394
6395    #[test]
6396    fn test_adaptive_compression_disabled_by_default() {
6397        let _guard = test_guard!();
6398        let config = TransferConfig::default();
6399        assert!(!config.adaptive_compression);
6400        // Should use fixed level when disabled
6401        assert_eq!(config.select_compression_level(Some(1_000_000)), 3);
6402        assert_eq!(config.select_compression_level(Some(500_000_000)), 3);
6403    }
6404
6405    #[test]
6406    fn test_adaptive_compression_small_payload() {
6407        let _guard = test_guard!();
6408        let config = TransferConfig {
6409            adaptive_compression: true,
6410            ..Default::default()
6411        };
6412        // < 10MB should use level 1
6413        assert_eq!(config.select_compression_level(Some(0)), 1);
6414        assert_eq!(config.select_compression_level(Some(1_000_000)), 1); // 1MB
6415        assert_eq!(config.select_compression_level(Some(9_999_999)), 1); // ~10MB
6416    }
6417
6418    #[test]
6419    fn test_adaptive_compression_medium_payload() {
6420        let _guard = test_guard!();
6421        let config = TransferConfig {
6422            adaptive_compression: true,
6423            ..Default::default()
6424        };
6425        // 10-200MB should use level 3
6426        assert_eq!(config.select_compression_level(Some(10_000_000)), 3); // 10MB
6427        assert_eq!(config.select_compression_level(Some(100_000_000)), 3); // 100MB
6428        assert_eq!(config.select_compression_level(Some(199_999_999)), 3); // ~200MB
6429    }
6430
6431    #[test]
6432    fn test_adaptive_compression_large_payload() {
6433        let _guard = test_guard!();
6434        let config = TransferConfig {
6435            adaptive_compression: true,
6436            ..Default::default()
6437        };
6438        // > 200MB should use level 7
6439        assert_eq!(config.select_compression_level(Some(200_000_000)), 7); // 200MB
6440        assert_eq!(config.select_compression_level(Some(500_000_000)), 7); // 500MB
6441        assert_eq!(config.select_compression_level(Some(1_000_000_000)), 7); // 1GB
6442    }
6443
6444    #[test]
6445    fn test_adaptive_compression_no_estimate() {
6446        let _guard = test_guard!();
6447        let config = TransferConfig {
6448            adaptive_compression: true,
6449            compression_level: 5,
6450            ..Default::default()
6451        };
6452        // No estimate should fallback to default level
6453        assert_eq!(config.select_compression_level(None), 5);
6454    }
6455
6456    #[test]
6457    fn test_adaptive_compression_respects_min_level() {
6458        let _guard = test_guard!();
6459        let config = TransferConfig {
6460            adaptive_compression: true,
6461            min_compression_level: 3,
6462            ..Default::default()
6463        };
6464        // Small payload would want level 1, but min is 3
6465        assert_eq!(config.select_compression_level(Some(1_000_000)), 3);
6466    }
6467
6468    #[test]
6469    fn test_adaptive_compression_respects_max_level() {
6470        let _guard = test_guard!();
6471        let config = TransferConfig {
6472            adaptive_compression: true,
6473            max_compression_level: 5,
6474            ..Default::default()
6475        };
6476        // Large payload would want level 7, but max is 5
6477        assert_eq!(config.select_compression_level(Some(500_000_000)), 5);
6478    }
6479
6480    #[test]
6481    fn test_adaptive_compression_serde_roundtrip() {
6482        let _guard = test_guard!();
6483        let config = TransferConfig {
6484            adaptive_compression: true,
6485            min_compression_level: 2,
6486            max_compression_level: 8,
6487            ..Default::default()
6488        };
6489        let json = serde_json::to_string(&config).unwrap();
6490        let parsed: TransferConfig = serde_json::from_str(&json).unwrap();
6491        assert!(parsed.adaptive_compression);
6492        assert_eq!(parsed.min_compression_level, 2);
6493        assert_eq!(parsed.max_compression_level, 8);
6494    }
6495
6496    // -------------------------------------------------------------------------
6497    // Self-Healing Config Tests (bd-59kg)
6498    // -------------------------------------------------------------------------
6499
6500    #[test]
6501    fn test_self_healing_config_defaults() {
6502        let _guard = test_guard!();
6503        // TEST START: SelfHealingConfig::default() returns expected values
6504        let config = SelfHealingConfig::default();
6505
6506        // Both self-healing behaviors enabled by default
6507        assert!(
6508            config.hook_starts_daemon,
6509            "hook_starts_daemon should be true by default"
6510        );
6511        assert!(
6512            config.daemon_installs_hooks,
6513            "daemon_installs_hooks should be true by default"
6514        );
6515
6516        // Timing defaults
6517        assert_eq!(
6518            config.auto_start_cooldown_secs, 30,
6519            "auto_start_cooldown_secs should default to 30"
6520        );
6521        assert_eq!(
6522            config.auto_start_timeout_secs, 3,
6523            "auto_start_timeout_secs should default to 3"
6524        );
6525        // TEST PASS: SelfHealingConfig defaults
6526    }
6527
6528    #[test]
6529    fn test_self_healing_config_serde_full() {
6530        let _guard = test_guard!();
6531        // TEST START: Full SelfHealingConfig serialization/deserialization
6532        let config = SelfHealingConfig {
6533            hook_starts_daemon: false,
6534            daemon_installs_hooks: false,
6535            auto_start_cooldown_secs: 60,
6536            auto_start_timeout_secs: 10,
6537            self_healing_log_level: SelfHealingLogLevel::Debug,
6538        };
6539
6540        let json = serde_json::to_string(&config).unwrap();
6541        assert!(json.contains("\"hook_starts_daemon\":false"));
6542        assert!(json.contains("\"daemon_installs_hooks\":false"));
6543        assert!(json.contains("\"auto_start_cooldown_secs\":60"));
6544        assert!(json.contains("\"auto_start_timeout_secs\":10"));
6545        assert!(json.contains("\"self_healing_log_level\":\"debug\""));
6546
6547        let parsed: SelfHealingConfig = serde_json::from_str(&json).unwrap();
6548        assert!(!parsed.hook_starts_daemon);
6549        assert!(!parsed.daemon_installs_hooks);
6550        assert_eq!(parsed.auto_start_cooldown_secs, 60);
6551        assert_eq!(parsed.auto_start_timeout_secs, 10);
6552        assert_eq!(parsed.self_healing_log_level, SelfHealingLogLevel::Debug);
6553        // TEST PASS: Full SelfHealingConfig serde
6554    }
6555
6556    // br-4zf3p: Tests for the self_healing_log_level field.
6557
6558    #[test]
6559    fn test_self_healing_log_level_default_is_info() {
6560        // TEST START: SelfHealingLogLevel::default() == Info
6561        let level = SelfHealingLogLevel::default();
6562        assert_eq!(level, SelfHealingLogLevel::Info);
6563        // Also verify the SelfHealingConfig default surfaces it.
6564        let config = SelfHealingConfig::default();
6565        assert_eq!(
6566            config.self_healing_log_level,
6567            SelfHealingLogLevel::Info,
6568            "config default should be Info"
6569        );
6570        // TEST PASS
6571    }
6572
6573    #[test]
6574    fn test_self_healing_log_level_serializes_lowercase() {
6575        // TEST START: serde uses lowercase variants
6576        let json = serde_json::to_string(&SelfHealingLogLevel::Warn).unwrap();
6577        assert_eq!(json, "\"warn\"");
6578        let parsed: SelfHealingLogLevel = serde_json::from_str("\"error\"").unwrap();
6579        assert_eq!(parsed, SelfHealingLogLevel::Error);
6580        // TEST PASS
6581    }
6582
6583    #[test]
6584    fn test_self_healing_log_level_from_env_str_accepts_known() {
6585        // TEST START: from_env_str parses each level (case-insensitive) and aliases
6586        assert_eq!(
6587            SelfHealingLogLevel::from_env_str("debug"),
6588            Some(SelfHealingLogLevel::Debug)
6589        );
6590        assert_eq!(
6591            SelfHealingLogLevel::from_env_str("DEBUG"),
6592            Some(SelfHealingLogLevel::Debug)
6593        );
6594        assert_eq!(
6595            SelfHealingLogLevel::from_env_str("info"),
6596            Some(SelfHealingLogLevel::Info)
6597        );
6598        assert_eq!(
6599            SelfHealingLogLevel::from_env_str("warn"),
6600            Some(SelfHealingLogLevel::Warn)
6601        );
6602        assert_eq!(
6603            SelfHealingLogLevel::from_env_str("warning"),
6604            Some(SelfHealingLogLevel::Warn),
6605            "warning should map to Warn"
6606        );
6607        assert_eq!(
6608            SelfHealingLogLevel::from_env_str("error"),
6609            Some(SelfHealingLogLevel::Error)
6610        );
6611        // Whitespace tolerance
6612        assert_eq!(
6613            SelfHealingLogLevel::from_env_str("  debug  "),
6614            Some(SelfHealingLogLevel::Debug)
6615        );
6616        // TEST PASS
6617    }
6618
6619    #[test]
6620    fn test_self_healing_log_level_from_env_str_rejects_unknown() {
6621        // TEST START: unknown values return None (caller falls back to default)
6622        assert!(SelfHealingLogLevel::from_env_str("banana").is_none());
6623        assert!(SelfHealingLogLevel::from_env_str("").is_none());
6624        assert!(SelfHealingLogLevel::from_env_str("trace").is_none());
6625        // TEST PASS
6626    }
6627
6628    #[test]
6629    fn test_self_healing_config_serde_partial_uses_defaults() {
6630        let _guard = test_guard!();
6631        // TEST START: Partial TOML/JSON uses defaults for missing fields
6632        let json = r#"{"hook_starts_daemon": false}"#;
6633        let config: SelfHealingConfig = serde_json::from_str(json).unwrap();
6634
6635        assert!(
6636            !config.hook_starts_daemon,
6637            "Explicit false should be parsed"
6638        );
6639        assert!(
6640            config.daemon_installs_hooks,
6641            "Missing field should use default (true)"
6642        );
6643        assert_eq!(
6644            config.auto_start_cooldown_secs, 30,
6645            "Missing field should use default (30)"
6646        );
6647        assert_eq!(
6648            config.auto_start_timeout_secs, 3,
6649            "Missing field should use default (3)"
6650        );
6651        // TEST PASS: Partial SelfHealingConfig uses defaults
6652    }
6653
6654    #[test]
6655    fn test_self_healing_config_toml_with_alias() {
6656        let _guard = test_guard!();
6657        // TEST START: daemon_start_timeout alias works for auto_start_timeout_secs
6658        let toml_str = r#"
6659            hook_starts_daemon = true
6660            daemon_installs_hooks = false
6661            auto_start_cooldown_secs = 45
6662            daemon_start_timeout = 7
6663        "#;
6664
6665        let config: SelfHealingConfig = toml::from_str(toml_str).unwrap();
6666        assert!(config.hook_starts_daemon);
6667        assert!(!config.daemon_installs_hooks);
6668        assert_eq!(config.auto_start_cooldown_secs, 45);
6669        assert_eq!(
6670            config.auto_start_timeout_secs, 7,
6671            "daemon_start_timeout alias should set auto_start_timeout_secs"
6672        );
6673        // TEST PASS: TOML alias works
6674    }
6675
6676    #[allow(unsafe_code)]
6677    mod self_healing_env_override_tests {
6678        use super::*;
6679        use crate::config::env_test_lock;
6680
6681        fn env_guard() -> std::sync::MutexGuard<'static, ()> {
6682            env_test_lock()
6683        }
6684
6685        fn set_env(key: &str, value: &str) {
6686            // SAFETY: Tests are serialized with env_guard().
6687            unsafe { std::env::set_var(key, value) };
6688        }
6689
6690        fn remove_env(key: &str) {
6691            // SAFETY: Tests are serialized with env_guard().
6692            unsafe { std::env::remove_var(key) };
6693        }
6694
6695        struct EnvVarGuard {
6696            key: &'static str,
6697            old: Option<String>,
6698        }
6699
6700        impl EnvVarGuard {
6701            fn set(key: &'static str, value: &str) -> Self {
6702                let old = std::env::var(key).ok();
6703                set_env(key, value);
6704                Self { key, old }
6705            }
6706        }
6707
6708        impl Drop for EnvVarGuard {
6709            fn drop(&mut self) {
6710                if let Some(old) = &self.old {
6711                    set_env(self.key, old);
6712                } else {
6713                    remove_env(self.key);
6714                }
6715            }
6716        }
6717
6718        #[test]
6719        fn test_self_healing_config_with_env_overrides_master_disable() {
6720            let _guard = test_guard!();
6721            let _guard = env_guard();
6722
6723            let _no_self_healing = EnvVarGuard::set("RCH_NO_SELF_HEALING", "1");
6724            let _hook_starts_daemon = EnvVarGuard::set("RCH_HOOK_STARTS_DAEMON", "1");
6725            let _daemon_installs_hooks = EnvVarGuard::set("RCH_DAEMON_INSTALLS_HOOKS", "1");
6726            let _cooldown = EnvVarGuard::set("RCH_AUTO_START_COOLDOWN_SECS", "99");
6727            let _timeout = EnvVarGuard::set("RCH_AUTO_START_TIMEOUT_SECS", "99");
6728
6729            let config = SelfHealingConfig::default().with_env_overrides();
6730            assert!(
6731                !config.hook_starts_daemon,
6732                "RCH_NO_SELF_HEALING should disable hook auto-start"
6733            );
6734            assert!(
6735                !config.daemon_installs_hooks,
6736                "RCH_NO_SELF_HEALING should disable daemon hook installation"
6737            );
6738
6739            // Master disable returns early; numeric overrides should not apply.
6740            assert_eq!(config.auto_start_cooldown_secs, 30);
6741            assert_eq!(config.auto_start_timeout_secs, 3);
6742        }
6743
6744        #[test]
6745        fn test_self_healing_config_with_env_overrides_toggles_and_numbers() {
6746            let _guard = test_guard!();
6747            let _guard = env_guard();
6748
6749            let _hook_starts_daemon = EnvVarGuard::set("RCH_HOOK_STARTS_DAEMON", "0");
6750            let _daemon_installs_hooks = EnvVarGuard::set("RCH_DAEMON_INSTALLS_HOOKS", "false");
6751            let _cooldown = EnvVarGuard::set("RCH_AUTO_START_COOLDOWN_SECS", "45");
6752            let _timeout = EnvVarGuard::set("RCH_AUTO_START_TIMEOUT_SECS", "7");
6753
6754            let config = SelfHealingConfig::default().with_env_overrides();
6755            assert!(!config.hook_starts_daemon);
6756            assert!(!config.daemon_installs_hooks);
6757            assert_eq!(config.auto_start_cooldown_secs, 45);
6758            assert_eq!(config.auto_start_timeout_secs, 7);
6759        }
6760
6761        #[test]
6762        fn test_self_healing_config_with_env_overrides_invalid_numbers_ignored() {
6763            let _guard = test_guard!();
6764            let _guard = env_guard();
6765
6766            let _cooldown = EnvVarGuard::set("RCH_AUTO_START_COOLDOWN_SECS", "not-a-number");
6767            let _timeout = EnvVarGuard::set("RCH_AUTO_START_TIMEOUT_SECS", "nope");
6768
6769            let config = SelfHealingConfig::default().with_env_overrides();
6770            assert_eq!(config.auto_start_cooldown_secs, 30);
6771            assert_eq!(config.auto_start_timeout_secs, 3);
6772        }
6773    }
6774
6775    // -------------------------------------------------------------------------
6776    // Preflight Health Guard Tests (bd-3eaa)
6777    // -------------------------------------------------------------------------
6778
6779    #[test]
6780    fn test_load_per_core_calculation() {
6781        let _guard = test_guard!();
6782        let mut caps = WorkerCapabilities::new();
6783        // No metrics -> None
6784        assert!(caps.load_per_core().is_none());
6785
6786        // Only load, no cpus -> None
6787        caps.load_avg_1 = Some(4.0);
6788        assert!(caps.load_per_core().is_none());
6789
6790        // Both available
6791        caps.num_cpus = Some(4);
6792        assert_eq!(caps.load_per_core(), Some(1.0)); // 4.0 / 4 = 1.0
6793
6794        // High load
6795        caps.load_avg_1 = Some(16.0);
6796        assert_eq!(caps.load_per_core(), Some(4.0)); // 16.0 / 4 = 4.0
6797    }
6798
6799    #[test]
6800    fn test_is_high_load() {
6801        let _guard = test_guard!();
6802        let mut caps = WorkerCapabilities::new();
6803        caps.load_avg_1 = Some(8.0);
6804        caps.num_cpus = Some(4);
6805        // load_per_core = 2.0
6806
6807        // Below threshold
6808        assert_eq!(caps.is_high_load(3.0), Some(false));
6809        // At threshold
6810        assert_eq!(caps.is_high_load(2.0), Some(false)); // equal is OK
6811        // Above threshold
6812        assert_eq!(caps.is_high_load(1.5), Some(true));
6813
6814        // No metrics -> None (fail-open)
6815        caps.load_avg_1 = None;
6816        assert!(caps.is_high_load(1.0).is_none());
6817    }
6818
6819    #[test]
6820    fn test_is_low_disk() {
6821        let _guard = test_guard!();
6822        let mut caps = WorkerCapabilities::new();
6823        caps.disk_free_gb = Some(15.0);
6824
6825        // Above threshold
6826        assert_eq!(caps.is_low_disk(10.0), Some(false));
6827        // At threshold
6828        assert_eq!(caps.is_low_disk(15.0), Some(false)); // equal is OK
6829        // Below threshold
6830        assert_eq!(caps.is_low_disk(20.0), Some(true));
6831
6832        // No metrics -> None (fail-open)
6833        caps.disk_free_gb = None;
6834        assert!(caps.is_low_disk(10.0).is_none());
6835    }
6836
6837    #[test]
6838    fn low_disk_judges_the_build_disk_not_a_small_tmpfs() {
6839        let _guard = test_guard!();
6840        // GH #78: a 16 GB tmpfs /tmp is the tightest mount by ratio, but the
6841        // build trees live on a roomy data disk.
6842        let mut caps = WorkerCapabilities::new();
6843        caps.disk_free_gb = Some(8.0);
6844        caps.disk_total_gb = Some(15.5);
6845        caps.build_disk_free_gb = Some(1700.0);
6846        caps.build_disk_total_gb = Some(1900.0);
6847        assert_eq!(caps.build_disk_gb(), (Some(1700.0), Some(1900.0)));
6848        assert_eq!(caps.is_low_disk(10.0), Some(false));
6849
6850        // A full build disk is low even when /tmp is roomy.
6851        caps.build_disk_free_gb = Some(4.0);
6852        assert_eq!(caps.is_low_disk(10.0), Some(true));
6853
6854        // An older rch-wkr without the build sample keeps the old behaviour.
6855        caps.build_disk_free_gb = None;
6856        caps.build_disk_total_gb = None;
6857        assert_eq!(caps.build_disk_gb(), (Some(8.0), Some(15.5)));
6858        assert_eq!(caps.is_low_disk(10.0), Some(true));
6859    }
6860
6861    #[test]
6862    fn build_disk_sample_is_optional_on_the_wire() {
6863        let _guard = test_guard!();
6864        let old: WorkerCapabilities =
6865            serde_json::from_str(r#"{"disk_free_gb":13.9,"disk_total_gb":15.5}"#).unwrap();
6866        assert_eq!(old.build_disk_free_gb, None);
6867        assert_eq!(old.build_disk_gb(), (Some(13.9), Some(15.5)));
6868
6869        let new: WorkerCapabilities = serde_json::from_str(
6870            r#"{"disk_free_gb":13.9,"disk_total_gb":15.5,"build_disk_free_gb":1700.0,"build_disk_total_gb":1900.0}"#,
6871        )
6872        .unwrap();
6873        assert_eq!(new.build_disk_gb(), (Some(1700.0), Some(1900.0)));
6874        let json = serde_json::to_string(&new).unwrap();
6875        assert!(json.contains("\"build_disk_free_gb\":1700.0"), "{json}");
6876    }
6877
6878    #[test]
6879    fn test_selection_config_preflight_defaults() {
6880        let _guard = test_guard!();
6881        let config = SelectionConfig::default();
6882        // Default thresholds
6883        assert_eq!(config.max_load_per_core, Some(2.0));
6884        assert_eq!(config.min_free_gb, Some(10.0));
6885        assert_eq!(config.disk_gb_per_slot, 10.0);
6886    }
6887
6888    #[test]
6889    fn test_selection_config_preflight_serde() {
6890        let _guard = test_guard!();
6891        let config = SelectionConfig {
6892            max_load_per_core: Some(3.5),
6893            min_free_gb: Some(25.0),
6894            disk_gb_per_slot: 0.83,
6895            ..Default::default()
6896        };
6897        let json = serde_json::to_string(&config).unwrap();
6898        let parsed: SelectionConfig = serde_json::from_str(&json).unwrap();
6899        assert_eq!(parsed.max_load_per_core, Some(3.5));
6900        assert_eq!(parsed.min_free_gb, Some(25.0));
6901        assert_eq!(parsed.disk_gb_per_slot, 0.83);
6902    }
6903
6904    #[test]
6905    fn test_selection_disk_slot_budget_validation() {
6906        let _guard = test_guard!();
6907        for value in ["0.0", "-1.0", "nan", "inf", "-inf"] {
6908            let result = toml::from_str::<SelectionConfig>(&format!("disk_gb_per_slot = {value}"));
6909            assert!(result.is_err(), "invalid disk slot budget {value}");
6910        }
6911        let default: SelectionConfig = toml::from_str("").unwrap();
6912        assert_eq!(default.disk_gb_per_slot, 10.0);
6913    }
6914
6915    #[test]
6916    fn test_selection_disk_weight_validation_and_roundtrip() {
6917        for value in ["-0.1", "1.1", "nan", "inf", "-inf"] {
6918            assert!(toml::from_str::<SelectionWeightConfig>(&format!("disk = {value}")).is_err());
6919        }
6920        for value in [0.0, 0.2, 1.0] {
6921            let weights: SelectionWeightConfig =
6922                toml::from_str(&format!("disk = {value}")).unwrap();
6923            assert_eq!(weights.disk, value);
6924            let roundtrip: SelectionWeightConfig =
6925                serde_json::from_str(&serde_json::to_string(&weights).unwrap()).unwrap();
6926            assert_eq!(roundtrip.disk, value);
6927        }
6928        let defaults: SelectionWeightConfig = toml::from_str("").unwrap();
6929        assert_eq!(defaults.disk, 0.2);
6930    }
6931
6932    #[test]
6933    fn test_worker_capabilities_health_metrics_serde() {
6934        let _guard = test_guard!();
6935        let caps = WorkerCapabilities {
6936            num_cpus: Some(8),
6937            load_avg_1: Some(1.5),
6938            load_avg_5: Some(2.0),
6939            load_avg_15: Some(1.8),
6940            disk_free_gb: Some(50.5),
6941            disk_total_gb: Some(100.0),
6942            ..Default::default()
6943        };
6944        let json = serde_json::to_string(&caps).unwrap();
6945        let parsed: WorkerCapabilities = serde_json::from_str(&json).unwrap();
6946        assert_eq!(parsed.num_cpus, Some(8));
6947        assert_eq!(parsed.load_avg_1, Some(1.5));
6948        assert_eq!(parsed.disk_free_gb, Some(50.5));
6949    }
6950
6951    #[test]
6952    fn microarch_level_classifies_ivy_bridge_as_v2() {
6953        // Abbreviated real flag set from ovh-b (Xeon E3-1245 V2, Ivy Bridge):
6954        // AVX present, but no avx2/bmi/fma — the bd-68hon SIGILL class.
6955        let ivy = "fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov \
6956                   pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx rdtscp lm \
6957                   constant_tsc pni pclmulqdq ssse3 cx16 sse4_1 sse4_2 x2apic \
6958                   popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm";
6959        assert_eq!(x86_64_microarch_level_from_flags(ivy), 2);
6960    }
6961
6962    #[test]
6963    fn microarch_level_classifies_v3_and_v4() {
6964        let v3 = "cx16 lahf_lm popcnt sse4_1 sse4_2 ssse3 abm avx avx2 bmi1 bmi2 \
6965                  f16c fma movbe xsave";
6966        assert_eq!(x86_64_microarch_level_from_flags(v3), 3);
6967
6968        let v4 = format!("{v3} avx512f avx512bw avx512cd avx512dq avx512vl");
6969        assert_eq!(x86_64_microarch_level_from_flags(&v4), 4);
6970    }
6971
6972    #[test]
6973    fn microarch_level_v1_for_ancient_or_empty_flags() {
6974        assert_eq!(x86_64_microarch_level_from_flags(""), 1);
6975        assert_eq!(x86_64_microarch_level_from_flags("fpu mmx sse sse2"), 1);
6976    }
6977
6978    #[test]
6979    fn pre_v3_predicate_only_fires_on_affirmative_evidence() {
6980        let mut caps = WorkerCapabilities::new();
6981        assert!(!caps.is_pre_v3_x86(), "unknown must not deprioritize");
6982        caps.cpu_microarch_level = Some(2);
6983        assert!(caps.is_pre_v3_x86());
6984        caps.cpu_microarch_level = Some(3);
6985        assert!(!caps.is_pre_v3_x86());
6986    }
6987}