rch 2.1.10

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
//! Worker binary deployment commands.
//!
//! This module contains commands for deploying the rch-wkr binary to
//! remote workers via SCP.

use crate::ui::context::OutputContext;
use crate::ui::theme::StatusIndicator;
use anyhow::{Context, Result};
use rch_common::ssh_utils::shell_escape_path_with_home;
use rch_common::{ApiError, ApiResponse, ErrorCode, WorkerConfig};
use serde::Serialize;
use std::path::{Path, PathBuf};
use tokio::process::Command;

use super::helpers::{
    classify_ssh_error_message, major_version_mismatch, ssh_key_path_from_identity,
};
use super::load_workers_from_config;

// =============================================================================
// Workers Deploy Binary Command
// =============================================================================

/// Deploy rch-wkr binary to workers.
///
/// Finds the local rch-wkr binary, checks version on remote workers,
/// and deploys if needed using scp. Falls back to user directories
/// if /usr/local/bin requires sudo.
pub async fn workers_deploy_binary(
    worker_id: Option<String>,
    all: bool,
    force: bool,
    dry_run: bool,
    ctx: &OutputContext,
) -> Result<()> {
    let style = ctx.theme();

    if worker_id.is_none() && !all {
        if ctx.is_json() {
            let _ = ctx.json(&ApiResponse::<()>::err(
                "workers deploy-binary",
                ApiError::new(
                    ErrorCode::ConfigValidationError,
                    "Specify either a worker ID or --all",
                ),
            ));
        } else {
            println!(
                "{} Specify either {} or {}",
                StatusIndicator::Error.display(style),
                style.highlight("<worker-id>"),
                style.highlight("--all")
            );
        }
        return Ok(());
    }

    // Load workers configuration
    let workers = load_workers_from_config()?;
    if workers.is_empty() {
        if ctx.is_json() {
            let _ = ctx.json(&ApiResponse::<()>::err(
                "workers deploy-binary",
                ApiError::new(
                    ErrorCode::ConfigNotFound,
                    "No workers configured. Run 'rch workers discover --add' first.",
                ),
            ));
        } else {
            println!(
                "{} No workers configured.",
                StatusIndicator::Error.display(style)
            );
            println!(
                "  {} Run '{}' first.",
                style.muted("→"),
                style.highlight("rch workers discover --add")
            );
        }
        return Ok(());
    }

    // Filter to target workers
    let target_workers: Vec<&WorkerConfig> = if all {
        workers.iter().collect()
    } else {
        let wid = worker_id.as_ref().unwrap();
        workers.iter().filter(|w| w.id.as_str() == wid).collect()
    };

    if target_workers.is_empty() {
        if ctx.is_json() {
            let _ = ctx.json(&ApiResponse::<()>::err(
                "workers deploy-binary",
                ApiError::new(
                    ErrorCode::ConfigInvalidWorker,
                    format!("Worker '{}' not found in configuration", worker_id.unwrap()),
                ),
            ));
        } else {
            println!(
                "{} Worker '{}' not found in configuration.",
                StatusIndicator::Error.display(style),
                worker_id.unwrap()
            );
        }
        return Ok(());
    }

    // The deployed artifact is THIS host's rch-wkr binary, so it can only run
    // on workers with the same OS. Deploying across platforms bricks the
    // worker's agent (a Linux ELF was once pushed over a Windows worker's
    // .exe, taking it out of the fleet until someone noticed — bd-jdcxd).
    // Unlabelled workers are the historical Linux fleet.
    let local_os = std::env::consts::OS;
    let (target_workers, os_mismatched): (Vec<&WorkerConfig>, Vec<&WorkerConfig>) =
        target_workers.into_iter().partition(|w| {
            worker_os_matches_local(rch_common::types::declared_os(&w.tags).as_deref(), local_os)
        });

    let mut results: Vec<DeployResult> = Vec::new();
    for worker in &os_mismatched {
        let worker_os =
            rch_common::types::declared_os(&worker.tags).unwrap_or_else(|| "linux".to_string());
        if !ctx.is_json() {
            println!(
                "{} Skipping {}: worker os '{}' does not match this host's binary platform '{}'. \
                 Deploy from a matching host or build rch-wkr on the worker itself.",
                StatusIndicator::Warning.display(style),
                style.highlight(worker.id.as_str()),
                worker_os,
                local_os,
            );
        }
        results.push(DeployResult {
            worker_id: worker.id.to_string(),
            success: false,
            deployed: false,
            local_version: String::new(),
            remote_version: None,
            error: Some(format!(
                "os mismatch: worker os '{worker_os}', local binary platform '{local_os}'"
            )),
        });
    }
    if target_workers.is_empty() {
        if ctx.is_json() {
            let _ = ctx.json(&ApiResponse::ok(
                "workers deploy-binary",
                serde_json::json!({ "local_version": null, "results": results }),
            ));
        }
        return Ok(());
    }

    // Find local binary
    let local_binary = find_local_binary("rch-wkr")?;
    let local_version = get_binary_version(&local_binary).await?;

    if !ctx.is_json() {
        println!(
            "{} Found local rch-wkr {} at {}",
            StatusIndicator::Success.display(style),
            style.highlight(&local_version),
            style.muted(&local_binary.display().to_string())
        );
        println!();
    }

    // Deploy to each worker
    for worker in target_workers {
        let result =
            deploy_binary_to_worker(worker, &local_binary, &local_version, force, dry_run, ctx)
                .await;
        results.push(result);
    }

    // Output JSON response if needed
    if ctx.is_json() {
        let _ = ctx.json(&ApiResponse::ok(
            "workers deploy-binary",
            serde_json::json!({
                "local_version": local_version,
                "results": results
            }),
        ));
    }

    Ok(())
}

