rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
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
//! `rho daemon` through the real binary. Here: its lifecycle (status,
//! single instance, and stop), and a dropped test sandbox stopping the
//! daemon a client in it started. The sessions it hosts are in
//! [`sessions`], the agent and setup a client opens one with in
//! [`setup`], forks of them in [`forks`], changing their settings in
//! [`configure`], and listing,
//! renaming, and deleting them in [`catalog`],
//! `rho attach` following them in [`attach`], and `rho run --detach`
//! starting them in [`detach`], and cleaning up the git worktrees they
//! work in in [`worktrees`]; the tool processes the daemon's stop ends
//! are in [`tools`], signing it in and out over its socket in [`auth`],
//! and the interactive logins it relays to clients, `rho login` among
//! them, in [`login`], signing in where no OS credential store answers in
//! [`headless`]; `rho mcp serve` driving its sessions is in [`mcp`],
//! and the sessions a session starts, as its children, in [`started`];
//! reading and changing settings over its socket is in [`config`], and
//! listing the MCP servers and hooks its configuration sets up in
//! [`configured`];
//! re-executing the daemon in place, for an upgrade or `rho daemon
//! restart`, is in [`upgrade`]; what a client of another version hears at
//! the handshake is in [`skew`]; what a daemon takes from the client that
//! starts it, and each session's project trust, is in [`identity`]; what
//! `rho doctor` reports about it is in [`doctor`]; what `rho update` and
//! `rho uninstall` do about it is in [`install`]; a turn whose provider
//! cannot be reached is in [`unreachable`]; what a session records about
//! what follows a compaction is in [`compaction`]; what a loaded session
//! costs the daemon in memory is in [`memory`]; a session's pull requests,
//! which clients list, show, link and unlink, are in [`pull_requests`].

use std::{
    fs::File,
    panic::AssertUnwindSafe,
    process::{Output, Stdio},
};

use pretty_assertions::assert_eq;
use serde_json::{json, Value};

#[path = "support/daemon_sessions.rs"]
mod sessions;

#[path = "support/daemon_setup.rs"]
mod setup;

// Unix: its agent is a shell shim that execs the scripted ACP agent.
#[cfg(unix)]
#[path = "support/daemon_acp_sessions.rs"]
mod acp_sessions;

#[cfg(unix)]
#[path = "support/daemon_acp_steer.rs"]
mod acp_steer;

#[cfg(unix)]
#[path = "support/daemon_acp_children.rs"]
mod acp_children;

#[path = "support/daemon_forks.rs"]
mod forks;

#[path = "support/daemon_surfaces.rs"]
mod surfaces;

#[path = "support/daemon_configure.rs"]
mod configure;

#[path = "support/daemon_catalog.rs"]
mod catalog;

#[path = "support/daemon_attach.rs"]
mod attach;

#[path = "support/daemon_detach.rs"]
mod detach;

#[path = "support/daemon_entries.rs"]
mod entries;

// Unix: the receiver's turn blocks in a shell command for the steer.
#[cfg(unix)]
#[path = "support/daemon_message_origins.rs"]
mod message_origins;

#[path = "support/git_repo.rs"]
mod git_repo;

#[path = "support/daemon_tool_output.rs"]
mod tool_output;

#[path = "support/daemon_worktrees.rs"]
mod worktrees;

// Unix: the tool processes are shell commands, found by process group.
#[cfg(unix)]
#[path = "support/daemon_tools.rs"]
mod tools;

// Unix: the probe MCP server is a Python script run through `python3`.
#[cfg(unix)]
#[path = "support/daemon_mcp_reload.rs"]
mod mcp_reload;

// Unix: its MCP servers are Python scripts run through `python3`.
#[cfg(unix)]
#[path = "support/daemon_mcp_probe.rs"]
mod mcp_probe;

// Unix: it starts `mcp_reload`'s probe MCP server.
#[cfg(unix)]
#[path = "support/daemon_mcp_seen.rs"]
mod mcp_seen;

#[path = "support/daemon_auth.rs"]
mod auth;

#[path = "support/daemon_login.rs"]
mod login;

#[path = "support/daemon_starting_auth.rs"]
mod starting_auth;

#[path = "support/daemon_headless.rs"]
mod headless;

// Unix: its sessions run shell commands, and its servers are shell scripts.
#[cfg(unix)]
#[path = "support/daemon_mcp.rs"]
mod mcp;

