rch 2.1.7

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
//! E2E: stderr/stdout Stream Isolation Tests
//!
//! Verifies that rich output ONLY goes to stderr, and stdout remains
//! pristine for machine-parseable data.
//!
//! This is critical for:
//! - Agent JSON parsing
//! - Compiler output capture
//! - Pipeline composition (rch compile 2>/dev/null | jq)
//!
//! Implements bead: bd-2ans

mod common;

use common::logging::{TestLogger, TestPhase, init_test_logging};
use std::io::Write;
use std::process::{Command, Stdio};

/// Marker for ANSI escape sequences.
const ANSI_ESC: &str = "\x1b[";

/// Get the path to the rch binary.
fn rch_binary() -> String {
    std::env::var("RCH_BINARY").unwrap_or_else(|_| env!("CARGO_BIN_EXE_rch").to_string())
}

/// Check if binary exists.
fn check_binary() -> bool {
    let rch = rch_binary();
    std::path::Path::new(&rch).exists()
}

/// Skip test if binary not available.
macro_rules! require_binary {
    () => {
        if !check_binary() {
            eprintln!("Skipping test: rch binary not found at {}", rch_binary());
            eprintln!("Build with: cargo build -p rch --release");
            return;
        }
    };
}

/// Run rch with arguments and return (exit_code, stdout, stderr).
fn run_rch(args: &[&str]) -> (i32, String, String) {
    let rch = rch_binary();

    let output = Command::new(&rch)
        .args(args)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .expect("Failed to run rch");

    (
        output.status.code().unwrap_or(-1),
        String::from_utf8_lossy(&output.stdout).to_string(),
        String::from_utf8_lossy(&output.stderr).to_string(),
    )
}

/// Run rch with environment variable and return (exit_code, stdout, stderr).
fn run_rch_with_env(args: &[&str], env_key: &str, env_val: &str) -> (i32, String, String) {
    let rch = rch_binary();

    let output = Command::new(&rch)
        .args(args)
        .env(env_key, env_val)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .expect("Failed to run rch");

    (
        output.status.code().unwrap_or(-1),
        String::from_utf8_lossy(&output.stdout).to_string(),
        String::from_utf8_lossy(&output.stderr).to_string(),
    )
}

/// Run hook with stdin input and return (exit_code, stdout, stderr).
fn run_hook(input: &str) -> (i32, String, String) {
    let rch = rch_binary();

    let mut child = Command::new(&rch)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("Failed to spawn rch");

    if let Some(mut stdin) = child.stdin.take() {
        stdin.write_all(input.as_bytes()).ok();
    }

    let output = child.wait_with_output().expect("Failed to wait for rch");

    (
        output.status.code().unwrap_or(-1),
        String::from_utf8_lossy(&output.stdout).to_string(),
        String::from_utf8_lossy(&output.stderr).to_string(),
    )
}

// =============================================================================
// TEST 1: --json flag outputs only to stdout
// =============================================================================

#[test]
fn test_rch_json_env_forces_machine_output_like_the_flag() {
    init_test_logging();
    let logger = TestLogger::for_test("test_rch_json_env_forces_machine_output_like_the_flag");

    require_binary!();

    // AGENTS.md and the README both document RCH_JSON=1 as the first thing
    // consulted when choosing an output mode, but the CLI built its context
    // from flags alone — so an agent that followed the documented env-var route
    // got a rich terminal panel where it expected a parseable envelope, and the
    // failure surfaced as malformed JSON rather than as a mode mismatch
    // (bd-e92eh). `admit` is the smallest surface that shows it: it needs no
    // daemon and always prints something.
    logger.log(TestPhase::Execute, "Running admit under RCH_JSON=1");
    let (_exit, stdout, _stderr) = run_rch_with_env(&["admit", "ls -la"], "RCH_JSON", "1");

    logger.log(TestPhase::Verify, "Checking the envelope");
    let parsed: serde_json::Value = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("RCH_JSON=1 must yield a JSON envelope ({e}); got: {stdout}"));
    assert_eq!(parsed["api_version"], "1.0", "got: {stdout}");
    assert_eq!(parsed["command"], "admit", "got: {stdout}");
    assert!(
        !stdout.contains(ANSI_ESC),
        "machine output must carry no ANSI: {stdout}"
    );

    // ...and the value is honored, not merely the variable's presence: a caller
    // who exported RCH_JSON=0 asked for no JSON.
    logger.log(TestPhase::Execute, "Running admit under RCH_JSON=0");
    let (_exit, stdout_off, _stderr) = run_rch_with_env(&["admit", "ls -la"], "RCH_JSON", "0");
    assert!(
        serde_json::from_str::<serde_json::Value>(&stdout_off).is_err(),
        "RCH_JSON=0 must not force the envelope; got: {stdout_off}"
    );

    logger.pass();
}

