trusty-agents-common 0.11.2

Stable agent-plugin surface (ToolExecutor, AgentPlugin, ToolResult) shared by trusty-assistants and external agent crates.
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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
//! Tests for `builder` — split out to keep `builder.rs` under the
//! 500-line hard cap enforced by `scripts/check_line_cap.sh`.
//!
//! Why: the implementation file (originally trusty-mpm's `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. Moved verbatim to
//! `trusty-agents-common::agents::builder_tests` alongside the implementation
//! in the #2892 extraction.
//! 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-agents-common -- agents::builder`.

use super::*;
// #4698: the YAML scalar helpers moved to `builder_yaml` when adding
// `provenance:` pushed `builder.rs` over the SLOC cap. `render_scalar` and the
// escape pair arrive through `super::*` (the composer imports them);
// `needs_quoting` has no caller in `builder.rs`, so it is named directly.
use crate::agents::builder_yaml::needs_quoting;
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}"
    );
}

// ── quote-on-emit regression tests (issue #3556) ─────────────────────────
//
// #389 (above) fixed the PARSE side: `parse_kv_line` splits on the first
// colon only, so a colon anywhere in a raw value survives reading. But
// `merge_frontmatter` re-EMITS every scalar as a bare plain YAML scalar
// regardless of content — so a description like "Rust specialist: memory-safe
// systems" composed to an UNQUOTED `description: Rust specialist: memory-safe
// systems` line, which trusty-mpm's own lenient reader tolerates but a real
// YAML parser (`serde_yaml`, what `trusty-agents`' `.md` agent loader uses)
// rejects with "mapping values are not allowed in this context". These tests
// assert the EMIT side is now also colon-safe, and that the composed output
// is actually valid strict YAML — not just re-parseable by the lenient
// reader that missed the bug in the first place.

#[test]
fn compose_description_with_colon_is_quoted_and_strict_yaml_valid() {
    // Reproduces the exact issue #3556 shape (rust-engineer's real
    // description). Before the fix this composed to an unquoted plain
    // scalar containing ": " — invalid YAML.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "rust-engineer",
        "---\nname: rust-engineer\nrole: engineer\ndescription: 'Rust 2024 edition specialist: memory-safe systems, zero-cost abstractions'\nmodel: sonnet\n---\n\n# Rust Engineer\n",
    );
    let composed = compose_agent("rust-engineer", tmp.path()).unwrap();

    // The frontmatter block, strict-parsed with the SAME parser
    // `trusty-agents`' `.md` agent loader uses, must be valid YAML.
    crate::agents::frontmatter::validate_frontmatter(&composed)
        .unwrap_or_else(|e| panic!("composed frontmatter must be valid YAML: {e}\n{composed}"));

    // The description text itself must survive verbatim (quoting must not
    // truncate or corrupt it).
    assert!(
        composed.contains("Rust 2024 edition specialist: memory-safe systems"),
        "description text must survive quoting; got:\n{composed}"
    );
}

#[test]
fn compose_description_without_colon_is_unquoted() {
    // A description with no colon needs no quoting — output must stay byte-
    // identical to today's plain-scalar emission so this fix does not
    // needlessly rewrite the other ~65 already-working deployed agents.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "plain-agent",
        "---\nname: plain-agent\nrole: engineer\ndescription: A plain specialist with no special characters\n---\n\n# Plain\n",
    );
    let composed = compose_agent("plain-agent", tmp.path()).unwrap();
    assert!(
        composed.contains("description: A plain specialist with no special characters\n"),
        "colon-free description must remain an unquoted plain scalar; got:\n{composed}"
    );
}

#[test]
fn needs_quoting_true_for_colon_space() {
    assert!(needs_quoting("has: a colon"));
    assert!(needs_quoting("trailing colon:"));
}

#[test]
fn needs_quoting_true_for_empty() {
    assert!(needs_quoting(""));
}

#[test]
fn needs_quoting_false_for_plain_value() {
    assert!(!needs_quoting("plain sonnet"));
    assert!(!needs_quoting(
        "https://example.com/model-api-no-space-colon"
    ));
}

#[test]
fn needs_quoting_true_for_mid_string_hash_comment() {
    // code-critic review finding on PR #3565 (HIGH): a space followed by `#`
    // starts a YAML comment ANYWHERE in a plain scalar, not just when `#` is
    // the very first character. The pre-fix `needs_quoting` only checked the
    // leading character, so this value composed to an unquoted line where
    // everything from `" #1..."` onward silently vanished as a comment —
    // `compose_agent` succeeded, `validate_frontmatter` accepted it (it IS
    // syntactically valid, truncated, YAML), and the real consumer
    // (`trusty-agents`' `.md` loader) deserialized a silently truncated
    // `description`. Exactly the #3556 root cause's blind spot, different
    // trigger character.
    assert!(needs_quoting(
        "Model context protocol #1 tool for delegating to sub-agents"
    ));
    // A `#` with no preceding space is NOT a comment marker in YAML and must
    // not force quoting that isn't needed.
    assert!(!needs_quoting("agent-name#1-no-space-before-hash"));
}