// Unix: its children block in shell commands.
#[cfg(unix)]
#[path = "support/daemon_child_delivery.rs"]
mod child_delivery;

#[path = "support/daemon_config.rs"]
mod config;
#[path = "support/daemon_config_tables.rs"]
mod config_tables;
#[path = "support/daemon_configured.rs"]
mod configured;
#[path = "support/daemon_hooks_config.rs"]
mod hooks_config;
#[path = "support/daemon_hooks_file.rs"]
mod hooks_file;
#[path = "support/daemon_plugins.rs"]
mod plugins;
#[path = "support/daemon_sync.rs"]
mod sync;
// Unix: only there does `rho daemon bridge setup` record a bridge to pair
// devices with.
#[cfg(unix)]
#[path = "support/daemon_devices.rs"]
mod devices;
// Unix: its sessions run shell commands.
#[cfg(unix)]
#[path = "support/daemon_started.rs"]
mod started;

// Unix: re-executing in place keeps the pid, lock and socket only on Unix.
#[cfg(unix)]
#[path = "support/daemon_upgrade.rs"]
mod upgrade;

// Windows: elsewhere a server re-executes in place, which `mcp`'s
// `upgrade` covers.
#[cfg(windows)]
#[path = "support/daemon_serve_relaunch.rs"]
mod serve_relaunch;

// Unix: it holds turns open with the FIFOs `upgrade` makes.
#[cfg(unix)]
#[path = "support/daemon_skew.rs"]
mod skew;

// Unix: its hooks are shell scripts.
#[cfg(unix)]
#[path = "support/daemon_hooks.rs"]
mod hooks;

// Unix: its hooks are shell scripts, and it reads `/proc`.
#[cfg(unix)]
#[path = "support/daemon_identity.rs"]
mod identity;

// Unix: its sessions run shell commands.
#[cfg(unix)]
#[path = "support/daemon_grants.rs"]
mod grants;

#[path = "support/daemon_doctor.rs"]
mod doctor;

#[path = "support/daemon_install.rs"]
mod install;

#[path = "support/daemon_unreachable.rs"]
mod unreachable;

#[path = "support/daemon_compaction.rs"]
mod compaction;

// glibc on Linux: it reads `/proc` and tunes glibc's allocator.
#[cfg(all(target_os = "linux", target_env = "gnu"))]
#[path = "support/daemon_memory.rs"]
mod memory;

// Unix: the `gh` it reads pull requests with is a shell script.
#[cfg(unix)]
#[path = "support/daemon_pull_requests.rs"]
mod pull_requests;

#[path = "support/key_checking_provider.rs"]
mod key_checking_provider;

#[path = "support/scripted_host.rs"]
mod scripted_host;

use sessions::Sandbox;

fn stderr(output: &Output) -> String {
    String::from_utf8_lossy(&output.stderr).into_owned()
}

// Covers: status, stop, and attach report a missing daemon without starting one; a
// running daemon reports its pid, refuses a second instance by name, and
// `rho daemon stop` makes it exit cleanly and remove its socket.
// Owner: CLI process (daemon lifecycle).
#[tokio::test]
async fn daemon_lifecycle_through_the_cli() {
    let sandbox = Sandbox::new();
    let output = |args: &[&str]| {
        sandbox
            .rho("fixed")
            .args(args)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .unwrap()
    };
    for args in [
        ["daemon", "status"],
        ["daemon", "stop"],
        ["attach", "session"],
    ] {
        let output = output(&args);
        assert_eq!(output.status.code(), Some(1), "{args:?}: {output:?}");
        assert_eq!(stderr(&output), "Error: rho daemon is not running\n");
    }
    assert_eq!(
        sandbox.isolated.daemon_socket(),
        None,
        "status, stop, and attach never spawn"
    );

    let mut daemon = sandbox
        .rho("fixed")
        .args(["daemon", "run"])
        .spawn()
        .unwrap();
    let socket = sandbox
        .poll_until("the daemon socket", async || {
            sandbox.isolated.daemon_socket()
        })
        .await;

    let status = output(&["daemon", "status", "--json"]);
    assert!(status.status.success(), "{status:?}");
    let status: Value = serde_json::from_slice(&status.stdout).unwrap();
    assert_eq!(status["pid"], Value::from(daemon.id()));
    assert_eq!(status["socket"], Value::from(socket.to_str().unwrap()));

    let second = output(&["daemon", "run"]);
    assert_eq!(second.status.code(), Some(1), "{second:?}");
    assert_eq!(
        stderr(&second),
        format!(
            "Error: rho daemon is already running (pid {}, version {}, socket {})\n",
            daemon.id(),
            env!("CARGO_PKG_VERSION"),
            socket.display()
        )
    );

    let stop = output(&["daemon", "stop"]);
    assert!(stop.status.success(), "{stop:?}");
    let exit = sandbox
        .poll_until("the daemon to exit", async || daemon.try_wait().unwrap())
        .await;
    assert!(exit.success(), "daemon exit: {exit:?}");
    assert_eq!(
        sandbox.isolated.daemon_socket(),
        None,
        "socket removed on stop"
    );
}

