rch 2.1.4

Remote Compilation Helper - PreToolUse hook CLI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
//! State detection and idempotent configuration primitives.
//!
//! This module provides the foundational building blocks for RCH's setup,
//! configuration, and state management. It ensures all operations are:
//!
//! - **Idempotent**: Can be called repeatedly without side effects
//! - **Atomic**: File operations use write-to-temp-then-rename
//! - **Safe**: Lock files prevent concurrent modifications
//! - **Traceable**: Clear exit codes and error messages
//!
//! # Module Structure
//!
//! - [`exit_codes`]: Exit codes following sysexits.h conventions
//! - [`primitives`]: Atomic, idempotent file operations
//! - [`lock`]: File-based locking with timeout support
//!
//! # Example
//!
//! ```no_run
//! use rch::state::{RchState, detect_state};
//!
//! // Detect current installation state
//! let state = detect_state()?;
//! match state.status {
//!     InstallStatus::Ready => println!("RCH is fully configured"),
//!     InstallStatus::NeedsSetup => println!("Run: rch setup"),
//!     _ => println!("Issues detected: {:?}", state.issues),
//! }
//! # Ok::<(), anyhow::Error>(())
//! ```

pub mod exit_codes;
pub mod lock;
pub mod primitives;

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

pub use exit_codes::{
    ALREADY_CURRENT, CONFIG, DAEMON_DOWN, ERROR, LOCKED, NEEDS_MIGRATION, NEEDS_SETUP, NO_WORKERS,
    OK, USAGE,
};
pub use lock::ConfigLock;
pub use primitives::{
    IdempotentResult, append_line_if_missing, atomic_write, create_backup, create_if_missing,
    ensure_directory, ensure_symlink, update_if_changed,
};

fn default_socket_path() -> PathBuf {
    PathBuf::from(rch_common::default_socket_path())
}

/// Complete RCH installation state.
///
/// This struct captures the entire state of an RCH installation, including
/// all components, configuration files, and any detected issues.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RchState {
    /// Global state assessment.
    pub status: InstallStatus,

    /// Individual component states.
    pub components: ComponentStates,

    /// Detected issues with remediation hints.
    pub issues: Vec<StateIssue>,

    /// Timestamp of state detection.
    pub detected_at: chrono::DateTime<chrono::Utc>,

    /// RCH version that performed this detection.
    pub rch_version: String,
}

/// Overall installation status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum InstallStatus {
    /// Fully configured and operational.
    Ready,
    /// Partially configured, needs setup.
    NeedsSetup,
    /// Not installed or critically broken.
    NotInstalled,
    /// Running but with warnings.
    Degraded,
    /// Config from older version, needs migration.
    NeedsMigration,
}

impl std::fmt::Display for InstallStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            InstallStatus::Ready => write!(f, "ready"),
            InstallStatus::NeedsSetup => write!(f, "needs setup"),
            InstallStatus::NotInstalled => write!(f, "not installed"),
            InstallStatus::Degraded => write!(f, "degraded"),
            InstallStatus::NeedsMigration => write!(f, "needs migration"),
        }
    }
}

/// State of all RCH components.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComponentStates {
    /// User-level configuration state.
    pub user_config: ConfigState,
    /// Project-level configuration state (if in a project).
    pub project_config: ConfigState,
    /// Workers configuration state.
    pub workers: WorkersState,
    /// Daemon state.
    pub daemon: DaemonState,
    /// Registered agent hooks.
    pub hooks: Vec<AgentHookState>,
    /// Binary installation state.
    pub binaries: BinaryState,
}

/// State of a configuration file.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfigState {
    /// Path to the configuration file.
    pub path: PathBuf,
    /// Whether the file exists.
    pub exists: bool,
    /// Whether the file is valid TOML/JSON.
    pub valid: bool,
    /// Version string from the config, if present.
    pub version: Option<String>,
    /// Whether the config needs migration.
    pub needs_migration: bool,
    /// Where this config's values came from.
    pub source: ConfigSource,
}