#[test]
fn compose_description_with_mid_string_hash_is_quoted_and_survives_verbatim() {
    // End-to-end reproduction of the code-critic finding: compose an agent
    // whose description contains a mid-string `" #"`, then parse the result
    // with a REAL strict YAML parser (the same one a consumer like
    // `trusty-agents`' `.md` loader uses) and confirm the deserialized value
    // is the FULL, untruncated text.
    //
    // Checking the raw composed TEXT for the substring (as an earlier
    // version of this test did) is NOT sufficient proof: pre-fix, the raw
    // emitted text still contained the full string byte-for-byte — only a
    // real YAML parser treats `" #1 tool..."` as a comment and silently
    // drops it from the DESERIALIZED value. Asserting on the parsed value,
    // not the raw text, is what actually exercises the bug.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "mcp-agent",
        "---\nname: mcp-agent\nrole: engineer\ndescription: 'Model context protocol #1 tool for delegating to sub-agents'\n---\n\n# MCP\n",
    );
    let composed = compose_agent("mcp-agent", tmp.path()).unwrap();
    crate::agents::frontmatter::validate_frontmatter(&composed)
        .unwrap_or_else(|e| panic!("composed frontmatter must be valid YAML: {e}\n{composed}"));

    let fm_block = composed
        .split("---")
        .nth(1)
        .expect("composed document must have a frontmatter block");
    let value: serde_yaml::Value =
        serde_yaml::from_str(fm_block).expect("frontmatter must strict-parse as YAML");
    let description = value
        .get("description")
        .and_then(|v| v.as_str())
        .expect("description key must be present and a string");
    assert_eq!(
        description, "Model context protocol #1 tool for delegating to sub-agents",
        "the full description, including everything after the mid-string `#`, \
         must survive the ACTUAL YAML PARSE — not merely appear in the raw text"
    );
}

#[test]
fn needs_quoting_true_for_embedded_newline() {
    // A literal newline breaks the single-line frontmatter grammar; must be
    // quoted (and escaped — see `description_with_embedded_newline_round_trips`).
    assert!(needs_quoting("first line\nsecond line"));
}

#[test]
fn description_with_embedded_newline_round_trips() {
    // MEDIUM (code-critic review, PR #3565): an embedded newline previously
    // had no escape support at all — `escape_yaml_double_quoted` had no
    // `\n` case, so a quoted value containing one still produced a
    // physically multi-line frontmatter block. That failed SAFE (rejected
    // as invalid YAML by `validate_frontmatter`, isolated per-agent, never a
    // silent-corruption risk) but was a capability gap. Closed: `\n` now
    // escapes to the two-character `\n` sequence on emit and decodes back
    // to a real newline on parse, verified via a full
    // compose -> split_frontmatter round trip.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "multiline-agent",
        "---\nname: multiline-agent\nrole: engineer\ndescription: 'first line'\n---\n\nBody.\n",
    );
    // compose_agent reads from a real source file (which cannot itself
    // contain a raw embedded newline inside one frontmatter line), so build
    // the composed-with-newline case directly through the merge/split pair
    // the way a genuinely multi-line source value would flow: parse a
    // hand-built frontmatter block containing the ESCAPED form, confirm it
    // decodes to a real newline, then re-emit and confirm it re-escapes
    // identically (the round trip `render_scalar` / `split_frontmatter`
    // both exercise).
    let raw = "---\nname: x\ndescription: \"first line\\nsecond line\"\n---\n\nBody.\n";
    let (fm, _) = split_frontmatter(raw).unwrap();
    assert_eq!(fm.description.as_deref(), Some("first line\nsecond line"));

    let composed = render_composed(&[fm], &["Body.".to_string()]);
    crate::agents::frontmatter::validate_frontmatter(&composed)
        .unwrap_or_else(|e| panic!("re-composed frontmatter must be valid YAML: {e}\n{composed}"));
    assert!(
        composed.contains("description: \"first line\\nsecond line\"\n"),
        "embedded newline must re-escape identically; got:\n{composed}"
    );
}

#[test]
fn needs_quoting_true_for_null_tokens() {
    // LOW (code-critic review, PR #3565): the YAML core-schema null tokens
    // deserialize a scalar field to `None` rather than the literal string,
    // unlike every other bool/number-shaped value (`true`, `007`, dates),
    // which round-trip fine through the typed `Option<String>` deserializer
    // — this is NOT the classic Norway-problem footgun, just these two
    // spellings (plus their case variants).
    assert!(needs_quoting("null"));
    assert!(needs_quoting("Null"));
    assert!(needs_quoting("NULL"));
    assert!(needs_quoting("~"));
}

#[test]
fn needs_quoting_indicator_characters() {
    // Table-driven coverage of every YAML indicator character `needs_quoting`
    // checks as a leading character (code-critic review, PR #3565 — prior
    // coverage only exercised 3 shapes plus one colon-free value despite the
    // doc comment's broader claim).
    let indicators = [
        '!', '&', '*', '-', '?', '|', '>', '%', '@', '`', '"', '\'', '#', ',', '[', ']', '{', '}',
        ':',
    ];
    for c in indicators {
        let value = format!("{c}leading-indicator");
        assert!(
            needs_quoting(&value),
            "leading `{c}` must require quoting, got needs_quoting({value:?}) == false"
        );
    }
}

