trusty-mpm 0.19.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
//! Tests for `agent_builder` — split out to keep `agent_builder.rs` under the
//! 500-line hard cap enforced by `scripts/check_line_cap.sh`.
//!
//! Why: the implementation file (agent_builder.rs) was approaching its frozen
//! budget; the #389 regression tests would have pushed it over, so the test
//! module was extracted here following the same pattern used elsewhere in the
//! crate (e.g. `delegation_authority_tests.rs`).
//! What: all unit and regression tests for [`compose_agent`] and
//! [`source_chain`], including colon-in-value round-trip checks.
//! Test: run with `cargo test -p trusty-mpm -- core::agent_builder`.

use super::*;
use std::fs;
use std::path::Path;
use tempfile::TempDir;

/// Write `<name>.md` into `dir` with the given raw content.
fn write_agent(dir: &Path, name: &str, content: &str) {
    fs::write(dir.join(format!("{name}.md")), content).expect("write agent");
}

#[test]
fn compose_base_only() {
    // An agent with no `extends` returns its own body under a merged
    // frontmatter block — no inheritance to resolve.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "base-agent",
        "---\nname: base-agent\nrole: base\n---\n\n# Base\n\nFoundation content.\n",
    );
    let composed = compose_agent("base-agent", tmp.path()).unwrap();
    assert!(composed.starts_with("---\n"));
    assert!(composed.contains("name: base-agent"));
    assert!(composed.contains("role: base"));
    assert!(composed.contains("Foundation content."));
    // `extends` must never leak into the composed frontmatter.
    assert!(!composed.contains("extends:"));
}

#[test]
fn compose_engineer_chain() {
    // engineer -> base-engineer -> base-agent must concatenate bodies
    // base-first and merge frontmatter child-wins.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "base-agent",
        "---\nname: base-agent\nrole: base\n---\n\n# Base\n\nBASE BODY\n",
    );
    write_agent(
        tmp.path(),
        "base-engineer",
        "---\nname: base-engineer\nrole: base-engineer\nextends: base-agent\n---\n\n# Base Engineer\n\nENGINEER BASE BODY\n",
    );
    write_agent(
        tmp.path(),
        "engineer",
        "---\nname: engineer\nrole: engineer\nextends: base-engineer\nmodel: sonnet\n---\n\n# Engineer\n\nLEAF BODY\n",
    );
    let composed = compose_agent("engineer", tmp.path()).unwrap();

    // Child fields win in the merged frontmatter.
    assert!(composed.contains("name: engineer"));
    assert!(composed.contains("role: engineer"));
    assert!(composed.contains("model: sonnet"));

    // Bodies appear base-first.
    let base = composed.find("BASE BODY").expect("base body present");
    let mid = composed
        .find("ENGINEER BASE BODY")
        .expect("base-engineer body present");
    let leaf = composed.find("LEAF BODY").expect("leaf body present");
    assert!(base < mid, "base body must precede base-engineer body");
    assert!(mid < leaf, "base-engineer body must precede leaf body");
}

#[test]
fn cycle_detection() {
    // A extends B, B extends A -> the chain forms a cycle.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "agent-a",
        "---\nname: agent-a\nextends: agent-b\n---\n\nA body\n",
    );
    write_agent(
        tmp.path(),
        "agent-b",
        "---\nname: agent-b\nextends: agent-a\n---\n\nB body\n",
    );
    let err = compose_agent("agent-a", tmp.path()).unwrap_err();
    match err {
        AgentBuildError::Cycle(chain) => {
            assert!(chain.contains(&"agent-a".to_string()));
            assert!(chain.contains(&"agent-b".to_string()));
        }
        other => panic!("expected Cycle, got {other:?}"),
    }
}

#[test]
fn depth_exceeded() {
    // A chain longer than MAX_DEPTH must fail with DepthExceeded.
    let tmp = TempDir::new().unwrap();
    // Build level0 (root) .. level10 each extending the previous.
    write_agent(tmp.path(), "level0", "---\nname: level0\n---\n\nroot\n");
    for i in 1..=10 {
        write_agent(
            tmp.path(),
            &format!("level{i}"),
            &format!(
                "---\nname: level{i}\nextends: level{}\n---\n\nbody{i}\n",
                i - 1
            ),
        );
    }
    let err = compose_agent("level10", tmp.path()).unwrap_err();
    assert!(
        matches!(err, AgentBuildError::DepthExceeded(MAX_DEPTH)),
        "expected DepthExceeded, got {err:?}"
    );
}

