rho-coding-agent 1.8.0

A lightweight agent harness inspired by Pi
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
use std::{
    io::Write,
    process::{Command, Output, Stdio},
};

use serde_json::Value;
use tempfile::TempDir;

const MODE_ENV: &str = "RHO_AUTOMATION_TEST_MODE";
const RESPONSE_ENV: &str = "RHO_AUTOMATION_TEST_RESPONSE";
const COMMAND_ENV: &str = "RHO_AUTOMATION_TEST_COMMAND";

#[test]
fn composes_prompt_arguments_stdin_and_combined_input() {
    let root = TempDir::new().unwrap();

    let arguments = run(&root, "inspect", &["run", "review", "this"], None);
    assert_success(&arguments);
    assert_eq!(user_prompt(&arguments), "review this");

    let stdin = run(&root, "inspect", &["run", "--stdin"], Some("diff contents"));
    assert_success(&stdin);
    assert_eq!(user_prompt(&stdin), "diff contents");

    let combined = run(
        &root,
        "inspect",
        &["run", "--stdin", "review"],
        Some("diff contents\n"),
    );
    assert_success(&combined);
    assert_eq!(user_prompt(&combined), "review\n\ndiff contents");
}

#[test]
fn applies_runtime_configuration_tools_and_workspace_instructions() {
    let root = TempDir::new().unwrap();
    std::fs::write(root.path().join("AGENTS.md"), "project automation rules").unwrap();
    std::fs::write(
        root.path().join("config.toml"),
        r#"provider = "xai"
model = "grok-fixture"
auth = "xai-oauth"
reasoning = "high"
web_search_provider = "disabled"
"#,
    )
    .unwrap();

    let output = run(
        &root,
        "inspect",
        &[
            "--auth",
            "xai-oauth",
            "--reasoning",
            "low",
            "run",
            "inspect",
        ],
        None,
    );
    assert_success(&output);
    let inspection = inspection(&output);

    assert_eq!(inspection["identity"]["provider"], "xai");
    assert_eq!(inspection["identity"]["model"], "grok-fixture");
    assert_eq!(inspection["reasoning"], "low");
    let system = inspection["messages"][0]["System"].as_str().unwrap();
    assert!(system.contains("project automation rules"));
    assert!(system.contains(&root.path().join("AGENTS.md").display().to_string()));

    let names = inspection["tools"]
        .as_array()
        .unwrap()
        .iter()
        .map(|tool| tool["name"].as_str().unwrap())
        .collect::<Vec<_>>();
    for expected in [
        "list_dir",
        "read_file",
        "write_file",
        "edit_file",
        "process",
        shell_tool_name(),
        "skill",
        "rho",
        "fetch_content",
        "get_search_content",
    ] {
        assert!(
            names.contains(&expected),
            "missing tool {expected}: {names:?}"
        );
    }
    assert!(!names.contains(&"web_search"));

    let config = std::fs::read_to_string(root.path().join("config.toml")).unwrap();
    assert!(config.contains("provider = \"xai\""));
    assert!(config.contains("model = \"grok-fixture\""));
    assert!(config.contains("auth = \"xai-oauth\""));
    assert!(config.contains("reasoning = \"low\""));
}

#[test]
fn applies_configured_tool_output_limit() {
    let root = TempDir::new().unwrap();
    std::fs::write(root.path().join("large.txt"), "abcdefgh").unwrap();
    std::fs::write(
        root.path().join("config.toml"),
        "max_output_bytes = 5\nweb_search_provider = \"disabled\"\n",
    )
    .unwrap();

    let output = run(&root, "read-file", &["run", "read the file"], None);

    assert_success(&output);
    assert_eq!(stdout(&output), "abcde\n[truncated]\n");
    assert!(output.stderr.is_empty());
}

#[test]
fn no_system_prompt_and_no_tools_only_affect_the_current_run() {
    let root = TempDir::new().unwrap();
    let output = run(
        &root,
        "inspect",
        &["--no-system-prompt", "--no-tools", "run", "hello"],
        None,
    );
    assert_success(&output);
    let inspection = inspection(&output);

    assert_eq!(inspection["messages"].as_array().unwrap().len(), 1);
    assert_eq!(user_prompt(&output), "hello");
    assert!(inspection["tools"].as_array().unwrap().is_empty());

    let config = std::fs::read_to_string(root.path().join("config.toml")).unwrap();
    assert!(!config.contains("no_system_prompt"));
    assert!(!config.contains("no_tools"));
}