// =============================================================================
// Helper Functions
// =============================================================================

/// Whether a worker's declared OS can run a binary built on `local_os`
/// (`std::env::consts::OS` values). Workers with no declared OS are the
/// historical unlabelled Linux fleet.
fn worker_os_matches_local(declared_os: Option<&str>, local_os: &str) -> bool {
    declared_os
        .unwrap_or("linux")
        .eq_ignore_ascii_case(local_os)
}

/// Find local binary path.
pub(super) fn find_local_binary(name: &str) -> Result<PathBuf> {
    // Check if running from cargo target directory
    let exe = std::env::current_exe()?;
    let exe_dir = exe
        .parent()
        .ok_or_else(|| anyhow::anyhow!("Cannot get exe directory"))?;

    // Check same directory as current executable
    let same_dir = exe_dir.join(name);
    if same_dir.exists() {
        return Ok(same_dir);
    }

    // Check if it's in PATH
    if let Ok(output) = std::process::Command::new("which").arg(name).output()
        && output.status.success()
    {
        let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
        if !path.is_empty() {
            return Ok(PathBuf::from(path));
        }
    }

    // Check common locations
    let common_paths = ["/usr/local/bin", "/usr/bin", "~/.cargo/bin", "~/.local/bin"];

    for base in common_paths {
        let expanded = shellexpand::tilde(base);
        let path = PathBuf::from(expanded.as_ref()).join(name);
        if path.exists() {
            return Ok(path);
        }
    }

    Err(anyhow::anyhow!(
        "Could not find '{}' binary. Make sure it's built and in PATH.",
        name
    ))
}