#[test]
fn compose_missing_agent() {
    // A request for a non-existent source file must surface NotFound.
    let tmp = TempDir::new().unwrap();
    let err = compose_agent("ghost", tmp.path()).unwrap_err();
    assert!(matches!(err, AgentBuildError::NotFound(name) if name == "ghost"));
}

#[test]
fn missing_parent_is_not_found() {
    // A child extending an absent parent must report the parent missing.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "child",
        "---\nname: child\nextends: nowhere\n---\n\nbody\n",
    );
    let err = compose_agent("child", tmp.path()).unwrap_err();
    assert!(matches!(err, AgentBuildError::NotFound(name) if name == "nowhere"));
}

#[test]
fn unterminated_frontmatter_errors() {
    // A frontmatter block missing its closing `---` is a parse error.
    let tmp = TempDir::new().unwrap();
    write_agent(tmp.path(), "broken", "---\nname: broken\n\n# No close\n");
    let err = compose_agent("broken", tmp.path()).unwrap_err();
    assert!(matches!(err, AgentBuildError::FrontmatterParse(_)));
}

#[test]
fn source_chain_engineer() {
    // The resolved chain must list ancestors base-first.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "base-agent",
        "---\nname: base-agent\n---\n\nb\n",
    );
    write_agent(
        tmp.path(),
        "base-engineer",
        "---\nname: base-engineer\nextends: base-agent\n---\n\nbe\n",
    );
    write_agent(
        tmp.path(),
        "engineer",
        "---\nname: engineer\nextends: base-engineer\n---\n\ne\n",
    );
    let chain = source_chain("engineer", tmp.path()).unwrap();
    assert_eq!(chain, vec!["base-agent", "base-engineer", "engineer"]);
}

#[test]
fn source_chain_base_only() {
    // A base agent's chain is just itself.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "base-agent",
        "---\nname: base-agent\n---\n\nb\n",
    );
    let chain = source_chain("base-agent", tmp.path()).unwrap();
    assert_eq!(chain, vec!["base-agent"]);
}

// ── colon-in-value regression tests (issue #389) ─────────────────────────

#[test]
fn url_value_round_trips() {
    // A value that is a URL (`https://...`) contains multiple colons; the
    // parser must split on the FIRST colon only and preserve the full URL.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "web-agent",
        "---\nname: web-agent\nrole: web\nmodel: https://example.com/model-api\n---\n\n# Web\n",
    );
    // compose_agent must not error; the URL must survive round-trip.
    let composed = compose_agent("web-agent", tmp.path()).unwrap();
    assert!(
        composed.contains("model: https://example.com/model-api"),
        "URL value must be preserved verbatim; got:\n{composed}"
    );
}

#[test]
fn timestamp_value_round_trips() {
    // ISO-8601 timestamps (`2026-06-05T14:31:34`) contain colons in the
    // time component; the parser must keep the entire timestamp.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "ts-agent",
        "---\nname: ts-agent\nrole: worker\ndescription: Created at 2026-06-05T14:31:34\n---\n\n# TS\n",
    );
    let composed = compose_agent("ts-agent", tmp.path()).unwrap();
    assert!(
        composed.contains("2026-06-05T14:31:34"),
        "timestamp in description must survive; got:\n{composed}"
    );
}

#[test]
fn bedrock_model_id_round_trips() {
    // Model ids like `bedrock/us.anthropic.claude-sonnet-4-6` contain
    // slashes and dots; the full id must survive the round-trip without
    // truncation at any embedded separator.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "ai-agent",
        "---\nname: ai-agent\nrole: ai\nmodel: bedrock/us.anthropic.claude-sonnet-4-6\n---\n\n# AI\n",
    );
    let composed = compose_agent("ai-agent", tmp.path()).unwrap();
    assert!(
        composed.contains("model: bedrock/us.anthropic.claude-sonnet-4-6"),
        "model id must be preserved; got:\n{composed}"
    );
}

// ── case-insensitive resolution regression test (issue #790) ─────────────────
//
// Root cause: base template files on disk are named `BASE-QA.md`,
// `BASE-ENGINEER.md`, etc. (UPPERCASE stems), but concrete agents declare
// `extends: base-qa` / `extends: base-engineer` (lowercase). On macOS
// (case-insensitive HFS+) the OS silently matched these; on Linux
// (case-sensitive ext4) it failed with `agent source not found: base-qa`.
//
// Fix: `build_source_map` keys files by their LOWERCASED stem, so the
// resolver looks up `name.to_lowercase()` and finds the UPPERCASE file
// regardless of the host filesystem's case behaviour.
//
// This test MUST NOT rely on filesystem case-folding to prove correctness.
// It writes the base file with an UPPERCASE stem (`BASE-QA.md`) and the
// concrete agent with `extends: base-qa` (lowercase), then asserts that
// composition succeeds. On a case-SENSITIVE filesystem this would fail
// with the old direct-path code but passes with the new map-based lookup.