/// Source of a configuration value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConfigSource {
    /// Built-in default value.
    Default,
    /// User configuration file (~/.config/rch/config.toml).
    UserConfig,
    /// Project configuration file (.rch/config.toml).
    ProjectConfig,
    /// Environment variable.
    Environment,
    /// Command line argument.
    CommandLine,
}

/// State of worker configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkersState {
    /// Path to workers.toml.
    pub config_path: PathBuf,
    /// Whether the workers file exists.
    pub exists: bool,
    /// Whether the workers file is valid.
    pub valid: bool,
    /// Number of configured workers.
    pub worker_count: usize,
    /// Number of reachable workers (if checked).
    pub reachable_count: Option<usize>,
}

/// State of the RCH daemon.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DaemonState {
    /// Whether the daemon is running.
    pub running: bool,
    /// Process ID if running.
    pub pid: Option<u32>,
    /// Socket path.
    pub socket_path: PathBuf,
    /// Whether the socket exists and is responsive.
    pub socket_responsive: bool,
    /// Daemon version (if running).
    pub version: Option<String>,
}

/// State of an agent hook registration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentHookState {
    /// Agent name (e.g., "claude-code", "codex").
    pub agent: String,
    /// Hook configuration path.
    pub hook_path: PathBuf,
    /// Whether the hook is properly registered.
    pub registered: bool,
    /// Hook version.
    pub version: Option<String>,
}

/// State of binary installations.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BinaryState {
    /// Path to rch binary.
    pub rch_path: Option<PathBuf>,
    /// Path to rchd binary.
    pub rchd_path: Option<PathBuf>,
    /// Path to rch-wkr binary.
    pub rch_wkr_path: Option<PathBuf>,
    /// Version of installed binaries.
    pub version: Option<String>,
    /// Whether binaries are in PATH.
    pub in_path: bool,
}

/// A detected issue with remediation hint.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StateIssue {
    /// Issue severity.
    pub severity: IssueSeverity,
    /// Component with the issue.
    pub component: String,
    /// Issue description.
    pub message: String,
    /// Suggested fix.
    pub remediation: String,
    /// Exit code associated with this issue.
    pub exit_code: i32,
}

/// Severity of a detected issue.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum IssueSeverity {
    /// Critical issue preventing operation.
    Critical,
    /// Warning that may affect operation.
    Warning,
    /// Informational notice.
    Info,
}

/// Detect the current RCH installation state.
///
/// This function examines all RCH components and configuration files
/// to determine the overall installation status.
///
/// # Returns
///
/// An `RchState` struct containing:
/// - Overall status (Ready, NeedsSetup, etc.)
/// - Individual component states
/// - Any detected issues with remediation hints
///
/// # Example
///
/// ```no_run
/// use rch::state::detect_state;
///
/// let state = detect_state()?;
/// if state.status == rch::state::InstallStatus::Ready {
///     println!("RCH is ready to use");
/// } else {
///     for issue in &state.issues {
///         println!("Issue: {} - Fix: {}", issue.message, issue.remediation);
///     }
/// }
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn detect_state() -> Result<RchState> {
    let mut issues = Vec::new();

    // Detect user config state
    let user_config = detect_user_config(&mut issues)?;

    // Detect project config state
    let project_config = detect_project_config(&mut issues)?;

    // Detect workers state
    let workers = detect_workers_state(&mut issues)?;

    // Detect daemon state
    let daemon = detect_daemon_state(&mut issues)?;

    // Detect hooks state
    let hooks = detect_hooks_state(&mut issues)?;

    // Detect binary state
    let binaries = detect_binary_state(&mut issues)?;

    let components = ComponentStates {
        user_config,
        project_config,
        workers,
        daemon,
        hooks,
        binaries,
    };

    // Determine overall status
    let status = determine_overall_status(&components, &issues);

    Ok(RchState {
        status,
        components,
        issues,
        detected_at: chrono::Utc::now(),
        rch_version: env!("CARGO_PKG_VERSION").to_string(),
    })
}