/// Get version string from binary.
pub(super) async fn get_binary_version(path: &Path) -> Result<String> {
    let output = Command::new(path)
        .arg("--version")
        .output()
        .await
        .context("Failed to run binary")?;

    if !output.status.success() {
        return Err(anyhow::anyhow!("Binary returned non-zero exit code"));
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    // Extract version from "rch-wkr 1.0.0" or similar
    let version = stdout
        .split_whitespace()
        .nth(1)
        .unwrap_or("unknown")
        .to_string();

    Ok(version)
}

/// Deploy binary to a single worker.
async fn deploy_binary_to_worker(
    worker: &WorkerConfig,
    local_binary: &Path,
    local_version: &str,
    force: bool,
    dry_run: bool,
    ctx: &OutputContext,
) -> DeployResult {
    let style = ctx.theme();

    if !ctx.is_json() {
        print!(
            "  {} {}@{} ... ",
            StatusIndicator::Info.display(style),
            style.highlight(&worker.user),
            style.highlight(&worker.host)
        );
    }

    // Check remote version
    let remote_version = get_remote_version(worker).await.ok();

    // Determine if we need to deploy
    let needs_deploy = if force {
        true
    } else if let Some(ref rv) = remote_version {
        major_version_mismatch(local_version, rv) || rv != local_version
    } else {
        true // Not installed
    };

    if !needs_deploy {
        if !ctx.is_json() {
            println!(
                "{} (already at {})",
                style.success("OK"),
                style.muted(remote_version.as_deref().unwrap_or("?"))
            );
        }
        return DeployResult {
            worker_id: worker.id.to_string(),
            success: true,
            deployed: false,
            local_version: local_version.to_string(),
            remote_version,
            error: None,
        };
    }

    if dry_run {
        if !ctx.is_json() {
            println!(
                "{} (would deploy {} → {})",
                style.info("DRY-RUN"),
                style.muted(remote_version.as_deref().unwrap_or("none")),
                style.highlight(local_version)
            );
        }
        return DeployResult {
            worker_id: worker.id.to_string(),
            success: true,
            deployed: false,
            local_version: local_version.to_string(),
            remote_version,
            error: Some("dry-run".to_string()),
        };
    }

    // Deploy via SCP
    match deploy_via_scp(worker, local_binary).await {
        Ok(remote_path) => {
            if !ctx.is_json() {
                println!(
                    "{} (deployed to {})",
                    style.success("OK"),
                    style.muted(remote_path)
                );
            }
            DeployResult {
                worker_id: worker.id.to_string(),
                success: true,
                deployed: true,
                local_version: local_version.to_string(),
                remote_version: Some(local_version.to_string()),
                error: None,
            }
        }
        Err(e) => {
            if !ctx.is_json() {
                println!("{}", style.error(&format!("FAILED: {}", e)));
            }
            DeployResult {
                worker_id: worker.id.to_string(),
                success: false,
                deployed: false,
                local_version: local_version.to_string(),
                remote_version,
                error: Some(e.to_string()),
            }
        }
    }
}

/// Get remote rch-wkr version via SSH.
pub(super) async fn get_remote_version(worker: &WorkerConfig) -> Result<String> {
    let mut cmd = Command::new("ssh");
    cmd.arg("-o").arg("BatchMode=yes");
    cmd.arg("-o").arg("ConnectTimeout=10");
    cmd.arg("-i").arg(&worker.identity_file);

    let target = format!("{}@{}", worker.user, worker.host);
    cmd.arg(&target);
    cmd.arg("rch-wkr --version 2>/dev/null || ~/.local/bin/rch-wkr --version 2>/dev/null || echo 'NOT_INSTALLED'");

    let output = cmd.output().await.context("SSH command failed")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let key_path = ssh_key_path_from_identity(Some(&worker.identity_file));
        let ssh_error = classify_ssh_error_message(
            &worker.host,
            &worker.user,
            key_path,
            &stderr,
            std::time::Duration::from_secs(10),
        );
        return Err(ssh_error.into());
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    if stdout.contains("NOT_INSTALLED") {
        return Err(anyhow::anyhow!("rch-wkr not installed"));
    }

    // Extract version from "rch-wkr 1.0.0" or similar
    let version = stdout
        .split_whitespace()
        .nth(1)
        .unwrap_or("unknown")
        .trim()
        .to_string();

    Ok(version)
}

/// Deploy binary via SCP to remote worker.
pub(super) async fn deploy_via_scp(
    worker: &WorkerConfig,
    local_binary: &Path,
) -> Result<&'static str> {
    // Try /usr/local/bin first, then fall back to ~/.local/bin
    let remote_paths = [
        ("/usr/local/bin/rch-wkr", "/usr/local/bin"),
        ("~/.local/bin/rch-wkr", "~/.local/bin"),
    ];
    let mut failures = Vec::new();
    let target = format!("{}@{}", worker.user, worker.host);

    for (remote_path, dir) in remote_paths {
        // Ensure target directory exists
        let mut mkdir_cmd = Command::new("ssh");
        mkdir_cmd.arg("-o").arg("BatchMode=yes");
        mkdir_cmd.arg("-o").arg("ConnectTimeout=10");
        mkdir_cmd.arg("-i").arg(&worker.identity_file);

        mkdir_cmd.arg(&target);
        mkdir_cmd.arg(remote_mkdir_command(dir)?);

        let mkdir_output = mkdir_cmd.output().await?;
        if !mkdir_output.status.success() {
            failures.push(deploy_failure(remote_path, "mkdir", &mkdir_output));
            continue;
        }

        // SCP the binary
        let mut scp_cmd = Command::new("scp");
        scp_cmd.arg("-o").arg("BatchMode=yes");
        scp_cmd.arg("-o").arg("ConnectTimeout=30");
        scp_cmd.arg("-i").arg(&worker.identity_file);
        scp_cmd.arg(local_binary);

        let remote_target = scp_remote_target(worker, remote_path);
        scp_cmd.arg(&remote_target);

        let output = scp_cmd.output().await?;

        if output.status.success() {
            // Make executable
            let mut chmod_cmd = Command::new("ssh");
            chmod_cmd.arg("-o").arg("BatchMode=yes");
            chmod_cmd.arg("-o").arg("ConnectTimeout=10");
            chmod_cmd.arg("-i").arg(&worker.identity_file);
            chmod_cmd.arg(&target);
            chmod_cmd.arg(remote_chmod_command(remote_path)?);

            let chmod_output = chmod_cmd.output().await?;
            if !chmod_output.status.success() {
                failures.push(deploy_failure(remote_path, "chmod", &chmod_output));
                continue;
            }

            return Ok(remote_path);
        } else {
            failures.push(deploy_failure(remote_path, "scp", &output));
        }
    }

    if failures.is_empty() {
        Err(anyhow::anyhow!(
            "Failed to deploy to any location on {}",
            worker.host
        ))
    } else {
        Err(anyhow::anyhow!(
            "Failed to deploy to any location on {} ({})",
            worker.host,
            failures.join("; ")
        ))
    }
}