// ── HR-1 deploy-time enrichment tests (issue #1406) ──────────────────────────

#[test]
fn tier_model_mapping() {
    // An agent declaring `resource_tier: intensive` with no explicit `model`
    // must receive the tier-derived default (`opus`). Mirrors claude-mpm's
    // RESOURCE_TIER_DEFAULTS.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "heavy",
        "---\nname: heavy\nrole: engineer\nresource_tier: intensive\n---\n\n# Heavy\n",
    );
    let composed = compose_agent("heavy", tmp.path()).unwrap();
    assert!(
        composed.contains("model: opus"),
        "intensive tier must map to opus; got:\n{composed}"
    );
    // The tier itself is preserved for downstream consumers.
    assert!(composed.contains("resource_tier: intensive"));
}

#[test]
fn tier_lightweight_maps_to_haiku() {
    // `lightweight` → haiku.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "light",
        "---\nname: light\nrole: ops\nresource_tier: lightweight\n---\n\n# Light\n",
    );
    let composed = compose_agent("light", tmp.path()).unwrap();
    assert!(
        composed.contains("model: haiku"),
        "lightweight tier must map to haiku; got:\n{composed}"
    );
}

#[test]
fn tier_high_and_standard_map_to_sonnet() {
    // Both `high` and `standard` map to sonnet.
    let tmp = TempDir::new().unwrap();
    for (name, tier) in [("hi", "high"), ("std", "standard")] {
        write_agent(
            tmp.path(),
            name,
            &format!("---\nname: {name}\nrole: engineer\nresource_tier: {tier}\n---\n\n# {name}\n"),
        );
        let composed = compose_agent(name, tmp.path()).unwrap();
        assert!(
            composed.contains("model: sonnet"),
            "{tier} tier must map to sonnet; got:\n{composed}"
        );
    }
}

#[test]
fn tier_unknown_falls_back_to_sonnet() {
    // An unrecognised tier falls back to the standard default (sonnet), per the
    // HR-1 error contract.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "weird",
        "---\nname: weird\nrole: engineer\nresource_tier: galaxy-brain\n---\n\n# Weird\n",
    );
    let composed = compose_agent("weird", tmp.path()).unwrap();
    assert!(
        composed.contains("model: sonnet"),
        "unknown tier must fall back to sonnet; got:\n{composed}"
    );
}

#[test]
fn explicit_model_wins_over_tier() {
    // An explicit `model` must override the tier-derived default — explicit
    // always wins, even when the tier would map to something else.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "pinned",
        "---\nname: pinned\nrole: engineer\nresource_tier: intensive\nmodel: haiku\n---\n\n# Pinned\n",
    );
    let composed = compose_agent("pinned", tmp.path()).unwrap();
    assert!(
        composed.contains("model: haiku"),
        "explicit model must win over tier-derived opus; got:\n{composed}"
    );
    assert!(
        !composed.contains("model: opus"),
        "tier-derived model must not appear when explicit model is set"
    );
}

#[test]
fn no_tier_no_model_emits_no_model() {
    // With neither tier nor explicit model, no `model:` line is synthesised —
    // the enrichment only fires when a tier is present.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "bare",
        "---\nname: bare\nrole: base\n---\n\n# Bare\n",
    );
    let composed = compose_agent("bare", tmp.path()).unwrap();
    assert!(
        !composed.contains("model:"),
        "no model should be emitted without tier or explicit model; got:\n{composed}"
    );
}

#[test]
fn initial_prompt_injected_by_role() {
    // An engineer-role agent that declares no initialPrompt must receive the
    // engineer default at compose time.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "eng",
        "---\nname: eng\nrole: engineer\nmodel: sonnet\n---\n\n# Eng\n",
    );
    let composed = compose_agent("eng", tmp.path()).unwrap();
    assert!(
        composed.contains(r#"initialPrompt: "Begin implementation."#),
        "engineer role must get the implementation initialPrompt; got:\n{composed}"
    );
}

