rho-coding-agent 3.10.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
use pretty_assertions::assert_eq;
use serde_json::{json, Value as Json};

use super::*;

/// Two hooks with comments before, inside, and after their tables, and
/// formatting no writer would choose.
const TWO_HOOKS: &str = r#"# My hooks.
version = 1

# Logs every tool call.
[[hook]]
id = "log"
on = "after_tool_use"
# How long it may run.
timeout = "1s" # generous
command = ["logger"]
env = ["TOKEN"]

# Notifies me.
[[hook]]
id = "notify"
on = "run_completed"
command = [ "notify-send", "done" ]
timeout = "2s"
"#;

const NOTIFY: &str = r#"
# Notifies me.
[[hook]]
id = "notify"
on = "run_completed"
command = [ "notify-send", "done" ]
timeout = "2s"
"#;

/// The first hook of [`TWO_HOOKS`] after a put that changes its `timeout`,
/// drops its `env`, and adds `tools`, with the text before it.
const LOG_EDITED: &str = r#"# My hooks.
version = 1

# Logs every tool call.
[[hook]]
id = "log"
on = "after_tool_use"
# How long it may run.
timeout = "5s" # generous
command = ["logger"]
tools = ["bash"]
"#;

fn put(id: &str, value: Json) -> HookConfigChange {
    HookConfigChange::Put {
        id: id.to_owned(),
        value,
    }
}

fn remove(id: &str) -> HookConfigChange {
    HookConfigChange::Remove { id: id.to_owned() }
}

fn logger() -> Json {
    json!({"on": "after_tool_use", "command": ["logger"], "timeout": "1s"})
}

// Covers: a put or remove of one hook rewrites only that hook: a new file
// starts at version 1, an existing hook keeps its place, its comments, and
// the keys it keeps as written, the other hooks stay byte for byte, a put
// writes `enabled` only when false, and a change the file cannot take is
// refused rather than half applied.
// Owner: hooks file editing.
#[test]
fn a_change_rewrites_only_the_hook_it_names() {
    struct Case {
        name: &'static str,
        file: Option<&'static str>,
        changes: Vec<HookConfigChange>,
        expected: Result<String, HookEditError>,
    }
    let new_file = "version = 1\n\n[[hook]]\nid = \"log\"\non = \"after_tool_use\"\ncommand = [\"logger\"]\ntimeout = \"1s\"\n";
    let cases = [
        Case {
            name: "a put into an absent file",
            file: None,
            changes: vec![put("log", logger())],
            expected: Ok(new_file.to_owned()),
        },
        Case {
            name: "a put into an empty file",
            file: Some(""),
            changes: vec![put("log", logger())],
            expected: Ok(new_file.to_owned()),
        },
        Case {
            name: "a put over a hook the file holds",
            file: Some(TWO_HOOKS),
            changes: vec![put(
                "log",
                json!({
                    "on": "after_tool_use",
                    "command": ["logger"],
                    "timeout": "5s",
                    "tools": ["bash"],
                }),
            )],
            expected: Ok(format!("{LOG_EDITED}{NOTIFY}")),
        },
        Case {
            name: "a put of a new hook",
            file: Some(TWO_HOOKS),
            changes: vec![put(
                "fmt",
                json!({"on": "after_tool_use", "command": ["fmt", "--all"], "timeout": "1s", "enabled": false}),
            )],
            expected: Ok(format!(
                "{TWO_HOOKS}\n[[hook]]\nid = \"fmt\"\non = \"after_tool_use\"\ncommand = [\"fmt\", \"--all\"]\ntimeout = \"1s\"\nenabled = false\n"
            )),
        },
        Case {
            name: "a put that turns a hook back on leaves `enabled` out",
            file: Some("version = 1\n\n[[hook]]\nid = \"log\"\non = \"after_tool_use\"\ncommand = [\"logger\"]\ntimeout = \"1s\"\nenabled = false\n"),
            changes: vec![put(
                "log",
                json!({"on": "after_tool_use", "command": ["logger"], "timeout": "1s", "enabled": true}),
            )],
            expected: Ok(new_file.to_owned()),
        },
        Case {
            name: "a remove",
            file: Some(TWO_HOOKS),
            changes: vec![remove("log")],
            expected: Ok(format!("# My hooks.\nversion = 1\n{NOTIFY}")),
        },
        Case {
            name: "a remove of the last hook",
            file: Some(new_file),
            changes: vec![remove("log")],
            expected: Ok("version = 1\n".to_owned()),
        },
        Case {
            name: "a remove of a hook the file lacks",
            file: Some(TWO_HOOKS),
            changes: vec![put("fmt", logger()), remove("nope")],
            expected: Err(HookEditError::Missing { id: "nope".into() }),
        },
        Case {
            name: "a put whose value holds its id",
            file: Some(TWO_HOOKS),
            changes: vec![put("log", json!({"id": "log", "on": "after_tool_use"}))],
            expected: Err(HookEditError::HoldsId { id: "log".into() }),
        },
        Case {
            name: "a put whose value is not a table",
            file: Some(TWO_HOOKS),
            changes: vec![put("log", json!(["logger"]))],
            expected: Err(HookEditError::NotTable { id: "log".into() }),
        },
        Case {
            name: "a put with a field TOML cannot hold",
            file: Some(TWO_HOOKS),
            changes: vec![put("log", json!({"on": "after_tool_use", "timeout": null}))],
            expected: Err(HookEditError::Field {
                id: "log".into(),
                field: "timeout".into(),
                problem: "must not be null".into(),
            }),
        },
    ];

    for case in cases {
        assert_eq!(
            apply_hook_changes(case.file, &case.changes),
            case.expected,
            "{}",
            case.name
        );
    }
}

// Covers: a read gives each hook by its id with its other keys as the file
// holds them, in file order, and refuses only text whose hooks cannot be
// told apart, which a client must send the person to fix by hand.
// Owner: hooks file editing.
#[test]
fn a_read_gives_each_hook_by_id_or_refuses_a_file_it_cannot_split() {
    // Each hook's id and its value as JSON text, which keeps key order; `Err`
    // when the file is refused as invalid.
    type Read<'a> = Result<Vec<(&'a str, &'a str)>, ()>;
    let cases: [(&str, &str, Read); 5] = [
        (
            "two hooks",
            TWO_HOOKS,
            Ok(vec![
                (
                    "log",
                    r#"{"on":"after_tool_use","timeout":"1s","command":["logger"],"env":["TOKEN"]}"#,
                ),
                (
                    "notify",
                    r#"{"on":"run_completed","command":["notify-send","done"],"timeout":"2s"}"#,
                ),
            ]),
        ),
        ("no hooks", "version = 1\n", Ok(vec![])),
        ("not TOML", "version = \n", Err(())),
        ("hook is not tables", "version = 1\nhook = 1\n", Err(())),
        (
            "a hook without an id",
            "version = 1\n[[hook]]\non = \"run_completed\"\n",
            Err(()),
        ),
    ];

    for (name, file, expected) in cases {
        let read = hook_entries(file)
            .map(|entries| {
                entries
                    .into_iter()
                    .map(|entry| (entry.id, serde_json::to_string(&entry.value).unwrap()))
                    .collect::<Vec<_>>()
            })
            .map_err(|error| match error {
                HookEditError::FileInvalid(_) => (),
                error => panic!("{name}: refused as {error:?}"),
            });
        let expected = expected.map(|hooks| {
            hooks
                .into_iter()
                .map(|(id, value)| (id.to_owned(), value.to_owned()))
                .collect::<Vec<_>>()
        });
        assert_eq!(read, expected, "{name}");
    }
}