// Covers: `rho/daemon/status` counts the other clients a stop or restart
// would disconnect, never the one asking (#1998), as `rho daemon status
// --json` reports them.
// Owner: CLI process (daemon status).
#[tokio::test]
async fn daemon_status_counts_the_other_clients() {
    let sandbox = Sandbox::new();
    let _first = sandbox.start_daemon("fixed").await;
    let clients = || {
        let output = sandbox
            .rho("fixed")
            .args(["daemon", "status", "--json"])
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .unwrap();
        assert!(output.status.success(), "{output:?}");
        let status: Value = serde_json::from_slice(&output.stdout).unwrap();
        status["clients"].clone()
    };

    // The daemon notices a connection leave on its own time, as that of
    // the last `rho daemon status`, so each count is awaited. One that
    // counts the asker never reaches it.
    let counts = async |others: u64, what: &str| {
        sandbox
            .poll_until(what, async || (clients() == others).then_some(()))
            .await;
    };
    counts(1, "the daemon to count one other client").await;
    let _second = sandbox.connect().await;
    counts(2, "the daemon to count two other clients").await;
}

// Covers: `rho daemon start` starts a daemon when none runs and exits once
// it answers; run again, it exits 0 and leaves that daemon the only one
// (#1730), and with `--json` it reports that daemon as running (#1997).
// Owner: CLI process (daemon lifecycle).
#[test]
fn daemon_start_is_idempotent() {
    let sandbox = Sandbox::new();
    let start = |args: &[&str]| {
        let output = sandbox
            .rho("fixed")
            .args(["daemon", "start"])
            .args(args)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .unwrap();
        let pid = sandbox.isolated.daemon_pid();
        (
            output.status.code(),
            String::from_utf8(output.stdout).unwrap(),
            pid,
        )
    };

    let first = start(&[]);
    let pid = first.2.expect("the started daemon's record");
    let second = start(&[]);
    let (code, json, recorded) = start(&["--json"]);
    let json: Value = serde_json::from_str(&json).unwrap_or_else(|error| {
        panic!("{error}: {json:?}\nlog:\n{}", sandbox.isolated.daemon_log())
    });

    let running = format!("rho daemon is running (pid {pid})\n");
    assert_eq!(
        (first, second, (code, json, recorded)),
        (
            (Some(0), running.clone(), Some(pid)),
            (Some(0), running, Some(pid)),
            (
                Some(0),
                json!({
                    "outcome": "running",
                    "pid": pid,
                    "version": env!("CARGO_PKG_VERSION"),
                }),
                Some(pid)
            ),
        ),
        "log:\n{}",
        sandbox.isolated.daemon_log()
    );
}

// Covers: a frontend's `rho_protocol::LocalDaemon` starts the stopped daemon
// of an isolated rho home through `rho daemon start` and connects to it, and
// a later one finds that daemon running, starting nothing.
// Owner: rho-protocol LocalDaemon against the real CLI.
#[tokio::test]
async fn a_frontend_starts_a_stopped_daemon_as_the_cli_does_then_finds_it() {
    use rho_protocol::{ClientHello, ClientInfo, LocalDaemon};

    let sandbox = Sandbox::new();
    let daemon = LocalDaemon::new(sandbox.isolated.rho_home())
        .with_xdg_runtime_dir(Some(sandbox.isolated.path().join("run")));
    let hello = || {
        ClientHello::frontend(ClientInfo {
            name: "local-daemon-test".into(),
            version: "0".into(),
        })
    };
    assert!(daemon.connect(hello()).await.unwrap().is_none(), "stopped");

    let (_client, _notifications, started) = daemon
        .connect_or_start(sandbox.rho("fixed"), hello())
        .await
        .unwrap();
    let pid = sandbox
        .isolated
        .daemon_pid()
        .expect("the started daemon's record");
    let no_rho = std::process::Command::new(sandbox.isolated.path().join("no-such-rho"));
    let (_client, _notifications, found) = daemon.connect_or_start(no_rho, hello()).await.unwrap();

    assert_eq!((started.daemon.pid, found.daemon.pid), (pid, pid));
}

