rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
use std::fs;

use pretty_assertions::assert_eq;
use rho_providers::model::{Message, ModelIdentity};

use super::{
    super::{persistence::MIN_SESSION_VERSION, tree::SessionTree, Session, SESSION_VERSION},
    SavedAgent, SavedRoot,
};
use crate::agent::{AgentDefinition, PromptPolicy};

// Covers: fresh delegated rebinding commits its identity, the root's it
// replaces, and initial state together for every supported header, survives
// resume and later appends, and cannot rewrite history.
// Owner: session agent identity.
#[test]
fn fresh_agent_identity_rewrite_preserves_append_and_resume() {
    for version in MIN_SESSION_VERSION..=SESSION_VERSION {
        let root = tempfile::tempdir().unwrap();
        let cwd = tempfile::tempdir().unwrap();
        let session =
            Session::create_in_root_with_agent(root.path(), cwd.path(), "root", "old").unwrap();
        // An older-format session with no conversation can still receive its
        // first delegated binding. Its new snapshot must use a readable format.
        let mut header = super::read_header(&session.path).unwrap();
        let super::SessionEntry::Session {
            version: stored_version,
            ..
        } = &mut header
        else {
            panic!("expected session header");
        };
        *stored_version = version;
        fs::write(
            &session.path,
            format!("{}\n", serde_json::to_string(&header).unwrap()),
        )
        .unwrap();
        // Prime the tree cache before replacing the header.
        session.cache_loaded_tree(SessionTree::load(&session.path).unwrap());
        assert_eq!(session.delegated_agent_id().unwrap(), None);
        let snapshot = session
            .snapshot_for_resume(
                ModelIdentity::new("test", "test", "selected"),
                "cache".into(),
            )
            .unwrap()
            .with_metadata("test-selection", "selected");
        let child = SavedAgent {
            id: "restricted-child".into(),
            fingerprint: "new-fingerprint".into(),
            prompt: Some(PromptPolicy::Extend("Restrict.".into())),
        };
        session
            .rebind_fresh_delegated_agent(&child, Some(&snapshot))
            .unwrap();
        let expected_identity = Some(child.clone());
        // The root moves aside, so a reload can cap the child at its tools.
        let expected_root = Some(SavedRoot::LaunchedFrom(SavedAgent::named("root", "old")));
        assert_eq!(session.stored_agent_identity().unwrap(), expected_identity);
        assert_eq!(session.root_agent().unwrap(), expected_root);
        assert_eq!(
            session.delegated_agent_id().unwrap(),
            Some("restricted-child".into())
        );
        assert_eq!(
            session.session_metadata("test-selection").unwrap(),
            Some("selected".into())
        );
        // A restart before any turn checkpoint must see both binding halves.
        let (reopened, _) =
            Session::open_by_id_in_root(root.path(), cwd.path(), session.id()).unwrap();
        assert_eq!(reopened.stored_agent_identity().unwrap(), expected_identity);
        assert_eq!(reopened.root_agent().unwrap(), expected_root);
        assert_eq!(
            reopened.session_metadata("test-selection").unwrap(),
            Some("selected".into())
        );
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            assert_eq!(
                fs::metadata(&session.path).unwrap().permissions().mode() & 0o777,
                0o600
            );
        }

        let message = Message::user_text("retained task");
        session.append_message(&message).unwrap();
        let before = fs::read(&session.path).unwrap();
        let root_again = SavedAgent::named("root", "old");
        assert!(session
            .rebind_fresh_delegated_agent(&root_again, /*initial_snapshot*/ None)
            .is_err());
        assert_eq!(fs::read(&session.path).unwrap(), before);
        let (reopened, history) =
            Session::open_by_id_in_root(root.path(), cwd.path(), session.id()).unwrap();
        assert_eq!(reopened.stored_agent_identity().unwrap(), expected_identity);
        assert_eq!(
            reopened.delegated_agent_id().unwrap(),
            Some("restricted-child".into())
        );
        let display: Vec<_> = reopened
            .active_display_history()
            .unwrap()
            .into_iter()
            .map(|row| row.message)
            .collect();
        assert_eq!((history, display), (vec![message.clone()], vec![message]));
    }
}