/// Detect user configuration state.
fn detect_user_config(issues: &mut Vec<StateIssue>) -> Result<ConfigState> {
    let config_dir = crate::config::config_dir()
        .ok_or_else(|| anyhow::anyhow!("Cannot determine config directory"))?;
    let config_path = config_dir.join("config.toml");

    let exists = config_path.exists();
    let mut valid = false;
    let mut version = None;
    let needs_migration = false;

    if exists {
        match std::fs::read_to_string(&config_path) {
            Ok(content) => {
                match toml::from_str::<toml::Value>(&content) {
                    Ok(value) => {
                        valid = true;
                        // Try to extract version from config
                        if let Some(v) = value.get("version").and_then(|v| v.as_str()) {
                            version = Some(v.to_string());
                        }
                    }
                    Err(e) => {
                        issues.push(StateIssue {
                            severity: IssueSeverity::Critical,
                            component: "user_config".to_string(),
                            message: format!("Invalid TOML in config.toml: {}", e),
                            remediation: "Fix the syntax error or run: rch config init --force"
                                .to_string(),
                            exit_code: exit_codes::CONFIG,
                        });
                    }
                }
            }
            Err(e) => {
                issues.push(StateIssue {
                    severity: IssueSeverity::Critical,
                    component: "user_config".to_string(),
                    message: format!("Cannot read config.toml: {}", e),
                    remediation: "Check file permissions".to_string(),
                    exit_code: exit_codes::CONFIG,
                });
            }
        }
    }

    Ok(ConfigState {
        path: config_path,
        exists,
        valid,
        version,
        needs_migration,
        source: if exists {
            ConfigSource::UserConfig
        } else {
            ConfigSource::Default
        },
    })
}

/// Detect project configuration state.
fn detect_project_config(_issues: &mut [StateIssue]) -> Result<ConfigState> {
    let cwd = std::env::current_dir().context("Cannot determine current directory")?;
    let config_path = cwd.join(".rch/config.toml");

    let exists = config_path.exists();
    let mut valid = false;
    let mut version = None;

    if exists
        && let Ok(content) = std::fs::read_to_string(&config_path)
        && let Ok(value) = toml::from_str::<toml::Value>(&content)
    {
        valid = true;
        if let Some(v) = value.get("version").and_then(|v| v.as_str()) {
            version = Some(v.to_string());
        }
    }

    Ok(ConfigState {
        path: config_path,
        exists,
        valid,
        version,
        needs_migration: false,
        source: if exists {
            ConfigSource::ProjectConfig
        } else {
            ConfigSource::Default
        },
    })
}

/// Detect workers configuration state.
fn detect_workers_state(issues: &mut Vec<StateIssue>) -> Result<WorkersState> {
    let config_dir = crate::config::config_dir()
        .ok_or_else(|| anyhow::anyhow!("Cannot determine config directory"))?;
    let config_path = config_dir.join("workers.toml");

    let exists = config_path.exists();
    let mut valid = false;
    let mut worker_count = 0;

    if exists {
        match std::fs::read_to_string(&config_path) {
            Ok(content) => {
                match toml::from_str::<toml::Value>(&content) {
                    Ok(value) => {
                        valid = true;
                        // Count workers
                        if let Some(workers) = value.get("workers").and_then(|w| w.as_array()) {
                            worker_count = workers.len();
                        }
                    }
                    Err(e) => {
                        issues.push(StateIssue {
                            severity: IssueSeverity::Critical,
                            component: "workers".to_string(),
                            message: format!("Invalid TOML in workers.toml: {}", e),
                            remediation: "Fix the syntax error in workers.toml".to_string(),
                            exit_code: exit_codes::CONFIG,
                        });
                    }
                }
            }
            Err(e) => {
                issues.push(StateIssue {
                    severity: IssueSeverity::Critical,
                    component: "workers".to_string(),
                    message: format!("Cannot read workers.toml: {}", e),
                    remediation: "Check file permissions".to_string(),
                    exit_code: exit_codes::CONFIG,
                });
            }
        }
    } else {
        issues.push(StateIssue {
            severity: IssueSeverity::Warning,
            component: "workers".to_string(),
            message: "No workers.toml found".to_string(),
            remediation: "Create ~/.config/rch/workers.toml or run: rch setup workers".to_string(),
            exit_code: exit_codes::NO_WORKERS,
        });
    }

    if exists && valid && worker_count == 0 {
        issues.push(StateIssue {
            severity: IssueSeverity::Warning,
            component: "workers".to_string(),
            message: "workers.toml exists but has no workers configured".to_string(),
            remediation: "Add worker entries to workers.toml".to_string(),
            exit_code: exit_codes::NO_WORKERS,
        });
    }

    Ok(WorkersState {
        config_path,
        exists,
        valid,
        worker_count,
        reachable_count: None, // Would require network check
    })
}