#[test]
fn needs_quoting_true_for_leading_and_trailing_whitespace() {
    assert!(needs_quoting(" leading space"));
    assert!(needs_quoting("trailing space "));
}

#[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"
    );
}

// ── DOC-42 (issue #2889) — `skills:` frontmatter parsing & merge ───────────

#[test]
fn compose_agent_with_no_skills_omits_the_key() {
    // Absent `skills:` must parse to empty and never appear in the composed
    // output — exactly today's behavior (backward compatibility).
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "plain",
        "---\nname: plain\nrole: base\n---\n\n# Plain\n\nBODY\n",
    );
    let composed = compose_agent("plain", tmp.path()).unwrap();
    assert!(!composed.contains("skills:"));
}

#[test]
fn compose_agent_declares_skills_inline_array() {
    // The normative grammar (DOC-42 §SPEC-AGENTSKILLS-01): a bracketed,
    // comma-separated inline array on the `skills:` line.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "critic",
        "---\nname: critic\nrole: qa\nskills: [code-review-standards, systematic-debugging]\n---\n\n# Critic\n\nBODY\n",
    );
    let composed = compose_agent("critic", tmp.path()).unwrap();
    assert!(composed.contains("skills: [code-review-standards, systematic-debugging]"));
}

#[test]
fn compose_agent_empty_skills_array_omits_the_key() {
    // `skills: []` is documented as equivalent to omission.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "plain",
        "---\nname: plain\nrole: engineer\nskills: []\n---\n\n# Plain\n\nBODY\n",
    );
    let composed = compose_agent("plain", tmp.path()).unwrap();
    assert!(!composed.contains("skills:"));
}

#[test]
fn skills_union_across_chain() {
    // A child agent's declared skills merge with its base's — both survive
    // in the composed output (list fields union, unlike scalar overrides).
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "base-qa",
        "---\nname: base-qa\nrole: base-qa\nskills: [verification-before-completion]\n---\n\n# Base QA\n\nBASE BODY\n",
    );
    write_agent(
        tmp.path(),
        "code-critic",
        "---\nname: code-critic\nrole: qa\nextends: base-qa\nskills: [code-review-standards]\n---\n\n# Critic\n\nLEAF BODY\n",
    );
    let composed = compose_agent("code-critic", tmp.path()).unwrap();
    assert!(composed.contains("skills: [verification-before-completion, code-review-standards]"));
}

#[test]
fn skills_deduplicated_across_chain() {
    // The same skill declared by both base and child must appear once, at
    // its first-seen (base-first) position.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "base-qa",
        "---\nname: base-qa\nrole: base-qa\nskills: [shared-skill]\n---\n\n# Base QA\n\nBASE BODY\n",
    );
    write_agent(
        tmp.path(),
        "code-critic",
        "---\nname: code-critic\nrole: qa\nextends: base-qa\nskills: [shared-skill, unique-skill]\n---\n\n# Critic\n\nLEAF BODY\n",
    );
    let composed = compose_agent("code-critic", tmp.path()).unwrap();
    assert!(composed.contains("skills: [shared-skill, unique-skill]"));
    // Must not appear twice.
    assert_eq!(composed.matches("shared-skill").count(), 1);
}

#[test]
fn compose_agent_matches_sibling_2890_code_critic_fixture() {
    // Cross-PR compatibility fixture (issue #2890, PR #2900 on
    // `feat-2890-code-critic-skills`): the sibling agent declares
    // `code-critic.md`'s `skills:` using the exact same inline flow-style
    // array syntax this parser implements —
    // `skills: [code-review-standards, contract-driven-testing]`. This test
    // pins that EXACT syntax (not the real bundled `code-critic.md`, which
    // lives on a branch not yet merged to main) so #2889's parser and
    // #2890's asset content compose correctly once both land.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "code-critic",
        "---\nname: code-critic\nrole: qa\nskills: [code-review-standards, contract-driven-testing]\n---\n\n# Code Critic\n\nBODY\n",
    );
    let composed = compose_agent("code-critic", tmp.path()).unwrap();
    assert!(composed.contains("skills: [code-review-standards, contract-driven-testing]"));
}

#[test]
fn compose_agent_parses_block_style_skills_list() {
    // Issue #2906 review (CRITICAL): DOC-42 §1.1's motivating example (and
    // every realistic upstream `claude-mpm-agents` asset) declares `skills:`
    // as a YAML BLOCK sequence, not the inline flow array:
    //   skills:
    //     - code-review-standards
    //     - code-production-process
    // This must compose successfully (not error) and populate BOTH items.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "code-critic",
        "---\nname: code-critic\nrole: qa\nskills:\n  - code-review-standards\n  - code-production-process\n---\n\n# Code Critic\n\nBODY\n",
    );
    let composed = compose_agent("code-critic", tmp.path());
    assert!(
        composed.is_ok(),
        "block-style skills list must compose successfully, got: {composed:?}"
    );
    let composed = composed.unwrap();
    assert!(composed.contains("skills: [code-review-standards, code-production-process]"));
}

