Skip to main content

trusty_code/agents/
mod.rs

1//! Agent configuration loading and types for tcode.
2//!
3//! Why: Sub-agents (and the PM itself) are defined declaratively in TOML files
4//! under `.claude/agents/` so model, prompt, and LLM parameters can evolve
5//! without code changes. This module is the assembly point for config types
6//! and the discovery helpers.
7//! What: Re-exports `AgentConfig` and all nested config types from `config`;
8//! provides `discover_agents` for scanning an agents directory.
9//! Test: `discover_agents` tests place TOML files in a tempdir and verify the
10//! returned list. `AgentConfig::load` tests read individual files.
11
12pub mod config;
13
14pub use config::{
15    AgentConfig, AgentInfo, LlmParams, RunnerConfig, RunnerKind, SystemPrompt, ToolsConfig,
16};
17
18use std::path::Path;
19
20/// Discover all agent configs in the given directory.
21///
22/// Why: tcode needs to know which agents are available before the PM loop
23/// starts so it can validate `delegate_to_agent` calls pre-flight.
24/// What: Scans `dir/*.toml` and returns `(name, path)` pairs sorted by name.
25/// Files that fail to parse are skipped with a tracing warning.
26/// Test: `discover_agents_finds_tomls`, `discover_agents_skips_non_toml`.
27pub fn discover_agents(dir: &Path) -> Vec<(String, std::path::PathBuf)> {
28    let Ok(entries) = std::fs::read_dir(dir) else {
29        tracing::debug!("agents dir not found or unreadable: {}", dir.display());
30        return vec![];
31    };
32    let mut agents: Vec<(String, std::path::PathBuf)> = entries
33        .flatten()
34        .filter_map(|e| {
35            let p = e.path();
36            if p.extension().and_then(|x| x.to_str()) == Some("toml") {
37                let name = p.file_stem()?.to_str()?.to_string();
38                Some((name, p))
39            } else {
40                None
41            }
42        })
43        .collect();
44    agents.sort_by(|a, b| a.0.cmp(&b.0));
45    agents
46}
47
48/// Load all agent configs from the given directory, skipping parse errors.
49///
50/// Why: Startup needs a map of all available agents; individual parse errors
51/// should not crash the whole harness.
52/// What: Calls `discover_agents`, then `AgentConfig::load` on each; returns
53/// successfully parsed configs only. Failures are logged at WARN level.
54/// Test: `load_all_agents_skips_invalid`.
55pub fn load_all_agents(dir: &Path) -> Vec<AgentConfig> {
56    discover_agents(dir)
57        .into_iter()
58        .filter_map(|(name, path)| match AgentConfig::load(&path) {
59            Ok(cfg) => Some(cfg),
60            Err(e) => {
61                tracing::warn!("skipping agent '{name}': {e}");
62                None
63            }
64        })
65        .collect()
66}
67
68/// Locate the agents directory for the given project root.
69///
70/// Why: projects may use either `.claude/agents` (Claude Code native) or
71/// `.open-mpm/agents` (open-mpm legacy). Checking both preserves
72/// compatibility. Shared between `main.rs`'s `run-task` CLI path and (#2056)
73/// `serve::build_router`'s `task.run` wiring, so a project's agents resolve
74/// identically whether driven from the CLI or the daemon.
75/// What: returns the first of the two conventional directories that exists;
76/// falls back to `.claude/agents` (which may not exist yet — callers that
77/// need it to exist check separately, e.g. via `AgentConfig::load`'s own
78/// error).
79/// Test: `agents::tests::locate_agents_dir_prefers_claude_then_open_mpm_then_default`.
80pub fn locate_agents_dir(project_root: &Path) -> std::path::PathBuf {
81    let claude_agents = project_root.join(".claude").join("agents");
82    if claude_agents.exists() {
83        return claude_agents;
84    }
85    let open_mpm_agents = project_root.join(".open-mpm").join("agents");
86    if open_mpm_agents.exists() {
87        return open_mpm_agents;
88    }
89    // Default to .claude/agents (may not exist yet).
90    claude_agents
91}
92
93// ── Tests ─────────────────────────────────────────────────────────────────────
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98
99    /// `discover_agents` finds TOML files and returns sorted (name, path) pairs.
100    ///
101    /// Why: Verify the scanning and sorting logic.
102    /// What: Place two TOML + one non-TOML in a tempdir; assert two results in order.
103    /// Test: This test.
104    #[test]
105    fn discover_agents_finds_tomls() {
106        let tmp = tempfile::tempdir().expect("tempdir");
107        std::fs::write(
108            tmp.path().join("qa-agent.toml"),
109            "[agent]\nname=\"qa-agent\"\n",
110        )
111        .expect("write");
112        std::fs::write(
113            tmp.path().join("engineer.toml"),
114            "[agent]\nname=\"engineer\"\n",
115        )
116        .expect("write");
117        std::fs::write(tmp.path().join("README.md"), "docs").expect("write");
118
119        let agents = discover_agents(tmp.path());
120        let names: Vec<&str> = agents.iter().map(|(n, _)| n.as_str()).collect();
121        assert_eq!(names, vec!["engineer", "qa-agent"], "sorted by name");
122    }
123
124    /// `discover_agents` returns empty when the directory does not exist.
125    ///
126    /// Why: Guard against panic on a missing `.claude/agents` dir.
127    /// What: Pass a non-existent path; expect empty Vec.
128    /// Test: This test.
129    #[test]
130    fn discover_agents_missing_dir_is_empty() {
131        let agents = discover_agents(std::path::Path::new("/nonexistent/path/agents"));
132        assert!(agents.is_empty());
133    }
134
135    /// `load_all_agents` skips files with invalid TOML.
136    ///
137    /// Why: A single bad config should not crash the harness.
138    /// What: Place one valid + one invalid TOML; `load_all_agents` returns 1 entry.
139    /// Test: This test.
140    #[test]
141    fn load_all_agents_skips_invalid() {
142        let tmp = tempfile::tempdir().expect("tempdir");
143        std::fs::write(
144            tmp.path().join("engineer.toml"),
145            "[agent]\nname=\"engineer\"\n",
146        )
147        .expect("write");
148        std::fs::write(tmp.path().join("broken.toml"), "<<NOT TOML>>").expect("write");
149
150        let agents = load_all_agents(tmp.path());
151        assert_eq!(agents.len(), 1);
152        assert_eq!(agents[0].agent.name, "engineer");
153    }
154
155    /// `locate_agents_dir` prefers `.claude/agents`, falls back to
156    /// `.open-mpm/agents`, and defaults to `.claude/agents` when neither
157    /// exists.
158    #[test]
159    fn locate_agents_dir_prefers_claude_then_open_mpm_then_default() {
160        let tmp = tempfile::tempdir().expect("tempdir");
161        assert_eq!(
162            locate_agents_dir(tmp.path()),
163            tmp.path().join(".claude").join("agents"),
164            "default (neither exists) must be .claude/agents"
165        );
166
167        std::fs::create_dir_all(tmp.path().join(".open-mpm").join("agents")).expect("mkdir");
168        assert_eq!(
169            locate_agents_dir(tmp.path()),
170            tmp.path().join(".open-mpm").join("agents"),
171            "must fall back to .open-mpm/agents when only it exists"
172        );
173
174        std::fs::create_dir_all(tmp.path().join(".claude").join("agents")).expect("mkdir");
175        assert_eq!(
176            locate_agents_dir(tmp.path()),
177            tmp.path().join(".claude").join("agents"),
178            "must prefer .claude/agents when both exist"
179        );
180    }
181}