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 under
4//! `.claude/agents/` so model, prompt, and LLM parameters can evolve without
5//! code changes. This module is the assembly point for config types and the
6//! discovery helpers. As of #2897 Slice D the on-disk source format is
7//! Markdown+frontmatter (`.md`) ONLY — the TOML loader that was
8//! DARK-LAUNCHED alongside `.md` in Slice B (#2897) has been retired.
9//! Pre-#2897 projects with `.claude/agents/*.toml` files must convert them;
10//! see [`discover_agents`]'s orphaned-`.toml` warning and
11//! `scripts/migrate-tcode-agents-toml-to-md.py`.
12//! What: Re-exports `AgentConfig` and all nested config types from `config`;
13//! provides `discover_agents` for scanning an agents directory (`*.md`
14//! only — a coexisting `*.toml` is warned about and skipped, never parsed),
15//! and `load_all_agents` for loading every discovered `.md` config.
16//! `load_all_agents` falls back to `crate::assets::DEFAULT_AGENTS` (#2895;
17//! expanded from 3 to 31 agents in Slice E3, #2958) when the *parsed* result
18//! is empty — not merely when no paths were discovered — so a
19//! `.claude/agents/` dir that exists but holds only unparseable (or
20//! exclusively orphaned-`.toml`) configs still yields a usable roster instead
21//! of silently starting with zero agents. A disk directory with even one
22//! successfully-parsed config is treated as the project opting in to its own
23//! catalog, so it is used as-is and the embedded defaults are not merged in.
24//! Test: `discover_agents` tests place `.md` (and, for the orphan-warning
25//! path, `.toml`) files in a tempdir and verify the returned list;
26//! `md_loader`'s own tests cover the loader itself.
27//! `load_all_agents_falls_back_to_embedded_when_disk_empty`,
28//! `load_all_agents_falls_back_to_embedded_when_disk_all_invalid`, and
29//! `load_all_agents_disk_wins_when_present` cover the fallback threshold.
30//!
31//! [`discover_agents`]: crate::agents::discover_agents
32
33pub mod config;
34pub mod md_loader;
35pub mod protocol;
36
37pub use config::{
38    AgentConfig, AgentInfo, LlmParams, RunnerConfig, RunnerKind, SystemPrompt, ToolsConfig,
39};
40pub use md_loader::load_md_agent;
41
42use std::path::{Path, PathBuf};
43
44/// Discover all agent configs in the given directory.
45///
46/// Why: tcode needs to know which agents are available before the PM loop
47/// starts so it can validate `delegate_to_agent` calls pre-flight. As of
48/// #2897 Slice D, `.toml` is no longer a loadable format — a project that
49/// has not migrated yet must be told LOUDLY, not silently ignored, or its
50/// agents would appear to vanish with no diagnostic.
51/// What: Scans `dir/*.md` and returns `(name, path)` pairs sorted by
52/// file-stem name. Any `dir/*.toml` file found in the SAME scan is never
53/// parsed and never appears in the returned list; instead every orphaned
54/// `.toml` path found in this call is named in ONE aggregated
55/// `tracing::warn!` pointing at the migration script — one call per
56/// `discover_agents` invocation (not one per file) so a directory with
57/// several un-migrated files does not spam the log, and no process-global
58/// latch is used (the crate convention is no global/`Once`-gated state for
59/// plain helpers — see repo `CLAUDE.md`), so the warning fires again on
60/// every subsequent scan for as long as the orphaned file remains.
61/// Test: `discover_agents_finds_md`, `discover_agents_ignores_toml`,
62/// `discover_agents_warns_on_orphaned_toml`,
63/// `discover_agents_missing_dir_is_empty`.
64pub fn discover_agents(dir: &Path) -> Vec<(String, PathBuf)> {
65    let Ok(entries) = std::fs::read_dir(dir) else {
66        tracing::debug!("agents dir not found or unreadable: {}", dir.display());
67        return vec![];
68    };
69
70    let mut agents: Vec<(String, PathBuf)> = Vec::new();
71    let mut orphaned_toml: Vec<PathBuf> = Vec::new();
72    for entry in entries.flatten() {
73        let p = entry.path();
74        match p.extension().and_then(|x| x.to_str()) {
75            Some("md") => {
76                if let Some(name) = p.file_stem().and_then(|s| s.to_str()) {
77                    agents.push((name.to_string(), p));
78                }
79            }
80            Some("toml") => orphaned_toml.push(p),
81            _ => {}
82        }
83    }
84
85    warn_on_orphaned_toml(&orphaned_toml);
86
87    agents.sort_by(|a, b| a.0.cmp(&b.0));
88    agents
89}
90
91/// Emit one aggregated warning naming every orphaned `.toml` agent file found
92/// in a single [`discover_agents`] scan.
93///
94/// Why: factored out of `discover_agents` so the "one call, every filename"
95/// aggregation rule (see that function's doc) is a single, independently
96/// readable/testable unit rather than inline branching.
97/// What: no-op when `orphaned` is empty; otherwise one `tracing::warn!`
98/// naming issue #2897, every orphaned path (comma-joined), and the
99/// migration script.
100/// Test: `discover_agents_warns_on_orphaned_toml`.
101fn warn_on_orphaned_toml(orphaned: &[PathBuf]) {
102    if orphaned.is_empty() {
103        return;
104    }
105    let names = orphaned
106        .iter()
107        .map(|p| p.display().to_string())
108        .collect::<Vec<_>>()
109        .join(", ");
110    tracing::warn!(
111        "trusty-code no longer loads TOML agents (#2897). Found {names} — convert \
112         with scripts/migrate-tcode-agents-toml-to-md.py. See CHANGELOG."
113    );
114}
115
116/// Load all agent configs from the given directory, skipping parse errors.
117///
118/// Why: Startup needs a map of all available agents; individual parse errors
119/// should not crash the whole harness. A project that has not yet created
120/// `.claude/agents/`, has created it but left it empty, or has populated it
121/// with only unparseable (or, post-#2897, only orphaned-`.toml`) configs must
122/// not start with zero agents — see the embedded-fallback note below.
123/// What: Calls `discover_agents` (which already excludes `.toml` paths — see
124/// its doc), then dispatches every discovered `.md` path to
125/// [`md_loader::load_md_agent`], collecting only the successfully parsed
126/// configs (failures are logged at WARN level and skipped). The fallback
127/// threshold is the *parsed* result being empty, not merely `discover_agents`
128/// finding no paths — a directory full of configs that all fail to parse (or
129/// that holds nothing but orphaned `.toml` files) must fall back exactly like
130/// an empty or missing directory does. Any single successfully-parsed disk
131/// config is treated as the project's own catalog and used as-is, never
132/// merged with the embedded set. Falls back to `load_embedded_default_agents`
133/// when parsing yields nothing. Disk agents always win when present.
134/// Test: `load_all_agents_skips_invalid`,
135/// `load_all_agents_falls_back_to_embedded_when_disk_empty`,
136/// `load_all_agents_falls_back_to_embedded_when_disk_all_invalid`,
137/// `load_all_agents_falls_back_when_disk_has_only_orphaned_toml`,
138/// `load_all_agents_disk_wins_when_present`.
139pub fn load_all_agents(dir: &Path) -> Vec<AgentConfig> {
140    let parsed: Vec<AgentConfig> = discover_agents(dir)
141        .into_iter()
142        .filter_map(|(name, path)| match md_loader::load_md_agent(&path) {
143            Ok(cfg) => Some(cfg),
144            Err(e) => {
145                tracing::warn!("skipping agent '{name}': {e}");
146                None
147            }
148        })
149        .collect();
150    if parsed.is_empty() {
151        return load_embedded_default_agents();
152    }
153    parsed
154}
155
156/// Project `crate::assets::DEFAULT_AGENTS` in-memory into `AgentConfig`s.
157///
158/// Why: The embedded fallback path for `load_all_agents` — no disk I/O, no
159/// materialization step (unlike trusty-mpm's install-time embed pattern). As
160/// of Slice E3 (#2958) `DEFAULT_AGENTS` mixes two projection strategies:
161/// tcode's original 3 defaults are flat `.md` strings (#2897 Slice C —
162/// previously native TOML, parsed via `AgentConfig::from_toml_str`; the
163/// format changed, the embedded-fallback behavior did not), while the 28 tm
164/// roster agents inherit from `BASE-*` templates and must be composed
165/// in-memory first.
166/// What: For each `EmbeddedAgent::Direct { name, md }`, calls
167/// [`md_loader::project_embedded_md`] directly — infallible, same as before
168/// Slice E3 (`agent_metadata_from_str` degrades to an empty default on a
169/// malformed document rather than erroring). For each
170/// `EmbeddedAgent::Composed { name }`, calls
171/// [`md_loader::project_embedded_md_with_extends`], which IS fallible (an
172/// unresolvable `extends:` chain returns `Err`); a failure is logged at
173/// ERROR level and the agent is skipped rather than panicking — this should
174/// be unreachable in practice (every roster name is pinned against
175/// `EMBEDDED_TM_AGENT_SOURCES` by `assets::tests::default_agents_parse_and_names_match`),
176/// but a compiled-in asset table defect must degrade gracefully, not crash
177/// the harness, exactly like the disk-parsing path in [`load_all_agents`]
178/// does for a malformed on-disk config.
179/// Test: `load_all_agents_falls_back_to_embedded_when_disk_empty`,
180/// `assets::tests::default_agents_field_identical_to_retired_toml`,
181/// `assets::tests::default_agents_parse_and_names_match`.
182pub(crate) fn load_embedded_default_agents() -> Vec<AgentConfig> {
183    crate::assets::DEFAULT_AGENTS
184        .iter()
185        .filter_map(|embedded| match embedded {
186            crate::assets::EmbeddedAgent::Direct { name, md } => {
187                Some(md_loader::project_embedded_md(name, md))
188            }
189            crate::assets::EmbeddedAgent::Composed { name } => {
190                match md_loader::project_embedded_md_with_extends(name) {
191                    Ok(cfg) => Some(cfg),
192                    Err(e) => {
193                        tracing::error!(
194                            "embedded roster agent '{name}' failed to compose \
195                             (build-time asset defect, not a runtime condition): {e}"
196                        );
197                        None
198                    }
199                }
200            }
201        })
202        .collect()
203}
204
205/// Locate the agents directory for the given project root.
206///
207/// Why: projects may use either `.claude/agents` (Claude Code native) or
208/// `.open-mpm/agents` (open-mpm legacy). Checking both preserves
209/// compatibility. Shared between `main.rs`'s `run-task` CLI path and (#2056)
210/// `serve::build_router`'s `task.run` wiring, so a project's agents resolve
211/// identically whether driven from the CLI or the daemon.
212/// What: returns the first of the two conventional directories that exists;
213/// falls back to `.claude/agents` (which may not exist yet — callers that
214/// need it to exist check separately, e.g. via [`md_loader::load_md_agent`]'s
215/// own error).
216/// Test: `agents::tests::locate_agents_dir_prefers_claude_then_open_mpm_then_default`.
217pub fn locate_agents_dir(project_root: &Path) -> std::path::PathBuf {
218    let claude_agents = project_root.join(".claude").join("agents");
219    if claude_agents.exists() {
220        return claude_agents;
221    }
222    let open_mpm_agents = project_root.join(".open-mpm").join("agents");
223    if open_mpm_agents.exists() {
224        return open_mpm_agents;
225    }
226    // Default to .claude/agents (may not exist yet).
227    claude_agents
228}
229
230/// Failure modes of [`resolve_agent`].
231///
232/// Why: `resolve_agent`'s callers need to distinguish "nothing named `name`
233/// exists anywhere" (a caller/LLM mistake — worth listing available agents
234/// for) from "a config for `name` exists but failed to load/compose" (a real
235/// bug in that specific file, on disk or embedded) — the same two shapes
236/// `RunnerError::UnknownAgent`/`ConfigLoad` already distinguish for the
237/// runner's own narrower `<dir>/<name>.md`-only lookup (#2897 Slice D).
238/// What: `NotFound` carries the searched `dir` and a precomputed
239/// `available` hint (disk ∪ embedded names, already joined for display —
240/// see [`available_agent_names`]). `Load` wraps the underlying
241/// `md_loader`/`compose` error, whether it came from an existing disk file
242/// or a compiled-in embedded asset.
243/// Test: `resolve_agent_unknown_name_lists_available_agents`,
244/// `resolve_agent_disk_parse_error_does_not_fall_back_to_embedded`.
245#[derive(Debug, thiserror::Error)]
246pub enum ResolveAgentError {
247    /// No config for `name` was found on disk or in the embedded roster.
248    #[error(
249        "unknown agent '{name}': no config found in {} and no embedded default \
250         named '{name}'. Available agents: {available}",
251        dir.display()
252    )]
253    NotFound {
254        /// The requested agent slug.
255        name: String,
256        /// The directory that was searched for `<name>.md`.
257        dir: PathBuf,
258        /// Disk ∪ embedded agent names, sorted/deduped and comma-joined.
259        available: String,
260    },
261    /// A config for `name` was found (on disk or embedded) but failed to
262    /// load, parse, or compose.
263    #[error("failed to load agent config for '{name}': {source}")]
264    Load {
265        /// The requested agent slug.
266        name: String,
267        /// The underlying load/parse/compose error.
268        #[source]
269        source: anyhow::Error,
270    },
271}
272
273/// Resolve a named agent's config, disk taking precedence over the embedded
274/// default roster (#3046 — the last gap in the #2958 embedded-roster arc).
275///
276/// Why: Slice E1-E3 (#2958) built a working embedded fallback for
277/// [`load_all_agents`] (the dir-wide scan), but five other production call
278/// sites — `runner::in_process::InProcessAgentRunner::load_agent`,
279/// `run_task::execute_run_task`'s and `task::executor`'s PM-config loads,
280/// `run_task::resolve_agent_model_slug`, and
281/// `tools::delegate::DelegateToAgentTool`'s pre-flight check — read
282/// `<dir>/<name>.md` directly by single-agent name, with no embedded
283/// consultation at all, so the 31-agent roster was unreachable from a real
284/// CLI run on a fresh project with no `.claude/agents/`. This is the ONE
285/// shared resolution helper all of them now route through, so the
286/// disk-wins/embedded-fallback precedence is written and tested exactly
287/// once.
288/// What: If `<dir>/<name>.md` EXISTS, loads it via [`md_loader::load_md_agent`]
289/// — a parse/compose error on an EXISTING disk file is returned as-is
290/// (`ResolveAgentError::Load`), NEVER silently falling through to an
291/// embedded copy of the same name: a project that deliberately overrode
292/// `name` gets its own broken override surfaced, not masked. If the disk
293/// file does not exist, looks `name` up in `crate::assets::DEFAULT_AGENTS`:
294/// a `Direct` entry projects via [`md_loader::project_embedded_md`]
295/// (infallible); a `Composed` entry projects via
296/// [`md_loader::project_embedded_md_with_extends`], and on `Err` (a
297/// build-time asset defect — see [`load_embedded_default_agents`]'s
298/// identical handling) logs `tracing::error!` and falls through to the
299/// not-found case below rather than propagating. If nothing matches
300/// anywhere, returns `ResolveAgentError::NotFound` with the disk ∪ embedded
301/// name list ([`available_agent_names`]) for a caller to surface.
302/// A namespaced `<plugin>:<local-name>` (issue #3539 — Phase 1 Claude Code
303/// plugin support) routes to [`crate::plugins::agents::find_plugin_agent_config`]
304/// instead of the disk/embedded precedence below: plugin agents are an
305/// independent, additive tier, never falling back to (or being shadowed
306/// by) disk/embedded resolution of the bare local name.
307/// Test: `resolve_agent_disk_wins_over_embedded`,
308/// `resolve_agent_falls_back_to_embedded_when_disk_misses`,
309/// `resolve_agent_disk_parse_error_does_not_fall_back_to_embedded`,
310/// `resolve_agent_unknown_name_lists_available_agents`,
311/// `resolve_agent_namespaced_name_resolves_plugin_agent`,
312/// `resolve_agent_namespaced_unknown_plugin_is_not_found`.
313pub fn resolve_agent(dir: &Path, name: &str) -> Result<AgentConfig, ResolveAgentError> {
314    if let Some((plugin, agent_name)) = name.split_once(':') {
315        return resolve_plugin_agent(dir, plugin, agent_name, name);
316    }
317
318    let disk_path = dir.join(format!("{name}.md"));
319    if disk_path.exists() {
320        return md_loader::load_md_agent(&disk_path).map_err(|source| ResolveAgentError::Load {
321            name: name.to_string(),
322            source,
323        });
324    }
325
326    if let Some(embedded) = crate::assets::DEFAULT_AGENTS
327        .iter()
328        .find(|a| a.name() == name)
329    {
330        match embedded {
331            crate::assets::EmbeddedAgent::Direct { name: n, md } => {
332                return Ok(md_loader::project_embedded_md(n, md));
333            }
334            crate::assets::EmbeddedAgent::Composed { name: n } => {
335                match md_loader::project_embedded_md_with_extends(n) {
336                    Ok(cfg) => return Ok(cfg),
337                    Err(e) => {
338                        tracing::error!(
339                            "embedded roster agent '{n}' failed to compose \
340                             (build-time asset defect, not a runtime condition): {e}"
341                        );
342                        // Fall through to the not-found error below, mirroring
343                        // `load_embedded_default_agents`'s own handling.
344                    }
345                }
346            }
347        }
348    }
349
350    Err(ResolveAgentError::NotFound {
351        name: name.to_string(),
352        dir: dir.to_path_buf(),
353        available: available_agent_names(dir).join(", "),
354    })
355}
356
357/// Resolve a namespaced `<plugin>:<agent_name>` for [`resolve_agent`]
358/// (issue #3539).
359///
360/// Why: split out so `resolve_agent`'s own precedence chain (disk ->
361/// embedded -> not-found) stays a single, unbranched read for the common
362/// unnamespaced case.
363/// What: recovers a project root from `dir` via
364/// [`crate::plugins::project_root_two_levels_up`] (works whether `dir` is
365/// project- or user-scoped — see that function's docs), then delegates to
366/// [`crate::plugins::agents::find_plugin_agent_config`]. `None` (no such
367/// plugin, or no such agent within it) maps to the same `NotFound` shape
368/// `resolve_agent`'s bare-name path uses, `full_name` preserving the
369/// caller's original namespaced spelling; `Some(Err)` (found but failed to
370/// parse) maps to `Load`.
371/// Test: `resolve_agent_namespaced_name_resolves_plugin_agent`,
372/// `resolve_agent_namespaced_unknown_plugin_is_not_found`,
373/// `resolve_agent_namespaced_unknown_agent_is_not_found`.
374fn resolve_plugin_agent(
375    dir: &Path,
376    plugin: &str,
377    agent_name: &str,
378    full_name: &str,
379) -> Result<AgentConfig, ResolveAgentError> {
380    let found = crate::plugins::project_root_two_levels_up(dir).and_then(|root| {
381        crate::plugins::agents::find_plugin_agent_config(&root, plugin, agent_name)
382    });
383
384    match found {
385        Some(Ok(cfg)) => Ok(cfg),
386        Some(Err(source)) => Err(ResolveAgentError::Load {
387            name: full_name.to_string(),
388            source,
389        }),
390        None => Err(ResolveAgentError::NotFound {
391            name: full_name.to_string(),
392            dir: dir.to_path_buf(),
393            available: available_agent_names(dir).join(", "),
394        }),
395    }
396}
397
398/// List every agent name resolvable via [`resolve_agent`] for `dir`: disk ∪
399/// embedded, sorted and deduped.
400///
401/// Why: Both `resolve_agent`'s own not-found error and
402/// `tools::delegate::DelegateToAgentTool::available_agents` (the
403/// "Available agents: ..." hint an LLM sees after naming an unknown agent)
404/// need the same union — computing it in one place means the hint always
405/// names real dispatchable agents, on disk or embedded, never just one or
406/// the other.
407/// What: `discover_agents(dir)`'s names, plus every
408/// `crate::assets::DEFAULT_AGENTS` name not already present, sorted and
409/// deduped.
410/// Test: `available_agent_names_unions_disk_and_embedded`.
411pub fn available_agent_names(dir: &Path) -> Vec<String> {
412    let mut names: Vec<String> = discover_agents(dir).into_iter().map(|(n, _)| n).collect();
413    for embedded in crate::assets::DEFAULT_AGENTS {
414        let n = embedded.name().to_string();
415        if !names.contains(&n) {
416            names.push(n);
417        }
418    }
419    names.sort();
420    names.dedup();
421    names
422}
423
424// ── Tests ─────────────────────────────────────────────────────────────────────
425
426#[cfg(test)]
427mod tests {
428    use super::*;
429
430    /// The 33-name default embedded roster, in `crate::assets::DEFAULT_AGENTS`'s
431    /// declared order (Slice E3, #2958; `pm` added for #3437, `ticketing` for
432    /// #4027) — shared by
433    /// every fallback test in this module so the expected list is written
434    /// once, not duplicated per-test with the risk of one copy drifting from
435    /// another.
436    ///
437    /// Why: three separate fallback scenarios (empty dir, all-invalid dir,
438    /// only-orphaned-toml dir) all assert the identical 33-name outcome; a
439    /// single source avoids a silent typo in one copy passing review
440    /// unnoticed.
441    /// What: tcode's original 4 (`engineer`, `qa-agent`, `code-reviewer`,
442    /// `pm`) followed by the 29 roster names, alphabetical, matching
443    /// `DEFAULT_AGENTS`'s literal declaration order.
444    /// Test: every `load_all_agents_falls_back_*` test below.
445    fn expected_default_agent_names() -> Vec<&'static str> {
446        vec![
447            "engineer",
448            "qa-agent",
449            "code-reviewer",
450            "pm",
451            "api-qa",
452            "code-analyzer",
453            "code-critic",
454            "dart-engineer",
455            "data-engineer",
456            "documentation",
457            "golang-engineer",
458            "java-engineer",
459            "javascript-engineer",
460            "local-ops",
461            "nextjs-engineer",
462            "elixir-engineer",
463            "phoenix-engineer",
464            "php-engineer",
465            "prompt-engineer",
466            "python-engineer",
467            "qa",
468            "react-engineer",
469            "refactoring-engineer",
470            "research",
471            "ruby-engineer",
472            "rust-engineer",
473            "security",
474            "svelte-engineer",
475            "tauri-engineer",
476            // #4027: non-coding ticketing specialist for the cross-product bridge.
477            "ticketing",
478            "typescript-engineer",
479            "web-qa",
480            "web-ui-engineer",
481        ]
482    }
483
484    /// `discover_agents` finds `.md` files and returns sorted (name, path)
485    /// pairs.
486    ///
487    /// Why: Verify the scanning and sorting logic. Uses a `.txt` file as the
488    /// "irrelevant extension" fixture.
489    /// What: Place two `.md` + one `.txt` in a tempdir; assert two results in
490    /// order.
491    /// Test: This test.
492    #[test]
493    fn discover_agents_finds_md() {
494        let tmp = tempfile::tempdir().expect("tempdir");
495        std::fs::write(
496            tmp.path().join("qa-agent.md"),
497            "---\nname: qa-agent\n---\n\nBody.\n",
498        )
499        .expect("write");
500        std::fs::write(
501            tmp.path().join("engineer.md"),
502            "---\nname: engineer\n---\n\nBody.\n",
503        )
504        .expect("write");
505        std::fs::write(tmp.path().join("README.txt"), "docs").expect("write");
506
507        let agents = discover_agents(tmp.path());
508        let names: Vec<&str> = agents.iter().map(|(n, _)| n.as_str()).collect();
509        assert_eq!(names, vec!["engineer", "qa-agent"], "sorted by name");
510    }
511
512    /// A `.toml` file in the agents dir is never discovered as an agent
513    /// (#2897 Slice D — TOML is retired, not merely deprioritised).
514    ///
515    /// Why: pins that the format cutover is a hard exclusion, not a
516    /// collision-resolution tiebreak (which is what Slice B/C had).
517    /// What: one `.md` + one `.toml`, distinct names; only the `.md` name
518    /// appears in the result.
519    /// Test: this test.
520    #[test]
521    fn discover_agents_ignores_toml() {
522        let tmp = tempfile::tempdir().expect("tempdir");
523        std::fs::write(
524            tmp.path().join("engineer.toml"),
525            "[agent]\nname=\"engineer\"\n",
526        )
527        .expect("write");
528        std::fs::write(
529            tmp.path().join("md-agent.md"),
530            "---\nname: md-agent\n---\n\nBody.\n",
531        )
532        .expect("write");
533
534        let agents = discover_agents(tmp.path());
535        let names: Vec<&str> = agents.iter().map(|(n, _)| n.as_str()).collect();
536        assert_eq!(names, vec!["md-agent"], "the .toml file must be excluded");
537    }
538
539    /// An orphaned `.toml` agent file triggers one aggregated WARN-level log
540    /// naming the file(s) and the migration script (#2897 Slice D).
541    ///
542    /// Why: silently dropping a project's pre-#2897 `.toml` agents (rather
543    /// than warning) would make them appear to vanish with no diagnostic —
544    /// the whole point of the migration-warning requirement.
545    /// What: two orphaned `.toml` files, no `.md`; asserts the captured
546    /// WARN-level log names both file stems, issue `#2897`, and the
547    /// converter script path.
548    /// Test: this test.
549    #[test]
550    fn discover_agents_warns_on_orphaned_toml() {
551        crate::test_support::begin_capture();
552
553        let tmp = tempfile::tempdir().expect("tempdir");
554        std::fs::write(
555            tmp.path().join("legacy-a.toml"),
556            "[agent]\nname=\"legacy-a\"\n",
557        )
558        .expect("write");
559        std::fs::write(
560            tmp.path().join("legacy-b.toml"),
561            "[agent]\nname=\"legacy-b\"\n",
562        )
563        .expect("write");
564
565        let agents = discover_agents(tmp.path());
566        assert!(agents.is_empty(), "orphaned .toml files are never agents");
567
568        let captured = crate::test_support::captured_at_least(tracing::Level::WARN);
569        let warning = captured
570            .iter()
571            .find(|m| m.contains("no longer loads TOML agents"))
572            .unwrap_or_else(|| panic!("expected an orphaned-.toml warning, got: {captured:?}"));
573        assert!(warning.contains("legacy-a.toml"), "got: {warning}");
574        assert!(warning.contains("legacy-b.toml"), "got: {warning}");
575        assert!(warning.contains("#2897"), "got: {warning}");
576        assert!(
577            warning.contains("scripts/migrate-tcode-agents-toml-to-md.py"),
578            "got: {warning}"
579        );
580    }
581
582    /// `discover_agents` returns empty when the directory does not exist.
583    ///
584    /// Why: Guard against panic on a missing `.claude/agents` dir.
585    /// What: Pass a non-existent path; expect empty Vec.
586    /// Test: This test.
587    #[test]
588    fn discover_agents_missing_dir_is_empty() {
589        let agents = discover_agents(std::path::Path::new("/nonexistent/path/agents"));
590        assert!(agents.is_empty());
591    }
592
593    /// `load_all_agents` skips files with invalid `.md` frontmatter.
594    ///
595    /// Why: A single bad config should not crash the harness.
596    /// What: Place one valid + one malformed `.md`; `load_all_agents` returns
597    /// the one entry that parsed.
598    /// Test: This test.
599    #[test]
600    fn load_all_agents_skips_invalid() {
601        let tmp = tempfile::tempdir().expect("tempdir");
602        std::fs::write(
603            tmp.path().join("engineer.md"),
604            "---\nname: engineer\n---\n\nBody.\n",
605        )
606        .expect("write");
607        // `extends:` a base that does not exist — a real `compose_agent`
608        // failure, unlike a TOML syntax error, since the `.md` loader has no
609        // "unparseable syntax" failure mode of its own (frontmatter degrades
610        // to empty defaults rather than erroring — see `md_loader`'s docs).
611        std::fs::write(
612            tmp.path().join("broken.md"),
613            "---\nname: broken\nextends: does-not-exist\n---\n\nBody.\n",
614        )
615        .expect("write");
616
617        let agents = load_all_agents(tmp.path());
618        assert_eq!(agents.len(), 1);
619        assert_eq!(agents[0].agent.name, "engineer");
620    }
621
622    /// `load_all_agents` falls back to the embedded defaults when the disk
623    /// directory has no `.md` files (missing dir and empty-but-existing dir
624    /// both hit this branch, since `discover_agents` returns `[]` for both).
625    ///
626    /// Why: This is the whole point of #2895 — a fresh project must not
627    /// start with zero agents. As of Slice E3 (#2958) the bundled roster is
628    /// 31 agents, not 3.
629    /// What: Load from a nonexistent dir; expect exactly the 31-agent
630    /// embedded roster, in `crate::assets::DEFAULT_AGENTS`'s declared order —
631    /// the original 3 defaults intact, followed by the 28 roster agents.
632    /// Test: this test.
633    #[test]
634    fn load_all_agents_falls_back_to_embedded_when_disk_empty() {
635        let agents = load_all_agents(std::path::Path::new("/nonexistent/agents/dir"));
636        let names: Vec<&str> = agents.iter().map(|a| a.agent.name.as_str()).collect();
637        assert_eq!(names, expected_default_agent_names());
638    }
639
640    /// A `.claude/agents/` dir that exists and holds `.md` files, but every
641    /// one of them fails to parse, must fall back to the embedded defaults
642    /// exactly like a missing/empty dir does — not silently return zero
643    /// agents (code-critic finding, #2895 follow-up).
644    ///
645    /// Why: The fallback threshold is the *parsed* result being empty, not
646    /// merely `discover_agents` finding no `.md` paths. Keying on paths
647    /// alone would defeat the "never zero agents" goal for a directory that
648    /// exists but is entirely malformed.
649    /// What: One `broken.md` (an `extends:` cycle — a real `compose_agent`
650    /// failure) on disk, nothing else; `load_all_agents` returns the
651    /// 31-agent bundled roster, not `[]`.
652    /// Test: this test.
653    #[test]
654    fn load_all_agents_falls_back_to_embedded_when_disk_all_invalid() {
655        let tmp = tempfile::tempdir().expect("tempdir");
656        std::fs::write(
657            tmp.path().join("broken.md"),
658            "---\nname: broken\nextends: broken\n---\n\nBody.\n",
659        )
660        .expect("write");
661
662        let agents = load_all_agents(tmp.path());
663        let names: Vec<&str> = agents.iter().map(|a| a.agent.name.as_str()).collect();
664        assert_eq!(names, expected_default_agent_names());
665    }
666
667    /// A directory holding ONLY orphaned `.toml` agents (no `.md` at all)
668    /// must fall back to the embedded defaults exactly like an empty
669    /// directory does — the warning fires, but the project still gets a
670    /// usable agent set (#2897 Slice D).
671    ///
672    /// Why: pins that the orphan-warning path and the never-zero-agents
673    /// fallback compose correctly: warning is a side effect, not a
674    /// substitute for a real agent.
675    /// What: one `legacy.toml` on disk, no `.md`; `load_all_agents` returns
676    /// the 31-agent bundled roster.
677    /// Test: this test.
678    #[test]
679    fn load_all_agents_falls_back_when_disk_has_only_orphaned_toml() {
680        let tmp = tempfile::tempdir().expect("tempdir");
681        std::fs::write(tmp.path().join("legacy.toml"), "[agent]\nname=\"legacy\"\n")
682            .expect("write");
683
684        let agents = load_all_agents(tmp.path());
685        let names: Vec<&str> = agents.iter().map(|a| a.agent.name.as_str()).collect();
686        assert_eq!(names, expected_default_agent_names());
687    }
688
689    /// A disk directory with even one valid config is used as-is; the
690    /// embedded defaults are never merged in alongside it.
691    ///
692    /// Why: Pins the fallback threshold (empty disk scan only) so a project
693    /// that has deliberately curated a single custom agent is not silently
694    /// joined by three more it did not ask for.
695    /// What: One `custom.md` on disk; `load_all_agents` returns exactly that
696    /// one config, not four.
697    /// Test: this test.
698    #[test]
699    fn load_all_agents_disk_wins_when_present() {
700        let tmp = tempfile::tempdir().expect("tempdir");
701        std::fs::write(
702            tmp.path().join("custom.md"),
703            "---\nname: custom\n---\n\nBody.\n",
704        )
705        .expect("write");
706
707        let agents = load_all_agents(tmp.path());
708        assert_eq!(agents.len(), 1);
709        assert_eq!(agents[0].agent.name, "custom");
710    }
711
712    /// `locate_agents_dir` prefers `.claude/agents`, falls back to
713    /// `.open-mpm/agents`, and defaults to `.claude/agents` when neither
714    /// exists.
715    #[test]
716    fn locate_agents_dir_prefers_claude_then_open_mpm_then_default() {
717        let tmp = tempfile::tempdir().expect("tempdir");
718        assert_eq!(
719            locate_agents_dir(tmp.path()),
720            tmp.path().join(".claude").join("agents"),
721            "default (neither exists) must be .claude/agents"
722        );
723
724        std::fs::create_dir_all(tmp.path().join(".open-mpm").join("agents")).expect("mkdir");
725        assert_eq!(
726            locate_agents_dir(tmp.path()),
727            tmp.path().join(".open-mpm").join("agents"),
728            "must fall back to .open-mpm/agents when only it exists"
729        );
730
731        std::fs::create_dir_all(tmp.path().join(".claude").join("agents")).expect("mkdir");
732        assert_eq!(
733            locate_agents_dir(tmp.path()),
734            tmp.path().join(".claude").join("agents"),
735            "must prefer .claude/agents when both exist"
736        );
737    }
738
739    /// `resolve_agent`: a disk override wins over an embedded agent of the
740    /// SAME name (#3046).
741    ///
742    /// Why: "project overrides always win" is the whole point of putting
743    /// disk-existence first in `resolve_agent`'s precedence.
744    /// What: `engineer` is BOTH on disk (with a distinguishing marker
745    /// description) and in the embedded roster; asserts the disk copy's
746    /// content came back, not the embedded one's.
747    /// Test: this test.
748    #[test]
749    fn resolve_agent_disk_wins_over_embedded() {
750        let tmp = tempfile::tempdir().expect("tempdir");
751        std::fs::write(
752            tmp.path().join("engineer.md"),
753            "---\nname: engineer\ndescription: DISK OVERRIDE MARKER\n---\n\nDisk body.\n",
754        )
755        .expect("write");
756
757        let cfg = resolve_agent(tmp.path(), "engineer").expect("resolve");
758        assert_eq!(
759            cfg.agent.description.as_deref(),
760            Some("DISK OVERRIDE MARKER")
761        );
762        assert_eq!(cfg.system_prompt.content, "Disk body.");
763    }
764
765    /// `resolve_agent`: a disk miss falls back to the embedded roster
766    /// (#3046).
767    ///
768    /// Why: this is the literal #3046 repro at the unit level — an empty
769    /// disk dir must still resolve a roster name like `rust-engineer`
770    /// (an `EmbeddedAgent::Composed` entry).
771    /// What: an empty/nonexistent agents dir; `resolve_agent(dir,
772    /// "rust-engineer")` must succeed and carry rust-engineer's known
773    /// composed content.
774    /// Test: this test.
775    #[test]
776    fn resolve_agent_falls_back_to_embedded_when_disk_misses() {
777        let tmp = tempfile::tempdir().expect("tempdir");
778        let cfg = resolve_agent(tmp.path(), "rust-engineer").expect("resolve embedded");
779        assert_eq!(cfg.agent.name, "rust-engineer");
780        assert!(
781            cfg.system_prompt.content.contains("toolchains-rust-core"),
782            "expected rust-engineer's composed body, got: {:?}",
783            cfg.system_prompt.content
784        );
785    }
786
787    /// `resolve_agent`: a parse/compose error on an EXISTING disk file must
788    /// error, never silently fall back to the embedded copy of the same
789    /// name (#3046).
790    ///
791    /// Why: masking a real on-disk config bug behind a silently-substituted
792    /// embedded default would hide the exact kind of typo/misconfiguration
793    /// this validation exists to surface.
794    /// What: a disk `rust-engineer.md` with a broken `extends:` chain (a
795    /// name that resolves to nothing); asserts `resolve_agent` errors with
796    /// `ResolveAgentError::Load`, not `Ok` with the embedded content.
797    /// Test: this test.
798    #[test]
799    fn resolve_agent_disk_parse_error_does_not_fall_back_to_embedded() {
800        let tmp = tempfile::tempdir().expect("tempdir");
801        std::fs::write(
802            tmp.path().join("rust-engineer.md"),
803            "---\nname: rust-engineer\nextends: does-not-exist\n---\n\nBroken.\n",
804        )
805        .expect("write");
806
807        let err = resolve_agent(tmp.path(), "rust-engineer")
808            .expect_err("a broken disk override must error, not fall back");
809        assert!(
810            matches!(err, ResolveAgentError::Load { .. }),
811            "expected Load, got: {err:?}"
812        );
813    }
814
815    /// `resolve_agent`: a name absent from disk AND the embedded roster
816    /// errors with a message listing available agents (#3046).
817    ///
818    /// Why: pins the `NotFound` shape callers rely on to build a helpful
819    /// "unknown agent, did you mean one of..." message.
820    /// What: an empty disk dir; `resolve_agent(dir, "totally-bogus")`
821    /// errors, and the error text names at least one real embedded agent
822    /// (`engineer`).
823    /// Test: this test.
824    #[test]
825    fn resolve_agent_unknown_name_lists_available_agents() {
826        let tmp = tempfile::tempdir().expect("tempdir");
827        let err = resolve_agent(tmp.path(), "totally-bogus").expect_err("must error");
828        let msg = err.to_string();
829        assert!(msg.contains("totally-bogus"), "got: {msg}");
830        assert!(
831            msg.contains("engineer"),
832            "expected the available-agents hint to name a real embedded agent, got: {msg}"
833        );
834    }
835
836    /// `resolve_agent` routes a namespaced `<plugin>:<name>` to
837    /// `plugins::agents::find_plugin_agent_config`, recovering the project
838    /// root from the `.claude/agents` dir it was given (#3539).
839    ///
840    /// Why: this is the acceptance criterion for the dispatch half of
841    /// #3539's namespacing decision — a namespaced name must actually
842    /// dispatch, not just appear in `agents.list`.
843    /// Test: this test.
844    #[test]
845    fn resolve_agent_namespaced_name_resolves_plugin_agent() {
846        let tmp = tempfile::tempdir().expect("tempdir");
847        let agents_dir = tmp.path().join(".claude").join("agents");
848        let plugin_agents_dir = tmp
849            .path()
850            .join(".claude")
851            .join("plugins")
852            .join("my-plugin")
853            .join("agents");
854        std::fs::create_dir_all(&plugin_agents_dir).expect("mkdir");
855        std::fs::write(
856            plugin_agents_dir.join("reviewer.md"),
857            "---\nname: reviewer\ndescription: Plugin reviewer\n---\n\nReview things.\n",
858        )
859        .expect("write");
860
861        let cfg = resolve_agent(&agents_dir, "my-plugin:reviewer").expect("resolve plugin agent");
862        assert_eq!(cfg.agent.name, "my-plugin:reviewer");
863        assert_eq!(cfg.agent.description.as_deref(), Some("Plugin reviewer"));
864        assert_eq!(cfg.system_prompt.content, "Review things.");
865    }
866
867    /// A namespaced name whose plugin does not exist errors `NotFound`, not
868    /// a silent fall-through to disk/embedded resolution of the bare name.
869    ///
870    /// Test: this test.
871    #[test]
872    fn resolve_agent_namespaced_unknown_plugin_is_not_found() {
873        let tmp = tempfile::tempdir().expect("tempdir");
874        let agents_dir = tmp.path().join(".claude").join("agents");
875
876        let err = resolve_agent(&agents_dir, "no-such-plugin:reviewer")
877            .expect_err("unknown plugin must not resolve");
878        assert!(
879            matches!(err, ResolveAgentError::NotFound { .. }),
880            "expected NotFound, got: {err:?}"
881        );
882    }
883
884    /// A namespaced name for a known plugin but an unknown local agent name
885    /// errors `NotFound`.
886    ///
887    /// Test: this test.
888    #[test]
889    fn resolve_agent_namespaced_unknown_agent_is_not_found() {
890        let tmp = tempfile::tempdir().expect("tempdir");
891        let agents_dir = tmp.path().join(".claude").join("agents");
892        let plugin_agents_dir = tmp
893            .path()
894            .join(".claude")
895            .join("plugins")
896            .join("my-plugin")
897            .join("agents");
898        std::fs::create_dir_all(&plugin_agents_dir).expect("mkdir");
899
900        let err = resolve_agent(&agents_dir, "my-plugin:ghost")
901            .expect_err("unknown agent within a known plugin must not resolve");
902        assert!(
903            matches!(err, ResolveAgentError::NotFound { .. }),
904            "expected NotFound, got: {err:?}"
905        );
906    }
907
908    /// `available_agent_names` unions disk and embedded names, sorted and
909    /// deduped (#3046).
910    ///
911    /// Why: shared by `resolve_agent`'s not-found hint and
912    /// `tools::delegate::DelegateToAgentTool::available_agents` — both need
913    /// the identical union, computed once.
914    /// What: one disk-only custom agent plus the embedded roster; asserts
915    /// both the disk name and a known embedded name are present, with no
916    /// duplicates.
917    /// Test: this test.
918    #[test]
919    fn available_agent_names_unions_disk_and_embedded() {
920        let tmp = tempfile::tempdir().expect("tempdir");
921        std::fs::write(
922            tmp.path().join("custom.md"),
923            "---\nname: custom\n---\n\nBody.\n",
924        )
925        .expect("write");
926
927        let names = available_agent_names(tmp.path());
928        assert!(names.contains(&"custom".to_string()), "got: {names:?}");
929        assert!(
930            names.contains(&"rust-engineer".to_string()),
931            "got: {names:?}"
932        );
933        let mut deduped = names.clone();
934        deduped.sort();
935        deduped.dedup();
936        assert_eq!(names, deduped, "must contain no duplicates");
937    }
938}