trusty_code/agents/md_loader.rs
1//! Markdown+frontmatter agent loader for tcode — the ONLY on-disk agent
2//! source format as of #2897 Slice D (epic #2892). It was DARK-LAUNCHED
3//! alongside the (now-retired) TOML loader in Slice B, and became the loader
4//! for tcode's own EMBEDDED default agents in Slice C.
5//!
6//! Why: trusty-agents-common's `agents::builder` compose machinery (Slice A,
7//! #2952) already resolves `extends:` inheritance chains for trusty-mpm's
8//! `.md` agent format and now carries `max_tokens`/`tools` frontmatter fields
9//! that mirror tcode's `AgentConfig` schema. Rather than fork a second `.md`
10//! parser, tcode reuses that composer and projects its output onto its
11//! existing `AgentConfig`. Slice C (#2897) additionally routes
12//! `crate::assets::DEFAULT_AGENTS`'s embedded fallback through this module:
13//! the embedded strings have no source directory to resolve an `extends:`
14//! chain against (they are compiled-in `&'static str`, not files on disk), so
15//! [`project_embedded_md`] skips `compose_agent` entirely and calls
16//! [`agent_metadata_from_str`]/[`extract_body`] directly on the raw string —
17//! both are already string-in, string/struct-out, so no file-path dependency
18//! stands in the way. The two entry points ([`load_md_agent`] for disk,
19//! [`project_embedded_md`] for embedded strings) share the exact same
20//! [`project_to_agent_config`] mapping, so there is only ever one frontmatter
21//! -> `AgentConfig` projection to maintain.
22//! What: [`load_md_agent`] reads a `.md` agent source file, calls
23//! `trusty_agents_common::agents::builder::compose_agent` to resolve its
24//! `extends:` chain into one flattened document, projects the composed
25//! frontmatter (via `agents::metadata::agent_metadata_from_str`) and prose
26//! body onto tcode's `AgentConfig`. [`project_embedded_md`] does the same
27//! projection for an in-memory `&'static str` with no `extends:` resolution.
28//! Test: `load_md_agent_base_case`, `tools_projection_*` (the
29//! `Option<Vec<String>>` direct-map), `hr1_initial_prompt_not_leaked_into_body`
30//! (the HR-1 guard), `assets::tests::*` (embedded-default field-identity vs.
31//! the retired TOML fixtures, kept as a historical regression pin).
32
33use std::path::Path;
34
35use trusty_agents_common::agents::builder::compose_agent;
36use trusty_agents_common::agents::builder_in_memory::{
37 build_in_memory_source_map, compose_agent_in_memory,
38};
39use trusty_agents_common::agents::metadata::{AgentMetadata, agent_metadata_from_str};
40
41use super::config::{AgentConfig, AgentInfo, LlmParams, SystemPrompt, ToolsConfig};
42
43/// Load a tcode [`AgentConfig`] from a `.md` agent source file.
44///
45/// Why: the primary entry point for the (now sole) agent loader — takes a
46/// file path and returns a fully-populated `AgentConfig` or a descriptive
47/// error.
48/// What: resolves `path`'s parent directory as the `extends:` source dir and
49/// its file stem as the agent name, composes the inheritance chain via
50/// `compose_agent`, then projects the result via [`project_to_agent_config`].
51/// A missing parent directory, an unreadable file stem, or any
52/// `AgentBuildError` (not found, cycle, depth exceeded, malformed
53/// frontmatter) is surfaced as a descriptive `anyhow::Error` — never a panic.
54/// Test: `load_md_agent_base_case`, `load_md_agent_missing_file_errors`,
55/// `load_md_agent_with_extends_resolves_chain`.
56pub fn load_md_agent(path: &Path) -> anyhow::Result<AgentConfig> {
57 let source_dir = path
58 .parent()
59 .ok_or_else(|| anyhow::anyhow!("agent file {} has no parent directory", path.display()))?;
60 let name = path
61 .file_stem()
62 .and_then(|s| s.to_str())
63 .ok_or_else(|| anyhow::anyhow!("agent file {} has no usable file stem", path.display()))?;
64
65 let composed = compose_agent(name, source_dir).map_err(|e| {
66 anyhow::anyhow!(
67 "failed to compose agent '{name}' from {}: {e}",
68 path.display()
69 )
70 })?;
71
72 let metadata = agent_metadata_from_str(&composed);
73 let body = extract_body(&composed);
74
75 Ok(project_to_agent_config(name, metadata, body))
76}
77
78/// Project an embedded (in-memory, no source directory) `.md` agent document
79/// onto tcode's [`AgentConfig`] — the entry point for
80/// `crate::assets::DEFAULT_AGENTS`'s embedded fallback (Slice C, #2897).
81///
82/// Why: `load_md_agent` resolves an `extends:` inheritance chain via
83/// `compose_agent`, which requires a real source directory to scan for
84/// sibling `.md` files. Embedded default agents are compiled-in
85/// `&'static str` constants with no filesystem location and no `extends:`
86/// chain, so composing would be both impossible (no directory to resolve
87/// against) and unnecessary (none of the three bundled defaults declare
88/// `extends:`). This function shares every other step of the projection —
89/// [`agent_metadata_from_str`] for the frontmatter and [`extract_body`] for
90/// the prose body — with [`load_md_agent`], so the frontmatter -> `AgentConfig`
91/// mapping in [`project_to_agent_config`] is written and tested exactly once.
92/// What: parses `raw`'s frontmatter and body directly (no `compose_agent`
93/// call), then delegates to [`project_to_agent_config`]. `default_name` is
94/// used only when `raw`'s frontmatter carries no `name:` field, mirroring
95/// `load_md_agent`'s file-stem fallback.
96/// Test: `assets::tests::default_agents_field_identical_to_retired_toml`,
97/// `assets::tests::default_agents_parse_and_names_match`.
98pub(crate) fn project_embedded_md(default_name: &str, raw: &str) -> AgentConfig {
99 let metadata = agent_metadata_from_str(raw);
100 let body = extract_body(raw);
101 project_to_agent_config(default_name, metadata, body)
102}
103
104/// Project an embedded tm-catalog agent onto tcode's [`AgentConfig`],
105/// resolving its `extends:` chain entirely against
106/// `crate::assets::EMBEDDED_TM_AGENT_SOURCES` -- no filesystem access
107/// (Slice E2, #2958).
108///
109/// Why: [`project_embedded_md`] handles tcode's own 3 defaults, none of
110/// which declare `extends:`. The bundled tm agent catalog (5 `BASE-*`
111/// templates + 28 coding-relevant roster agents) DOES use `extends:`
112/// chains -- e.g. `rust-engineer` extends `base-engineer` extends
113/// `base-agent` -- and [`compose_agent`] can't resolve those because it
114/// requires a real `source_dir` to scan, which embedded `&'static str`
115/// constants don't have. `trusty_agents_common::agents::builder_in_memory`
116/// (Slice E1, PR #3013) supplies the disk-free counterpart: an
117/// `InMemorySources` map plus `compose_agent_in_memory`, built here from
118/// `crate::assets::EMBEDDED_TM_AGENT_SOURCES` and passed the requested
119/// `name`.
120/// What: builds an `InMemorySources` map from the embedded catalog table,
121/// resolves `name`'s `extends:` chain via `compose_agent_in_memory`, then
122/// projects the composed document through the same
123/// `agent_metadata_from_str` + `extract_body` + [`project_to_agent_config`]
124/// pipeline [`load_md_agent`] uses for the disk path -- so embedded and
125/// on-disk `.md` agents share one frontmatter -> `AgentConfig` mapping. Any
126/// `AgentBuildError` (unknown name, cycle, depth exceeded, malformed
127/// frontmatter anywhere in the chain) is surfaced as a descriptive
128/// `anyhow::Error`, never a panic. Called from
129/// `crate::agents::load_embedded_default_agents` for every
130/// `crate::assets::EmbeddedAgent::Composed` entry in `DEFAULT_AGENTS` (Slice
131/// E3, #2958) -- the 28 roster agents are dispatchable defaults as of this
132/// slice.
133/// Test: `project_embedded_md_with_extends_resolves_rust_engineer_from_base_engineer`,
134/// `project_embedded_md_with_extends_unknown_name_errors`,
135/// `assets::tests::default_agents_parse_and_names_match`.
136pub fn project_embedded_md_with_extends(name: &str) -> anyhow::Result<AgentConfig> {
137 let sources =
138 build_in_memory_source_map(crate::assets::EMBEDDED_TM_AGENT_SOURCES.iter().copied());
139
140 let composed = compose_agent_in_memory(name, &sources).map_err(|e| {
141 anyhow::anyhow!("failed to compose embedded tm-catalog agent '{name}': {e}")
142 })?;
143
144 let metadata = agent_metadata_from_str(&composed);
145 let body = extract_body(&composed);
146
147 Ok(project_to_agent_config(name, metadata, body))
148}
149
150/// Strip the leading YAML frontmatter block from a composed agent document.
151///
152/// Why: `compose_agent`'s merged frontmatter block may carry an HR-1-injected
153/// `initialPrompt` (auto-derived from the agent's `role:`, keyed off
154/// trusty-mpm's role table — see
155/// `trusty_agents_common::agents::builder::merge_frontmatter`'s "HR-1 Part B"
156/// enrichment). tcode's own role vocabulary (`engineer`/`qa`) collides with
157/// that table, so an mpm-role-derived `initialPrompt` must NEVER leak into
158/// tcode's `system_prompt.content` — tcode's system prompt is the composed
159/// PROSE BODY only, exactly as the TOML loader's `system_prompt.content` is a
160/// hand-authored prompt with no injected preamble. `AgentMetadata` (the
161/// public frontmatter projection this module also uses) already omits
162/// `initial_prompt`/`resource_tier` entirely, so there is no accessor that
163/// could leak it into the projection; this function provides the second,
164/// independent guarantee on the body side by never inspecting the
165/// frontmatter block's contents at all — it locates the closing fence
166/// structurally and returns only what follows.
167/// What: `compose_agent`'s output always opens with a `---` line; this scans
168/// past it to the next `---` line and returns everything after, trimmed. A
169/// document with no opening fence (defensive fallback; `compose_agent` always
170/// emits one) returns the whole string trimmed.
171/// Test: `hr1_initial_prompt_not_leaked_into_body`,
172/// `interior_horizontal_rule_survives_in_body`,
173/// `frontmatter_only_agent_has_empty_body`.
174///
175/// `pub(crate)`: also reused by `plugins::agents::load_plugin_agent` (#3539)
176/// so a plugin agent's body is stripped identically to a disk agent's,
177/// without a second frontmatter-fence scanner.
178pub(crate) fn extract_body(composed: &str) -> String {
179 let mut lines = composed.lines();
180 match lines.next() {
181 Some(first) if first.trim() == "---" => {}
182 _ => return composed.trim().to_string(),
183 }
184
185 let mut in_frontmatter = true;
186 let mut body_lines: Vec<&str> = Vec::new();
187 for line in lines {
188 if in_frontmatter {
189 if line.trim() == "---" {
190 in_frontmatter = false;
191 }
192 continue;
193 }
194 body_lines.push(line);
195 }
196 body_lines.join("\n").trim().to_string()
197}
198
199/// Project a composed `.md` agent's metadata + body onto tcode's `AgentConfig`.
200///
201/// Why: centralises the frontmatter -> TOML-schema field mapping so
202/// `load_md_agent` stays a thin IO/compose wrapper.
203/// What:
204/// - `name` -> `agent.name` (falls back to the file-stem `default_name` when
205/// the frontmatter declares no `name:`, mirroring how a source file is
206/// identified by its filename).
207/// - `role`/`description` -> `agent.role`/`agent.description` (direct map).
208/// - `model` -> `agent.model` (the higher-precedence slot per
209/// `provider::routing::resolve_model`; `llm.model_override` is left unset —
210/// the `.md` frontmatter has exactly one model concept, matching how the
211/// TOML fixtures set `[agent].model` and leave `[llm].model_override` unset).
212/// - `max_tokens` -> `llm.max_tokens` (direct map).
213/// - `tools: Option<Vec<String>>` -> `ToolsConfig.allowed` (DIRECT map — both
214/// sides share identical `None`=all-allowed / `Some([])`=deny-all /
215/// `Some(list)`=allowlist semantics, per `Frontmatter::tools`'s doc comment
216/// and `runner::in_process`'s `agent.tools.as_ref().and_then(|t|
217/// t.allowed.as_ref())` consumer, which treats an absent `[tools]` section
218/// (outer `None`) and a present-but-unset `allowed` identically — so always
219/// wrapping in `Some(ToolsConfig { allowed })` is safe and matches the
220/// instructed direct-map).
221/// - composed prose body -> `system_prompt.content`.
222/// - `skills:` -> intentionally DROPPED. `SystemPrompt::append_skills` exists
223/// in tcode's schema but has no consumer anywhere in the codebase (verified:
224/// `grep -rn append_skills crates/trusty-code/src` only shows the field
225/// declaration and TOML asset literals that set it — nothing reads it). The
226/// shared frontmatter's `skills:` list is real and populated
227/// (DOC-42/#2889), but mapping it into a dead field would fabricate a
228/// consumer that doesn't exist. Left as a gap for a future slice that adds
229/// an actual skills consumer to tcode.
230///
231/// `pub(crate)`: also reused by `plugins::agents::load_plugin_agent` (#3539),
232/// which calls this with the plugin's LOCAL agent name (not yet namespaced)
233/// and overrides `agent.name` with the namespaced form afterward — so the
234/// frontmatter -> `AgentConfig` mapping stays written exactly once across
235/// disk, embedded, and plugin agents.
236pub(crate) fn project_to_agent_config(
237 default_name: &str,
238 meta: AgentMetadata,
239 body: String,
240) -> AgentConfig {
241 AgentConfig {
242 agent: AgentInfo {
243 name: meta.name.unwrap_or_else(|| default_name.to_string()),
244 role: meta.role,
245 model: meta.model,
246 description: meta.description,
247 },
248 llm: LlmParams {
249 temperature: None,
250 max_tokens: meta.max_tokens,
251 model_override: None,
252 },
253 system_prompt: SystemPrompt {
254 content: body,
255 // Gap: no tcode consumer for agent-declared skills yet — see the
256 // doc comment above. Left empty rather than mapping into a dead
257 // field.
258 append_skills: Vec::new(),
259 },
260 tools: Some(ToolsConfig {
261 allowed: meta.tools,
262 }),
263 runner: None,
264 }
265}
266
267#[cfg(test)]
268mod tests {
269 use super::*;
270
271 /// A `.md` agent with no `extends:` composes and projects cleanly.
272 ///
273 /// Why: the base case — a self-contained agent, no inheritance chain.
274 /// What: writes a single `.md` file, loads it, asserts every projected
275 /// field.
276 /// Test: this test.
277 #[test]
278 fn load_md_agent_base_case() {
279 let tmp = tempfile::tempdir().expect("tempdir");
280 std::fs::write(
281 tmp.path().join("solo.md"),
282 "---\nname: solo\nrole: engineer\ndescription: A lone agent\nmodel: sonnet\nmax_tokens: 4096\ntools: [read_file, grep]\n---\n\nYou are a solo agent.\n",
283 )
284 .expect("write");
285
286 let cfg = load_md_agent(&tmp.path().join("solo.md")).expect("load");
287 assert_eq!(cfg.agent.name, "solo");
288 assert_eq!(cfg.agent.role.as_deref(), Some("engineer"));
289 assert_eq!(cfg.agent.description.as_deref(), Some("A lone agent"));
290 assert_eq!(cfg.agent.model.as_deref(), Some("sonnet"));
291 assert_eq!(cfg.llm.max_tokens, Some(4096));
292 assert_eq!(cfg.system_prompt.content, "You are a solo agent.");
293 assert_eq!(
294 cfg.tools.and_then(|t| t.allowed),
295 Some(vec!["read_file".to_string(), "grep".to_string()])
296 );
297 }
298
299 /// `tools:` projects with identical `Option<Vec<String>>` semantics on
300 /// both sides: absent key -> `None` (all allowed), `tools: []` ->
301 /// `Some([])` (deny-all), `tools: [a, b]` -> `Some([a, b])` (allowlist).
302 ///
303 /// Why: this is the load-bearing contract from Slice A (#2952) — a naive
304 /// `is_empty()` check would collapse deny-all into "inherit"/"allow-all".
305 /// What: three fixtures, one per case.
306 /// Test: this test.
307 #[test]
308 fn tools_projection_absent_is_none() {
309 let tmp = tempfile::tempdir().expect("tempdir");
310 std::fs::write(
311 tmp.path().join("a.md"),
312 "---\nname: a\nrole: engineer\n---\n\nBody.\n",
313 )
314 .expect("write");
315 let cfg = load_md_agent(&tmp.path().join("a.md")).expect("load");
316 assert_eq!(cfg.tools.and_then(|t| t.allowed), None);
317 }
318
319 #[test]
320 fn tools_projection_empty_list_is_deny_all() {
321 let tmp = tempfile::tempdir().expect("tempdir");
322 std::fs::write(
323 tmp.path().join("a.md"),
324 "---\nname: a\nrole: engineer\ntools: []\n---\n\nBody.\n",
325 )
326 .expect("write");
327 let cfg = load_md_agent(&tmp.path().join("a.md")).expect("load");
328 assert_eq!(cfg.tools.and_then(|t| t.allowed), Some(vec![]));
329 }
330
331 #[test]
332 fn tools_projection_list_is_allowlist() {
333 let tmp = tempfile::tempdir().expect("tempdir");
334 std::fs::write(
335 tmp.path().join("a.md"),
336 "---\nname: a\nrole: engineer\ntools: [read_file, grep]\n---\n\nBody.\n",
337 )
338 .expect("write");
339 let cfg = load_md_agent(&tmp.path().join("a.md")).expect("load");
340 assert_eq!(
341 cfg.tools.and_then(|t| t.allowed),
342 Some(vec!["read_file".to_string(), "grep".to_string()])
343 );
344 }
345
346 /// HR-1 GUARD: a `.md` agent declaring `role: engineer` must NOT get an
347 /// mpm-role-derived `initialPrompt` injected into its `system_prompt.content`.
348 ///
349 /// Why: `merge_frontmatter`'s HR-1 Part B enrichment auto-injects
350 /// `initialPrompt: "Begin implementation. ..."` for `role: engineer` (and
351 /// a distinct prompt for `role: qa`) because trusty-mpm agents rely on
352 /// that injection. tcode's roles collide with that same table by name,
353 /// but tcode's system prompt is the composed PROSE BODY only — the
354 /// injected `initialPrompt` lives in the frontmatter block, which
355 /// `extract_body` never inspects, and `AgentMetadata` (the frontmatter
356 /// projection) has no `initial_prompt` field at all. This test proves
357 /// both guarantees hold end-to-end.
358 /// What: an `engineer`-role agent whose body is a short known string;
359 /// asserts `system_prompt.content` equals exactly that string with no
360 /// HR-1 preamble prepended or appended.
361 /// Test: this test.
362 #[test]
363 fn hr1_initial_prompt_not_leaked_into_body() {
364 let tmp = tempfile::tempdir().expect("tempdir");
365 std::fs::write(
366 tmp.path().join("eng.md"),
367 "---\nname: eng\nrole: engineer\n---\n\nYou write Rust code.\n",
368 )
369 .expect("write");
370
371 let cfg = load_md_agent(&tmp.path().join("eng.md")).expect("load");
372 assert_eq!(
373 cfg.system_prompt.content, "You write Rust code.",
374 "HR-1's role-derived initialPrompt must not leak into the body"
375 );
376 assert!(
377 !cfg.system_prompt.content.contains("Begin implementation"),
378 "HR-1's engineer-role initialPrompt text must not appear anywhere in the body"
379 );
380 }
381
382 /// `extends:` chains resolve through `compose_agent` exactly as
383 /// trusty-mpm's own `.md` agents do.
384 ///
385 /// Why: proves the composer is genuinely reused, not reimplemented.
386 /// What: a base + child fixture; the child's `AgentConfig` carries the
387 /// base's body concatenated before the child's, and the child's
388 /// `max_tokens` wins (scalar child-wins merge).
389 /// Test: this test.
390 #[test]
391 fn load_md_agent_with_extends_resolves_chain() {
392 let tmp = tempfile::tempdir().expect("tempdir");
393 std::fs::write(
394 tmp.path().join("base-x.md"),
395 "---\nname: base-x\nmax_tokens: 1000\n---\n\nBase instructions.\n",
396 )
397 .expect("write");
398 std::fs::write(
399 tmp.path().join("child.md"),
400 "---\nname: child\nextends: base-x\nmax_tokens: 2000\n---\n\nChild instructions.\n",
401 )
402 .expect("write");
403
404 let cfg = load_md_agent(&tmp.path().join("child.md")).expect("load");
405 assert_eq!(cfg.agent.name, "child");
406 assert_eq!(cfg.llm.max_tokens, Some(2000), "child max_tokens wins");
407 assert!(cfg.system_prompt.content.contains("Base instructions."));
408 assert!(cfg.system_prompt.content.contains("Child instructions."));
409 }
410
411 /// A missing `.md` file surfaces a descriptive error, never a panic.
412 ///
413 /// Why: `load_all_agents` needs a fallible, never-panicking contract so
414 /// it can `filter_map` a directory listing without one bad path
415 /// crashing the whole scan.
416 /// What: `load_md_agent` on a nonexistent path returns `Err`.
417 /// Test: this test.
418 #[test]
419 fn load_md_agent_missing_file_errors() {
420 let result = load_md_agent(Path::new("/nonexistent/agents/dir/ghost.md"));
421 assert!(result.is_err());
422 }
423
424 /// A full-fidelity `.md` fixture projects every field the schema exposes
425 /// in one document (name, role, model, max_tokens, tools, system-prompt
426 /// body) — the successor to Slice B's retired
427 /// `parallel_fixture_equivalence` (which additionally compared against a
428 /// hand-authored TOML twin; #2897 Slice D removed the TOML loader that
429 /// comparison depended on, so this test keeps the full-field-set
430 /// assertion on the `.md` fixture alone).
431 ///
432 /// Why: pins that every projected field — not just the ones individual
433 /// narrower tests each cover — round-trips together from one realistic
434 /// agent document.
435 /// What: one `.md` fixture setting every field; asserts `model`,
436 /// `max_tokens`, `tools.allowed`, and `system_prompt.content` all match
437 /// the authored values.
438 /// Test: this test.
439 #[test]
440 fn full_fidelity_md_fixture_projects_every_field() {
441 let tmp = tempfile::tempdir().expect("tempdir");
442
443 std::fs::write(
444 tmp.path().join("twin.md"),
445 "---\nname: twin\nrole: engineer\nmodel: sonnet\nmax_tokens: 8192\ntools: [read_file, grep]\n---\n\nYou are a twin agent.\n",
446 )
447 .expect("write md");
448
449 let cfg = load_md_agent(&tmp.path().join("twin.md")).expect("load md");
450
451 assert_eq!(cfg.agent.name, "twin");
452 assert_eq!(cfg.agent.role.as_deref(), Some("engineer"));
453 assert_eq!(cfg.agent.model.as_deref(), Some("sonnet"));
454 assert_eq!(cfg.llm.max_tokens, Some(8192));
455 assert_eq!(
456 cfg.tools.and_then(|t| t.allowed),
457 Some(vec!["read_file".to_string(), "grep".to_string()])
458 );
459 assert_eq!(cfg.system_prompt.content, "You are a twin agent.");
460 }
461
462 /// `extract_body` closes the frontmatter block on the FIRST `---` fence
463 /// only and never re-enters — a `---` line appearing later, inside the
464 /// prose body (a markdown horizontal rule between two paragraphs), must
465 /// survive verbatim in `system_prompt.content` rather than being mistaken
466 /// for a second frontmatter delimiter.
467 ///
468 /// Why: code-critic finding on PR #2954 — this is the highest-risk edge
469 /// case in the fence-scanning loop (`in_frontmatter` flips to `false` and
470 /// stays `false`), and had no regression pin.
471 /// What: a `.md` fixture whose body contains a paragraph, a bare `---`
472 /// horizontal-rule line, then a second paragraph. Loads through the real
473 /// `compose_agent` -> `load_md_agent` path (not `extract_body` in
474 /// isolation) so the assertion exercises the actual composed output.
475 /// Asserts the horizontal rule is present verbatim as its own line in the
476 /// resulting body.
477 /// Test: this test.
478 #[test]
479 fn interior_horizontal_rule_survives_in_body() {
480 let tmp = tempfile::tempdir().expect("tempdir");
481 std::fs::write(
482 tmp.path().join("hr.md"),
483 "---\nname: hr\nrole: engineer\n---\n\nFirst paragraph.\n\n---\n\nSecond paragraph.\n",
484 )
485 .expect("write");
486
487 let cfg = load_md_agent(&tmp.path().join("hr.md")).expect("load");
488 assert!(
489 cfg.system_prompt
490 .content
491 .lines()
492 .any(|line| line.trim() == "---"),
493 "interior horizontal rule must survive verbatim as its own line; got: {:?}",
494 cfg.system_prompt.content
495 );
496 assert!(cfg.system_prompt.content.contains("First paragraph."));
497 assert!(cfg.system_prompt.content.contains("Second paragraph."));
498 }
499
500 /// A `.md` agent with a valid frontmatter block and NO prose body after
501 /// the closing fence projects to an EMPTY `system_prompt.content` — no
502 /// panic, no leftover blank lines, no stray `---`.
503 ///
504 /// Why: code-critic finding on PR #2954 — the frontmatter-only/empty-body
505 /// case is the other edge of the fence-scanning loop and had no
506 /// regression pin.
507 /// What: a `.md` fixture whose closing fence is the last line of the
508 /// file. Loads through the real `compose_agent` -> `load_md_agent` path.
509 /// Asserts `system_prompt.content == ""`.
510 /// Test: this test.
511 #[test]
512 fn frontmatter_only_agent_has_empty_body() {
513 let tmp = tempfile::tempdir().expect("tempdir");
514 std::fs::write(
515 tmp.path().join("empty.md"),
516 "---\nname: empty\nrole: engineer\n---\n",
517 )
518 .expect("write");
519
520 let cfg = load_md_agent(&tmp.path().join("empty.md")).expect("load");
521 assert_eq!(
522 cfg.system_prompt.content, "",
523 "frontmatter-only agent must project to an empty body, got: {:?}",
524 cfg.system_prompt.content
525 );
526 }
527
528 /// `project_embedded_md_with_extends` resolves a real 3-level
529 /// `extends:` chain (`rust-engineer` -> `base-engineer` -> `base-agent`)
530 /// entirely against the embedded tm catalog table, with no filesystem
531 /// access.
532 ///
533 /// Why: this is the acceptance criterion for Slice E2 (#2958) -- the
534 /// embedded-extends entry point must actually compose a chain, not just
535 /// parse a single flat document. `rust-engineer.md`'s frontmatter
536 /// declares `extends: base-engineer`, which itself declares
537 /// `extends: base-agent` (see `assets/agents/rust-engineer.md` and
538 /// `assets/agents/BASE-ENGINEER.md`), so a correct compose must pull
539 /// prose from all three tiers into the final body.
540 /// What: calls `project_embedded_md_with_extends("rust-engineer")` and
541 /// asserts the name/role/model project correctly and that the composed
542 /// body contains marker text unique to each of the three tiers
543 /// (BASE-AGENT's "Foundation for all trusty-mpm agents", BASE-ENGINEER's
544 /// "Foundation for all engineer agents", and rust-engineer's own
545 /// "toolchains-rust-core").
546 /// Test: this test.
547 #[test]
548 fn project_embedded_md_with_extends_resolves_rust_engineer_from_base_engineer() {
549 let cfg = project_embedded_md_with_extends("rust-engineer").expect("compose rust-engineer");
550
551 assert_eq!(cfg.agent.name, "rust-engineer");
552 assert_eq!(cfg.agent.role.as_deref(), Some("engineer"));
553 assert_eq!(cfg.agent.model.as_deref(), Some("sonnet"));
554 assert!(
555 cfg.system_prompt
556 .content
557 .contains("Foundation for all trusty-mpm agents"),
558 "composed body must include BASE-AGENT tier content"
559 );
560 assert!(
561 cfg.system_prompt
562 .content
563 .contains("Foundation for all engineer agents"),
564 "composed body must include BASE-ENGINEER tier content"
565 );
566 assert!(
567 cfg.system_prompt.content.contains("toolchains-rust-core"),
568 "composed body must include rust-engineer's own content"
569 );
570 }
571
572 /// `project_embedded_md_with_extends` surfaces an unknown agent name as
573 /// a descriptive `anyhow::Error`, never a panic.
574 ///
575 /// Why: mirrors `load_md_agent`'s error-surfacing contract for the fs
576 /// path -- a caller iterating the embedded catalog with a typo'd name
577 /// must get a message it can log, not an unwind.
578 /// What: requests a name absent from `EMBEDDED_TM_AGENT_SOURCES` and
579 /// asserts the call errors.
580 /// Test: this test.
581 #[test]
582 fn project_embedded_md_with_extends_unknown_name_errors() {
583 let result = project_embedded_md_with_extends("does-not-exist");
584 assert!(result.is_err(), "unknown embedded agent name must error");
585 }
586}