rch 2.1.18

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
//! Configuration doctor command for diagnosing issues.
//!
//! This module handles the `rch config doctor` command, which performs
//! deeper health checks than `config lint`.

use anyhow::Result;
use rch_common::RchConfig;
use schemars::JsonSchema;
use serde::Serialize;
use std::path::{Path, PathBuf};

use crate::config;
use crate::ui::context::OutputContext;

use super::helpers::{config_dir, load_workers_from_config};

// =============================================================================
// Config Doctor Command
// =============================================================================

/// Severity levels for doctor diagnostics.
#[derive(Debug, Clone, Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum DoctorSeverity {
    Error,
    Warning,
    Info,
}

/// A single diagnostic from config doctor.
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct DoctorDiagnostic {
    pub severity: DoctorSeverity,
    pub code: String,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub remediation: Option<String>,
}

/// Response type for config doctor command.
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct ConfigDoctorResponse {
    pub diagnostics: Vec<DoctorDiagnostic>,
    pub error_count: usize,
    pub warning_count: usize,
    pub info_count: usize,
    pub healthy: bool,
}

/// Diagnose configuration and system health issues.
///
/// Performs deeper checks than `config lint`:
/// - Socket path writability
/// - SSH identity file existence and permissions
/// - Remote path format validation
/// - Glob pattern syntax
/// - File permission issues
pub fn config_doctor(ctx: &OutputContext) -> Result<()> {
    let mut diagnostics = Vec::new();

    // Load configuration
    let config = match config::load_config() {
        Ok(c) => c,
        Err(e) => {
            diagnostics.push(DoctorDiagnostic {
                severity: DoctorSeverity::Error,
                code: "DOC-E001".to_string(),
                message: "Failed to load configuration".to_string(),
                detail: Some(e.to_string()),
                remediation: Some("Run 'rch config init' to create configuration".to_string()),
            });
            // Can't continue without config
            return output_doctor_results(ctx, diagnostics);
        }
    };

    // Check 1: Socket path writability
    check_socket_path(&config, &mut diagnostics);

    // Check 2: SSH identity files
    check_identity_files(&mut diagnostics);

    // Check 3: Remote paths are absolute
    check_remote_paths(&mut diagnostics);

    // Check 4: Glob pattern syntax
    check_glob_patterns(&config, &mut diagnostics);

    // Check 5: File permissions
    check_file_permissions(&mut diagnostics);

    // Check 6: Daemon status
    check_daemon_status(&config, &mut diagnostics);

    // Check 7: Remediation knobs (bd-...remediation-ocv9i.17.2)
    check_remediation_config(&config, &mut diagnostics);

    output_doctor_results(ctx, diagnostics)
}

/// Check 7: validate the central remediation knobs
/// (bd-...remediation-ocv9i.17.2).
///
/// Maps each `RemediationConfig::validate()` finding to a doctor diagnostic so
/// unsafe, contradictory, or out-of-range remediation settings are reported
/// here with a concrete next step. When everything validates, emit one Info so
/// operators can see the section was checked (defaults apply where unset).
fn check_remediation_config(config: &RchConfig, diagnostics: &mut Vec<DoctorDiagnostic>) {
    let issues = config.remediation.validate();
    if issues.is_empty() {
        diagnostics.push(DoctorDiagnostic {
            severity: DoctorSeverity::Info,
            code: "DOC-I100".to_string(),
            message: "Remediation settings are valid".to_string(),
            detail: Some(
                "All [remediation] knobs are within safe ranges (defaults apply where unset)."
                    .to_string(),
            ),
            remediation: None,
        });
        return;
    }
    for issue in issues {
        let (severity, code) = match issue.severity {
            rch_common::remediation_config::IssueSeverity::Error => {
                (DoctorSeverity::Error, "DOC-E100")
            }
            rch_common::remediation_config::IssueSeverity::Warning => {
                (DoctorSeverity::Warning, "DOC-W100")
            }
        };
        diagnostics.push(DoctorDiagnostic {
            severity,
            code: code.to_string(),
            message: format!("{}: {}", issue.field, issue.message),
            detail: None,
            remediation: Some(format!(
                "Adjust `{}` under [remediation] (or the matching RCH_REMEDIATION_* env var).",
                issue.field
            )),
        });
    }
}

fn configured_socket_path(config: &RchConfig) -> PathBuf {
    PathBuf::from(shellexpand::tilde(&config.general.socket_path).into_owned())
}

