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