#[test]
fn compose_agent_block_style_skills_survives_inheritance() {
    // The block-style form must union across `extends:` exactly like the
    // inline flow form does.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "base-qa",
        "---\nname: base-qa\nrole: base-qa\nskills:\n  - verification-before-completion\n---\n\n# Base QA\n\nBASE BODY\n",
    );
    write_agent(
        tmp.path(),
        "code-critic",
        "---\nname: code-critic\nrole: qa\nextends: base-qa\nskills:\n  - code-review-standards\n---\n\n# Critic\n\nLEAF BODY\n",
    );
    let composed = compose_agent("code-critic", tmp.path()).unwrap();
    assert!(composed.contains("skills: [verification-before-completion, code-review-standards]"));
}

#[test]
fn compose_agent_block_style_skills_with_trailing_content() {
    // A block sequence followed by MORE frontmatter keys (not immediately the
    // closing fence) must still parse: the block ends on the first
    // non-`-`/non-blank line, and that line is then parsed normally.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "critic",
        "---\nname: critic\nskills:\n  - code-review-standards\n  - systematic-debugging\nmodel: sonnet\n---\n\nBODY\n",
    );
    let composed = compose_agent("critic", tmp.path()).unwrap();
    assert!(composed.contains("skills: [code-review-standards, systematic-debugging]"));
    assert!(composed.contains("model: sonnet"));
}

#[test]
fn compose_agent_empty_block_style_skills_omits_the_key() {
    // A bare `skills:` with NO continuation items (block never populated)
    // must degrade to empty — equivalent to omission — not error.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "plain",
        "---\nname: plain\nskills:\nmodel: sonnet\n---\n\nBODY\n",
    );
    let composed = compose_agent("plain", tmp.path());
    assert!(composed.is_ok(), "empty block-style skills must not error");
    assert!(!composed.unwrap().contains("skills:"));
}

#[test]
fn skills_malformed_value_is_treated_as_empty() {
    // A `skills:` line whose value doesn't look like a list (e.g. blank)
    // must never hard-error the compose — it parses to an empty list.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "plain",
        "---\nname: plain\nrole: engineer\nskills:\n---\n\n# Plain\n\nBODY\n",
    );
    let composed = compose_agent("plain", tmp.path());
    assert!(composed.is_ok(), "malformed skills value must not error");
    assert!(!composed.unwrap().contains("skills:"));
}

#[test]
fn skills_malformed_inline_value_never_errors() {
    // Issue #2906 review (MEDIUM finding): a genuinely unparseable inline
    // value (comma(s) with no real elements) must still degrade to an empty
    // list rather than error — the fix adds a `tracing::warn!` at this call
    // site (not directly assertable in a unit test without a subscriber),
    // but the never-halt contract IS assertable here.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "plain",
        "---\nname: plain\nskills: ,\n---\n\nBODY\n",
    );
    let composed = compose_agent("plain", tmp.path());
    assert!(composed.is_ok(), "malformed inline skills must not error");
    assert!(!composed.unwrap().contains("skills:"));
}

// ── #2897: max_tokens + tools (tcode agent-format unification, epic #2892) ─

#[test]
fn max_tokens_parses_from_frontmatter() {
    // A bare `max_tokens:` scalar must parse and emit unchanged when there
    // is no `extends` chain to merge across.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "solo",
        "---\nname: solo\nrole: engineer\nmax_tokens: 4096\n---\n\n# Solo\n",
    );
    let composed = compose_agent("solo", tmp.path()).unwrap();
    assert!(composed.contains("max_tokens: 4096"), "got:\n{composed}");
}

#[test]
fn max_tokens_child_wins_across_chain() {
    // Scalar child-wins merge, mirroring `model:` — the child's explicit
    // value overrides the parent's.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "base-agent",
        "---\nname: base-agent\nrole: base\nmax_tokens: 8192\n---\n\n# Base\n",
    );
    write_agent(
        tmp.path(),
        "leaf",
        "---\nname: leaf\nrole: engineer\nextends: base-agent\nmax_tokens: 4096\n---\n\n# Leaf\n",
    );
    let composed = compose_agent("leaf", tmp.path()).unwrap();
    assert!(
        composed.contains("max_tokens: 4096"),
        "child's max_tokens must win; got:\n{composed}"
    );
    assert!(!composed.contains("max_tokens: 8192"));
}

#[test]
fn max_tokens_unset_child_inherits_parent() {
    // A child that omits `max_tokens:` must inherit the parent's value
    // rather than clearing it — same child-wins-only-when-set semantics as
    // `model:`.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "base-agent",
        "---\nname: base-agent\nrole: base\nmax_tokens: 8192\n---\n\n# Base\n",
    );
    write_agent(
        tmp.path(),
        "leaf",
        "---\nname: leaf\nrole: engineer\nextends: base-agent\n---\n\n# Leaf\n",
    );
    let composed = compose_agent("leaf", tmp.path()).unwrap();
    assert!(
        composed.contains("max_tokens: 8192"),
        "child must inherit parent's max_tokens when unset; got:\n{composed}"
    );
}