fn check_socket_path(config: &RchConfig, diagnostics: &mut Vec<DoctorDiagnostic>) {
    let socket_path = configured_socket_path(config);

    // Check if parent directory exists and is writable
    if let Some(parent) = socket_path.parent() {
        if !parent.exists() {
            diagnostics.push(DoctorDiagnostic {
                severity: DoctorSeverity::Error,
                code: "DOC-E010".to_string(),
                message: format!("Socket directory does not exist: {}", parent.display()),
                detail: None,
                remediation: Some(format!("Create directory: mkdir -p {}", parent.display())),
            });
        } else {
            // Check writability by attempting to create a temp file
            let test_file = parent.join(".rch_write_test");
            match std::fs::File::create(&test_file) {
                Ok(_) => {
                    let _ = std::fs::remove_file(&test_file);
                }
                Err(e) => {
                    diagnostics.push(DoctorDiagnostic {
                        severity: DoctorSeverity::Error,
                        code: "DOC-E011".to_string(),
                        message: format!("Socket directory is not writable: {}", parent.display()),
                        detail: Some(e.to_string()),
                        remediation: Some(format!(
                            "Fix permissions: chmod u+w {}",
                            parent.display()
                        )),
                    });
                }
            }
        }
    }

    // Check if socket already exists (stale socket)
    if socket_path.exists() {
        // Try to determine if it's a valid socket or stale
        diagnostics.push(DoctorDiagnostic {
            severity: DoctorSeverity::Info,
            code: "DOC-I010".to_string(),
            message: format!("Socket file exists: {}", socket_path.display()),
            detail: Some("This may be from a running daemon or a stale socket".to_string()),
            remediation: Some(
                "If daemon is not running, remove with: rm -f <socket_path>".to_string(),
            ),
        });
    }
}

fn check_identity_files(diagnostics: &mut Vec<DoctorDiagnostic>) {
    let workers = match load_workers_from_config() {
        Ok(w) => w,
        Err(_) => return, // Skip if workers can't be loaded
    };

    // Group workers by (expanded) identity_file so a shared missing key only
    // produces one diagnostic that names every referencing worker.
    let mut by_identity: std::collections::BTreeMap<PathBuf, Vec<String>> =
        std::collections::BTreeMap::new();

    for worker in &workers {
        let identity_path = match shellexpand::full(&worker.identity_file) {
            Ok(expanded) => PathBuf::from(expanded.into_owned()),
            Err(err) => {
                diagnostics.push(DoctorDiagnostic {
                    severity: DoctorSeverity::Error,
                    code: "RCH-E009".to_string(),
                    message: format!(
                        "identity_file {:?} for worker '{}' is unresolvable: {}",
                        worker.identity_file, worker.id, err
                    ),
                    detail: None,
                    remediation: Some(
                        "Set the referenced environment variable, or replace the reference \
                        with an absolute path / ~-relative path in workers.toml"
                            .to_string(),
                    ),
                });
                continue;
            }
        };
        by_identity
            .entry(identity_path)
            .or_default()
            .push(worker.id.as_str().to_string());
    }

    for (identity_path, worker_ids) in &by_identity {
        if !identity_path.exists() {
            let referencing = worker_ids.join(", ");
            diagnostics.push(DoctorDiagnostic {
                severity: DoctorSeverity::Error,
                code: "RCH-E009".to_string(),
                message: format!(
                    "SSH identity file not found: {} (referenced by workers: {})",
                    identity_path.display(),
                    referencing
                ),
                detail: None,
                remediation: Some(format!(
                    "Generate key: ssh-keygen -t ed25519 -f {}",
                    identity_path.display()
                )),
            });
            continue;
        }
        check_shared_identity_file_permissions(identity_path, worker_ids, diagnostics);
    }
}

/// Emit at most one permissions warning per unique identity_file, listing
/// every worker that references it. Keeps `rch config doctor` output short
/// when many workers share a single key.
fn check_shared_identity_file_permissions(
    identity_path: &Path,
    worker_ids: &[String],
    diagnostics: &mut Vec<DoctorDiagnostic>,
) {
    #[cfg(not(unix))]
    {
        let _ = (identity_path, worker_ids, diagnostics);
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let Ok(metadata) = identity_path.metadata() else {
            return;
        };
        let mode = metadata.permissions().mode() & 0o777;
        if mode == 0o600 || mode == 0o400 {
            return;
        }
        diagnostics.push(DoctorDiagnostic {
            severity: DoctorSeverity::Warning,
            code: "DOC-W020".to_string(),
            message: format!(
                "Identity file {} has insecure permissions {:o} (referenced by workers: {})",
                identity_path.display(),
                mode,
                worker_ids.join(", ")
            ),
            detail: Some("SSH may refuse to use keys with permissions too open".to_string()),
            remediation: Some(format!(
                "Fix permissions: chmod 600 {}",
                identity_path.display()
            )),
        });
    }
}

fn check_remote_paths(_diagnostics: &mut Vec<DoctorDiagnostic>) {
    // WorkerConfig currently doesn't have optional remote path fields.
    // This check is a placeholder for when those fields are added.
    // Future checks could validate:
    // - remote_home is absolute
    // - remote_work_dir is absolute or ~-prefixed
}