#[test]
fn provider_and_tool_failures_stay_off_stdout() {
    let root = TempDir::new().unwrap();
    let provider_failure = run(&root, "fail", &["run", "hello"], None);
    assert_eq!(provider_failure.status.code(), Some(1));
    assert!(provider_failure.stdout.is_empty());
    assert!(stderr(&provider_failure).contains("deterministic provider failure"));

    let mut command = command(&root, "tool-failure");
    command
        .env(RESPONSE_ENV, "recovered after tool failure")
        .args(["run", "use a tool"]);
    let tool_failure = command.output().unwrap();
    assert_success(&tool_failure);
    assert_eq!(stdout(&tool_failure), "recovered after tool failure\n");
    assert!(tool_failure.stderr.is_empty());
}

#[test]
fn output_run_persists_agent_identity() {
    let root = TempDir::new().unwrap();
    std::fs::write(
        root.path().join("config.toml"),
        "provider = \"openai\"\nmodel = \"gpt-5.5\"\n",
    )
    .unwrap();
    let output_file = root.path().join("result.json");
    let mut command = command(&root, "fixed");
    command.env(RESPONSE_ENV, "done").args([
        "--no-subagents",
        "--agent",
        "worker",
        "run",
        "--output-file",
        output_file.to_str().unwrap(),
        "complete the task",
    ]);
    let output = command.output().unwrap();
    assert_success(&output);

    let result: Value =
        serde_json::from_str(&std::fs::read_to_string(&output_file).unwrap()).unwrap();
    assert_eq!(result["state"], "ok");
    assert_eq!(result["agent_id"], "worker");
    assert_eq!(result["agent_fingerprint"].as_str().unwrap().len(), 64);
    assert_eq!(result["provider"], "openai");
    assert!(result["model"]
        .as_str()
        .is_some_and(|model| !model.is_empty()));
    let events = std::fs::read_to_string(root.path().join("events.jsonl")).unwrap();
    assert!(events.contains("complete the task"));
}

#[test]
fn failed_output_run_persists_resolved_provider_and_model() {
    let root = TempDir::new().unwrap();
    let output_file = root.path().join("result.json");
    let mut command = command(&root, "fail");
    command.args([
        "--no-subagents",
        "run",
        "--output-file",
        output_file.to_str().unwrap(),
        "complete the task",
    ]);
    let output = command.output().unwrap();
    assert_eq!(output.status.code(), Some(1));

    let result: Value =
        serde_json::from_str(&std::fs::read_to_string(&output_file).unwrap()).unwrap();
    assert_eq!(result["state"], "error");
    assert_eq!(result["provider"], "openai");
    assert_eq!(result["model"], "gpt-5.5");
    assert!(result["error"]
        .as_str()
        .unwrap()
        .contains("deterministic provider failure"));
}

#[test]
fn final_answer_is_the_only_stdout_content() {
    let root = TempDir::new().unwrap();
    let mut command = command(&root, "fixed");
    command
        .env(RESPONSE_ENV, "answer for a pipeline")
        .args(["run", "hello"]);
    let output = command.output().unwrap();

    assert_success(&output);
    assert_eq!(stdout(&output), "answer for a pipeline\n");
    assert!(output.stderr.is_empty());

    let ledger = rusqlite::Connection::open(root.path().join(".rho/usage.sqlite3")).unwrap();
    let request: (String, String, String) = ledger
        .query_row(
            "SELECT provider, model, purpose FROM usage_events",
            [],
            |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
        )
        .unwrap();
    assert_eq!(request, ("openai".into(), "gpt-5.5".into(), "agent".into()));
}