#[test]
fn max_tokens_malformed_value_is_dropped_not_panicking() {
    // Code-critic finding on PR #2952 (MEDIUM): a non-numeric, negative, or
    // out-of-range `max_tokens:` value must warn-and-drop (parse to `None`)
    // rather than panicking or hard-erroring the compose — mirroring
    // `skills_malformed_inline_value_never_errors`.
    let tmp = TempDir::new().unwrap();
    for (name, raw) in [
        ("non-numeric", "not-a-number"),
        ("negative", "-42"),
        ("too-large", "99999999999999999999"), // far beyond u32::MAX
    ] {
        write_agent(
            tmp.path(),
            name,
            &format!("---\nname: {name}\nrole: engineer\nmax_tokens: {raw}\n---\n\n# {name}\n"),
        );
        let composed = compose_agent(name, tmp.path());
        assert!(
            composed.is_ok(),
            "malformed max_tokens ({name} = {raw:?}) must not error"
        );
        assert!(
            !composed.unwrap().contains("max_tokens:"),
            "malformed max_tokens ({name} = {raw:?}) must drop to None, not \
             synthesise a `max_tokens:` line"
        );
    }
}

#[test]
fn tools_parses_as_a_list() {
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "solo",
        "---\nname: solo\nrole: engineer\ntools: [read, write, bash]\n---\n\n# Solo\n",
    );
    let composed = compose_agent("solo", tmp.path()).unwrap();
    assert!(
        composed.contains("tools: [read, write, bash]"),
        "got:\n{composed}"
    );
}

#[test]
fn tools_malformed_inline_value_never_errors() {
    // Mirrors `skills_malformed_inline_value_never_errors`: a genuinely
    // unparseable inline value (comma with no real elements) must never
    // hard-error the compose. Since the `tools:` key IS present (even though
    // malformed), it parses to `Some(vec![])` — same as an explicit
    // `tools: []` — which is the correct, safe degrade: a garbled
    // restriction is not silently discarded back into "inherit everything".
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "plain",
        "---\nname: plain\nrole: engineer\ntools: ,\n---\n\nBODY\n",
    );
    let composed = compose_agent("plain", tmp.path());
    assert!(composed.is_ok(), "malformed inline tools must not error");
    assert!(
        composed.unwrap().contains("tools: []"),
        "a malformed but present `tools:` key must degrade to an explicit \
         empty override, not silently vanish"
    );
}

#[test]
fn tools_override_across_chain() {
    // Unlike `skills:`, `tools:` REPLACES the parent's list entirely when
    // the child declares a non-empty `tools:` — a restrictive leaf must be
    // able to narrow a permissive base's tool set.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "base-agent",
        "---\nname: base-agent\nrole: base\ntools: [x, y, z]\n---\n\n# Base\n",
    );
    write_agent(
        tmp.path(),
        "leaf",
        "---\nname: leaf\nrole: engineer\nextends: base-agent\ntools: [a, b]\n---\n\n# Leaf\n",
    );
    let composed = compose_agent("leaf", tmp.path()).unwrap();
    assert!(
        composed.contains("tools: [a, b]"),
        "child's tools must replace the parent's; got:\n{composed}"
    );
    assert!(!composed.contains("x, y, z"));
}

#[test]
fn tools_unset_child_inherits_parent() {
    // A child that omits `tools:` must inherit the parent's list unchanged.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "base-agent",
        "---\nname: base-agent\nrole: base\ntools: [x, y, z]\n---\n\n# Base\n",
    );
    write_agent(
        tmp.path(),
        "leaf",
        "---\nname: leaf\nrole: engineer\nextends: base-agent\n---\n\n# Leaf\n",
    );
    let composed = compose_agent("leaf", tmp.path()).unwrap();
    assert!(
        composed.contains("tools: [x, y, z]"),
        "child must inherit parent's tools when unset; got:\n{composed}"
    );
}

#[test]
fn tools_empty_list_overrides_to_deny_all() {
    // Code-critic finding on PR #2952 (MEDIUM): `tools: []` must be a
    // distinguishable, explicit deny-all override — NOT collapse into the
    // same "inherit the parent" behaviour an omitted `tools:` key produces.
    // A non-empty parent list must be overridden down to zero, and this must
    // be provably different from `tools_unset_child_inherits_parent` above
    // (same parent, different child declaration, opposite outcome).
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "base-agent",
        "---\nname: base-agent\nrole: base\ntools: [x, y, z]\n---\n\n# Base\n",
    );
    write_agent(
        tmp.path(),
        "leaf",
        "---\nname: leaf\nrole: engineer\nextends: base-agent\ntools: []\n---\n\n# Leaf\n",
    );
    let composed = compose_agent("leaf", tmp.path()).unwrap();
    assert!(
        composed.contains("tools: []"),
        "an explicit empty `tools:` must override the parent's list down to \
         zero (deny-all), not inherit; got:\n{composed}"
    );
    assert!(
        !composed.contains("x, y, z"),
        "the parent's tools must not survive an explicit `tools: []` \
         override; got:\n{composed}"
    );
}