// Covers: a launch that names an agent resumes a session saved as that
// agent, whatever definition it was saved under, and refuses a session
// saved as another agent or with no stored identity (#1661).
// Owner: session agent identity (launch check).
#[test]
fn a_launch_naming_an_agent_resumes_only_its_sessions() {
    let root = tempfile::tempdir().unwrap();
    let cwd = tempfile::tempdir().unwrap();
    let lead = definition("lead", "[read_file]", "Lead.");
    let saved_as = |id: &str, fingerprint: &str| {
        let session =
            Session::create_in_root_with_agent(root.path(), cwd.path(), id, fingerprint).unwrap();
        super::validate_launch(&session.path, &lead).is_ok()
    };
    let unnamed = Session::create_in_root(root.path(), cwd.path()).unwrap();

    assert_eq!(
        [
            saved_as("lead", &lead.fingerprint().to_string()),
            saved_as("lead", &"f".repeat(64)),
            saved_as("worker", &lead.fingerprint().to_string()),
            super::validate_launch(&unnamed.path, &lead).is_ok(),
        ],
        [true, true, false, false]
    );
}

// Covers: a session created as an agent saves that agent's instructions on
// its header, which a reopen runs, since a prompt that replaces Rho's
// cannot be read back from the saved prompt. A miss reopens such a session
// on the agent's current instructions after they change.
// Owner: session agent identity (creation).
#[test]
fn a_created_session_saves_its_agents_instructions() {
    let root = tempfile::tempdir().unwrap();
    let cwd = tempfile::tempdir().unwrap();
    let agent = SavedAgent {
        prompt: Some(PromptPolicy::Replace("Archive.".into())),
        ..SavedAgent::named("archivist", "f")
    };
    let session = Session::create_with_id_in_root(
        root.path(),
        cwd.path(),
        "s",
        Some(&agent),
        crate::session::SessionOrigin::Interactive.into(),
    )
    .unwrap();

    assert_eq!(session.stored_agent_identity().unwrap(), Some(agent));
}

// Covers: the header keeps an agent's instructions as `{"extend": text}` or
// `{"replace": text}`, so a renamed variant cannot silently change what
// older files say, and a header without them still reads.
// Owner: session agent identity (header format).
#[test]
fn a_header_keeps_instructions_in_its_saved_shape() {
    let header = |prompt: &str| {
        format!(
            r#"{{"type":"session","version":{SESSION_VERSION},"id":"s","timestamp":"0","cwd":"/w","agent_id":"lead","agent_fingerprint":"f"{prompt}}}"#
        )
    };
    let cases = [
        (
            r#","agent_prompt":{"extend":"Lead."}"#,
            Some(PromptPolicy::Extend("Lead.".into())),
        ),
        (
            r#","agent_prompt":{"replace":"Lead."}"#,
            Some(PromptPolicy::Replace("Lead.".into())),
        ),
        ("", None),
    ];
    for (prompt, expected) in cases {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("session.jsonl");
        fs::write(&path, format!("{}\n", header(prompt))).unwrap();

        let saved = super::read_agent_identity(&path).unwrap().unwrap();

        assert_eq!(saved.prompt, expected, "{prompt}");
    }
}

/// Agent `id`'s definition, with `tools` and instructions `text`.
fn definition(id: &str, tools: &str, text: &str) -> AgentDefinition {
    crate::agent::parse_definition(
        std::path::Path::new(&format!("{id}.md")),
        id,
        &format!("---\ndescription: {id}\ntools: {tools}\n---\n{text}\n"),
    )
    .unwrap()
}