#[cfg(unix)]
#[test]
fn interrupt_reports_herdr_lifecycle_and_cleans_up_background_processes() {
    use std::{
        os::unix::net::UnixListener,
        sync::{Arc, Mutex},
        time::{Duration, Instant},
    };

    let root = TempDir::new().unwrap();
    let ready = root.path().join("process-ready");
    let leaked = root.path().join("process-leaked");
    let socket = root.path().join("herdr.sock");
    let requests = Arc::new(Mutex::new(Vec::new()));
    let server_requests = Arc::clone(&requests);
    let listener = UnixListener::bind(&socket).unwrap();
    let server = std::thread::spawn(move || {
        for _ in 0..3 {
            let (mut stream, _) = listener.accept().unwrap();
            let mut line = String::new();
            let mut reader = std::io::BufReader::new(stream.try_clone().unwrap());
            std::io::BufRead::read_line(&mut reader, &mut line).unwrap();
            server_requests
                .lock()
                .unwrap()
                .push(serde_json::from_str::<Value>(&line).unwrap());
            stream.write_all(b"{}\n").unwrap();
        }
    });

    let process_command = format!(
        "printf started > '{}'; sleep 5; printf leaked > '{}'",
        ready.display(),
        leaked.display()
    );
    let mut command = command(&root, "process-then-delay");
    command
        .env(COMMAND_ENV, process_command)
        .env("HERDR_ENV", "1")
        .env("HERDR_SOCKET_PATH", &socket)
        .env("HERDR_PANE_ID", "%fixture")
        .args(["run", "start background work"])
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    let child = command.spawn().unwrap();

    let deadline = Instant::now() + Duration::from_secs(5);
    while !ready.exists() && Instant::now() < deadline {
        std::thread::sleep(Duration::from_millis(20));
    }
    assert!(ready.exists(), "fixture process did not start");
    let signal_status = Command::new("kill")
        .args(["-INT", &child.id().to_string()])
        .status()
        .unwrap();
    assert!(signal_status.success());
    let output = child.wait_with_output().unwrap();
    assert_eq!(output.status.code(), Some(130));
    assert!(output.stdout.is_empty());
    assert!(stderr(&output).contains("interrupted by SIGINT"));

    server.join().unwrap();
    let methods = requests
        .lock()
        .unwrap()
        .iter()
        .map(|request| request["method"].as_str().unwrap().to_string())
        .collect::<Vec<_>>();
    assert_eq!(
        methods,
        [
            "pane.report_agent",
            "pane.report_agent",
            "pane.release_agent"
        ]
    );
    let states = requests
        .lock()
        .unwrap()
        .iter()
        .filter_map(|request| request["params"]["state"].as_str().map(str::to_string))
        .collect::<Vec<_>>();
    assert_eq!(states, ["working", "idle"]);

    std::thread::sleep(Duration::from_millis(300));
    assert!(!leaked.exists(), "background process survived rho shutdown");
}

fn run(root: &TempDir, mode: &str, args: &[&str], input: Option<&str>) -> Output {
    let mut command = command(root, mode);
    command.args(args);
    if input.is_some() {
        command.stdin(Stdio::piped());
    }
    let mut child = command.spawn().unwrap();
    if let Some(input) = input {
        child
            .stdin
            .take()
            .unwrap()
            .write_all(input.as_bytes())
            .unwrap();
    }
    child.wait_with_output().unwrap()
}

fn command(root: &TempDir, mode: &str) -> Command {
    let mut command = Command::new(env!("CARGO_BIN_EXE_rho"));
    command
        .current_dir(root.path())
        .env("HOME", root.path())
        .env("RHO_HOME", root.path().join(".rho"))
        .env(MODE_ENV, mode)
        .env_remove(RESPONSE_ENV)
        .env_remove(COMMAND_ENV)
        .env_remove("HERDR_ENV")
        .env_remove("HERDR_SOCKET_PATH")
        .env_remove("HERDR_PANE_ID")
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .arg("--config")
        .arg(root.path().join("config.toml"));
    command
}

fn inspection(output: &Output) -> Value {
    serde_json::from_str(stdout(output).trim()).unwrap()
}

fn user_prompt(output: &Output) -> String {
    let inspection = inspection(output);
    inspection["messages"].as_array().unwrap().last().unwrap()["User"][0]["Text"]
        .as_str()
        .unwrap()
        .to_string()
}

fn assert_success(output: &Output) {
    assert!(
        output.status.success(),
        "status: {}\nstdout: {}\nstderr: {}",
        output.status,
        stdout(output),
        stderr(output)
    );
}

fn stdout(output: &Output) -> &str {
    std::str::from_utf8(&output.stdout).unwrap()
}

fn stderr(output: &Output) -> &str {
    std::str::from_utf8(&output.stderr).unwrap()
}

fn shell_tool_name() -> &'static str {
    if cfg!(windows) {
        "powershell"
    } else {
        "bash"
    }
}