#[test]
fn tools_override_contrasts_with_skills_union() {
    // Same chain shape, both a `skills:` and a `tools:` declaration at each
    // level — `skills:` must UNION (both survive) while `tools:` must
    // OVERRIDE (only the child's survive). Proves the two list fields do not
    // share merge logic.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "base-agent",
        "---\nname: base-agent\nrole: base\nskills: [base-skill]\ntools: [base-tool]\n---\n\n# Base\n",
    );
    write_agent(
        tmp.path(),
        "leaf",
        "---\nname: leaf\nrole: engineer\nextends: base-agent\nskills: [leaf-skill]\ntools: [leaf-tool]\n---\n\n# Leaf\n",
    );
    let composed = compose_agent("leaf", tmp.path()).unwrap();
    // skills: union — both survive.
    assert!(
        composed.contains("skills: [base-skill, leaf-skill]"),
        "skills must union; got:\n{composed}"
    );
    // tools: override — only the child's tool survives.
    assert!(
        composed.contains("tools: [leaf-tool]"),
        "tools must override, not union; got:\n{composed}"
    );
    assert!(
        !composed.contains("base-tool"),
        "the parent's tool must not survive the override; got:\n{composed}"
    );
}

/// `tcode_tools:` is a second, independent allowlist (#7683).
///
/// Why: one roster, two runtimes. `tools:` carries Claude Code's vocabulary
/// and `tcode_tools:` trusty-code's; if the two shared a field, a Claude
/// allowlist would gate trusty-code's registry to zero callable tools. This
/// pins that they parse, merge and emit separately — and that `tcode_tools:`
/// follows the SAME override rule, so a restrictive tcode leaf still narrows
/// a permissive base.
/// Test: this test.
#[test]
fn tcode_tools_parses_and_overrides_independently_of_tools() {
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "base-agent",
        "---\nname: base-agent\nrole: base\ntools: [Read]\ntcode_tools: [read_file]\n---\n\n# Base\n",
    );
    write_agent(
        tmp.path(),
        "leaf",
        "---\nname: leaf\nrole: engineer\nextends: base-agent\ntcode_tools: [bash, finish_task]\n---\n\n# Leaf\n",
    );
    let composed = compose_agent("leaf", tmp.path()).unwrap();
    assert!(
        composed.contains("tcode_tools: [bash, finish_task]"),
        "the child's tcode_tools must override the parent's; got:\n{composed}"
    );
    assert!(
        !composed.contains("read_file"),
        "the parent's tcode_tools must not survive the override; got:\n{composed}"
    );
    assert!(
        composed.contains("tools: [Read]"),
        "an untouched `tools:` must still be inherited verbatim; got:\n{composed}"
    );
}

#[test]
fn no_max_tokens_no_tools_agent_composes_unchanged() {
    // Behavior-preservation for tm (#2897): a tm-style agent that never sets
    // `max_tokens:`/`tools:` must compose byte-identically to the pre-#2897
    // output — no `max_tokens:` or `tools:` line is synthesised, and no
    // other field is perturbed.
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "base-engineer",
        "---\nname: base-engineer\nrole: base-engineer\n---\n\n# Base Engineer\n\nBASE BODY\n",
    );
    write_agent(
        tmp.path(),
        "rust-engineer",
        "---\nname: rust-engineer\nrole: engineer\nextends: base-engineer\nmodel: sonnet\nskills: [toolchains-rust-core]\n---\n\n# Rust Engineer\n\nLEAF BODY\n",
    );
    let composed = compose_agent("rust-engineer", tmp.path()).unwrap();
    let expected = "---\nname: rust-engineer\nrole: engineer\nmodel: sonnet\nskills: [toolchains-rust-core]\ninitialPrompt: \"Begin implementation. Read the task context and start coding immediately.\"\n---\n\n# Base Engineer\n\nBASE BODY\n\n# Rust Engineer\n\nLEAF BODY\n";
    assert_eq!(
        composed, expected,
        "tm-style agent (no max_tokens/tools) must compose byte-identically \
         to pre-#2897 output"
    );
    assert!(!composed.contains("max_tokens:"));
    assert!(!composed.contains("tools:"));
}

/// #4511: parsing `agent_type:` must NOT change what compose emits.
///
/// Why: the field was added so a READER can see the claude-mpm-format
/// spelling of an agent's declared domain. This composer canonicalises on
/// `role:` — emitting a second domain key would change the bytes of every
/// deployed artifact for a value nothing in the compose path consumes. Before
/// the field existed the key was parsed into the discard bucket and dropped;
/// it must still be dropped.
#[test]
fn agent_type_is_parsed_but_never_emitted() {
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "aws-ops",
        "---\nname: aws-ops\nagent_type: ops\n---\n\n# AWS Ops\n\nBODY\n",
    );

    // The reader sees it...
    let (fm, _body) =
        split_frontmatter(&fs::read_to_string(tmp.path().join("aws-ops.md")).unwrap()).unwrap();
    assert_eq!(fm.agent_type.as_deref(), Some("ops"));

    // ...and compose still drops it, byte-identically to pre-#4511 output.
    let composed = compose_agent("aws-ops", tmp.path()).unwrap();
    assert_eq!(composed, "---\nname: aws-ops\n---\n\n# AWS Ops\n\nBODY\n");
}

