rho-coding-agent 3.13.0

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

use super::{reopened, Instructions};
use crate::{
    agent::{AgentDefinition, PromptPolicy},
    app::subagent_messaging::CHILD_COMMUNICATION_CONTRACT,
    prompt::agent_instructions::section,
    session::SavedAgent,
};

/// Where a saved session's instructions come from, in [`reopened`].
#[derive(Debug)]
enum Saved {
    /// Its header keeps them.
    Kept,
    /// Its header keeps none, and it was saved under the current definition.
    Unchanged,
    /// Its header keeps none, and its saved prompt holds them.
    InItsPrompt,
    /// As [`Self::InItsPrompt`], a child's, whose prompt ends in the child
    /// contract after them.
    InAChildsPrompt,
    /// Its header keeps none, and its saved prompt holds none.
    Nowhere,
    /// Its header keeps none, and its saved prompt could not be read.
    Unreadable,
    /// Its header keeps none, and they are not the session's: the root a
    /// session `/agent:` rebound was rebound from.
    LaunchedFrom,
    /// It was saved as another agent.
    AnotherAgent,
}

// Covers: a session reopens with its agent's current definition (tools,
// model, runtime) and the instructions it was created with: those its
// header keeps, else those its saved prompt holds when the definition
// changed, without a child's contract, else the current ones; a prompt it
// cannot read fails the reopen; the root of a rebound session never reads
// the child's prompt as its own; never as another agent. A miss runs an old
// conversation on instructions it was never given, or as an agent it was
// not saved as.
// Owner: agent reopen.
#[test]
fn a_session_reopens_with_the_instructions_it_was_created_with() {
    let current = definition("lead", "[read_file, write]", "Lead now.");
    let earlier = definition("lead", "[read_file]", "Lead then.");
    let with_prompt = |prompt: &str| AgentDefinition {
        prompt: PromptPolicy::Extend(prompt.into()),
        ..current.clone()
    };
    let cases = [
        (Saved::Kept, Ok(with_prompt("Lead then."))),
        (Saved::Unchanged, Ok(current.clone())),
        (Saved::InItsPrompt, Ok(with_prompt("Lead then."))),
        (Saved::InAChildsPrompt, Ok(with_prompt("Lead then."))),
        (Saved::Nowhere, Ok(current.clone())),
        (Saved::Unreadable, Err(())),
        (Saved::LaunchedFrom, Ok(current.clone())),
        (Saved::AnotherAgent, Err(())),
    ];
    for (saved, expected) in cases {
        let unkept = |definition: &AgentDefinition| SavedAgent {
            prompt: None,
            ..saved_as(definition)
        };
        let (agent, prompt): (SavedAgent, anyhow::Result<Option<String>>) = match saved {
            Saved::Kept => (saved_as(&earlier), Ok(None)),
            Saved::Unchanged => (unkept(&current), Ok(Some(rendered("Ignored.")))),
            Saved::InItsPrompt => (unkept(&earlier), Ok(Some(rendered("Lead then.")))),
            Saved::InAChildsPrompt => (
                unkept(&earlier),
                Ok(Some(format!(
                    "{}\n\n{CHILD_COMMUNICATION_CONTRACT}",
                    rendered("Lead then.")
                ))),
            ),
            Saved::Nowhere => (unkept(&earlier), Ok(Some("Base.".into()))),
            Saved::Unreadable => (unkept(&earlier), Err(anyhow::anyhow!("corrupt"))),
            Saved::LaunchedFrom => (unkept(&earlier), Ok(Some(rendered("Child.")))),
            Saved::AnotherAgent => (
                saved_as(&definition("worker", "[read_file]", "Work.")),
                Ok(None),
            ),
        };
        let read = || match &prompt {
            Ok(prompt) => Ok(prompt.clone()),
            Err(error) => Err(anyhow::anyhow!("{error}")),
        };
        let instructions = match saved {
            Saved::LaunchedFrom => Instructions::NotRendered,
            _ => Instructions::Rendered(&read),
        };

        let reopened = reopened(&agent, &current, instructions).map_err(|_| ());

        assert_eq!(reopened, expected, "{saved:?}");
    }
}

/// What a session created as `definition` saves of it.
fn saved_as(definition: &AgentDefinition) -> SavedAgent {
    SavedAgent {
        id: definition.id.as_str().to_owned(),
        fingerprint: definition.fingerprint().to_string(),
        prompt: Some(definition.prompt.clone()),
    }
}

/// A system prompt that renders `instructions` as its agent's.
fn rendered(instructions: &str) -> String {
    format!("Base.{}", section(instructions))
}

/// 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()
}