fn check_glob_patterns(config: &RchConfig, diagnostics: &mut Vec<DoctorDiagnostic>) {
    use glob::Pattern;

    for (i, pattern) in config.transfer.exclude_patterns.iter().enumerate() {
        if let Err(e) = Pattern::new(pattern) {
            diagnostics.push(DoctorDiagnostic {
                severity: DoctorSeverity::Error,
                code: "DOC-E040".to_string(),
                message: format!(
                    "Invalid glob pattern in exclude_patterns[{}]: {}",
                    i, pattern
                ),
                detail: Some(e.to_string()),
                remediation: Some("Fix the pattern syntax in your configuration".to_string()),
            });
        }
    }
}

fn check_file_permissions(diagnostics: &mut Vec<DoctorDiagnostic>) {
    // Check config directory permissions
    if let Some(config_dir) = config_dir()
        && config_dir.exists()
    {
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            if let Ok(metadata) = config_dir.metadata() {
                let mode = metadata.permissions().mode() & 0o777;
                // Config dir should not be world-readable if it contains sensitive data
                if mode & 0o007 != 0 {
                    diagnostics.push(DoctorDiagnostic {
                        severity: DoctorSeverity::Warning,
                        code: "DOC-W050".to_string(),
                        message: format!("Config directory is world-accessible: {:o}", mode),
                        detail: Some(format!(
                            "Directory {} may contain sensitive configuration",
                            config_dir.display()
                        )),
                        remediation: Some(format!(
                            "Restrict access: chmod 700 {}",
                            config_dir.display()
                        )),
                    });
                }
            }
        }
    }

    // Check workers.toml permissions
    if let Some(workers_path) = config_dir().map(|d| d.join("workers.toml"))
        && workers_path.exists()
    {
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            if let Ok(metadata) = workers_path.metadata() {
                let mode = metadata.permissions().mode() & 0o777;
                if mode & 0o077 != 0 {
                    diagnostics.push(DoctorDiagnostic {
                        severity: DoctorSeverity::Info,
                        code: "DOC-I050".to_string(),
                        message: format!("workers.toml is group/world accessible: {:o}", mode),
                        detail: Some(
                            "Consider restricting if it contains sensitive paths".to_string(),
                        ),
                        remediation: Some(format!(
                            "Restrict access: chmod 600 {}",
                            workers_path.display()
                        )),
                    });
                }
            }
        }
    }
}

fn check_daemon_status(config: &RchConfig, diagnostics: &mut Vec<DoctorDiagnostic>) {
    let socket_path = configured_socket_path(config);

    #[cfg(unix)]
    {
        if socket_path.exists() {
            // Socket exists, try a quick connection test
            match std::os::unix::net::UnixStream::connect(&socket_path) {
                Ok(_) => {
                    diagnostics.push(DoctorDiagnostic {
                        severity: DoctorSeverity::Info,
                        code: "DOC-I060".to_string(),
                        message: "Daemon is running and accepting connections".to_string(),
                        detail: None,
                        remediation: None,
                    });
                }
                Err(e) => {
                    diagnostics.push(DoctorDiagnostic {
                        severity: DoctorSeverity::Warning,
                        code: "DOC-W060".to_string(),
                        message: "Socket exists but connection failed".to_string(),
                        detail: Some(e.to_string()),
                        remediation: Some("Try: rch daemon restart".to_string()),
                    });
                }
            }
        } else {
            diagnostics.push(DoctorDiagnostic {
                severity: DoctorSeverity::Warning,
                code: "DOC-W061".to_string(),
                message: "Daemon does not appear to be running".to_string(),
                detail: Some(format!("No socket at {}", socket_path.display())),
                remediation: Some("Start daemon with: rch daemon start".to_string()),
            });
        }
    }

    #[cfg(not(unix))]
    {
        let _ = socket_path;
        diagnostics.push(DoctorDiagnostic {
            severity: DoctorSeverity::Info,
            code: "DOC-I062".to_string(),
            message: "Daemon status check skipped (Unix sockets not available on this platform)"
                .to_string(),
            detail: None,
            remediation: None,
        });
    }
}