// ---------------------------------------------------------------------------
// #4698: the `provenance:` frontmatter field.
// ---------------------------------------------------------------------------

/// The field parses, merges, and is re-emitted, so a composed file stays
/// self-describing about who wrote it.
#[test]
fn provenance_parsed_merged_and_emitted() {
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "qa",
        "---\nname: qa\nrole: base\nprovenance: tm-agent-manager-built\n---\n\n# QA\n\nBODY\n",
    );

    let (fm, _body) =
        split_frontmatter(&fs::read_to_string(tmp.path().join("qa.md")).unwrap()).unwrap();
    assert_eq!(fm.provenance, Some(Provenance::TmAgentManagerBuilt));

    let composed = compose_agent("qa", tmp.path()).unwrap();
    assert_eq!(
        composed,
        "---\nname: qa\nrole: base\nprovenance: tm-agent-manager-built\n---\n\n# QA\n\nBODY\n"
    );
}

/// Absence is the signal #4698 relies on, so an agent that declares nothing
/// composes to output with no `provenance:` line at all — byte-identical to
/// what the composer emitted before this field existed.
#[test]
fn absent_provenance_emits_no_line() {
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "plain",
        "---\nname: plain\nrole: base\n---\n\n# Plain\n\nBODY\n",
    );
    let composed = compose_agent("plain", tmp.path()).unwrap();
    assert_eq!(
        composed,
        "---\nname: plain\nrole: base\n---\n\n# Plain\n\nBODY\n"
    );
    assert!(!composed.contains("provenance"));
}

/// Scalar child-wins across an `extends` chain, matching `model:`.
#[test]
fn provenance_child_wins_across_chain() {
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "base-agent",
        "---\nname: base-agent\nprovenance: framework-owned\n---\n\nBASE\n",
    );
    write_agent(
        tmp.path(),
        "child",
        "---\nname: child\nextends: base-agent\nprovenance: user-authored\n---\n\nCHILD\n",
    );
    let composed = compose_agent("child", tmp.path()).unwrap();
    assert!(composed.contains("provenance: user-authored"));
    assert!(!composed.contains("framework-owned"));

    // And a child that declares nothing inherits the base's declaration.
    write_agent(
        tmp.path(),
        "quiet",
        "---\nname: quiet\nextends: base-agent\n---\n\nQUIET\n",
    );
    assert!(
        compose_agent("quiet", tmp.path())
            .unwrap()
            .contains("provenance: framework-owned")
    );
}

/// An unrecognised value is REJECTED with the typed error, never coerced to
/// the absent default — coercion would read a typo as user-authored and freeze
/// a framework file (#4408's shape).
#[test]
fn unknown_provenance_value_is_rejected() {
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "typo",
        "---\nname: typo\nprovenance: framework_owned\n---\n\nBODY\n",
    );
    let err = compose_agent("typo", tmp.path()).unwrap_err();
    match &err {
        AgentBuildError::InvalidProvenance(inner) => assert_eq!(inner.value, "framework_owned"),
        other => panic!("expected InvalidProvenance, got {other:?}"),
    }
    assert!(
        err.to_string().contains("framework_owned"),
        "the message names the offending value: {err}"
    );
    // The typed payload is reachable through `source()` too.
    assert!(std::error::Error::source(&err).is_some());
}

/// The deployer supplies the value; the source need not declare one.
#[test]
fn compose_with_provenance_stamps_the_field() {
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "plain",
        "---\nname: plain\nrole: base\n---\n\n# Plain\n\nBODY\n",
    );
    let composed =
        compose_agent_with_provenance("plain", tmp.path(), Provenance::FrameworkOwned).unwrap();
    assert_eq!(
        composed,
        "---\nname: plain\nrole: base\nprovenance: framework-owned\n---\n\n# Plain\n\nBODY\n"
    );
    // Removing the stamped line recovers the unstamped composition exactly —
    // the property the deployer's adoption path depends on.
    assert_eq!(
        crate::agents::provenance::without_provenance_line(&composed),
        compose_agent("plain", tmp.path()).unwrap()
    );
}

/// The writer's claim about its own authorship overrides the source's.
#[test]
fn compose_with_provenance_overrides_a_source_declaration() {
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "claims",
        "---\nname: claims\nprovenance: user-authored\n---\n\nBODY\n",
    );
    let composed =
        compose_agent_with_provenance("claims", tmp.path(), Provenance::FrameworkOwned).unwrap();
    assert!(composed.contains("provenance: framework-owned"));
    assert!(!composed.contains("user-authored"));
}