#[test]
fn test_status_json_outputs_to_stdout() {
    init_test_logging();
    let logger = TestLogger::for_test("test_status_json_outputs_to_stdout");

    require_binary!();

    logger.log(TestPhase::Execute, "Running status --json");
    let (_exit, stdout, _stderr) = run_rch(&["status", "--json"]);

    logger.log(TestPhase::Verify, "Checking JSON validity");
    // stdout should be valid JSON or empty
    if !stdout.is_empty() {
        let parsed: Result<serde_json::Value, _> = serde_json::from_str(&stdout);
        assert!(
            parsed.is_ok(),
            "status --json stdout must be valid JSON, got: {}",
            stdout
        );
    }

    // stdout must NOT contain ANSI codes
    assert!(
        !stdout.contains(ANSI_ESC),
        "status --json stdout contains ANSI codes: {}",
        stdout
    );

    logger.pass();
}

#[test]
fn test_workers_list_json_outputs_to_stdout() {
    init_test_logging();
    let logger = TestLogger::for_test("test_workers_list_json_outputs_to_stdout");

    require_binary!();

    logger.log(TestPhase::Execute, "Running workers list --json");
    let (_exit, stdout, _stderr) = run_rch(&["workers", "list", "--json"]);

    logger.log(TestPhase::Verify, "Checking JSON validity");
    if !stdout.is_empty() {
        let parsed: Result<serde_json::Value, _> = serde_json::from_str(&stdout);
        assert!(
            parsed.is_ok(),
            "workers list --json stdout must be valid JSON, got: {}",
            stdout
        );
    }

    assert!(
        !stdout.contains(ANSI_ESC),
        "workers list --json stdout contains ANSI codes: {}",
        stdout
    );

    logger.pass();
}

#[test]
fn test_config_show_json_outputs_to_stdout() {
    require_binary!();

    let (_exit, stdout, _stderr) = run_rch(&["config", "show", "--json"]);

    if !stdout.is_empty() {
        let parsed: Result<serde_json::Value, _> = serde_json::from_str(&stdout);
        assert!(
            parsed.is_ok(),
            "config show --json stdout must be valid JSON, got: {}",
            stdout
        );
    }

    assert!(
        !stdout.contains(ANSI_ESC),
        "config show --json stdout contains ANSI codes: {}",
        stdout
    );
}

// =============================================================================
// TEST 2: Hook output isolation
// =============================================================================

#[test]
fn test_hook_stdout_is_clean() {
    require_binary!();

    let input = r#"{"tool_name":"Bash","tool_input":{"command":"echo hello"}}"#;
    let (_exit, stdout, _stderr) = run_hook(input);

    if !stdout.is_empty() {
        let parsed: Result<serde_json::Value, _> = serde_json::from_str(&stdout);
        assert!(
            parsed.is_ok(),
            "hook stdout must be valid JSON or empty, got: {}",
            stdout
        );
    }

    assert!(
        !stdout.contains(ANSI_ESC),
        "hook stdout contains ANSI codes: {}",
        stdout
    );
}

#[test]
fn test_hook_cargo_stdout_is_clean() {
    require_binary!();

    // Cargo build command
    let input = r#"{"tool_name":"Bash","tool_input":{"command":"cargo build"}}"#;
    let (_exit, stdout, _stderr) = run_hook(input);

    if !stdout.is_empty() {
        let parsed: Result<serde_json::Value, _> = serde_json::from_str(&stdout);
        assert!(
            parsed.is_ok(),
            "hook stdout must be valid JSON or empty, got: {}",
            stdout
        );
    }

    assert!(
        !stdout.contains(ANSI_ESC),
        "hook stdout contains ANSI codes: {}",
        stdout
    );
}

// =============================================================================
// TEST 3: NO_COLOR environment variable
// =============================================================================

#[test]
fn test_no_color_disables_ansi_in_stdout() {
    require_binary!();

    let (_exit, stdout, _stderr) = run_rch_with_env(&["status"], "NO_COLOR", "1");

    assert!(
        !stdout.contains(ANSI_ESC),
        "stdout has ANSI codes with NO_COLOR=1: {}",
        stdout
    );
}

#[test]
fn test_no_color_disables_ansi_in_stderr() {
    require_binary!();

    let (_exit, _stdout, stderr) = run_rch_with_env(&["status"], "NO_COLOR", "1");

    assert!(
        !stderr.contains(ANSI_ESC),
        "stderr has ANSI codes with NO_COLOR=1: {}",
        stderr
    );
}

// =============================================================================
// TEST 4: Error output goes to stderr
// =============================================================================

