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,
};
#[derive(Debug)]
enum Saved {
Kept,
Unchanged,
InItsPrompt,
InAChildsPrompt,
Nowhere,
Unreadable,
LaunchedFrom,
AnotherAgent,
}
#[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(¤t), 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, ¤t, instructions).map_err(|_| ());
assert_eq!(reopened, expected, "{saved:?}");
}
}
fn saved_as(definition: &AgentDefinition) -> SavedAgent {
SavedAgent {
id: definition.id.as_str().to_owned(),
fingerprint: definition.fingerprint().to_string(),
prompt: Some(definition.prompt.clone()),
}
}
fn rendered(instructions: &str) -> String {
format!("Base.{}", section(instructions))
}
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()
}