/// #9011: a block-form `metadata:` map is parsed, carried through the merge,
/// and emitted last as a block with a double-quoted value. The indented
/// `version:` never becomes a top-level key.
#[test]
fn metadata_block_parsed_merged_and_emitted() {
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "solo",
        "---\nname: solo\nrole: qa\nmetadata:\n  version: \"1.0.0\"\n\n  # note\nmodel: sonnet\n---\n\nBODY\n",
    );
    let (fm, _) =
        split_frontmatter(&fs::read_to_string(tmp.path().join("solo.md")).unwrap()).unwrap();
    assert_eq!(
        fm.metadata,
        vec![("version".to_string(), "1.0.0".to_string())]
    );
    assert_eq!(
        fm.model.as_deref(),
        Some("sonnet"),
        "the block ends at the next top-level key"
    );

    let composed = compose_agent("solo", tmp.path()).unwrap();
    assert!(
        composed.starts_with("---\nname: solo\nrole: qa\nmodel: sonnet\n"),
        "{composed}"
    );
    assert!(
        composed.contains("\nmetadata:\n  version: \"1.0.0\"\n---\n"),
        "{composed}"
    );
    assert!(crate::agents::frontmatter::validate_frontmatter(&composed).is_ok());
}

/// #9011: the one-line flow form reads the same as the block form.
#[test]
fn metadata_flow_form_is_parsed() {
    let (fm, _) =
        split_frontmatter("---\nname: a\nmetadata: {version: \"0.3.0\", owner: x}\n---\n\nB\n")
            .unwrap();
    assert_eq!(
        fm.metadata,
        vec![
            ("version".to_string(), "0.3.0".to_string()),
            ("owner".to_string(), "x".to_string()),
        ]
    );
}

/// #9011: per-key child-wins — the leaf's `version` replaces the base's, and a
/// key only the base declares is inherited.
#[test]
fn metadata_child_wins_across_chain() {
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "base-agent",
        "---\nname: base-agent\nmetadata:\n  version: \"1.0.0\"\n  owner: core\n---\n\nBASE\n",
    );
    write_agent(
        tmp.path(),
        "child",
        "---\nname: child\nextends: base-agent\nmetadata:\n  version: \"2.0.0\"\n---\n\nCHILD\n",
    );
    let composed = compose_agent("child", tmp.path()).unwrap();
    assert!(
        composed.contains("metadata:\n  version: \"2.0.0\"\n  owner: \"core\"\n---\n"),
        "{composed}"
    );
}

/// #9011: `metadata:` is a map; a scalar or a non-`key: value` child is a
/// parse error, not a silently dropped version.
#[test]
fn metadata_non_map_value_is_rejected() {
    for doc in [
        "---\nname: a\nmetadata: 1.0.0\n---\n\nB\n",
        "---\nname: a\nmetadata:\n  - 1.0.0\n---\n\nB\n",
    ] {
        assert!(
            matches!(
                split_frontmatter(doc),
                Err(AgentBuildError::FrontmatterParse(_))
            ),
            "{doc:?}"
        );
    }
}

/// #8199: a `permissions:` block — including a nested argument table — is
/// re-emitted verbatim, and its indented rule keys never leak into the
/// top-level fields (`model:` below is a tool glob, not the agent's model).
/// FAILS before #8199: the composer had no `permissions` field and dropped it.
/// Test: this test.
#[test]
fn permissions_block_survives_compose_verbatim() {
    let block =
        "permissions:\n  bash:\n    \"rm *\": deny\n    \"*\": ask\n  model: deny\n  edit: ask\n";
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "solo",
        &format!("---\nname: solo\nrole: pm\n{block}model: sonnet\n---\n\nBODY\n"),
    );
    let composed = compose_agent("solo", tmp.path()).unwrap();
    assert!(composed.contains(&format!("\n{block}")), "{composed}");
    assert!(composed.contains("\nmodel: sonnet\n"), "{composed}");
    assert!(crate::agents::frontmatter::validate_frontmatter(&composed).is_ok());
}

/// #8199: the block belongs to the file that declares it (#7948) — a base's
/// block is not inherited, and a chain declaring none emits no key at all.
/// Test: this test.
#[test]
fn permissions_block_is_leaf_only_and_absent_emits_nothing() {
    let tmp = TempDir::new().unwrap();
    write_agent(
        tmp.path(),
        "base",
        "---\nname: base\npermissions:\n  bash: deny\n---\n\nBASE\n",
    );
    write_agent(
        tmp.path(),
        "child",
        "---\nname: child\nextends: base\n---\n\nCHILD\n",
    );
    write_agent(
        tmp.path(),
        "leaf",
        "---\nname: leaf\nextends: base\npermissions:\n  bash: ask\n---\n\nLEAF\n",
    );
    let child = compose_agent("child", tmp.path()).unwrap();
    assert!(!child.contains("permissions"), "{child}");
    let leaf = compose_agent("leaf", tmp.path()).unwrap();
    assert!(leaf.contains("\npermissions:\n  bash: ask\n"), "{leaf}");
    assert!(!leaf.contains("bash: deny"), "{leaf}");
    // The deploy path appends a provenance stamp entry; it must not clear it.
    let stamped =
        compose_agent_with_provenance("leaf", tmp.path(), Provenance::FrameworkOwned).unwrap();
    assert!(
        stamped.contains("\npermissions:\n  bash: ask\n"),
        "{stamped}"
    );
}