fn remote_mkdir_command(dir: &str) -> Result<String> {
    let escaped_dir = remote_shell_path(dir)?;
    Ok(format!("mkdir -p -- {escaped_dir}"))
}

fn remote_chmod_command(remote_path: &str) -> Result<String> {
    let escaped_path = remote_shell_path(remote_path)?;
    Ok(format!("chmod +x -- {escaped_path}"))
}

fn scp_remote_target(worker: &WorkerConfig, remote_path: &str) -> String {
    format!("{}@{}:{remote_path}", worker.user, worker.host)
}

fn remote_shell_path(path: &str) -> Result<String> {
    shell_escape_path_with_home(path)
        .ok_or_else(|| anyhow::anyhow!("Remote path contains unsupported control characters"))
}

fn deploy_failure(remote_path: &str, stage: &str, output: &std::process::Output) -> String {
    format!(
        "{remote_path}: {stage} failed: {}",
        command_failure_summary(output)
    )
}

fn command_failure_summary(output: &std::process::Output) -> String {
    let stderr = String::from_utf8_lossy(&output.stderr);
    let stdout = String::from_utf8_lossy(&output.stdout);
    let detail = stderr.trim();
    let detail = if detail.is_empty() {
        stdout.trim()
    } else {
        detail
    };

    match output.status.code() {
        Some(code) if detail.is_empty() => format!("exit {code}"),
        Some(code) => format!("exit {code}: {detail}"),
        None if detail.is_empty() => "terminated by signal".to_string(),
        None => format!("terminated by signal: {detail}"),
    }
}

// =============================================================================
// Response Types
// =============================================================================

/// Result of deploying to a single worker.
#[derive(Debug, Clone, Serialize)]
struct DeployResult {
    worker_id: String,
    success: bool,
    deployed: bool,
    local_version: String,
    remote_version: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    error: Option<String>,
}

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

    /// Regression guard for the wsurf incident (bd-jdcxd): a deploy must
    /// never push this host's binary to a worker with a different OS, and
    /// unlabelled workers are the historical Linux fleet.
    #[test]
    fn deploy_refuses_cross_os_workers() {
        assert!(worker_os_matches_local(None, "linux"));
        assert!(worker_os_matches_local(Some("linux"), "linux"));
        assert!(worker_os_matches_local(Some("Windows"), "windows"));
        assert!(!worker_os_matches_local(Some("windows"), "linux"));
        assert!(!worker_os_matches_local(Some("linux"), "windows"));
        // A macOS host must not push its darwin binary at the Linux fleet.
        assert!(!worker_os_matches_local(None, "macos"));
    }

    #[test]
    fn remote_deploy_shell_commands_quote_paths() {
        assert_eq!(
            remote_mkdir_command("/usr/local/bin").expect("mkdir command"),
            "mkdir -p -- '/usr/local/bin'"
        );
        assert_eq!(
            remote_mkdir_command("~/.local/bin").expect("mkdir command"),
            "mkdir -p -- \"$HOME/.local/bin\""
        );
        assert_eq!(
            remote_chmod_command("~/.local/bin/rch-wkr").expect("chmod command"),
            "chmod +x -- \"$HOME/.local/bin/rch-wkr\""
        );
        assert_eq!(
            remote_chmod_command("dir with spaces/rch-wkr").expect("chmod command"),
            "chmod +x -- 'dir with spaces/rch-wkr'"
        );
    }

    #[test]
    fn remote_deploy_shell_commands_reject_control_characters() {
        let err = remote_chmod_command("bad\npath")
            .expect_err("control characters should be rejected")
            .to_string();
        assert!(err.contains("control characters"));
    }
}