#[test]
fn test_daemon_status_error_to_stderr() {
    require_binary!();

    let isolated = tempfile::tempdir().expect("isolated daemon status configuration");
    let socket = isolated.path().join("absent.sock");
    let mut command = Command::new(rch_binary()); // ubs:ignore — trusted test binary from Cargo or RCH_BINARY.
    command
        .args(["daemon", "status"])
        .current_dir(isolated.path())
        .env("RCH_CONFIG_DIR", isolated.path().join("config"))
        .env("RCH_SOCKET_PATH", &socket)
        .env("FORCE_COLOR", "1")
        .env_remove("NO_COLOR")
        .env_remove("RCH_JSON")
        .env_remove("RCH_OUTPUT_FORMAT")
        .env_remove("RCH_HOOK_MODE");
    let output = command.output().expect("run colored daemon status");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(output.status.success(), "daemon status failed: {stderr}");

    // stdout should be minimal for non-JSON commands
    // Errors (like daemon not running) should go to stderr
    assert!(
        !stdout.contains(ANSI_ESC),
        "daemon status stdout contains ANSI codes: {}",
        stdout
    );
    assert!(
        stdout.is_empty(),
        "human diagnostics belong on stderr: {stdout}"
    );
    assert!(
        stderr.contains(ANSI_ESC),
        "forced color must remain available on stderr: {stderr}"
    );
    assert!(
        stderr.contains("Not running"),
        "missing status diagnostic: {stderr}"
    );
    assert!(
        stderr.contains("rch daemon start"),
        "missing recovery hint: {stderr}"
    );

    let json_output = command
        .arg("--json")
        .output()
        .expect("run daemon status JSON");
    assert!(json_output.status.success());
    let json_stdout = String::from_utf8_lossy(&json_output.stdout);
    assert!(
        !json_stdout.contains(ANSI_ESC),
        "JSON must not contain ANSI: {json_stdout}"
    );
    let response: serde_json::Value = serde_json::from_str(&json_stdout).unwrap_or_else(|error| {
        panic!("daemon status JSON must stay on stdout: {error}: {json_stdout}") // ubs:ignore — malformed test output must fail the assertion.
    });
    assert_eq!(response["success"], true);
    assert_eq!(response["data"]["running"], false);
    assert_eq!(
        response["data"]["socket_path"],
        socket.to_str().expect("socket path")
    );
}

// =============================================================================
// TEST 5: JSON commands produce parseable output
// =============================================================================

#[test]
fn test_all_json_commands_parseable() {
    require_binary!();

    let json_commands = [
        vec!["status", "--json"],
        vec!["workers", "list", "--json"],
        vec!["config", "show", "--json"],
    ];

    for args in json_commands {
        let (_exit, stdout, _stderr) = run_rch(&args);

        if !stdout.is_empty() {
            let parsed: Result<serde_json::Value, _> = serde_json::from_str(&stdout);
            assert!(
                parsed.is_ok(),
                "{} output must be valid JSON, got: {}",
                args.join(" "),
                stdout
            );
        }

        assert!(
            !stdout.contains(ANSI_ESC),
            "{} stdout contains ANSI codes",
            args.join(" ")
        );
    }
}

// =============================================================================
// TEST 6: Consistency across multiple runs
// =============================================================================

#[test]
fn test_stream_isolation_consistent() {
    require_binary!();

    // Run the same command multiple times, verify consistent isolation
    for _ in 0..3 {
        let (_exit, stdout, _stderr) = run_rch(&["status", "--json"]);

        assert!(
            !stdout.contains(ANSI_ESC),
            "stdout contains ANSI codes on repeated run"
        );
    }
}

// =============================================================================
// Summary Test
// =============================================================================

#[test]
fn test_stream_isolation_summary() {
    require_binary!();

    eprintln!("\n=== Stream Isolation Test Summary ===\n");

    // Test JSON commands
    let json_commands = [
        ("status --json", vec!["status", "--json"]),
        ("workers list --json", vec!["workers", "list", "--json"]),
        ("config show --json", vec!["config", "show", "--json"]),
    ];

    for (name, args) in json_commands {
        let (_exit, stdout, _stderr) = run_rch(&args);

        let is_valid_json =
            stdout.is_empty() || serde_json::from_str::<serde_json::Value>(&stdout).is_ok();
        let has_ansi = stdout.contains(ANSI_ESC);

        eprintln!(
            "{}: valid_json={}, ansi_free={}",
            name, is_valid_json, !has_ansi
        );

        assert!(is_valid_json, "{} must produce valid JSON", name);
        assert!(!has_ansi, "{} must not have ANSI in stdout", name);
    }

    // Test hook
    let input = r#"{"tool_name":"Bash","tool_input":{"command":"echo test"}}"#;
    let (_exit, stdout, _stderr) = run_hook(input);
    let hook_clean = !stdout.contains(ANSI_ESC);
    eprintln!("hook: ansi_free={}", hook_clean);
    assert!(hook_clean, "hook must not have ANSI in stdout");

    // Test NO_COLOR
    let (_exit, stdout, stderr) = run_rch_with_env(&["status"], "NO_COLOR", "1");
    let no_color_works = !stdout.contains(ANSI_ESC) && !stderr.contains(ANSI_ESC);
    eprintln!("NO_COLOR=1: ansi_free={}", no_color_works);
    assert!(no_color_works, "NO_COLOR must disable ANSI everywhere");

    eprintln!("\n=== All Stream Isolation Tests PASSED ===\n");
}