/// Detect daemon state.
fn detect_daemon_state(issues: &mut Vec<StateIssue>) -> Result<DaemonState> {
    let socket_path = default_socket_path();
    let socket_exists = socket_path.exists();

    // Try to check if daemon is responsive
    let socket_responsive = if socket_exists {
        // A simple check - try to connect (Unix sockets only).
        #[cfg(unix)]
        {
            std::os::unix::net::UnixStream::connect(&socket_path).is_ok()
        }
        #[cfg(not(unix))]
        {
            false
        }
    } else {
        false
    };

    let running = socket_responsive;
    let pid = None; // Would need to query daemon

    if !running {
        issues.push(StateIssue {
            severity: IssueSeverity::Warning,
            component: "daemon".to_string(),
            message: "RCH daemon is not running".to_string(),
            remediation: "Start the daemon with: rchd or rch daemon start".to_string(),
            exit_code: exit_codes::DAEMON_DOWN,
        });
    }

    Ok(DaemonState {
        running,
        pid,
        socket_path,
        socket_responsive,
        version: None,
    })
}

/// Detect hooks state.
fn detect_hooks_state(_issues: &mut [StateIssue]) -> Result<Vec<AgentHookState>> {
    // Check for Claude Code hook
    let mut hooks = Vec::new();

    // Claude Code settings location
    let claude_settings = dirs::config_dir().map(|p| p.join("claude-code/settings.json"));

    if let Some(path) = claude_settings {
        let registered = path.exists();
        // Could parse the settings to verify hook registration
        hooks.push(AgentHookState {
            agent: "claude-code".to_string(),
            hook_path: path,
            registered,
            version: None,
        });
    }

    Ok(hooks)
}

/// Detect binary installation state.
fn detect_binary_state(issues: &mut Vec<StateIssue>) -> Result<BinaryState> {
    let rch_path = which::which("rch").ok();
    let rchd_path = which::which("rchd").ok();
    let rch_wkr_path = which::which("rch-wkr").ok();

    let in_path = rch_path.is_some();

    if rch_path.is_none() {
        issues.push(StateIssue {
            severity: IssueSeverity::Warning,
            component: "binaries".to_string(),
            message: "rch binary not found in PATH".to_string(),
            remediation: "Add ~/.local/bin to PATH or install with: cargo install --path rch"
                .to_string(),
            exit_code: exit_codes::NEEDS_SETUP,
        });
    }

    Ok(BinaryState {
        rch_path,
        rchd_path,
        rch_wkr_path,
        version: Some(env!("CARGO_PKG_VERSION").to_string()),
        in_path,
    })
}

/// Determine overall status from component states and issues.
fn determine_overall_status(components: &ComponentStates, issues: &[StateIssue]) -> InstallStatus {
    // Check for critical issues
    let has_critical = issues.iter().any(|i| i.severity == IssueSeverity::Critical);
    if has_critical {
        return InstallStatus::NotInstalled;
    }

    // Check if needs migration
    if components.user_config.needs_migration {
        return InstallStatus::NeedsMigration;
    }

    // Check for basic setup requirements
    let config_ready = components.user_config.exists && components.user_config.valid;
    let workers_ready = components.workers.exists
        && components.workers.valid
        && components.workers.worker_count > 0;

    if !config_ready || !workers_ready {
        return InstallStatus::NeedsSetup;
    }

    // Check for warnings (degraded state)
    let has_warnings = issues.iter().any(|i| i.severity == IssueSeverity::Warning);
    if has_warnings {
        return InstallStatus::Degraded;
    }

    InstallStatus::Ready
}