#[test]
fn initial_prompt_role_qa_and_ops() {
    // qa and ops roles get their type-specific prompts.
    let tmp = TempDir::new().unwrap();
    write_agent(tmp.path(), "q", "---\nname: q\nrole: qa\n---\n\n# Q\n");
    write_agent(tmp.path(), "o", "---\nname: o\nrole: ops\n---\n\n# O\n");
    let q = compose_agent("q", tmp.path()).unwrap();
    let o = compose_agent("o", tmp.path()).unwrap();
    assert!(
        q.contains(r#"initialPrompt: "Begin verification."#),
        "qa prompt:\n{q}"
    );
    assert!(
        o.contains(r#"initialPrompt: "Begin operations."#),
        "ops prompt:\n{o}"
    );
}

#[test]
fn initial_prompt_excluded_role() {
    // Special-purpose / interactive roles (e.g. `base`, `ticketing`) must NOT
    // get an injected initialPrompt — they wait for direction.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "mgr",
        "---\nname: mgr\nrole: base\nmodel: sonnet\n---\n\n# Mgr\n",
    );
    let composed = compose_agent("mgr", tmp.path()).unwrap();
    assert!(
        !composed.contains("initialPrompt:"),
        "excluded role must not get an initialPrompt; got:\n{composed}"
    );
}

#[test]
fn initial_prompt_explicit_wins() {
    // A source-declared initialPrompt must survive verbatim and override the
    // role-derived default.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "custom",
        "---\nname: custom\nrole: engineer\ninitialPrompt: Do the special thing first.\n---\n\n# Custom\n",
    );
    let composed = compose_agent("custom", tmp.path()).unwrap();
    assert!(
        composed.contains(r#"initialPrompt: "Do the special thing first.""#),
        "explicit initialPrompt must win; got:\n{composed}"
    );
    assert!(
        !composed.contains("Begin implementation."),
        "role default must not appear when an explicit prompt is set"
    );
}

#[test]
fn enrichment_survives_inheritance_chain() {
    // tier and role come from the child; the enrichment must apply to the fully
    // composed chain, and base content must still be present.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "base-agent",
        "---\nname: base-agent\nrole: base\n---\n\n# Base\n\nBASE GUARANTEE\n",
    );
    write_agent(
        tmp.path(),
        "base-engineer",
        "---\nname: base-engineer\nrole: base-engineer\nextends: base-agent\n---\n\n# Base Eng\n\nENG GUARANTEE\n",
    );
    write_agent(
        tmp.path(),
        "leaf",
        "---\nname: leaf\nrole: engineer\nextends: base-engineer\nresource_tier: intensive\n---\n\n# Leaf\n\nLEAF GUARANTEE\n",
    );
    let composed = compose_agent("leaf", tmp.path()).unwrap();
    // Enrichments applied from the merged (child-wins) frontmatter.
    assert!(
        composed.contains("model: opus"),
        "tier→model on chain:\n{composed}"
    );
    assert!(
        composed.contains(r#"initialPrompt: "Begin implementation."#),
        "role-derived prompt on chain:\n{composed}"
    );
    // Inherited base content still present.
    assert!(composed.contains("BASE GUARANTEE"));
    assert!(composed.contains("ENG GUARANTEE"));
    assert!(composed.contains("LEAF GUARANTEE"));
}

#[test]
fn initial_prompt_with_embedded_quote_round_trips() {
    // A source initialPrompt containing an embedded double-quote must emit
    // valid, parseable frontmatter and survive a compose→re-compose cycle
    // verbatim (the embedded quote is escaped on emit, decoded on re-parse).
    let tmp = TempDir::new().unwrap();
    let original = r#"Run the "fast path" then stop."#;
    write_agent(
        tmp.path(),
        "quoted",
        &format!("---\nname: quoted\nrole: engineer\ninitialPrompt: {original}\n---\n\n# Quoted\n"),
    );

    let composed = compose_agent("quoted", tmp.path()).unwrap();
    // Emitted line must escape the inner quotes — never a bare `"` that would
    // prematurely close the YAML scalar.
    assert!(
        composed.contains(r#"initialPrompt: "Run the \"fast path\" then stop.""#),
        "embedded quote must be escaped in emitted frontmatter; got:\n{composed}"
    );

    // Round-trip: feed the composed file back through compose_agent. The
    // emitted camelCase key re-parses, the escapes decode, and the prompt is
    // recovered unchanged.
    write_agent(tmp.path(), "quoted2", &composed);
    let (fm, _) = split_frontmatter(&composed).expect("composed frontmatter must re-parse");
    assert_eq!(
        fm.initial_prompt.as_deref(),
        Some(original),
        "initialPrompt must survive the compose→re-parse cycle verbatim"
    );

    // And a full re-compose of the round-tripped file emits the same line.
    let recomposed = compose_agent("quoted2", tmp.path()).unwrap();
    assert!(
        recomposed.contains(r#"initialPrompt: "Run the \"fast path\" then stop.""#),
        "re-composed frontmatter must be stable; got:\n{recomposed}"
    );
}

#[test]
fn initial_prompt_with_backslash_round_trips() {
    // A backslash in the prompt must be escaped (`\` → `\\`) on emit and
    // decoded on re-parse so a path-like or regex-like prompt survives.
    let tmp = TempDir::new().unwrap();
    let original = r#"Use the C:\path and the \d+ pattern."#;
    write_agent(
        tmp.path(),
        "slash",
        &format!("---\nname: slash\nrole: engineer\ninitialPrompt: {original}\n---\n\n# Slash\n"),
    );
    let composed = compose_agent("slash", tmp.path()).unwrap();
    let (fm, _) = split_frontmatter(&composed).expect("composed frontmatter must re-parse");
    assert_eq!(
        fm.initial_prompt.as_deref(),
        Some(original),
        "backslash-bearing initialPrompt must round-trip verbatim; got:\n{composed}"
    );
}

#[test]
fn initial_prompt_role_default_round_trips() {
    // The role-derived default prompt (no source initialPrompt) must also be
    // stable across a compose→re-compose cycle, confirming the in-lower /
    // out-camel key convention round-trips.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "eng",
        "---\nname: eng\nrole: engineer\n---\n\n# Eng\n",
    );
    let composed = compose_agent("eng", tmp.path()).unwrap();
    let (fm, _) = split_frontmatter(&composed).expect("composed frontmatter must re-parse");
    assert_eq!(
        fm.initial_prompt.as_deref(),
        Some("Begin implementation. Read the task context and start coding immediately."),
        "role default initialPrompt must re-parse unchanged; got:\n{composed}"
    );
    // Re-composing the round-tripped file yields identical frontmatter for the
    // initialPrompt line (camelCase key, escaped scalar).
    write_agent(tmp.path(), "eng2", &composed);
    let recomposed = compose_agent("eng2", tmp.path()).unwrap();
    let first_line = "initialPrompt: \"Begin implementation.";
    assert!(
        composed.contains(first_line) && recomposed.contains(first_line),
        "initialPrompt line must be stable across the cycle"
    );
}

#[test]
fn case_insensitive_resolve_via_map() {
    // Write `BASE-QA.md` (UPPERCASE stem, as shipped in the bundle) and a
    // concrete `qa.md` that extends it via the lowercase name `base-qa`.
    // The SourceMap must bridge the case gap so compose_agent succeeds on
    // both case-sensitive (Linux) and case-insensitive (macOS) filesystems.
    let tmp = TempDir::new().unwrap();

    // Write the base file with an UPPERCASE stem — matching the real asset name.
    fs::write(
        tmp.path().join("BASE-QA.md"),
        "---\nname: base-qa\nrole: base-qa\n---\n\n# Base QA\n\nBASE QA BODY\n",
    )
    .expect("write BASE-QA.md");

    // Concrete agent uses lowercase in extends — matching the real qa.md.
    write_agent(
        tmp.path(),
        "qa",
        "---\nname: qa\nrole: qa\nextends: base-qa\n---\n\n# QA Agent\n\nQA BODY\n",
    );

    // Verify the SourceMap correctly maps "base-qa" -> BASE-QA.md path.
    let map = build_source_map(tmp.path());
    assert!(
        map.contains_key("base-qa"),
        "SourceMap must contain 'base-qa' key (from BASE-QA.md); map keys: {:?}",
        map.keys().collect::<Vec<_>>()
    );
    assert!(
        map["base-qa"].ends_with("BASE-QA.md"),
        "SourceMap['base-qa'] must point to BASE-QA.md, got {:?}",
        map["base-qa"]
    );

    // The composition must succeed: lowercase extends-value finds UPPERCASE file.
    let composed = compose_agent("qa", tmp.path())
        .expect("compose_agent must succeed: base-qa (lowercase) -> BASE-QA.md (uppercase)");

    // Base body appears before the concrete agent body.
    let base_pos = composed.find("BASE QA BODY").expect("base body present");
    let qa_pos = composed.find("QA BODY").expect("qa body present");
    assert!(
        base_pos < qa_pos,
        "base body must precede concrete agent body"
    );

    // Merged frontmatter carries the child's name.
    assert!(
        composed.contains("name: qa"),
        "merged frontmatter has child name"
    );
    // `extends:` must not leak into the output.
    assert!(
        !composed.contains("extends:"),
        "extends must not appear in output"
    );
}