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 composed =
super::skill_refs::resolve_skill_refs(&composed, &super::skill_refs::user_skill_refs_dir());
let metadata = agent_metadata_from_str(&composed);
let body = extract_body(&composed);
let mut config = project_to_agent_config(name, metadata.clone(), body);
super::claude_tools::apply_claude_tools_fallback(&mut config, &metadata);
let raw = std::fs::read_to_string(path)
.map_err(|e| anyhow::anyhow!("failed to read agent file {}: {e}", path.display()))?;
config.permissions = crate::permissions::parse_permissions(&path.display().to_string(), &raw)?;
if config.permissions.is_none() {
config.permissions = deployed_roster_permissions(name, &raw)?;
}
Ok(config)
}
fn deployed_roster_permissions(
name: &str,
raw: &str,
) -> anyhow::Result<Option<crate::permissions::PermissionMap>> {
if agent_metadata_from_str(raw).provenance
!= Some(trusty_agents_common::agents::provenance::Provenance::FrameworkOwned)
{
return Ok(None);
}
let Some(md) = crate::assets::content::load_direct_agent(name)? else {
return Ok(None);
};
Ok(crate::permissions::parse_permissions(name, &md)?)
}
pub(crate) fn project_embedded_md(default_name: &str, raw: &str) -> anyhow::Result<AgentConfig> {
let metadata = agent_metadata_from_str(raw);
let body = extract_body(raw);
let mut config = project_to_agent_config(default_name, metadata, body);
config.permissions =
crate::permissions::parse_permissions(&format!("embedded agent '{default_name}'"), raw)?;
Ok(config)
}
pub fn project_embedded_md_with_extends(name: &str) -> anyhow::Result<AgentConfig> {
project_embedded_md_with_extends_at(name, &super::skill_refs::user_skill_refs_dir())
}
pub fn project_embedded_md_with_extends_at(
name: &str,
skill_refs_root: &Path,
) -> anyhow::Result<AgentConfig> {
let catalog = crate::assets::load_tm_agent_sources()?;
project_embedded_md_with_extends_from(name, &catalog, skill_refs_root)
}
pub(crate) fn project_embedded_md_with_extends_from(
name: &str,
catalog: &[(String, String)],
skill_refs_root: &Path,
) -> anyhow::Result<AgentConfig> {
let entries: Vec<(&str, &str)> = catalog
.iter()
.map(|(file, md)| (file.as_str(), md.as_str()))
.collect();
project_in_memory_catalog(name, &entries, skill_refs_root)
}
fn project_in_memory_catalog(
name: &str,
entries: &[(&str, &str)],
skill_refs_root: &Path,
) -> anyhow::Result<AgentConfig> {
let sources = build_in_memory_source_map(entries.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 composed = super::skill_refs::resolve_skill_refs(&composed, skill_refs_root);
let metadata = agent_metadata_from_str(&composed);
let body = extract_body(&composed);
let mut config = project_to_agent_config(name, metadata, body);
let own = own_catalog_source(name, entries).ok_or_else(|| {
anyhow::anyhow!("embedded tm-catalog agent '{name}' composed but has no source entry")
})?;
config.permissions =
crate::permissions::parse_permissions(&format!("embedded tm-catalog agent '{name}'"), own)?;
Ok(config)
}
fn own_catalog_source<'a>(name: &str, entries: &[(&'a str, &'a str)]) -> Option<&'a str> {
fn key(s: &str) -> String {
let lower = s.to_lowercase();
lower.strip_suffix(".md").unwrap_or(&lower).to_string()
}
let wanted = key(name);
entries
.iter()
.rev()
.find(|(file, _)| key(file) == wanted)
.map(|(_, md)| *md)
}
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: meta.skills,
},
tools: Some(ToolsConfig {
allowed: meta.tcode_tools,
}),
runner: None,
permissions: 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\ntcode_tools: [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\ntcode_tools: []\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\ntcode_tools: [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\ntcode_tools: [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("# Rust Engineer"),
"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");
}
#[tokio::test]
async fn embedded_agent_skill_pointers_open_with_read_file() {
use crate::tools::ReadFileTool;
use crate::tools::traits::ToolExecutor;
use trusty_agents_common::agents::skill_root::SKILLS_ROOT_PLACEHOLDER;
let refs = tempfile::tempdir().expect("tempdir");
let refs_root = refs.path().join("skill-refs");
let cfg = project_embedded_md_with_extends_at("rust-engineer", &refs_root)
.expect("compose rust-engineer");
let body = &cfg.system_prompt.content;
assert!(
!body.contains(SKILLS_ROOT_PLACEHOLDER),
"raw placeholder leaked"
);
let project = tempfile::tempdir().expect("project");
let scratch = tempfile::tempdir().expect("projectless scratch");
for root in [project.path(), scratch.path()] {
let tool = ReadFileTool::new(root).with_skill_refs(&refs_root);
for (relative, content) in crate::agents::skill_refs::tests::test_refs().iter() {
let pointer = refs_root.join(relative).display().to_string();
assert!(body.contains(&format!("Read `{pointer}`")), "{pointer}");
let out = tool.execute(serde_json::json!({ "path": pointer })).await;
assert!(!out.is_error(), "{pointer}: {}", out.content());
assert_eq!(out.content(), content);
}
}
assert!(
!refs_root.exists(),
"compose and read must not write the refs dir"
);
}
#[cfg(unix)]
#[test]
fn embedded_agent_composes_when_refs_dir_is_unwritable() {
use std::os::unix::fs::PermissionsExt;
let home = tempfile::tempdir().expect("tempdir");
std::fs::set_permissions(home.path(), std::fs::Permissions::from_mode(0o555))
.expect("chmod");
let refs_root = home.path().join(".trusty-code").join("skill-refs");
let composed = project_embedded_md_with_extends_at("rust-engineer", &refs_root);
std::fs::set_permissions(home.path(), std::fs::Permissions::from_mode(0o755))
.expect("chmod back");
let cfg = composed.expect("an unwritable refs dir must not drop the agent");
assert!(cfg.system_prompt.content.contains(&format!(
"{}/self-improvement-loop/SKILL.md",
refs_root.display()
)));
}
#[test]
fn embedded_agent_composes_when_refs_dir_is_relative() {
use trusty_agents_common::agents::skill_root::SKILLS_ROOT_PLACEHOLDER;
let cfg = project_embedded_md_with_extends_at(
"rust-engineer",
Path::new(".trusty-code/skill-refs"),
)
.expect("a relative refs dir must not drop the agent");
assert!(cfg.system_prompt.content.contains(SKILLS_ROOT_PLACEHOLDER));
}
#[test]
fn permissions_block_projects_onto_agent_config() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("solo.md");
std::fs::write(
&path,
"---\nname: solo\nrole: engineer\npermissions:\n read_file: allow\n bash:\n \"rm *\": deny\n---\n\nBody.\n",
)
.expect("write");
let cfg = load_md_agent(&path).expect("loads");
assert_eq!(
cfg.permissions
.expect("the block must reach the config")
.len(),
2
);
}
#[test]
fn malformed_permissions_block_fails_the_load() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("broken.md");
std::fs::write(
&path,
"---\nname: broken\nrole: engineer\npermissions:\n bash: allowed\n---\n\nBody.\n",
)
.expect("write");
let err = load_md_agent(&path).expect_err("a typo'd decision must fail the load");
let text = err.to_string();
assert!(text.contains("broken.md"), "must name the file: {text}");
assert!(text.contains("allowed"), "must quote the value: {text}");
}
const PERMISSIONS_MD: &str = "---\nname: solo\nrole: engineer\npermissions:\n read_file: allow\n bash:\n \"rm *\": deny\n---\n\nBody.\n";
const MALFORMED_PERMISSIONS_MD: &str =
"---\nname: broken\nrole: engineer\npermissions:\n bash: allowed\n---\n\nBody.\n";
fn permissions_catalog(child_md: &'static str) -> [(&'static str, &'static str); 3] {
[
(
"BASE-FIXTURE.md",
"---\nname: base-fixture\nrole: engineer\npermissions:\n bash: deny\n---\n\nBase.\n",
),
("child.md", child_md),
(
"heir.md",
"---\nname: heir\nextends: base-fixture\n---\n\nHeir.\n",
),
]
}
#[test]
fn embedded_permissions_block_projects_onto_agent_config() {
let cfg = project_embedded_md("solo", PERMISSIONS_MD).expect("loads");
assert_eq!(
cfg.permissions
.expect("the block must reach the config")
.len(),
2
);
}
#[test]
fn embedded_extends_permissions_block_projects_onto_agent_config() {
let catalog = permissions_catalog(
"---\nname: child\nextends: base-fixture\npermissions:\n read_file: allow\n bash:\n \"rm *\": deny\n---\n\nChild.\n",
);
let refs = Path::new("unused-skill-refs");
let child = project_in_memory_catalog("child", &catalog, refs).expect("child loads");
assert_eq!(
child
.permissions
.expect("the block must reach the config")
.len(),
2
);
let heir = project_in_memory_catalog("heir", &catalog, refs).expect("heir loads");
assert!(heir.permissions.is_none(), "a base block is not inherited");
}
#[test]
fn malformed_embedded_permissions_block_fails_the_load() {
let err = project_embedded_md("broken", MALFORMED_PERMISSIONS_MD)
.expect_err("a typo'd decision must fail the load");
let text = err.to_string();
assert!(text.contains("broken"), "must name the agent: {text}");
assert!(text.contains("allowed"), "must quote the value: {text}");
}
#[test]
fn malformed_embedded_extends_permissions_block_fails_the_load() {
let catalog = permissions_catalog(
"---\nname: child\nextends: base-fixture\npermissions:\n bash: allowed\n---\n\nChild.\n",
);
let err = project_in_memory_catalog("child", &catalog, Path::new("unused-skill-refs"))
.expect_err("a typo'd decision must fail the load");
let text = err.to_string();
assert!(text.contains("child"), "must name the agent: {text}");
assert!(text.contains("allowed"), "must quote the value: {text}");
}
#[test]
fn deployed_roster_copy_recovers_the_cards_permissions() {
let tmp = tempfile::tempdir().expect("tempdir");
std::fs::write(
tmp.path().join("pm.md"),
"---\nname: pm\nrole: pm\nprovenance: framework-owned\nmodel: sonnet\n\
tcode_tools: [read_file, write_file, bash]\n---\n\nYou are the PM.\n",
)
.expect("write");
let cfg = load_md_agent(&tmp.path().join("pm.md")).expect("loads");
let permissions = cfg
.permissions
.expect("a deployed roster card must carry its source's block");
assert!(
!permissions.is_empty(),
"the recovered block must carry the card's rules"
);
}
#[test]
fn quoted_provenance_still_recovers_the_cards_permissions() {
let tmp = tempfile::tempdir().expect("tempdir");
std::fs::write(
tmp.path().join("pm.md"),
"---\nname: pm\nrole: pm\nprovenance: \"framework-owned\"\nmodel: sonnet\n\
tcode_tools: [read_file, write_file, bash]\n---\n\nYou are the PM.\n",
)
.expect("write");
let cfg = load_md_agent(&tmp.path().join("pm.md")).expect("loads");
assert!(
cfg.permissions.is_some_and(|p| !p.is_empty()),
"a quoted `provenance:` is the same declaration as an unquoted one"
);
}
#[test]
fn hand_authored_file_gets_no_embedded_permissions() {
let tmp = tempfile::tempdir().expect("tempdir");
std::fs::write(
tmp.path().join("pm.md"),
"---\nname: pm\nmodel: sonnet\ntcode_tools: [read_file]\n---\n\nMy own PM.\n",
)
.expect("write");
let cfg = load_md_agent(&tmp.path().join("pm.md")).expect("loads");
assert!(
cfg.permissions.is_none(),
"a hand-authored card must not inherit the roster's rules"
);
}
}