/// Get the exit code for the current state.
///
/// This is useful for scripting: `rch state --check` can return
/// an exit code indicating the installation status.
pub fn state_to_exit_code(state: &RchState) -> i32 {
    // Return the most severe issue's exit code
    if let Some(issue) = state
        .issues
        .iter()
        .find(|i| i.severity == IssueSeverity::Critical)
    {
        return issue.exit_code;
    }

    match state.status {
        InstallStatus::Ready => exit_codes::OK,
        InstallStatus::NeedsSetup => exit_codes::NEEDS_SETUP,
        InstallStatus::NotInstalled => exit_codes::NEEDS_SETUP,
        InstallStatus::Degraded => exit_codes::OK, // Degraded is still usable
        InstallStatus::NeedsMigration => exit_codes::NEEDS_MIGRATION,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::sync::{Arc, Barrier};
    use std::thread;
    use std::time::Duration;
    use tempfile::TempDir;
    use tracing::info;
    use uuid::Uuid;

    fn log_test_start(name: &str) {
        info!("TEST START: {}", name);
    }

    fn log_test_pass(name: &str) {
        info!("TEST PASS: {}", name);
    }

    fn build_test_state(status: InstallStatus) -> RchState {
        RchState {
            status,
            components: ComponentStates {
                user_config: ConfigState {
                    path: PathBuf::from("/test"),
                    exists: true,
                    valid: true,
                    version: Some("1.0".to_string()),
                    needs_migration: false,
                    source: ConfigSource::UserConfig,
                },
                project_config: ConfigState {
                    path: PathBuf::from("/test/.rch"),
                    exists: false,
                    valid: false,
                    version: None,
                    needs_migration: false,
                    source: ConfigSource::Default,
                },
                workers: WorkersState {
                    config_path: PathBuf::from("/test/workers.toml"),
                    exists: true,
                    valid: true,
                    worker_count: 2,
                    reachable_count: None,
                },
                daemon: DaemonState {
                    running: true,
                    pid: Some(12345),
                    socket_path: default_socket_path(),
                    socket_responsive: true,
                    version: Some("0.1.0".to_string()),
                },
                hooks: vec![],
                binaries: BinaryState {
                    rch_path: Some(PathBuf::from("/usr/local/bin/rch")),
                    rchd_path: Some(PathBuf::from("/usr/local/bin/rchd")),
                    rch_wkr_path: None,
                    version: Some("0.1.0".to_string()),
                    in_path: true,
                },
            },
            issues: vec![],
            detected_at: chrono::Utc::now(),
            rch_version: "0.1.0".to_string(),
        }
    }

    #[test]
    fn test_install_status_display() {
        log_test_start("test_install_status_display");
        assert_eq!(format!("{}", InstallStatus::Ready), "ready");
        assert_eq!(format!("{}", InstallStatus::NeedsSetup), "needs setup");
        assert_eq!(format!("{}", InstallStatus::NotInstalled), "not installed");
        assert_eq!(format!("{}", InstallStatus::Degraded), "degraded");
        assert_eq!(
            format!("{}", InstallStatus::NeedsMigration),
            "needs migration"
        );
        log_test_pass("test_install_status_display");
    }

    #[test]
    fn test_state_serialization() {
        log_test_start("test_state_serialization");
        let state = build_test_state(InstallStatus::Ready);

        // Should serialize to JSON without error
        let json = serde_json::to_string(&state).unwrap();
        assert!(json.contains("ready"));
        assert!(json.contains("user_config"));
        log_test_pass("test_state_serialization");
    }

    #[test]
    fn test_state_serialization_round_trip_file() {
        log_test_start("test_state_serialization_round_trip_file");
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("state.json");

        let state = build_test_state(InstallStatus::Ready);
        let json = serde_json::to_string(&state).unwrap();
        atomic_write(&path, json.as_bytes()).unwrap();

        let loaded: RchState = serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
        assert_eq!(loaded.status, InstallStatus::Ready);
        assert_eq!(loaded.components.workers.worker_count, 2);
        log_test_pass("test_state_serialization_round_trip_file");
    }

    #[test]
    fn test_state_to_exit_code() {
        log_test_start("test_state_to_exit_code");
        let ready_state = RchState {
            status: InstallStatus::Ready,
            components: ComponentStates {
                user_config: ConfigState {
                    path: PathBuf::new(),
                    exists: true,
                    valid: true,
                    version: None,
                    needs_migration: false,
                    source: ConfigSource::Default,
                },
                project_config: ConfigState {
                    path: PathBuf::new(),
                    exists: false,
                    valid: false,
                    version: None,
                    needs_migration: false,
                    source: ConfigSource::Default,
                },
                workers: WorkersState {
                    config_path: PathBuf::new(),
                    exists: true,
                    valid: true,
                    worker_count: 1,
                    reachable_count: None,
                },
                daemon: DaemonState {
                    running: true,
                    pid: None,
                    socket_path: PathBuf::new(),
                    socket_responsive: true,
                    version: None,
                },
                hooks: vec![],
                binaries: BinaryState {
                    rch_path: None,
                    rchd_path: None,
                    rch_wkr_path: None,
                    version: None,
                    in_path: false,
                },
            },
            issues: vec![],
            detected_at: chrono::Utc::now(),
            rch_version: "0.1.0".to_string(),
        };

        assert_eq!(state_to_exit_code(&ready_state), exit_codes::OK);
        log_test_pass("test_state_to_exit_code");
    }

    #[test]
    fn test_state_to_exit_code_prefers_critical_issue() {
        log_test_start("test_state_to_exit_code_prefers_critical_issue");
        let mut state = build_test_state(InstallStatus::Ready);
        state.issues.push(StateIssue {
            severity: IssueSeverity::Critical,
            component: "daemon".to_string(),
            message: "daemon down".to_string(),
            remediation: "start daemon".to_string(),
            exit_code: exit_codes::DAEMON_DOWN,
        });

        assert_eq!(state_to_exit_code(&state), exit_codes::DAEMON_DOWN);
        log_test_pass("test_state_to_exit_code_prefers_critical_issue");
    }

    #[test]
    #[serial_test::serial]
    fn test_concurrent_state_access_with_lock() {
        log_test_start("test_concurrent_state_access_with_lock");
        let tmp = TempDir::new().unwrap();
        let state_path = Arc::new(tmp.path().join("state_counter.txt"));
        let lock_name = Arc::new(format!("state-lock-{}", Uuid::new_v4()));

        let threads = 4;
        let start_barrier = Arc::new(Barrier::new(threads));
        let mut handles = Vec::new();

        for i in 0..threads {
            let state_path = Arc::clone(&state_path);
            let lock_name = Arc::clone(&lock_name);
            let start = Arc::clone(&start_barrier);

            handles.push(thread::spawn(move || {
                start.wait();
                let _lock = ConfigLock::acquire_with_timeout(
                    &lock_name,
                    Duration::from_secs(30),
                    &format!("thread-{i}"),
                )
                .expect("lock acquisition failed");
                let current = fs::read_to_string(&*state_path)
                    .ok()
                    .and_then(|s| s.parse::<usize>().ok())
                    .unwrap_or(0);
                let next = current + 1;
                atomic_write(&state_path, next.to_string().as_bytes())
                    .expect("atomic write failed");
            }));
        }

        for handle in handles {
            handle.join().expect("thread panicked");
        }

        let final_value: usize = fs::read_to_string(&*state_path).unwrap().parse().unwrap();
        assert_eq!(final_value, threads);
        log_test_pass("test_concurrent_state_access_with_lock");
    }
}