use std::path::Path;
use trusty_agents_common::agents::builder::compose_agent;
use trusty_agents_common::agents::builder_in_memory::{
build_in_memory_source_map, compose_agent_in_memory,
};
use trusty_agents_common::agents::metadata::{AgentMetadata, agent_metadata_from_str};
use super::config::{AgentConfig, AgentInfo, LlmParams, SystemPrompt, ToolsConfig};
pub fn load_md_agent(path: &Path) -> anyhow::Result<AgentConfig> {
let source_dir = path
.parent()
.ok_or_else(|| anyhow::anyhow!("agent file {} has no parent directory", path.display()))?;
let name = path
.file_stem()
.and_then(|s| s.to_str())
.ok_or_else(|| anyhow::anyhow!("agent file {} has no usable file stem", path.display()))?;
let composed = compose_agent(name, source_dir).map_err(|e| {
anyhow::anyhow!(
"failed to compose agent '{name}' from {}: {e}",
path.display()
)
})?;
let metadata = agent_metadata_from_str(&composed);
let body = extract_body(&composed);
Ok(project_to_agent_config(name, metadata, body))
}
pub(crate) fn project_embedded_md(default_name: &str, raw: &str) -> AgentConfig {
let metadata = agent_metadata_from_str(raw);
let body = extract_body(raw);
project_to_agent_config(default_name, metadata, body)
}
pub fn project_embedded_md_with_extends(name: &str) -> anyhow::Result<AgentConfig> {
let sources =
build_in_memory_source_map(crate::assets::EMBEDDED_TM_AGENT_SOURCES.iter().copied());
let composed = compose_agent_in_memory(name, &sources).map_err(|e| {
anyhow::anyhow!("failed to compose embedded tm-catalog agent '{name}': {e}")
})?;
let metadata = agent_metadata_from_str(&composed);
let body = extract_body(&composed);
Ok(project_to_agent_config(name, metadata, body))
}
pub(crate) fn extract_body(composed: &str) -> String {
let mut lines = composed.lines();
match lines.next() {
Some(first) if first.trim() == "---" => {}
_ => return composed.trim().to_string(),
}
let mut in_frontmatter = true;
let mut body_lines: Vec<&str> = Vec::new();
for line in lines {
if in_frontmatter {
if line.trim() == "---" {
in_frontmatter = false;
}
continue;
}
body_lines.push(line);
}
body_lines.join("\n").trim().to_string()
}
pub(crate) fn project_to_agent_config(
default_name: &str,
meta: AgentMetadata,
body: String,
) -> AgentConfig {
AgentConfig {
agent: AgentInfo {
name: meta.name.unwrap_or_else(|| default_name.to_string()),
role: meta.role,
model: meta.model,
description: meta.description,
},
llm: LlmParams {
temperature: None,
max_tokens: meta.max_tokens,
model_override: None,
},
system_prompt: SystemPrompt {
content: body,
append_skills: Vec::new(),
},
tools: Some(ToolsConfig {
allowed: meta.tools,
}),
runner: None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn load_md_agent_base_case() {
let tmp = tempfile::tempdir().expect("tempdir");
std::fs::write(
tmp.path().join("solo.md"),
"---\nname: solo\nrole: engineer\ndescription: A lone agent\nmodel: sonnet\nmax_tokens: 4096\ntools: [read_file, grep]\n---\n\nYou are a solo agent.\n",
)
.expect("write");
let cfg = load_md_agent(&tmp.path().join("solo.md")).expect("load");
assert_eq!(cfg.agent.name, "solo");
assert_eq!(cfg.agent.role.as_deref(), Some("engineer"));
assert_eq!(cfg.agent.description.as_deref(), Some("A lone agent"));
assert_eq!(cfg.agent.model.as_deref(), Some("sonnet"));
assert_eq!(cfg.llm.max_tokens, Some(4096));
assert_eq!(cfg.system_prompt.content, "You are a solo agent.");
assert_eq!(
cfg.tools.and_then(|t| t.allowed),
Some(vec!["read_file".to_string(), "grep".to_string()])
);
}
#[test]
fn tools_projection_absent_is_none() {
let tmp = tempfile::tempdir().expect("tempdir");
std::fs::write(
tmp.path().join("a.md"),
"---\nname: a\nrole: engineer\n---\n\nBody.\n",
)
.expect("write");
let cfg = load_md_agent(&tmp.path().join("a.md")).expect("load");
assert_eq!(cfg.tools.and_then(|t| t.allowed), None);
}
#[test]
fn tools_projection_empty_list_is_deny_all() {
let tmp = tempfile::tempdir().expect("tempdir");
std::fs::write(
tmp.path().join("a.md"),
"---\nname: a\nrole: engineer\ntools: []\n---\n\nBody.\n",
)
.expect("write");
let cfg = load_md_agent(&tmp.path().join("a.md")).expect("load");
assert_eq!(cfg.tools.and_then(|t| t.allowed), Some(vec![]));
}
#[test]
fn tools_projection_list_is_allowlist() {
let tmp = tempfile::tempdir().expect("tempdir");
std::fs::write(
tmp.path().join("a.md"),
"---\nname: a\nrole: engineer\ntools: [read_file, grep]\n---\n\nBody.\n",
)
.expect("write");
let cfg = load_md_agent(&tmp.path().join("a.md")).expect("load");
assert_eq!(
cfg.tools.and_then(|t| t.allowed),
Some(vec!["read_file".to_string(), "grep".to_string()])
);
}
#[test]
fn hr1_initial_prompt_not_leaked_into_body() {
let tmp = tempfile::tempdir().expect("tempdir");
std::fs::write(
tmp.path().join("eng.md"),
"---\nname: eng\nrole: engineer\n---\n\nYou write Rust code.\n",
)
.expect("write");
let cfg = load_md_agent(&tmp.path().join("eng.md")).expect("load");
assert_eq!(
cfg.system_prompt.content, "You write Rust code.",
"HR-1's role-derived initialPrompt must not leak into the body"
);
assert!(
!cfg.system_prompt.content.contains("Begin implementation"),
"HR-1's engineer-role initialPrompt text must not appear anywhere in the body"
);
}
#[test]
fn load_md_agent_with_extends_resolves_chain() {
let tmp = tempfile::tempdir().expect("tempdir");
std::fs::write(
tmp.path().join("base-x.md"),
"---\nname: base-x\nmax_tokens: 1000\n---\n\nBase instructions.\n",
)
.expect("write");
std::fs::write(
tmp.path().join("child.md"),
"---\nname: child\nextends: base-x\nmax_tokens: 2000\n---\n\nChild instructions.\n",
)
.expect("write");
let cfg = load_md_agent(&tmp.path().join("child.md")).expect("load");
assert_eq!(cfg.agent.name, "child");
assert_eq!(cfg.llm.max_tokens, Some(2000), "child max_tokens wins");
assert!(cfg.system_prompt.content.contains("Base instructions."));
assert!(cfg.system_prompt.content.contains("Child instructions."));
}
#[test]
fn load_md_agent_missing_file_errors() {
let result = load_md_agent(Path::new("/nonexistent/agents/dir/ghost.md"));
assert!(result.is_err());
}
#[test]
fn full_fidelity_md_fixture_projects_every_field() {
let tmp = tempfile::tempdir().expect("tempdir");
std::fs::write(
tmp.path().join("twin.md"),
"---\nname: twin\nrole: engineer\nmodel: sonnet\nmax_tokens: 8192\ntools: [read_file, grep]\n---\n\nYou are a twin agent.\n",
)
.expect("write md");
let cfg = load_md_agent(&tmp.path().join("twin.md")).expect("load md");
assert_eq!(cfg.agent.name, "twin");
assert_eq!(cfg.agent.role.as_deref(), Some("engineer"));
assert_eq!(cfg.agent.model.as_deref(), Some("sonnet"));
assert_eq!(cfg.llm.max_tokens, Some(8192));
assert_eq!(
cfg.tools.and_then(|t| t.allowed),
Some(vec!["read_file".to_string(), "grep".to_string()])
);
assert_eq!(cfg.system_prompt.content, "You are a twin agent.");
}
#[test]
fn interior_horizontal_rule_survives_in_body() {
let tmp = tempfile::tempdir().expect("tempdir");
std::fs::write(
tmp.path().join("hr.md"),
"---\nname: hr\nrole: engineer\n---\n\nFirst paragraph.\n\n---\n\nSecond paragraph.\n",
)
.expect("write");
let cfg = load_md_agent(&tmp.path().join("hr.md")).expect("load");
assert!(
cfg.system_prompt
.content
.lines()
.any(|line| line.trim() == "---"),
"interior horizontal rule must survive verbatim as its own line; got: {:?}",
cfg.system_prompt.content
);
assert!(cfg.system_prompt.content.contains("First paragraph."));
assert!(cfg.system_prompt.content.contains("Second paragraph."));
}
#[test]
fn frontmatter_only_agent_has_empty_body() {
let tmp = tempfile::tempdir().expect("tempdir");
std::fs::write(
tmp.path().join("empty.md"),
"---\nname: empty\nrole: engineer\n---\n",
)
.expect("write");
let cfg = load_md_agent(&tmp.path().join("empty.md")).expect("load");
assert_eq!(
cfg.system_prompt.content, "",
"frontmatter-only agent must project to an empty body, got: {:?}",
cfg.system_prompt.content
);
}
#[test]
fn project_embedded_md_with_extends_resolves_rust_engineer_from_base_engineer() {
let cfg = project_embedded_md_with_extends("rust-engineer").expect("compose rust-engineer");
assert_eq!(cfg.agent.name, "rust-engineer");
assert_eq!(cfg.agent.role.as_deref(), Some("engineer"));
assert_eq!(cfg.agent.model.as_deref(), Some("sonnet"));
assert!(
cfg.system_prompt
.content
.contains("Foundation for all trusty-mpm agents"),
"composed body must include BASE-AGENT tier content"
);
assert!(
cfg.system_prompt
.content
.contains("Foundation for all engineer agents"),
"composed body must include BASE-ENGINEER tier content"
);
assert!(
cfg.system_prompt.content.contains("toolchains-rust-core"),
"composed body must include rust-engineer's own content"
);
}
#[test]
fn project_embedded_md_with_extends_unknown_name_errors() {
let result = project_embedded_md_with_extends("does-not-exist");
assert!(result.is_err(), "unknown embedded agent name must error");
}
}