// Covers: a client whose environment sets an unknown RHO_CREDENTIAL_STORE
// starts no daemon, which would refuse its sessions and sign-ins for it,
// and names the variable at once; with a daemon already running it
// connects, and that daemon refuses what needs the store.
// Owner: CLI process (daemon ensure-running path).
#[test]
fn an_unknown_credential_store_stops_only_a_daemon_start() {
    let sandbox = Sandbox::new();
    let start = |store: &str| {
        let output = sandbox
            .rho("fixed")
            .env("RHO_CREDENTIAL_STORE", store)
            .args(["daemon", "start"])
            .stderr(Stdio::piped())
            .output()
            .unwrap();
        (output.status.code(), stderr(&output))
    };

    let (code, refused) = start("fiel");
    assert_eq!(
        (
            code,
            refused.contains("RHO_CREDENTIAL_STORE"),
            sandbox.isolated.daemon_pid()
        ),
        (Some(1), true, None),
        "{refused}"
    );
    assert_eq!(start("file").0, Some(0));
    assert_eq!(start("fiel"), (Some(0), String::new()));
}

// Covers: `rho daemon restart` returns once a daemon answers again, however
// the platform restarts one: in place, where a client waits in the socket's
// backlog, or as a new process, where the old one must leave nothing a
// client could connect to in between.
// Owner: CLI process (daemon restart).
#[test]
fn restart_returns_once_a_daemon_answers_again() {
    let sandbox = Sandbox::new();
    let run = |args: &[&str]| {
        sandbox
            .rho("fixed")
            .args(args)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .unwrap()
    };
    let started = run(&["daemon", "start"]);

    let restarted = run(&["daemon", "restart"]);
    let status = run(&["daemon", "status"]);

    assert_eq!(
        [started, restarted, status].map(|output| (output.status.code(), stderr(&output))),
        [
            (Some(0), String::new()),
            (Some(0), String::new()),
            (Some(0), String::new())
        ],
        "log:\n{}",
        sandbox.isolated.daemon_log()
    );
}

// Covers: dropping a sandbox stops the daemon a client in it started, so a
// test that fails, or forgets to stop it, leaves no daemon running.
// Owner: daemon test sandbox teardown (process).
#[test]
fn a_dropped_sandbox_stops_the_daemon_a_client_started() {
    let sandbox = Sandbox::new();
    // `rho run --detach` starts a daemon, which outlives it.
    let detached = sandbox
        .rho("fixed")
        .args(["run", "--detach", "hello"])
        .status()
        .unwrap();
    assert!(
        detached.success(),
        "log:\n{}",
        sandbox.isolated.daemon_log()
    );
    // Kept open, it still probes the daemon's lock once the sandbox's
    // directory is deleted.
    let lock = File::open(sandbox.isolated.rho_home().join("daemon/daemon.lock")).unwrap();
    // Whether a shared lock is granted, which the daemon's exclusive one
    // refuses until it exits.
    let free = || fs2::FileExt::try_lock_shared(&lock).is_ok();
    assert!(!free(), "the daemon holds its lock");
    let pid = sandbox.isolated.daemon_pid().expect("the daemon's record");

    // Caught so the daemon is killed below if the teardown panics because it
    // failed to stop it.
    let teardown = std::panic::catch_unwind(AssertUnwindSafe(|| drop(sandbox)));
    let released = free();
    if !released {
        // The daemon must not outlive a failed test.
        kill(pid);
    }
    if let Err(panic) = teardown {
        std::panic::resume_unwind(panic);
    }
    assert!(released, "the daemon (pid {pid}) still holds its lock");
}

/// Ends process `pid` at once.
fn kill(pid: u32) {
    #[cfg(unix)]
    // SAFETY: `kill` takes no pointers.
    unsafe {
        libc::kill(libc::pid_t::try_from(pid).unwrap(), libc::SIGKILL);
    }
    #[cfg(windows)]
    let _ = std::process::Command::new("taskkill")
        .args(["/F", "/PID", &pid.to_string()])
        .output();
}