fn output_doctor_results(ctx: &OutputContext, diagnostics: Vec<DoctorDiagnostic>) -> Result<()> {
    let style = ctx.theme();

    let error_count = diagnostics
        .iter()
        .filter(|d| matches!(d.severity, DoctorSeverity::Error))
        .count();
    let warning_count = diagnostics
        .iter()
        .filter(|d| matches!(d.severity, DoctorSeverity::Warning))
        .count();
    let info_count = diagnostics
        .iter()
        .filter(|d| matches!(d.severity, DoctorSeverity::Info))
        .count();

    let response = ConfigDoctorResponse {
        diagnostics: diagnostics.clone(),
        error_count,
        warning_count,
        info_count,
        healthy: error_count == 0,
    };

    if ctx.is_json() {
        ctx.json(&response)?;
        if error_count > 0 {
            std::process::exit(1);
        }
        return Ok(());
    }

    // Human-readable output
    println!();
    println!("{}", style.format_header("Configuration Doctor"));
    println!();

    if diagnostics.is_empty() {
        println!("  {} All checks passed!", style.success("✓"));
    } else {
        for diag in &diagnostics {
            let (icon, _severity_style) = match diag.severity {
                DoctorSeverity::Error => (style.error("✗"), "error"),
                DoctorSeverity::Warning => (style.warning("!"), "warning"),
                DoctorSeverity::Info => (style.info("i"), "info"),
            };

            println!("  {} [{}] {}", icon, diag.code, diag.message);
            if let Some(ref detail) = diag.detail {
                println!("      {}", style.muted(detail));
            }
            if let Some(ref remediation) = diag.remediation {
                println!("      {}", style.highlight(&format!("→ {}", remediation)));
            }
            println!();
        }

        // Summary
        let mut summary_parts = Vec::new();
        if error_count > 0 {
            summary_parts.push(format!(
                "{} error{}",
                error_count,
                if error_count == 1 { "" } else { "s" }
            ));
        }
        if warning_count > 0 {
            summary_parts.push(format!(
                "{} warning{}",
                warning_count,
                if warning_count == 1 { "" } else { "s" }
            ));
        }
        if info_count > 0 {
            summary_parts.push(format!("{} info", info_count));
        }

        let status = if error_count > 0 {
            style.error("unhealthy")
        } else if warning_count > 0 {
            style.warning("healthy with warnings")
        } else {
            style.success("healthy")
        };

        println!("  Status: {} ({})", status, summary_parts.join(", "));
    }

    if error_count > 0 {
        std::process::exit(1);
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(unix)]
    #[test]
    fn doctor_reporter_delivers_formats_and_propagates_real_output_failures() {
        use crate::ui::context::{
            ColorChoice, OutputConfig, OutputError, OutputFormat, OutputMode,
        };
        use crate::ui::writer::OutputWriter;
        use std::os::unix::net::UnixStream;

        let retained = tempfile::tempdir().unwrap().keep();
        for format in [OutputFormat::Json, OutputFormat::Toon] {
            for closed in [false, true] {
                let path = retained.join(format!("{format:?}-{closed}.output"));
                let stdout = if closed {
                    let (socket, peer) = UnixStream::pair().unwrap();
                    socket
                        .set_write_timeout(Some(std::time::Duration::from_secs(2)))
                        .unwrap();
                    drop(peer);
                    OutputWriter::new(socket, false)
                } else {
                    OutputWriter::new(std::fs::File::create_new(&path).unwrap(), false)
                };
                let ctx = OutputContext::with_writers(
                    OutputConfig {
                        force_mode: Some(OutputMode::Json),
                        color: ColorChoice::Never,
                        format,
                        ..Default::default()
                    },
                    stdout,
                    OutputWriter::stderr(),
                );
                // Reporter-only test: an empty diagnostic set is not a claim
                // about actual configuration, daemon or worker health.
                let result = output_doctor_results(&ctx, Vec::new());
                if closed {
                    let error = result.unwrap_err();
                    assert!(matches!(
                        error.downcast_ref::<OutputError>(),
                        Some(OutputError::Delivery(cause))
                            if cause.kind() == std::io::ErrorKind::BrokenPipe
                    ));
                    assert!(!path.exists());
                } else {
                    result.unwrap();
                    let bytes = std::fs::read(path).unwrap();
                    let report = if format == OutputFormat::Toon {
                        serde_json::from_str::<serde_json::Value>(
                            &toon_rust::toon_to_json(std::str::from_utf8(&bytes).unwrap()).unwrap(),
                        )
                        .unwrap()
                    } else {
                        serde_json::from_slice::<serde_json::Value>(&bytes).unwrap()
                    };
                    assert_eq!(report["healthy"], true);
                    assert_eq!(report["diagnostics"], serde_json::json!([]));
                    // TOON decodes every number as f64, so compare numerically.
                    for count in ["error_count", "warning_count", "info_count"] {
                        assert_eq!(report[count].as_f64(), Some(0.0), "{format:?} {count}");
                    }
                }
            }
        }
    }

    #[test]
    fn configured_socket_path_expands_tilde() {
        let mut config = RchConfig::default();
        config.general.socket_path = "~/rch-config-doctor.sock".to_string();

        let socket_path = configured_socket_path(&config);

        assert_ne!(socket_path, PathBuf::from("~/rch-config-doctor.sock"));
        assert!(socket_path.ends_with("rch-config-doctor.sock"));
    }
}