trusty-mpm 1.8.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
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
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
//! Tests for the bundle module.
//!
//! Why: `bundle.rs` is split to stay under the 500-line cap while keeping all
//! test coverage for embedded artifact integrity, policy correctness, and
//! agent inheritance-chain round-trips in one focused location.
//! What: unit and integration tests for every bundled artifact constant and
//! the [`crate::core::bundle::ALL`] table.
//! Test: this file is the test coverage; run with `cargo test -p trusty-mpm bundle`.
use super::*;
use crate::core::content_source::test_support::rc;

/// A skill file's text from the checkout's content (#9012: skills are runtime
/// content, no longer compiled-in constants).
fn skill_text(path: &str) -> &'static str {
    rc().skill(path)
        .unwrap_or_else(|| panic!("{path} must be in the content tree"))
}

/// An instruction file's text from the checkout's content (#9012).
fn instruction_text(path: &str) -> &'static str {
    rc().instruction(path)
        .unwrap_or_else(|| panic!("instructions/{path} must be in the content tree"))
}

/// Every artifact `tm install` writes: the compiled-in hook policies, then the
/// content's skills and bundled docs (#9012: runtime content), in the shape the
/// pre-#9012 `ALL` table had so the registration tests keep their meaning.
fn deployed() -> Vec<BundledArtifact> {
    let docs = [
        "docs/WHAT-IS-TRUSTY-MPM.md",
        "docs/ARCHITECTURE-MEMORY-SESSIONS-SEARCH.md",
    ]
    .into_iter()
    .map(|rel| (rel, instruction_text(rel)));
    ALL.iter()
        .copied()
        .chain(
            rc().skills()
                .chain(docs)
                .map(|(rel_path, contents)| BundledArtifact {
                    rel_path,
                    contents,
                    install: InstallPolicy::Overwrite,
                }),
        )
        .collect()
}

#[test]
fn constants_are_non_empty() {
    // Every embedded artifact must carry real content — an empty
    // `include_str!` target would mean a missing or truncated asset file.
    assert!(!OPTIMIZER_TOML.trim().is_empty());
    assert!(!OVERSEER_TOML.trim().is_empty());
    // Increment 3 agents
    assert!(
        !skill_text("skills/code-review-standards.md")
            .trim()
            .is_empty()
    );
    assert!(
        !skill_text("skills/contract-driven-testing.md")
            .trim()
            .is_empty()
    );
    assert!(
        !instruction_text("output-styles/trusty-mpm.md")
            .trim()
            .is_empty()
    );
    assert!(
        !instruction_text("output-styles/trusty-mpm-teacher.md")
            .trim()
            .is_empty()
    );
    assert!(
        !instruction_text("output-styles/trusty-mpm-research.md")
            .trim()
            .is_empty()
    );
    assert!(!skill_text("skills/tm-doctor.md").trim().is_empty());
    // /tm- portfolio (tm-skills-portfolio epic)
    assert!(!skill_text("skills/tm-circuit-breaker.md").trim().is_empty());
    assert!(
        !skill_text("skills/tm-verification-protocols.md")
            .trim()
            .is_empty()
    );
    assert!(
        !skill_text("skills/tm-tool-usage-guide.md")
            .trim()
            .is_empty()
    );
    assert!(
        !skill_text("skills/tm-git-file-tracking.md")
            .trim()
            .is_empty()
    );
    assert!(!skill_text("skills/tm-adr.md").trim().is_empty());
    assert!(!skill_text("skills/tm-workflow.md").trim().is_empty());
    assert!(
        !skill_text("skills/tm-agent-architecture.md")
            .trim()
            .is_empty()
    );
    assert!(!skill_text("skills/tm-postmortem.md").trim().is_empty());
    assert!(!skill_text("skills/tm-prose-style.md").trim().is_empty());
    assert!(!skill_text("skills/tm-bug-reporting.md").trim().is_empty());
    assert!(
        !skill_text("skills/tm-teaching-templates.md")
            .trim()
            .is_empty()
    );
    assert!(!skill_text("skills/tm-ticketing.md").trim().is_empty());
    assert!(
        !skill_text("skills/tm-delegation-patterns.md")
            .trim()
            .is_empty()
    );
    assert!(
        !skill_text("skills/tm-session-management.md")
            .trim()
            .is_empty()
    );
    assert!(!skill_text("skills/tm-session-pause.md").trim().is_empty());
    assert!(!skill_text("skills/tm-session-resume.md").trim().is_empty());
    assert!(!skill_text("skills/tm-init.md").trim().is_empty());
    assert!(!skill_text("skills/tm.md").trim().is_empty());
    assert!(!skill_text("skills/tm-issues-prune.md").trim().is_empty());
    assert!(!skill_text("skills/tm-cli-operations.md").trim().is_empty());
    assert!(
        !instruction_text("docs/WHAT-IS-TRUSTY-MPM.md")
            .trim()
            .is_empty()
    );
    // --- BEGIN issue #2911: documentation-style bundled skill (append-only) ---
    assert!(
        !skill_text("skills/documentation-style.md")
            .trim()
            .is_empty()
    );
    assert!(
        !skill_text("skills/documentation-style/references/spec.md")
            .trim()
            .is_empty()
    );
    assert!(
        !skill_text("skills/documentation-style/references/readme.md")
            .trim()
            .is_empty()
    );
    assert!(
        !skill_text("skills/documentation-style/references/file-level.md")
            .trim()
            .is_empty()
    );
    assert!(
        !skill_text("skills/documentation-style/references/class.md")
            .trim()
            .is_empty()
    );
    assert!(
        !skill_text("skills/documentation-style/references/method-function.md")
            .trim()
            .is_empty()
    );
    assert!(
        !skill_text("skills/documentation-style/references/block-inline.md")
            .trim()
            .is_empty()
    );
    // --- END issue #2911 ---
    assert!(
        !skill_text("skills/rust-build-performance.md")
            .trim()
            .is_empty()
    );
}

#[test]
fn tm_skills_are_in_bundle() {
    // The /tm- portfolio (tm-skills-portfolio epic) must be present in ALL so
    // `trusty-mpm install` deploys every skill offline.
    let skill_paths: Vec<&str> = deployed()
        .into_iter()
        .filter(|a| a.rel_path.starts_with("skills/tm-") || a.rel_path == "skills/tm.md")
        .map(|a| a.rel_path)
        .collect();

    for expected in &[
        "skills/tm-doctor.md",
        "skills/tm-circuit-breaker.md",
        "skills/tm-verification-protocols.md",
        "skills/tm-tool-usage-guide.md",
        "skills/tm-git-file-tracking.md",
        "skills/tm-adr.md",
        "skills/tm-workflow.md",
        "skills/tm-agent-architecture.md",
        "skills/tm-postmortem.md",
        "skills/tm-prose-style.md",
        "skills/tm-bug-reporting.md",
        "skills/tm-teaching-templates.md",
        "skills/tm-ticketing.md",
        "skills/tm-delegation-patterns.md",
        "skills/tm-session-management.md",
        "skills/tm-session-pause.md",
        "skills/tm-session-resume.md",
        "skills/tm-init.md",
        "skills/tm.md",
        "skills/tm-issues-prune.md",
        "skills/tm-cli-operations.md",
        "skills/tm-slack.md",
        "skills/tm-secrets.md",
        "skills/tm-architect-setup.md",
        // #8376: entry file plus its four reference files.
        "skills/tm-epic.md",
        "skills/tm-epic/references/tracker-template.md",
        "skills/tm-epic/references/phase-template.md",
        "skills/tm-epic/references/manual-procedure.md",
        "skills/tm-epic/references/anti-patterns.md",
    ] {
        assert!(
            skill_paths.contains(expected),
            "missing bundled /tm- skill: {expected}"
        );
    }
}

/// #5202: `tm-pr-workflow` is RETIRED, not aliased.
///
/// Why: the consolidation only holds if there is exactly ONE workflow skill. A
/// re-registered alias, or a re-added asset file, restores the second editable
/// source the issue removed — and it would do so silently, because every other
/// test here only asserts what IS present.
/// What: asserts the retired stem appears in no bundled artifact path, and that
/// the skill it was consolidated into is present.
/// Test: this IS the test.
#[test]
fn retired_pr_workflow_skill_is_not_bundled() {
    let paths: Vec<&str> = deployed().into_iter().map(|a| a.rel_path).collect();
    assert!(
        !paths.iter().any(|p| p.contains("tm-pr-workflow")),
        "tm-pr-workflow was retired into tm-workflow (#5202); re-registering it \
         restores the split this consolidation removed"
    );
    assert!(
        paths.contains(&"skills/tm-workflow.md"),
        "tm-workflow must remain bundled — it now carries the whole delivery chain"
    );
}

#[test]
fn tm_capabilities_is_in_bundle() {
    // Issue #2913: the generated tm-capabilities entry + all five
    // references/*.md files, plus the hand-authored references/workflows.md,
    // must be present in ALL so `trusty-mpm install` deploys them offline —
    // the same "registration here is what makes deploy_all_skill_tiers ship
    // it" lesson as the code-critic bundled-skills fix (issue #2890).
    let paths: Vec<&str> = deployed().into_iter().map(|a| a.rel_path).collect();
    for expected in &[
        "skills/tm-capabilities.md",
        "skills/tm-capabilities/references/cli.md",
        "skills/tm-capabilities/references/mcp-tools.md",
        "skills/tm-capabilities/references/agents.md",
        "skills/tm-capabilities/references/skills.md",
        "skills/tm-capabilities/references/doctor.md",
        "skills/tm-capabilities/references/framework.md",
        "skills/tm-capabilities/references/workflows.md",
    ] {
        assert!(paths.contains(expected), "missing bundled file: {expected}");
    }
}

#[test]
fn tm_capabilities_has_frontmatter() {
    // The entry file must carry the standard bundled-skill frontmatter shape
    // (name/description/user-invocable), same convention as every other
    // skill in ALL.
    assert!(skill_text("skills/tm-capabilities.md").starts_with("---\nname: tm-capabilities\n"));
    assert!(skill_text("skills/tm-capabilities.md").contains("user-invocable: false"));
}

#[test]
fn tm_capabilities_constants_are_non_empty() {
    assert!(!skill_text("skills/tm-capabilities.md").trim().is_empty());
    assert!(
        !skill_text("skills/tm-capabilities/references/cli.md")
            .trim()
            .is_empty()
    );
    assert!(
        !skill_text("skills/tm-capabilities/references/mcp-tools.md")
            .trim()
            .is_empty()
    );
    assert!(
        !skill_text("skills/tm-capabilities/references/agents.md")
            .trim()
            .is_empty()
    );
    assert!(
        !skill_text("skills/tm-capabilities/references/skills.md")
            .trim()
            .is_empty()
    );
    assert!(
        !skill_text("skills/tm-capabilities/references/doctor.md")
            .trim()
            .is_empty()
    );
    assert!(
        !skill_text("skills/tm-capabilities/references/framework.md")
            .trim()
            .is_empty()
    );
    assert!(
        !skill_text("skills/tm-capabilities/references/workflows.md")
            .trim()
            .is_empty()
    );
}

/// The heading of the one section that states the labels/project/milestone
/// standard (#7274).
const STANDARD_HEADING: &str = "## The Labels, Project, Milestone Standard";

/// The one sentence that states it. Asserting on the sentence, not the
/// heading, is what makes "stated once" mechanical.
const STANDARD_RULE: &str = "Every issue and every pull request carries the same four things: the\n\
     `ws/<session>` label, its component label(s), its project, and its milestone.";

#[test]
fn the_labels_project_milestone_standard_is_stated_once() {
    // #7274, owner ruling 2026-09-09: one standard covering issues AND pull
    // requests, stated in `tm-ticketing` and pointed at from the three files
    // that carry the mechanics. A second statement of the rule is the drift
    // this consolidation removed — #6939 and #7073 hand-edited two copies in
    // step, which worked only for as long as someone remembered to.
    assert!(
        skill_text("skills/tm-ticketing.md").contains(STANDARD_HEADING),
        "`tm-ticketing.md` must hold the section `{STANDARD_HEADING}`"
    );
    let stated: Vec<&str> = [
        ("tm-ticketing.md", skill_text("skills/tm-ticketing.md")),
        ("ticketing.md", agent("ticketing.md")),
        ("version-control.md", agent("version-control.md")),
        ("tm-workflow.md", skill_text("skills/tm-workflow.md")),
    ]
    .into_iter()
    .filter(|(_, body)| body.contains(STANDARD_RULE))
    .map(|(name, _)| name)
    .collect();
    assert_eq!(
        stated,
        vec!["tm-ticketing.md"],
        "the rule sentence must appear in `tm-ticketing.md` and nowhere else"
    );

    // The three mechanics files reach the rule by naming the section, so a
    // reader landing in any of them can find it without knowing it exists.
    let name = STANDARD_HEADING.trim_start_matches('#').trim();
    for (file, body) in [
        ("ticketing.md", agent("ticketing.md")),
        ("version-control.md", agent("version-control.md")),
        ("tm-workflow.md", skill_text("skills/tm-workflow.md")),
    ] {
        assert!(
            body.contains(name),
            "`{file}` must reference the shared section by name (`{name}`)"
        );
        assert!(
            body.contains("tm-ticketing"),
            "`{file}` must say which skill holds the shared section"
        );
    }

    // `version-control.md` also has to say what applies its half.
    assert!(
        agent("version-control.md").contains("`tm pr open` applies your half itself"),
        "`version-control.md` must say `tm pr open` applies the PR side (#7274)"
    );
}

#[test]
fn tm_skills_have_frontmatter() {
    // Every /tm- skill must carry YAML frontmatter with a tm-native `name:`
    // and must not leak unadapted claude-mpm references.
    let skills = [
        (
            "tm-circuit-breaker",
            skill_text("skills/tm-circuit-breaker.md"),
        ),
        (
            "tm-verification-protocols",
            skill_text("skills/tm-verification-protocols.md"),
        ),
        (
            "tm-tool-usage-guide",
            skill_text("skills/tm-tool-usage-guide.md"),
        ),
        (
            "tm-git-file-tracking",
            skill_text("skills/tm-git-file-tracking.md"),
        ),
        ("tm-adr", skill_text("skills/tm-adr.md")),
        ("tm-workflow", skill_text("skills/tm-workflow.md")),
        (
            "tm-agent-architecture",
            skill_text("skills/tm-agent-architecture.md"),
        ),
        ("tm-postmortem", skill_text("skills/tm-postmortem.md")),
        ("tm-prose-style", skill_text("skills/tm-prose-style.md")),
        ("tm-bug-reporting", skill_text("skills/tm-bug-reporting.md")),
        (
            "tm-teaching-templates",
            skill_text("skills/tm-teaching-templates.md"),
        ),
        ("tm-ticketing", skill_text("skills/tm-ticketing.md")),
        (
            "tm-delegation-patterns",
            skill_text("skills/tm-delegation-patterns.md"),
        ),
        (
            "tm-session-management",
            skill_text("skills/tm-session-management.md"),
        ),
        ("tm-session-pause", skill_text("skills/tm-session-pause.md")),
        (
            "tm-session-resume",
            skill_text("skills/tm-session-resume.md"),
        ),
        ("tm-init", skill_text("skills/tm-init.md")),
        ("tm", skill_text("skills/tm.md")),
        ("tm-issues-prune", skill_text("skills/tm-issues-prune.md")),
        (
            "tm-cli-operations",
            skill_text("skills/tm-cli-operations.md"),
        ),
        ("tm-slack", skill_text("skills/tm-slack.md")),
        ("tm-secrets", skill_text("skills/tm-secrets.md")),
        (
            "tm-architect-setup",
            skill_text("skills/tm-architect-setup.md"),
        ),
        ("tm-epic", skill_text("skills/tm-epic.md")),
    ];
    for (name, content) in skills {
        assert!(
            content.starts_with("---\n"),
            "skill {name} is missing YAML frontmatter"
        );
        assert!(
            content.contains(&format!("name: {name}")),
            "skill {name} frontmatter name must match its file stem"
        );
        assert!(
            !content.contains("claude-mpm") || content.contains("trusty-mpm"),
            "skill {name} contains an unadapted claude-mpm reference"
        );
        // tm-session-management is the one deliberate exception: it documents
        // `tm session catchup`'s real dual-format cutover bridge (#1762),
        // which genuinely reads the legacy `.claude-mpm/sessions/` path
        // alongside the native one — this is accurate, not an unadapted
        // leftover, and the skill explicitly calls it "legacy".
        assert!(
            !content.contains(".claude-mpm/") || name == "tm-session-management",
            "skill {name} references the legacy .claude-mpm/ path"
        );
    }
}

#[test]
fn output_style_has_matching_frontmatter_name() {
    // Claude Code matches the `outputStyle` settings key against the
    // `name:` in the style file's frontmatter; a mismatch silently falls
    // back to the operator's default style.
    assert!(instruction_text("output-styles/trusty-mpm.md").contains("name: trusty-mpm"));
}

/// #9012: every registry style's body is runtime content — a required
/// instruction file whose frontmatter `name:` is the registry id.
#[test]
fn every_bundled_style_reads_from_content() {
    for style in OUTPUT_STYLES {
        assert!(
            crate::core::framework_content::REQUIRED_INSTRUCTIONS.contains(&style.content_path),
            "{} must be a required instruction, or a load would not guarantee it",
            style.content_path
        );
        assert_eq!(
            style.content_path,
            format!("output-styles/{}", style.file_name),
            "a style deploys under the file name its content carries"
        );
        let body = style.content(rc());
        assert!(
            body.contains(&format!("\nname: {}\n", style.id)),
            "{} must declare name: {}",
            style.content_path,
            style.id
        );
    }
}

#[test]
fn output_style_registry_has_four_distinct_ids() {
    // HR-4 bundles three PM styles; #8453 adds the supervisor style. Ids and
    // file names are distinct.
    assert_eq!(OUTPUT_STYLES.len(), 4);
    let mut ids: Vec<&str> = OUTPUT_STYLES.iter().map(|s| s.id).collect();
    ids.sort_unstable();
    ids.dedup();
    assert_eq!(ids.len(), 4, "style ids must be distinct");

    let mut files: Vec<&str> = OUTPUT_STYLES.iter().map(|s| s.file_name).collect();
    files.sort_unstable();
    files.dedup();
    assert_eq!(files.len(), 4, "style file names must be distinct");
}

#[test]
fn the_pm_styles_are_every_style_but_the_supervisor_style() {
    // #8453: the PM-invariant tests iterate `pm_output_styles()`; it must drop
    // exactly the supervisor style and nothing else.
    let pm: Vec<&str> = pm_output_styles().map(|s| s.id).collect();
    assert_eq!(
        pm,
        ["trusty-mpm", "trusty-mpm-teacher", "trusty-mpm-research"]
    );
    assert!(OUTPUT_STYLES.iter().any(|s| s.id
        == crate::core::session_profile::SUPERVISOR_OUTPUT_STYLE_ID
        && s.content(rc()) == instruction_text("output-styles/trusty-mpm-supervisor.md")));
}

#[test]
fn output_style_registry_ids_match_frontmatter() {
    // Each registry id MUST equal the file's frontmatter `name:`, or Claude Code
    // silently falls back to the operator's default style.
    for style in OUTPUT_STYLES {
        assert!(
            !style.content(rc()).trim().is_empty(),
            "{} non-empty",
            style.id
        );
        assert!(
            style.content(rc()).contains(&format!("name: {}", style.id)),
            "{} frontmatter name must match registry id",
            style.id
        );
    }
}

#[test]
fn output_styles_carry_identity_protocol_and_load_marker() {
    // DOC-28 R2/R4(b): every bundled output style must carry the non-overridable
    // Identity & Self-Awareness Protocol section, and the marker line
    // `<!-- trusty-mpm-instructions-loaded: v1 -->` must be the literal first
    // line of that section (so a stale/degraded style is greppably distinct
    // from one carrying the current floor).
    const MARKER: &str = "<!-- trusty-mpm-instructions-loaded: v1 -->";
    const HEADING: &str = "## Identity & Self-Awareness Protocol (Non-Overridable)";
    for style in OUTPUT_STYLES {
        assert!(
            style.content(rc()).contains(HEADING),
            "{} is missing the Identity & Self-Awareness Protocol section",
            style.id
        );
        let marker_pos = style
            .content(rc())
            .find(MARKER)
            .unwrap_or_else(|| panic!("{} is missing the load marker", style.id));
        let heading_pos = style.content(rc()).find(HEADING).expect("heading present");
        let between = &style.content(rc())[marker_pos + MARKER.len()..heading_pos];
        assert_eq!(
            between.trim(),
            "",
            "{}: marker must be the first line immediately preceding the heading",
            style.id
        );
        // Forbidden shell-probe list must be greppable for regressions.
        assert!(style.content(rc()).contains("pip3 show"));
        assert!(style.content(rc()).contains("which claude-mpm"));
    }
}

#[test]
fn output_style_registry_default_resolves() {
    // The default id is present and points at the professional style.
    let default = OUTPUT_STYLES
        .iter()
        .find(|s| s.id == DEFAULT_OUTPUT_STYLE_ID)
        .expect("default style must be in the registry");
    assert_eq!(
        default.content(rc()),
        instruction_text("output-styles/trusty-mpm.md")
    );
    assert_eq!(default.file_name, "trusty-mpm.md");
}

#[test]
fn seed_once_constructor_builds_the_expected_artifact() {
    // Issue #3381: no shipped artifact currently uses `SeedOnce`, so the
    // `seed_once()` constructor (the counterpart to `overwrite()`) is only
    // exercised here rather than via a real `ALL` entry. Pins its shape so
    // a future user-owned artifact can rely on it.
    let artifact = all_inner::seed_once("instructions/CLAUDE.md", "stub contents");
    assert_eq!(artifact.rel_path, "instructions/CLAUDE.md");
    assert_eq!(artifact.contents, "stub contents");
    assert_eq!(artifact.install, InstallPolicy::SeedOnce);
}

#[test]
fn optimizer_toml_is_parseable() {
    // The shipped policy must be valid TOML or the installer would deploy
    // a file the daemon then fails to load.
    let parsed: toml::Value = toml::from_str(OPTIMIZER_TOML).expect("valid TOML");
    assert!(parsed.get("default").is_some());
}

#[test]
fn bundle_table_is_complete() {
    // `ALL` must enumerate every artifact with unique, non-empty paths.
    // Count: 4 hooks/instructions + 5 base agents + 37 concrete agents +
    // 2 code-critic bundled skills (#2890) + 21 /tm- skills + 1 DOC-28
    // self-description doc + 1 issue #2034 bundled architecture doc = 71
    // (A4, tm-skills-portfolio epic: the `example-skill.md` placeholder was
    // removed — it shipped to every user with no real content. A3: the
    // previously-orphaned tm-doctor.md is now wired in. The 11 Phase 1 (#770)
    // mpm-* guidance skills were removed entirely, superseded by the /tm-
    // portfolio below.)
    // Increment 1 (9): qa, research, ops, security, documentation, data-engineer,
    //   version-control, ticketing, code-analyzer
    // Increment 2 (12): python-engineer, typescript-engineer, golang-engineer,
    //   rust-engineer, java-engineer, php-engineer, ruby-engineer,
    //   react-engineer, nextjs-engineer, svelte-engineer, web-qa, api-qa
    // Plus engineer.md (core engineer agent)
    // Increment 3 (14): javascript-engineer, phoenix-engineer, dart-engineer,
    //   tauri-engineer, web-ui-engineer, refactoring-engineer, prompt-engineer,
    //   code-critic, gcp-ops, vercel-ops, local-ops,
    //   memory-manager, mpm-agent-manager, mpm-skills-manager
    // Increment 4 (1): dotnet-engineer (#2831 — C#/.NET 8+ with VB.NET awareness)
    // Issue #2890 (2): code-review-standards, contract-driven-testing — the
    //   `skills:` dependencies code-critic declares in its frontmatter (DOC-42).
    //   Registration here (not just the asset file existing) is what makes
    //   `deploy_all_skill_tiers` actually ship them — the historical
    //   orphaned-tm-doctor.md bug this mirrors is documented in
    //   `bundle_tm_skills.rs`'s module doc.
    // /tm- portfolio (tm-skills-portfolio epic + issues #2185/#2321) (21): tm-doctor,
    //   tm-circuit-breaker, tm-verification-protocols, tm-tool-usage-guide,
    //   tm-git-file-tracking, tm-adr, tm-workflow, tm-agent-architecture,
    //   tm-postmortem, tm-bug-reporting, tm-teaching-templates, tm-ticketing,
    //   tm-delegation-patterns, tm-session-management,
    //   tm-session-pause, tm-session-resume, tm-init, tm (overview),
    //   tm-issues-prune (#2185: gh issue backlog prune/prioritize),
    //   tm-cli-operations (#2321: tm CLI operation incl. MCP setup/management)
    // DOC-28 R1 (1): docs/WHAT-IS-TRUSTY-MPM.md
    // Issue #2034 (1): docs/ARCHITECTURE-MEMORY-SESSIONS-SEARCH.md
    // Issue #2903 (93, skill-port batch 1, epic #2902): 25 upstream
    //   universal/ skills (entry SKILL.md files) plus 68 references/*.md
    //   files carried alongside multi-file skills — systematic-debugging,
    //   verification-before-completion, git-workflow, test-driven-development,
    //   requesting-code-review, writing-plans, json-data-handling,
    //   root-cause-tracing, internal-comms, brainstorming, software-patterns,
    //   security-scanning, api-design-patterns, database-migration,
    //   env-manager, web-performance-optimization, artifacts-builder,
    //   condition-based-waiting, model-context-builder, test-quality-inspector,
    //   testing-anti-patterns, webapp-testing, api-documentation, xlsx,
    //   code-production-process. 71 + 93 = 164.
    // Issue #2911 (7): documentation-style bundled skill — entry SKILL.md plus
    //   6 references/*.md files (spec, readme, file-level, class,
    //   method-function, block-inline). 164 + 7 = 171.
    // Issue #2913 (7): tm-capabilities auto-generated harness capability
    //   catalog — entry `skills/tm-capabilities.md` plus five generated
    //   `references/{cli,mcp-tools,agents,skills,doctor}.md` files plus one
    //   hand-authored `references/workflows.md`. 171 + 7 = 178.
    // rust-build-performance (1, per Bob directive 2026-07-17): a single
    //   flat-file bundled skill (no references/ — small enough to not need
    //   one), declared by rust-engineer and tauri-engineer. 178 + 1 = 179.
    // Issue #3374: the dead `instructions/CLAUDE.md` SeedOnce stub artifact
    //   was removed — it was never read back by any consumer; the project
    //   `CLAUDE.md` actually delivered to users is `CLAUDE_MD_STUB` in
    //   `instruction_pipeline.rs`, a separate string not part of this table.
    //   179 - 1 = 178.
    // Issue #4447 (1): tm-slack-canvas-delivery — a single flat-file bundled
    //   skill (no references/), the same shape as rust-build-performance.
    //   178 + 1 = 179.
    // Issue #4286 split A (-1): the `instructions/INSTRUCTIONS.md` bundled
    //   stub artifact was removed — `tm install`/`tm launch` always overwrite
    //   that same on-disk path with the assembled system prompt in the same
    //   call, so the stub's content never reached a live session; the
    //   `FRAMEWORK_INSTRUCTIONS` constant it backed is gone too. 179 - 1 = 178.
    // Issue #4761 (+/-0): tm-slack-canvas-delivery's entry (#4447) is swapped
    //   1-for-1 for tm-slack — same flat-file shape, general Slack delivery
    //   coverage replacing canvas-only scope. Count unchanged at 178.
    // Issue #4760 (+/-0): `agents/ops.md` is DELETED (deprecated in delegation
    //   prose since long before it had any code-level effect, superseded by
    //   `local-ops`), and `agents/elixir-engineer.md` is ADDED (Phoenix's
    //   `mix.exs` gate narrowed to Phoenix-only, which would otherwise leave
    //   plain Elixir with no engineer). -1 +1, count unchanged at 178.
    // Issue #4946 (+1): tm-capabilities gains a sixth generated reference,
    //   `references/framework.md` — the harness's own install layout and tier
    //   precedence, rendered from the path constants and tier resolvers the
    //   runtime uses. 178 + 1 = 179.
    // Issue #5202 (-1): `skills/tm-pr-workflow.md` is RETIRED — its live policy
    //   was consolidated into `tm-workflow`, leaving one workflow skill rather
    //   than an alias or a second editable source. 179 - 1 = 178.
    // Issue #7423 (+1): `skills/tm-prose-style.md` is NEW — it carries the
    //   worked example and observed-instance inventories the output style and
    //   BASE-AGENT.md used to state inline. 178 + 1 = 179.
    // Issue #7527 (epic #7517) (+1): `skills/tm-secrets.md` is NEW — the
    //   operator/PM reference for `tm secrets` (1Password/Keeper/Keychain
    //   behind trusty-common), bundled ahead of the CLI itself (#7521/#7525)
    //   per the DOC-74 design. 179 + 1 = 180.
    // Issue #7526 (epic #7517) (+1): `agents/secrets-manager.md` is NEW — the
    //   bundled framework agent that operates `tm secrets` on behalf of the PM
    //   and other agents (DOC-74). 180 + 1 = 181.
    // Issue #7723 (+1): `skills/self-improvement-loop.md` is NEW — the
    //   self-analysis/fast-loop content moved out of the resident
    //   `BASE-AGENT.md`, on-demand only. 181 + 1 = 182.
    // Issue #7727 (+2): `tm-ticketing` and `tm-workflow` gain a
    //   `references/README.md` each — the folders no-`Skill` agents reach by a
    //   `{{TM_SKILLS}}` Read path. 182 + 2 = 184.
    // Issue #8192 (+1): `skills/rust-delivery-workflow.md` is NEW — the Rust
    //   DELIVERY-PROCESS half split out from `rust-build-performance`'s
    //   build-speed scope, declared by `rust-engineer`. 184 + 1 = 185.
    // Issue #8376 (+5): `skills/tm-epic.md` is NEW — tracker + phase-issue
    //   authoring — plus four `references/*.md` files (tracker-template,
    //   phase-template, manual-procedure, anti-patterns). 185 + 5 = 190.
    // Issue #8436 (+1): `skills/tm-architect-setup.md` is NEW — the
    //   Architect setup skill, shipped ahead of `tm fleet`. 190 + 1 = 191.
    // Issue #9011 (-43): the 43 `agents/*.md` rows left the table — the agent
    //   roster is runtime content (`content/agents`). 191 - 43 = 148.
    assert_eq!(deployed().len(), 148);
    let mut paths: Vec<&str> = deployed().into_iter().map(|a| a.rel_path).collect();
    paths.sort_unstable();
    paths.dedup();
    assert_eq!(paths.len(), 148, "artifact paths must be unique");
    for artifact in deployed() {
        assert!(!artifact.rel_path.is_empty());
        assert!(!artifact.contents.trim().is_empty());
    }
}

#[test]
fn overseer_toml_is_parseable() {
    // The shipped overseer policy must be valid TOML and ship disabled —
    // oversight is opt-in, so installing it must not silently enable it.
    let parsed: toml::Value = toml::from_str(OVERSEER_TOML).expect("valid TOML");
    assert_eq!(
        parsed
            .get("overseer")
            .and_then(|o| o.get("enabled"))
            .and_then(toml::Value::as_bool),
        Some(false)
    );
}

#[test]
fn overseer_toml_is_in_bundle() {
    // `ALL` must include the overseer policy so `trusty-mpm install`
    // deploys it.
    assert!(
        deployed()
            .into_iter()
            .any(|a| a.rel_path == "hooks/overseer.toml"),
        "overseer.toml must be a bundled artifact"
    );
}

#[test]
fn new_concrete_agents_are_in_bundle() {
    // Every newly-ported concrete agent must be present in ALL so
    // `trusty-mpm install` deploys them offline.
    // #9011: the agents ship as content, written by `tm install` from the roster.
    let agent_paths: Vec<String> = crate::core::content_source::test_support::repo_roster()
        .iter()
        .map(|(name, _)| format!("agents/{name}"))
        .collect();

    for expected in &[
        // Increment 1 agents
        "agents/qa.md",
        "agents/research.md",
        "agents/security.md",
        "agents/documentation.md",
        "agents/data-engineer.md",
        "agents/version-control.md",
        "agents/ticketing.md",
        "agents/code-analyzer.md",
        // Increment 2 language engineers
        "agents/python-engineer.md",
        "agents/typescript-engineer.md",
        "agents/golang-engineer.md",
        "agents/rust-engineer.md",
        "agents/java-engineer.md",
        "agents/php-engineer.md",
        "agents/ruby-engineer.md",
        "agents/react-engineer.md",
        "agents/nextjs-engineer.md",
        "agents/svelte-engineer.md",
        // Increment 2 QA variants
        "agents/web-qa.md",
        "agents/api-qa.md",
        // Increment 3 agents
        "agents/javascript-engineer.md",
        "agents/elixir-engineer.md",
        "agents/phoenix-engineer.md",
        "agents/dart-engineer.md",
        "agents/dotnet-engineer.md",
        "agents/tauri-engineer.md",
        "agents/web-ui-engineer.md",
        "agents/refactoring-engineer.md",
        "agents/prompt-engineer.md",
        "agents/code-critic.md",
        "agents/gcp-ops.md",
        "agents/vercel-ops.md",
        "agents/local-ops.md",
        "agents/memory-manager.md",
        "agents/mpm-agent-manager.md",
        "agents/mpm-skills-manager.md",
    ] {
        assert!(
            agent_paths.iter().any(|p| p == expected),
            "missing bundled agent: {expected}"
        );
    }
}

#[test]
fn new_concrete_agents_have_extends_in_frontmatter() {
    // Each new concrete agent must declare `extends:` so the inheritance
    // chain resolves correctly at deploy time.
    let agents = [
        // Increment 1 agents
        ("qa", agent("qa.md")),
        ("research", agent("research.md")),
        ("security", agent("security.md")),
        ("documentation", agent("documentation.md")),
        ("data-engineer", agent("data-engineer.md")),
        ("version-control", agent("version-control.md")),
        ("ticketing", agent("ticketing.md")),
        ("code-analyzer", agent("code-analyzer.md")),
        // Increment 2 language engineers
        ("python-engineer", agent("python-engineer.md")),
        ("typescript-engineer", agent("typescript-engineer.md")),
        ("golang-engineer", agent("golang-engineer.md")),
        ("rust-engineer", agent("rust-engineer.md")),
        ("java-engineer", agent("java-engineer.md")),
        ("php-engineer", agent("php-engineer.md")),
        ("ruby-engineer", agent("ruby-engineer.md")),
        ("react-engineer", agent("react-engineer.md")),
        ("nextjs-engineer", agent("nextjs-engineer.md")),
        ("svelte-engineer", agent("svelte-engineer.md")),
        // Increment 2 QA variants
        ("web-qa", agent("web-qa.md")),
        ("api-qa", agent("api-qa.md")),
        // Increment 3 agents
        ("javascript-engineer", agent("javascript-engineer.md")),
        ("elixir-engineer", agent("elixir-engineer.md")),
        ("phoenix-engineer", agent("phoenix-engineer.md")),
        ("dart-engineer", agent("dart-engineer.md")),
        ("dotnet-engineer", agent("dotnet-engineer.md")),
        ("tauri-engineer", agent("tauri-engineer.md")),
        ("web-ui-engineer", agent("web-ui-engineer.md")),
        ("refactoring-engineer", agent("refactoring-engineer.md")),
        ("prompt-engineer", agent("prompt-engineer.md")),
        ("code-critic", agent("code-critic.md")),
        ("gcp-ops", agent("gcp-ops.md")),
        ("vercel-ops", agent("vercel-ops.md")),
        ("local-ops", agent("local-ops.md")),
        ("memory-manager", agent("memory-manager.md")),
        ("mpm-agent-manager", agent("mpm-agent-manager.md")),
        ("mpm-skills-manager", agent("mpm-skills-manager.md")),
    ];
    for (name, content) in agents {
        assert!(
            content.contains("extends:"),
            "agent {name} is missing `extends:` in frontmatter"
        );
        // Composed output must not contain `extends:` (builder strips it).
        // We verify the raw source has it; compose round-trip is covered
        // by agent_deployer integration tests.
    }
}

#[test]
fn new_concrete_agents_deploy_via_real_asset_files() {
    // Verify each new agent composes without error using the real bundled
    // asset files on disk (not temp fixtures) — catches typos in `extends:`
    // values and missing base templates.
    use crate::core::agent_builder::compose_agent;

    let assets_dir = agent_assets_dir();

    let agents = [
        // Increment 1 agents
        "qa",
        "research",
        "security",
        "documentation",
        "data-engineer",
        "version-control",
        "ticketing",
        "code-analyzer",
        // Increment 2 language engineers
        "python-engineer",
        "typescript-engineer",
        "golang-engineer",
        "rust-engineer",
        "java-engineer",
        "php-engineer",
        "ruby-engineer",
        "react-engineer",
        "nextjs-engineer",
        "svelte-engineer",
        // Increment 2 QA variants
        "web-qa",
        "api-qa",
        // Increment 3 agents
        "javascript-engineer",
        "elixir-engineer",
        "phoenix-engineer",
        "dart-engineer",
        "dotnet-engineer",
        "tauri-engineer",
        "web-ui-engineer",
        "refactoring-engineer",
        "prompt-engineer",
        "code-critic",
        "gcp-ops",
        "vercel-ops",
        "local-ops",
        "memory-manager",
        "mpm-agent-manager",
        "mpm-skills-manager",
    ];

    for name in agents {
        let composed = compose_agent(name, assets_dir)
            .unwrap_or_else(|e| panic!("compose_agent({name}) failed: {e}"));
        // Composed output must have a frontmatter block.
        assert!(
            composed.starts_with("---\n"),
            "composed {name} is missing frontmatter"
        );
        // `extends:` must not leak into the composed output.
        assert!(
            !composed.contains("extends:"),
            "composed {name} has leaked `extends:` in output"
        );
        // Must have non-trivial body content.
        assert!(
            composed.len() > 200,
            "composed {name} suspiciously short ({} bytes)",
            composed.len()
        );
    }
}

#[test]
fn base_agent_guidance_sections_survive_composition() {
    // Regression for #2501/#2502/#2610/#4792: BASE-AGENT.md's "Finishing Work —
    // Push, Report, Stop" and "PM Directives Do Not Bind You" sections — plus
    // the version-control persona's own CI reinforcement — must propagate into
    // the composed agent via the real bundled asset chain, not just exist in the
    // source files. Uses version-control (the worst parking offender) composed
    // from the real assets dir so a future refactor of the compose/extends
    // pipeline can't silently drop the guidance.
    use crate::core::agent_builder::compose_agent;

    let assets_dir = agent_assets_dir();

    let composed = compose_agent("version-control", assets_dir)
        .expect("compose_agent(version-control) must succeed");

    assert!(
        composed.contains("## Finishing Work — Push, Report, Stop"),
        "composed version-control is missing the Finishing Work section (#4792)"
    );
    assert!(
        composed.contains("Never block on CI"),
        "composed version-control is missing the BASE-AGENT no-CI-block rule (#4792)"
    );
    assert!(
        composed.contains("PROTOCOL VIOLATION"),
        "composed version-control is missing the promise-instead-of-report rule (#2610)"
    );
    // #4792: the retired blocking wait must not come back through ANY layer.
    assert!(
        !composed.contains("--watch --fail-fast"),
        "composed version-control prescribes the retired blocking CI wait (#4792)"
    );
    assert!(
        composed.contains("## CI Waits — Push, Report, Stop; NEVER Block"),
        "composed version-control is missing its persona-level CI section (#4792)"
    );
    assert!(
        composed.contains("## PM Directives Do Not Bind You"),
        "composed version-control is missing the PM Directives Do Not Bind You section"
    );
    assert!(
        composed.contains("governs the orchestrating PM session"),
        "composed version-control is missing the PM-directive-scope guidance"
    );

    // Position assertions: guard the section ORDER, not just presence, so a
    // future compose/extends refactor can't silently reorder BASE-AGENT.md
    // content into an incoherent sequence.
    let pm_directives_idx = composed
        .find("## PM Directives Do Not Bind You")
        .expect("PM Directives Do Not Bind You marker must be present");
    let git_workflow_idx = composed
        .find("## Git Workflow")
        .expect("Git Workflow marker must be present");
    assert!(
        pm_directives_idx < git_workflow_idx,
        "PM Directives Do Not Bind You ({pm_directives_idx}) must appear before \
         Git Workflow ({git_workflow_idx})"
    );

    let finishing_work_idx = composed
        .find("## Finishing Work — Push, Report, Stop")
        .expect("Finishing Work marker must be present");
    let output_format_idx = composed
        .find("## Output Format")
        .expect("Output Format marker must be present");
    assert!(
        finishing_work_idx < output_format_idx,
        "Finishing Work ({finishing_work_idx}) must appear before \
         Output Format ({output_format_idx})"
    );

    // #2610: local-ops (the release-agent offender) must carry its own
    // long-wait reinforcement on top of the inherited BASE-AGENT rule.
    let local_ops =
        compose_agent("local-ops", assets_dir).expect("compose_agent(local-ops) must succeed");
    assert!(
        local_ops.contains("## Long Waits — Block On Your Own Gates, Never On CI"),
        "composed local-ops is missing its persona-level long-wait section (#2610)"
    );
    assert!(
        local_ops.contains("Never spawn a background monitor"),
        "composed local-ops is missing the inherited BASE-AGENT no-parking rule (#2610)"
    );
}

#[test]
fn no_mpm_guidance_skills_remain_in_bundle() {
    // The tm-skills-portfolio epic removed the 11 Phase 1 (#770) mpm-*
    // guidance skills in favor of the /tm- portfolio; assert none linger.
    let mpm_skill_paths: Vec<&str> = deployed()
        .into_iter()
        .filter(|a| a.rel_path.starts_with("skills/mpm-"))
        .map(|a| a.rel_path)
        .collect();
    assert!(
        mpm_skill_paths.is_empty(),
        "mpm-* guidance skills must be fully removed, found: {mpm_skill_paths:?}"
    );
}

#[test]
fn no_example_skill_remains_in_bundle() {
    // A4 (tm-skills-portfolio epic): the example-skill.md placeholder must
    // never reappear in ALL.
    assert!(
        !deployed()
            .into_iter()
            .any(|a| a.rel_path == "skills/example-skill.md"),
        "example-skill.md must not be present in ALL"
    );
}

#[test]
fn tm_doctor_skill_is_wired_into_bundle() {
    // A3 (tm-skills-portfolio epic): tm-doctor.md existed as an asset file
    // but was never wired into a const or the ALL table, so it silently
    // never shipped. Assert both are now true, and that it carries valid
    // frontmatter naming the skill `tm-doctor`.
    assert!(
        deployed()
            .into_iter()
            .any(|a| a.rel_path == "skills/tm-doctor.md"),
        "tm-doctor.md must be present in the ALL bundle table"
    );
    assert!(skill_text("skills/tm-doctor.md").starts_with("---\n"));
    assert!(skill_text("skills/tm-doctor.md").contains("name: tm-doctor"));
}

#[test]
fn code_critic_declared_skills_are_in_bundle() {
    // Issue #2890: code-critic's `skills:` frontmatter declares
    // `code-review-standards` and `contract-driven-testing`. Both asset files
    // existed under `src/assets/skills/` but were not wired into a const or
    // the `ALL` table on first cut — the exact historical tm-doctor.md bug
    // (see `tm_doctor_skill_is_wired_into_bundle` above and
    // `bundle_tm_skills.rs`'s module doc): a file existing on disk is not
    // sufficient for `deploy_all_skill_tiers` to ever see it, since that
    // function reads from the framework-root `skills/` directory, which is
    // populated exclusively from `ALL` entries at `tm install` time.
    assert!(
        deployed()
            .into_iter()
            .any(|a| a.rel_path == "skills/code-review-standards.md"),
        "code-review-standards.md must be present in the ALL bundle table"
    );
    assert!(
        deployed()
            .into_iter()
            .any(|a| a.rel_path == "skills/contract-driven-testing.md"),
        "contract-driven-testing.md must be present in the ALL bundle table"
    );
    assert!(skill_text("skills/code-review-standards.md").starts_with("---\n"));
    assert!(skill_text("skills/code-review-standards.md").contains("name: code-review-standards"));
    assert!(skill_text("skills/contract-driven-testing.md").starts_with("---\n"));
    assert!(
        skill_text("skills/contract-driven-testing.md").contains("name: contract-driven-testing")
    );
    // The agent's declared `skills:` frontmatter must name both of these,
    // so the DOC-42 co-deployment mechanism has something real to resolve —
    // issue #2903 extended the declaration with four more batch-1 skills
    // code-critic's upstream counterpart also names (code-production-process,
    // software-patterns, systematic-debugging, verification-before-completion),
    // so this only asserts the two #2890-era names are still present, not the
    // full six-skill list (that full-list assertion lives in
    // `code_critic_declares_batch1_skills`).
    assert!(agent("code-critic.md").contains("code-review-standards"));
    assert!(agent("code-critic.md").contains("contract-driven-testing"));
    assert!(agent("code-critic.md").contains("skills: ["));
}

#[test]
fn code_review_standards_flags_github_token_protected_branch_pushes_8016() {
    // Issue #8016: `code-review-standards` had no check for a workflow
    // granted `contents: write` that pushes to a protected branch using
    // `GITHUB_TOKEN` — GitHub never allows the Actions identity as a
    // restriction or ruleset bypass actor, so the workflow is unworkable no
    // matter how green its first (nothing-to-publish) run looked.
    assert!(
        contains_prose_anchor(
            skill_text("skills/code-review-standards.md"),
            "GitHub never allows the Actions identity as a restriction or \
             ruleset bypass actor"
        ),
        "code-review-standards must flag a GITHUB_TOKEN push to a protected \
         branch (#8016)"
    );
}

#[test]
fn code_review_standards_flags_format_interpolated_structured_payloads_7624() {
    // Issue #7624: `code-review-standards` had no check for a test helper
    // that builds a structured (JSON/YAML/TOML/SQL) payload by `format!`
    // interpolating a caller-supplied value into a string literal instead of
    // the format's own builder/serializer — the #7550 failure mode, where a
    // caller value containing the format's escape/delimiter characters
    // malformed the payload and the system under test answered it with a
    // permissive default indistinguishable from a real pass.
    assert!(
        contains_prose_anchor(
            skill_text("skills/code-review-standards.md"),
            "builds a JSON/YAML/TOML/SQL payload by `format!` interpolating \
             a caller-supplied value into a string literal"
        ),
        "code-review-standards must flag format!-interpolated structured \
         test payloads (#7624)"
    );
}

#[test]
fn code_critic_declares_batch1_skills() {
    // Issue #2903 ported the full upstream six-skill set. #4642 cuts it back to
    // the two that code-critic's own body tells it to load on turn one: the
    // harness renders every listed skill's FULL body into the prompt at
    // dispatch, so the other four (code-production-process, software-patterns,
    // systematic-debugging, verification-before-completion) were 30 KB of
    // reference material paid on every review. They remain bundled and
    // invokable via the Skill tool; only the resident declaration shrank.
    assert!(
        agent("code-critic.md")
            .contains("skills: [code-review-standards, contract-driven-testing]"),
        "code-critic's resident skills are its rubric and its contract-test \
         reference, nothing else (#4642)"
    );
}

#[test]
fn skill_port_batch1_skills_are_in_bundle() {
    // Issue #2903 (epic #2902): all 25 batch-1 universal/ skill entry points
    // must be present in `ALL` — mirrors `tm_doctor_skill_is_wired_into_bundle`
    // and `code_critic_declared_skills_are_in_bundle` above: a source file
    // existing under `src/assets/skills/` is not sufficient, only `ALL`
    // registration makes `deploy_all_skill_tiers` ship it.
    const BATCH1_ENTRIES: &[&str] = &[
        "skills/systematic-debugging.md",
        "skills/verification-before-completion.md",
        "skills/git-workflow.md",
        "skills/test-driven-development.md",
        "skills/requesting-code-review.md",
        "skills/writing-plans.md",
        "skills/json-data-handling.md",
        "skills/root-cause-tracing.md",
        "skills/internal-comms.md",
        "skills/brainstorming.md",
        "skills/software-patterns.md",
        "skills/security-scanning.md",
        "skills/api-design-patterns.md",
        "skills/database-migration.md",
        "skills/env-manager.md",
        "skills/web-performance-optimization.md",
        "skills/artifacts-builder.md",
        "skills/condition-based-waiting.md",
        "skills/model-context-builder.md",
        "skills/test-quality-inspector.md",
        "skills/testing-anti-patterns.md",
        "skills/webapp-testing.md",
        "skills/api-documentation.md",
        "skills/xlsx.md",
        "skills/code-production-process.md",
    ];
    assert_eq!(BATCH1_ENTRIES.len(), 25);
    for rel_path in BATCH1_ENTRIES {
        assert!(
            deployed().into_iter().any(|a| &a.rel_path == rel_path),
            "{rel_path} must be present in the ALL bundle table"
        );
    }
}

#[test]
fn skill_port_batch1_references_land_on_disk() {
    // A sample of multi-file batch-1 skills must carry their references/*.md
    // files as SEPARATE `ALL` entries alongside the entry-point SKILL.md — the
    // multi-file skill-directory extension this issue adds to the bundle/
    // deploy machinery (epic #2902 constraint #2). Real deploy-reachability
    // (landing under a deployed `.claude/skills/<name>/references/`) is
    // proven end-to-end in `tests_behavior_2903_skills_tests.rs`.
    for (entry, refs) in [
        (
            "skills/systematic-debugging.md",
            &[
                "skills/systematic-debugging/references/anti-patterns.md",
                "skills/systematic-debugging/references/examples.md",
                "skills/systematic-debugging/references/troubleshooting.md",
                "skills/systematic-debugging/references/workflow.md",
            ][..],
        ),
        (
            "skills/software-patterns.md",
            &[
                "skills/software-patterns/references/anti-patterns.md",
                "skills/software-patterns/references/code-smell-signals.md",
                "skills/software-patterns/references/decision-trees.md",
                "skills/software-patterns/references/examples.md",
                "skills/software-patterns/references/foundational-patterns.md",
                "skills/software-patterns/references/situational-patterns.md",
            ][..],
        ),
    ] {
        assert!(
            deployed().into_iter().any(|a| a.rel_path == entry),
            "{entry} must be present in the ALL bundle table"
        );
        for rel_path in refs {
            assert!(
                deployed().into_iter().any(|a| &a.rel_path == rel_path),
                "{rel_path} must be present in the ALL bundle table"
            );
        }
    }
}

#[test]
fn what_is_trusty_mpm_is_in_bundle() {
    // DOC-28 R1 acceptance: the canonical self-description doc must be a
    // bundled artifact so `tm install` deploys it to every framework root,
    // not just the trusty-tools repo's own source tree.
    let artifact = deployed()
        .into_iter()
        .find(|a| a.rel_path == "docs/WHAT-IS-TRUSTY-MPM.md")
        .expect("WHAT-IS-TRUSTY-MPM.md must be a bundled artifact");
    assert_eq!(
        artifact.install,
        InstallPolicy::Overwrite,
        "the doc is framework-owned and must track upgrades"
    );
    assert_eq!(
        artifact.contents,
        instruction_text("docs/WHAT-IS-TRUSTY-MPM.md")
    );
}

#[test]
fn what_is_trusty_mpm_disambiguates_claude_mpm() {
    // DOC-28 R1 acceptance: the doc must contain the literal substrings that
    // prove it identifies the project (Rust, tm, tcode) and explicitly
    // disambiguates it from the unrelated Python claude-mpm package.
    assert!(instruction_text("docs/WHAT-IS-TRUSTY-MPM.md").contains("Rust"));
    assert!(instruction_text("docs/WHAT-IS-TRUSTY-MPM.md").contains("tm"));
    assert!(instruction_text("docs/WHAT-IS-TRUSTY-MPM.md").contains("tcode"));
    assert!(instruction_text("docs/WHAT-IS-TRUSTY-MPM.md").contains("claude-mpm"));
    // The claude-mpm substring must appear inside an explicit disambiguation
    // sentence, not incidentally — assert it co-occurs with "NOT" nearby.
    assert!(
        instruction_text("docs/WHAT-IS-TRUSTY-MPM.md").contains("NOT")
            && instruction_text("docs/WHAT-IS-TRUSTY-MPM.md").contains("claude-mpm"),
        "doc must explicitly disambiguate from claude-mpm, not mention it incidentally"
    );
}

#[test]
fn idle_park_mitigation_2833_guidance_survives_composition() {
    // Regression for #2833's code-critic review (MEDIUM finding): the prior
    // `base_agent_guidance_sections_survive_composition` test only asserted the
    // pre-existing #2501/#2610 strings — none of the #2833 idle-park-mitigation
    // content (the BASE-AGENT hand-back guidance, the PM-side re-engagement
    // protocol, the version-control persona bullets) was ever exercised
    // through the REAL bundled asset chain. This test closes that gap using the
    // same real-composition approach as its sibling: `compose_agent` reading
    // the actual `assets/agents` dir for the two agent-tier assertions, and
    // `assemble_system_prompt` (the real PM_INSTRUCTIONS/WORKFLOW/
    // AGENT_DELEGATION/BASE_PM assembly used at session launch) for the
    // PM-tier assertion — not a hand-built fixture string.
    use crate::core::agent_builder::compose_agent;
    use crate::core::instruction_pipeline::assemble_system_prompt;

    let assets_dir = agent_assets_dir();

    // (a) BASE-AGENT.md's report-don't-promise subsection (which replaced the
    // retired chunked-repoll guidance in #4792) must reach a composed agent
    // that inherits BASE-AGENT (version-control extends it).
    let composed = compose_agent("version-control", assets_dir)
        .expect("compose_agent(version-control) must succeed");
    assert!(
        composed.contains("### Report, don't promise"),
        "composed version-control is missing the BASE-AGENT report-don't-promise subsection (#4792)"
    );

    // (c) version-control's own merge-decision bullets (distinct from the
    // inherited BASE-AGENT section) must also survive composition.
    assert!(
        composed.contains("Repeated `gh pr update-branch` is a treadmill"),
        "composed version-control is missing its persona-level update-branch bullet (#4792)"
    );

    // (b) The Parked-Subagent Re-Engagement TRIGGER must survive the real PM
    // system-prompt assembly (not just exist in the source .md file). The
    // trigger is what cannot be deferred: an agent handing back with CI pending
    // is the moment the PM must act, and a PM that never learns to act does not
    // know to load anything.
    let pm_prompt = assemble_system_prompt(rc());
    assert!(
        pm_prompt.contains("## Parked-Subagent Re-Engagement (issues #2833, #4792)"),
        "assembled PM system prompt is missing the Parked-Subagent \
         Re-Engagement section (#2833, #4792)"
    );
    // #4969: the MECHANICS moved to `tm-delegation-patterns` (per-prompt rule: an
    // instruction not needed on EVERY prompt lives in a skill). The resident
    // text must therefore name the call explicitly — a bare `[SKILL: name]`
    // mention is documentation style, not a tool invocation, and is exactly how
    // the previous pointer decayed into decoration beside a re-inlined copy.
    assert!(
        pm_prompt.contains(r#"Skill(skill="tm-delegation-patterns")"#),
        "the resident re-engagement trigger must name the Skill call that \
         carries the mechanics, not merely mention the skill (#2833, #4792)"
    );
    assert!(
        !pm_prompt.contains("never a 30-second blind poll"),
        "the anti-spam MECHANICS belong to the skill now; re-inlining them in \
         the prompt is the redundancy this rule removes (#2833)"
    );

    // …and the mechanics must actually BE in the skill, or the pointer above is
    // a dangling reference. Asserted against the real bundled asset.
    let skill = skill_text("skills/tm-delegation-patterns.md");
    assert!(
        skill.contains("30-second blind poll") && skill.contains("counter-failure"),
        "tm-delegation-patterns must carry the PM-side anti-spam-monitoring \
         guidance the prompt now points at (#2833)"
    );
    assert!(
        skill.contains("## PM Re-Engagement (issues #2833, #4792, #5843)"),
        "tm-delegation-patterns must carry the PM Re-Engagement section the \
         prompt names by title (#2833, #4792)"
    );
    // The skill has to be REACHABLE by relevance too: its description is what a
    // relevance match sees, and "delegation matrices" alone never fires at the
    // moment an agent hands back with pending CI.
    assert!(
        skill.contains("CI pending") && skill.contains("re-engagement"),
        "tm-delegation-patterns' frontmatter description must mention the \
         CI-wait / re-engagement trigger, or it cannot fire on its own (#4792)"
    );
}

/// 🔴 #8004 REGRESSION: PM Re-Engagement said `SendMessage` the same agent
/// unconditionally. A worktree-isolated subagent's clean tree was reclaimed
/// between turns, so the resumed agent landed in the main checkout, where
/// ADR-0061/#5649 forbid it from committing.
#[test]
fn pm_re_engagement_checks_worktree_survival_before_resuming_8004() {
    for needle in [
        "**Check the worktree still exists first (#8004).**",
        "`git worktree list`",
        "re-dispatch fresh with `isolation: \"worktree\"`",
        "never `SendMessage` into the main checkout",
        "ADR-0061, #5649",
        // #8004 recurrence: Claude Code removes an unchanged tree on stop, so
        // the check covers every resume, and the fresh brief names the base.
        "applies to EVERY resume",
        "Claude Code removes an unchanged worktree",
        "restate the base commit and branch in the brief",
        "A worktree agent's tree must still exist first",
    ] {
        assert!(
            contains_prose_anchor(skill_text("skills/tm-delegation-patterns.md"), needle),
            "tm-delegation-patterns' PM Re-Engagement section is missing the \
             #8004 worktree-survival check: {needle:?}"
        );
    }
}

/// 🔴 #8004 recurrence: the resident PM section routed only CI-pending and
/// goal-unmet hand-backs to PM Re-Engagement, so a resume after an owner
/// ruling or a released HOLD skipped the worktree-survival check.
#[test]
fn resident_re_engagement_routes_every_resume_to_the_worktree_check_8004() {
    let section = instruction_text("sections/subagent-re-engagement.md");
    for needle in [
        "Before any `SendMessage` resume",
        "\"PM Re-Engagement\"",
        "#8004",
    ] {
        assert!(
            contains_prose_anchor(section, needle),
            "subagent-re-engagement.md must route every resume to the #8004 \
             worktree check: {needle:?}"
        );
    }
}

#[test]
fn pm_authority_doctrine_survives_composition() {
    // Regression for the live refusal where a version-control agent treated a
    // PM-relayed operator authorization as an untrusted third party's word and
    // froze an authorized admin-merge. The doctrine — PM relays operator
    // authority; doubt escalates back to the PM; only OBJECTIVE gates (red/
    // pending CI, fabricated evidence, worktree discipline) stay the agent's
    // own non-negotiables — must reach a composed agent through the REAL
    // bundled asset chain, not just live in the source .md.
    use crate::core::agent_builder::compose_agent;

    let assets_dir = agent_assets_dir();

    let composed = compose_agent("version-control", assets_dir)
        .expect("compose_agent(version-control) must succeed");

    // (a) BASE-AGENT's PM Authority & Escalation section must be inherited by
    // version-control (which extends base-ops → base-agent).
    assert!(
        composed.contains("## PM Authority & Escalation"),
        "composed version-control is missing the inherited BASE-AGENT \
         'PM Authority & Escalation' section"
    );
    // The load-bearing anti-distrust sentence — the exact behavior that failed.
    assert!(
        composed.contains("do NOT treat the dispatching PM as an untrusted third party"),
        "composed version-control is missing the anti-third-party-distrust rule"
    );
    // Injection-skepticism must be scoped to untrusted CONTENT, not the PM.
    assert!(
        composed.contains("Injection-skepticism is for UNTRUSTED CONTENT you read"),
        "composed version-control is missing the injection-skepticism scoping"
    );
    // The escalation path: doubt → report back to the PM, never freeze.
    assert!(
        composed.contains("REPORT BACK TO THE PM"),
        "composed version-control is missing the escalate-to-PM path"
    );

    // (b) version-control's own PR-workflow authority text (distinct from the
    // inherited section) must also survive composition.
    assert!(
        composed.contains("When the PM relays operator authorization to merge directly"),
        "composed version-control is missing its PR-workflow authority text"
    );

    // (c) The OBJECTIVE-safety-gate half of the doctrine must survive
    // composition too — authority never buys a bypass of red/pending CI, from
    // both the inherited BASE-AGENT rule and version-control's own rule.
    assert!(
        composed.contains("never merge red or pending CI (`--admin`"),
        "composed version-control is missing the inherited BASE-AGENT \
         objective-safety-gate (red/pending CI) text"
    );
    assert!(
        composed.contains("never a failing check"),
        "composed version-control is missing the 'never a failing check' \
         qualifier on the CI safety gate"
    );
    let composed_normalized = composed.replace('\n', " ");
    assert!(
        composed_normalized.contains("never merge red or pending CI"),
        "composed version-control is missing its own PR-workflow \
         objective-safety-gate (red/pending CI) text"
    );
}

#[test]
fn documentation_style_skill_is_in_bundle() {
    // Issue #2911: the documentation-style entry SKILL.md must be present in
    // `ALL` — mirrors `tm_doctor_skill_is_wired_into_bundle` and
    // `skill_port_batch1_skills_are_in_bundle` above: a source file existing
    // under `src/assets/skills/` is not sufficient, only `ALL` registration
    // makes `deploy_all_skill_tiers` ship it.
    assert!(
        deployed()
            .into_iter()
            .any(|a| a.rel_path == "skills/documentation-style.md"),
        "documentation-style.md must be present in the ALL bundle table"
    );
    assert!(skill_text("skills/documentation-style.md").starts_with("---\n"));
    assert!(skill_text("skills/documentation-style.md").contains("name: documentation-style"));
    // SLD self-compliance (DOC-38 §2.5): the entry SKILL.md carries
    // `spec_refs:` frontmatter pointing at the grammar section it defers to,
    // with `anchor` equal to `id` per DOC-38's self-check rule.
    assert!(skill_text("skills/documentation-style.md").contains("spec_refs:"));
    assert!(skill_text("skills/documentation-style.md").contains("id: SPEC-SLD-02~draft"));
    assert!(skill_text("skills/documentation-style.md").contains("anchor: SPEC-SLD-02~draft"));
}

#[test]
fn documentation_style_references_land_on_disk() {
    // Issue #2911: all 6 references/*.md files must be SEPARATE `ALL` entries
    // alongside the entry-point SKILL.md — mirrors
    // `skill_port_batch1_references_land_on_disk`. Real deploy-reachability
    // (landing under a deployed `.claude/skills/documentation-style/references/`)
    // is proven end-to-end in `tests_behavior_2911_documentation_style_tests.rs`.
    assert!(
        deployed()
            .into_iter()
            .any(|a| a.rel_path == "skills/documentation-style.md")
    );
    for rel_path in [
        "skills/documentation-style/references/spec.md",
        "skills/documentation-style/references/readme.md",
        "skills/documentation-style/references/file-level.md",
        "skills/documentation-style/references/class.md",
        "skills/documentation-style/references/method-function.md",
        "skills/documentation-style/references/block-inline.md",
    ] {
        assert!(
            deployed().into_iter().any(|a| a.rel_path == rel_path),
            "{rel_path} must be present in the ALL bundle table"
        );
    }
}

#[test]
fn documentation_style_unions_into_engineer_family_via_base_engineer() {
    // Issue #2911: BASE-ENGINEER.md now declares `skills: [documentation-style]`;
    // compose_agent's DOC-42 union-across-chain merge (builder.rs
    // `merge_frontmatter`) must propagate it into every concrete engineer-family
    // agent composed from the REAL bundled asset files, not a synthetic fixture.
    use crate::core::agent_builder::compose_agent;

    let assets_dir = agent_assets_dir();

    let composed = compose_agent("rust-engineer", assets_dir)
        .expect("compose_agent(rust-engineer) must succeed");
    assert!(
        composed.contains("documentation-style"),
        "composed rust-engineer is missing the BASE-ENGINEER-declared \
         documentation-style skill (union-across-chain, DOC-42): {composed}"
    );
}

#[test]
fn rust_build_performance_skill_is_in_bundle() {
    // Per Bob directive 2026-07-17: the rust-build-performance entry SKILL.md
    // must be present in `ALL` — mirrors `documentation_style_skill_is_in_bundle`:
    // a source file existing under `src/assets/skills/` is not sufficient,
    // only `ALL` registration makes `deploy_all_skill_tiers` ship it.
    assert!(
        deployed()
            .into_iter()
            .any(|a| a.rel_path == "skills/rust-build-performance.md"),
        "rust-build-performance.md must be present in the ALL bundle table"
    );
    assert!(skill_text("skills/rust-build-performance.md").starts_with("---\n"));
    assert!(
        skill_text("skills/rust-build-performance.md").contains("name: rust-build-performance")
    );
}

#[test]
fn rust_delivery_workflow_skill_is_in_bundle() {
    // Issue #8192: same reachability contract as the sibling above — the asset
    // file under `src/assets/skills/` only ships once `ALL` names it.
    assert!(
        deployed()
            .into_iter()
            .any(|a| a.rel_path == "skills/rust-delivery-workflow.md"),
        "rust-delivery-workflow.md must be present in the ALL bundle table"
    );
    assert!(skill_text("skills/rust-delivery-workflow.md").starts_with("---\n"));
    assert!(
        skill_text("skills/rust-delivery-workflow.md").contains("name: rust-delivery-workflow")
    );
}

#[test]
fn rust_delivery_workflow_states_each_delivery_rule() {
    // Issue #8192: the skill exists to carry rules that previously lived only
    // in incident prose. A body that dropped one would still pass the
    // reachability test above, so pin the rule set itself — one needle per
    // section that a rewrite must not silently lose.
    for (fact, needle) in [
        (
            "it defers build speed to the sibling skill",
            "rust-build-performance",
        ),
        (
            "the gate chain is preceded by a commit",
            "Commit and push the branch",
        ),
        (
            "CI's workflow file is the clippy pin's source",
            "CI workflow file is the source of truth",
        ),
        (
            "a crate-scoped local pass is not CI evidence",
            "is not evidence",
        ),
        (
            "concurrent builds contend for RAM, not just the build lock",
            "CPU and RAM bound",
        ),
        ("the job cap is read off the machine", "CARGO_BUILD_JOBS"),
        (
            "env must be prefixed inline per command",
            "does not persist",
        ),
        ("gate output is a verdict", "EXIT=$?"),
        (
            "sccache is recommended, never silently enabled",
            "never silently enable",
        ),
        ("installs batch across a merge batch", "one `cargo install`"),
        ("test scope widens by stage", "Test Scope Widens by Stage"),
    ] {
        assert!(
            skill_text("skills/rust-delivery-workflow.md").contains(needle),
            "`rust-delivery-workflow.md` must state that {fact} (#8192)"
        );
    }
}

#[test]
fn self_improvement_loop_skill_is_in_bundle() {
    // Issue #7723: the self-improvement-loop entry SKILL.md must be present
    // in `ALL` — a source file existing under `src/assets/skills/` is not
    // sufficient, only `ALL` registration makes `deploy_all_skill_tiers`
    // ship it (the historical orphaned-tm-doctor.md bug).
    assert!(
        deployed()
            .into_iter()
            .any(|a| a.rel_path == "skills/self-improvement-loop.md"),
        "self-improvement-loop.md must be present in the ALL bundle table"
    );
    assert!(skill_text("skills/self-improvement-loop.md").starts_with("---\n"));
    assert!(skill_text("skills/self-improvement-loop.md").contains("name: self-improvement-loop"));
}

#[test]
fn self_improvement_loop_skill_carries_the_moved_anchors() {
    // Issue #7723: `self_analysis_reporting_ships_in_the_base_agent`
    // (`trusty-agents-common::agent_assets`) now asserts only the resident
    // trigger and the skill name in `BASE-AGENT.md`; this test asserts the
    // ten anchors that section used to carry directly, against the skill
    // they moved into.
    let flat = skill_text("skills/self-improvement-loop.md").replace('\n', " ");
    for (fact, needle) in [
        (
            "the section exists",
            "## Self-Analysis and Improvement Reporting",
        ),
        (
            "the fast-loop section exists",
            "## Continuous Self-Improvement — the Fast Loop",
        ),
        (
            "the detection heuristics are headed and findable",
            "**Detection heuristics.**",
        ),
        (
            "the one memory tag is named",
            "The tag is `self-improvement-hypothesis`",
        ),
        (
            "the post-mortem's query is spelled out",
            r#"memory_list(tag: "self-improvement-hypothesis")"#,
        ),
        (
            "trusty-tools is the fixed destination",
            "bobmatnyc/trusty-tools",
        ),
        (
            "a subagent returns a block instead of filing",
            "Improvement recommendations",
        ),
        (
            "dedup runs against the label",
            "`self-improvement` label first",
        ),
        ("a clean run files nothing", "A clean run reports nothing"),
        ("the post-mortem tracker is named", "#6933"),
    ] {
        assert!(
            flat.contains(needle),
            "`self-improvement-loop.md` must state that {fact} (#6935, #6937, #7723)"
        );
    }
}

#[test]
fn rust_build_performance_declared_by_rust_family_agents() {
    // Per Bob directive 2026-07-17: rust-engineer and tauri-engineer both
    // declare `rust-build-performance` directly in their own `skills:`
    // frontmatter (NOT via BASE-ENGINEER — not every engineer compiles
    // Rust), proven against the REAL bundled asset files via compose_agent,
    // mirroring `documentation_style_unions_into_engineer_family_via_base_engineer`.
    use crate::core::agent_builder::compose_agent;

    let assets_dir = agent_assets_dir();

    for agent in ["rust-engineer", "tauri-engineer"] {
        let composed = compose_agent(agent, assets_dir)
            .unwrap_or_else(|e| panic!("compose_agent({agent}) must succeed: {e}"));
        assert!(
            composed.contains("rust-build-performance"),
            "composed {agent} is missing its own declared \
             rust-build-performance skill: {composed}"
        );
    }
}

#[test]
fn rust_engineer_declares_delivery_workflow_and_names_no_absent_skill() {
    // Issue #8192, two halves of one contract. (1) `rust-engineer` declares
    // `rust-delivery-workflow` in its own `skills:` (not via BASE-ENGINEER —
    // no other engineer runs cargo gates). (2) The body's first-action
    // instruction no longer names `toolchains-rust-core`, which ships in no
    // bundle: #2904 claimed to port it and never did, so every dispatched
    // rust-engineer was told to load a skill that does not exist.
    use crate::core::agent_builder::compose_agent;

    let assets_dir = agent_assets_dir();
    let composed = compose_agent("rust-engineer", assets_dir)
        .expect("compose_agent(rust-engineer) must succeed");

    assert!(
        composed.contains("rust-delivery-workflow"),
        "composed rust-engineer is missing its own declared \
         rust-delivery-workflow skill: {composed}"
    );
    assert!(
        !composed.contains("toolchains-rust-core"),
        "composed rust-engineer still names `toolchains-rust-core`, a skill \
         present in no bundle (#8192)"
    );
}

#[test]
fn tm_init_surfaces_build_performance_pointer_for_rust_projects() {
    // The `rust-build-performance` skill (per-agent, resident in
    // `rust-engineer`/`tauri-engineer` — see
    // `rust_build_performance_declared_by_rust_family_agents` above) only
    // reaches a session that dispatches one of those agents. Nothing at
    // PROJECT-SETUP time surfaced it before a build already felt slow — this
    // test pins the `/tm-init` fix: a Rust project's scaffolded/refreshed
    // `CLAUDE.md` MUST get a durable Build Performance pointer, and that
    // pointer must not assert a benefit the in-flight sccache measurement
    // has not established.
    assert!(
        skill_text("skills/tm-init.md").contains("Cargo.toml"),
        "tm-init must key the Build Performance pointer off the same \
         Cargo.toml marker rust-engineer deploys on"
    );
    assert!(
        skill_text("skills/tm-init.md").contains("Build Performance"),
        "tm-init is missing the Build Performance section instruction for \
         Rust projects"
    );
    assert!(
        skill_text("skills/tm-init.md").contains("rust-build-performance"),
        "tm-init's Build Performance pointer must reference the bundled \
         rust-build-performance skill"
    );
    assert!(
        skill_text("skills/tm-init.md").contains("cargo build --timings"),
        "tm-init must direct a new Rust project toward measuring a baseline \
         with --timings, not toward a compiler-flag or cache guess"
    );
    assert!(
        skill_text("skills/tm-init.md").contains("Never assert that `sccache`"),
        "tm-init must not let a scaffolded CLAUDE.md assert an unmeasured \
         sccache speedup — the skill's own §6 caveats (no default hit on \
         incremental path-crate builds) must be preserved, not silently \
         dropped, by the pointer this test guards"
    );
}

#[test]
fn output_styles_keep_claude_code_coding_instructions() {
    // Claude Code strips its built-in software-engineering instructions (how to
    // scope changes, write comments, verify work) from any custom output style
    // unless `keep-coding-instructions` is true — the field defaults to FALSE.
    // All three PM styles are PM-orchestration styles layered ON TOP of
    // normal coding behaviour, so all three must opt back in.
    let frontmatter = |style: &BundledStyle| {
        style
            .content(rc())
            .split("---")
            .nth(1)
            .unwrap_or_else(|| panic!("{} must open with a YAML frontmatter block", style.id))
            .to_string()
    };
    for style in pm_output_styles() {
        assert!(
            frontmatter(style).contains("keep-coding-instructions: true"),
            "{} frontmatter must set `keep-coding-instructions: true`, or Claude \
             Code silently drops its built-in coding instructions",
            style.id
        );
    }
    // #8453: the supervisor is not a coder — its style drops them on purpose,
    // as the reference supervisor's style did.
    let supervisor = OUTPUT_STYLES
        .iter()
        .find(|s| s.id == crate::core::session_profile::SUPERVISOR_OUTPUT_STYLE_ID)
        .expect("the supervisor style is bundled");
    assert!(frontmatter(supervisor).contains("keep-coding-instructions: false"));
}

/// Every prose RULE the output styles must state resident, as a short anchor.
///
/// Why: #7423 moved the worked example and the observed-instance inventories
/// into `tm-prose-style` and left each rule as a one-line statement. Pinning the
/// paragraph wording would re-forbid that trim on the next pass; pinning one
/// anchor per rule still fails the moment a rule is dropped.
/// What: one substring per surviving rule, plus the #2647 rationale and the
/// `tm-prose-style` pointer that carries the evidence.
/// Test: `bundle_tests::output_styles_state_every_pm_prose_rule`.
/// Does `haystack` state `anchor`, ignoring where Markdown broke the lines?
///
/// Why: #7709 — the prose-anchor loops matched a multi-word anchor with a plain
/// `contains`, so a rewrap that moved the anchor's last word onto the next line
/// failed a pin whose prose had not changed at all (found in #7683 round 2).
/// What: collapses every run of whitespace in both sides to a single space
/// before the substring test, so a newline and its indentation read as the
/// single space a reflow replaced.
/// Test: `prose_rule_anchors_survive_a_markdown_rewrap_7709`.
fn contains_prose_anchor(haystack: &str, anchor: &str) -> bool {
    fn collapse(text: &str) -> String {
        text.split_whitespace().collect::<Vec<_>>().join(" ")
    }
    collapse(haystack).contains(&collapse(anchor))
}

const PROSE_RULE_ANCHORS: &[&str] = &[
    "## Communication — Write Plainly",
    "issue #2647",
    "**Tone**",
    "**No mocks**",
    "**no placeholders**",
    "concrete referent",
    "closing aphorisms",
    "**Do not embellish.**",
    "**Don't justify the restraint**",
    "trailing emphatic negation",
    "**No praise for the user.**",
    "**If you are saying it, its worth is implied.**",
    "**Banned word — \"honest\"**",
    "**No borrowed-metaphor jargon.**",
    "ASD-STE-100",
    "**Ticket and PR bodies**",
    "never whether it is said",
    "Skill(skill=\"tm-prose-style\")",
];

#[test]
fn output_styles_state_every_pm_prose_rule() {
    // #2647: the output style is the only channel that survives a manual
    // `claude` launch with no tm-appended system prompt, so every PM prose rule
    // is stated RESIDENT here rather than referenced. #7423 kept the rules and
    // moved their examples behind `Skill(skill="tm-prose-style")`, so the
    // contract is "the rule is still stated, and its evidence is one hop away".
    // #8453: the PM styles; the supervisor style's prose section is pinned
    // verbatim by `the_supervisor_style_carries_write_plainly_verbatim`.
    for style in pm_output_styles() {
        for needle in PROSE_RULE_ANCHORS {
            // #7709: whitespace-insensitive, so a rewrap is not a regression.
            assert!(
                contains_prose_anchor(style.content(rc()), needle),
                "{} is missing prose rule anchor {needle:?} (#2647, #7423)",
                style.id
            );
        }
        // The superseded lighter rule set must be FOLDED IN, not left alongside
        // the mirrored rules as a second overlapping statement of the same thing.
        assert!(
            !style
                .content(rc())
                .contains("**Tone**: Professional, neutral"),
            "{}: the old Communication block must be folded into the mirrored \
             prose rules, not duplicated beside them",
            style.id
        );
    }
}

/// 🔴 #7709 REGRESSION: the prose-anchor loops matched with a plain `contains`,
/// so a Markdown rewrap that wrapped a multi-word anchor across two lines broke
/// the pin even though the prose was unchanged (found in #7683 round 2).
#[test]
fn prose_rule_anchors_survive_a_markdown_rewrap_7709() {
    /// Rewraps `text` at `words_per_line`, the way a reflow moves a phrase's
    /// tail onto the next line — every multi-word anchor ends up split.
    fn rewrap(text: &str, words_per_line: usize) -> String {
        text.split_whitespace()
            .collect::<Vec<_>>()
            .chunks(words_per_line)
            .map(|chunk| chunk.join(" "))
            .collect::<Vec<_>>()
            .join("\n")
    }

    for style in pm_output_styles() {
        let rewrapped = rewrap(style.content(rc()), 3);
        // A reflow-broken anchor must still match…
        for needle in PROSE_RULE_ANCHORS {
            assert!(
                contains_prose_anchor(&rewrapped, needle),
                "{}: anchor {needle:?} stopped matching after a Markdown rewrap \
                 (#7709)",
                style.id
            );
        }
        // …and the pre-fix matcher is what fails on exactly that text, so the
        // loop above is not passing for the trivial reason that nothing broke.
        assert!(
            PROSE_RULE_ANCHORS
                .iter()
                .any(|needle| !rewrapped.contains(needle)),
            "{}: rewrap must actually split at least one anchor, or this test \
             proves nothing (#7709)",
            style.id
        );
    }

    // Normalizing whitespace must not turn the match into a tautology: an
    // anchor the text does not state still fails, wrapped or not.
    assert!(
        !contains_prose_anchor(
            "a rule that is\n  stated here",
            "a rule that is not stated here"
        ),
        "whitespace normalization must not make an absent anchor match (#7709)"
    );
}

#[test]
fn the_borrowed_metaphor_ban_reaches_both_prose_channels() {
    // The owner banned "load-bearing" on 2026-08-10 as an instance of a
    // category. It has to bind PM prose (the output styles, #2647) and agent
    // prose (BASE-AGENT.md composition) alike. #7423 split the two halves: the
    // RULE stays resident in both channels, and the category statement that
    // keeps it from degenerating into a phrase list moved to `tm-prose-style`.
    // Both halves are asserted, in their new homes.
    use crate::core::agent_builder::compose_agent;

    const RESIDENT: &[&str] = &["**No borrowed-metaphor jargon.**", "load-bearing"];

    for style in OUTPUT_STYLES {
        for needle in RESIDENT {
            assert!(
                style.content(rc()).contains(needle),
                "{} is missing the borrowed-metaphor ban {needle:?}",
                style.id
            );
        }
    }

    let assets_dir = agent_assets_dir();
    let composed =
        compose_agent("version-control", assets_dir).expect("compose_agent must succeed");
    for needle in RESIDENT {
        assert!(
            composed.contains(needle),
            "composed agent is missing the borrowed-metaphor ban {needle:?}"
        );
    }

    // The category statement and the scope note are what stop the ban becoming
    // a word list; they now live one Skill call away, not in either channel.
    for needle in [
        "an engineering metaphor borrowed to signal precision",
        "Scope: PM and agent prose.",
    ] {
        assert!(
            skill_text("skills/tm-prose-style.md").contains(needle),
            "tm-prose-style must carry the borrowed-metaphor category statement {needle:?}"
        );
    }
}

#[test]
fn the_honest_ban_reaches_both_prose_channels() {
    // The word ban used to live only in the manifest block the composed prompt
    // carries, so a manual `claude` launch never received it and the output
    // styles pointed at a rule they did not state. It now states the rule, in
    // every position the word can take — the owner's flagged instance was the
    // heading modifier "Distribution, stated honestly", not a bare "honest".
    use crate::core::agent_builder::compose_agent;

    const RESIDENT: &[&str] = &["**Banned word — \"honest\"**", "label on your own register"];

    for style in OUTPUT_STYLES {
        for needle in RESIDENT {
            assert!(
                style.content(rc()).contains(needle),
                "{} is missing the \"honest\" ban {needle:?}",
                style.id
            );
        }
    }

    let assets_dir = agent_assets_dir();
    let composed =
        compose_agent("version-control", assets_dir).expect("compose_agent must succeed");
    for needle in RESIDENT {
        assert!(
            composed.contains(needle),
            "composed agent is missing the \"honest\" ban {needle:?}"
        );
    }

    // Every position the word can take, and the owner's flagged instance, moved
    // to `tm-prose-style` in #7423. The ban is useless without them, so they are
    // asserted there rather than dropped.
    for needle in [
        "adjective, adverb, heading modifier, parenthetical",
        "\"Distribution, stated honestly:\"",
        "plainly, candidly, bluntly,",
    ] {
        assert!(
            skill_text("skills/tm-prose-style.md").contains(needle),
            "tm-prose-style must carry the \"honest\" ban's detail {needle:?}"
        );
    }
}

#[test]
fn the_asd_ste_100_layer_reaches_both_prose_channels() {
    // The owner added ASD-STE-100 as a sentence-CONSTRUCTION layer on top of
    // the existing stance rules, in spirit only: the ~900-word approved
    // vocabulary is deliberately NOT adopted, because it forbids common verbs
    // and would make trade-off discussion stilted. Both halves are asserted —
    // the layer's presence, and the refusal that keeps a future reader from
    // "fixing" it into literal conformance. Reaches PM prose (output styles,
    // #2647) and agent prose (BASE-AGENT.md composition) alike, per the
    // keep-the-two-in-step rule the section states.
    use crate::core::agent_builder::compose_agent;

    const RESIDENT: &[&str] = &[
        "ASD-STE-100, applied in spirit",
        "one idea per",
        "active voice",
        // ADD, not replace: the stance rules the layer sits on top of.
        "**No praise for the user.**",
    ];

    for style in OUTPUT_STYLES {
        for needle in RESIDENT {
            assert!(
                style.content(rc()).contains(needle),
                "{} is missing the ASD-STE-100 construction layer {needle:?}",
                style.id
            );
        }
        // The superseded bullet was FOLDED IN, not left beside the layer as a
        // second statement of "one idea per sentence" in different words.
        assert!(
            !style
                .content(rc())
                .contains("Short sentences, one idea each"),
            "{}: the old short-sentence bullet must be folded into the \
             ASD-STE-100 layer, not duplicated beside it",
            style.id
        );
    }

    let assets_dir = agent_assets_dir();
    let composed =
        compose_agent("version-control", assets_dir).expect("compose_agent must succeed");
    for needle in RESIDENT {
        assert!(
            composed.contains(needle),
            "composed agent is missing the ASD-STE-100 construction layer {needle:?}"
        );
    }

    // The seven construction rules in full, and the refusal that stops a future
    // reader "fixing" the spirit adoption into literal conformance, moved to
    // `tm-prose-style` in #7423.
    for needle in [
        "approved vocabulary does NOT",
        "literal conformance with the word list",
        "One idea per sentence; one instruction per sentence.",
        "No noun cluster longer than three words.",
    ] {
        assert!(
            skill_text("skills/tm-prose-style.md").contains(needle),
            "tm-prose-style must carry the ASD-STE-100 detail {needle:?}"
        );
    }
}

#[test]
fn the_default_output_style_stays_within_its_resident_budget() {
    // #7423: the style is resident in every PM turn, so its size is a cost paid
    // continuously. 8 KB is the budget the trim landed under — a rule added here
    // must displace text, not extend the file. Examples and inventories belong
    // in `tm-prose-style`, which loads on demand.
    const BUDGET_BYTES: usize = 8_000;
    assert!(
        instruction_text("output-styles/trusty-mpm.md").len() <= BUDGET_BYTES,
        "output style `{DEFAULT_OUTPUT_STYLE_ID}` is {} bytes, over the \
         {BUDGET_BYTES}-byte resident budget — move examples into \
         `tm-prose-style` rather than growing it",
        instruction_text("output-styles/trusty-mpm.md").len()
    );
}

#[test]
fn output_styles_name_the_todowrite_fallback() {
    // #2799: every bundled style used to mandate `TodoWrite` unconditionally, so
    // a PM on a harness that does not expose it announced the gap and improvised
    // its own tracking. The section must state the CONDITION and the fallback;
    // pinning both halves keeps a future trim from dropping one of them.
    // #8453: a PM section; the supervisor style carries no TodoWrite mandate.
    for style in pm_output_styles() {
        assert!(
            style.content(rc()).contains("where the harness exposes it"),
            "{}: the TodoWrite section must make the tool conditional (#2799)",
            style.id
        );
        assert!(
            style.content(rc()).contains("prose task list"),
            "{}: the TodoWrite section must name the prose fallback (#2799)",
            style.id
        );
    }
}

/// The resident budget every deployed agent body is measured against.
///
/// Issue #7723 (epic #7681): composed rust-engineer (BASE-AGENT +
/// BASE-ENGINEER + rust-engineer body) measured 55,872 bytes on 2026-09-13,
/// 19,981 tokens per turn (32% of an engineer subagent's floor, the single
/// largest component — `docs/research/token-floor-measurement-2026-09-13.md`).
/// The #7723 trim target was ~40,000; 42,000 leaves headroom without licensing
/// the file to regrow back toward its pre-trim size.
const RESIDENT_BODY_BUDGET_BYTES: usize = 42_000;

/// Bodies already over [`RESIDENT_BODY_BUDGET_BYTES`] when #7825 widened the
/// gate from rust-engineer alone to every deployed agent, each pinned at a
/// ratchet ceiling with the issue tracking its trim.
///
/// Why: #7825 named four; widening the gate surfaced four more on
/// 2026-09-15 — java, nextjs, python and svelte engineer were over too, each
/// by under 600 bytes; #8047 trimmed all four back under the default budget,
/// so their entries are gone. Raising the budget for everyone would hide the
/// rest; excluding them would drop the coverage the issue asked for. A
/// per-stem ceiling keeps each one measured and lets it shrink but never grow.
/// What: `(stem, ceiling_bytes, tracking_issue)`. The ceiling is the measured
/// size rounded up to the next 500 bytes, so an unrelated BASE-AGENT edit does
/// not flip the gate while real regrowth still does. An entry whose body has
/// fallen back under the default budget fails the gate as stale — that is how
/// the allowlist empties itself.
/// Test: `every_deployed_agent_composed_body_stays_within_its_resident_budget`.
const OVER_BUDGET_BODY_BASELINES: &[(&str, usize, &str)] = &[
    ("dotnet-engineer", 43_500, "#7825"),
    ("elixir-engineer", 44_000, "#7825"),
    ("ticketing", 47_000, "#7727"),
    ("version-control", 47_500, "#7727"),
];

/// The bundled agent assets directory the composer reads.
fn agent_assets_dir() -> &'static std::path::Path {
    // #9011: the roster's checkout directory, `content/agents`.
    static DIR: std::sync::OnceLock<std::path::PathBuf> = std::sync::OnceLock::new();
    DIR.get_or_init(crate::core::content_source::test_support::repo_agents_dir)
}

/// One roster file's body from the checkout roster (#9011), which replaced the
/// compiled-in `*_AGENT` consts.
fn agent(file_name: &str) -> &'static str {
    static ROSTER: std::sync::OnceLock<crate::core::content_source::AgentRoster> =
        std::sync::OnceLock::new();
    ROSTER
        .get_or_init(crate::core::content_source::test_support::repo_roster)
        .require(file_name)
        .unwrap_or_else(|e| panic!("{e}"))
}

/// Every deployed (non-foundation) bundled agent stem, sorted.
fn deployed_agent_stems() -> Vec<String> {
    let mut stems: Vec<String> = std::fs::read_dir(agent_assets_dir())
        .expect("bundled agent assets dir")
        .flatten()
        .map(|entry| entry.path())
        .filter(|path| path.extension().and_then(|e| e.to_str()) == Some("md"))
        .filter_map(|path| {
            path.file_stem()
                .and_then(|s| s.to_str())
                .map(str::to_string)
        })
        .filter(|stem| !crate::core::delegation_authority::is_foundation_file(stem))
        .collect();
    stems.sort();
    stems
}

/// Per-asset byte ledger for one composed agent body, base-first.
///
/// Why: #7915 — the budget assertion below reported one total, so a one-line
/// addition anywhere in the `extends:` chain turned the gate red with no
/// pointer to which file grew. The ledger names the contributors.
/// What: walks the same `extends:` chain [`compose_agent`] resolves and renders
/// one `name.md = N bytes` entry per link, then the composed total and the
/// headroom (or overrun) against `budget`.
/// Test: `composed_body_ledger_names_every_chain_link_7915`.
fn composed_body_ledger(stem: &str, composed_len: usize, budget: usize) -> String {
    use crate::core::agent_builder::source_chain;

    let chain = source_chain(stem, agent_assets_dir()).unwrap_or_else(|_| vec![stem.to_string()]);
    let mut parts: Vec<String> = chain
        .iter()
        .map(|link| match agent_source_bytes(link) {
            Some(bytes) => format!("{link}.md = {bytes} bytes"),
            None => format!("{link}.md = <source not found>"),
        })
        .collect();
    parts.push(format!("composed = {composed_len} bytes"));
    parts.push(if composed_len > budget {
        format!("OVER budget {budget} by {}", composed_len - budget)
    } else {
        format!("budget {budget}, {} bytes headroom", budget - composed_len)
    });
    parts.join("; ")
}

/// Byte size of one chain link's source file, resolved case-insensitively.
///
/// The composer matches `extends: base-agent` to `BASE-AGENT.md` on
/// case-sensitive filesystems, so the ledger has to resolve the same way.
fn agent_source_bytes(link: &str) -> Option<u64> {
    let want = link.to_lowercase();
    for entry in std::fs::read_dir(agent_assets_dir()).ok()?.flatten() {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("md") {
            continue;
        }
        let matches = path
            .file_stem()
            .and_then(|s| s.to_str())
            .is_some_and(|stem| stem.to_lowercase() == want);
        if matches {
            return std::fs::metadata(&path).ok().map(|m| m.len());
        }
    }
    None
}

#[test]
fn rust_engineer_composed_body_stays_within_its_resident_budget() {
    use crate::core::agent_builder::compose_agent;

    let composed = compose_agent("rust-engineer", agent_assets_dir())
        .expect("compose_agent(rust-engineer) must succeed");
    assert!(
        composed.len() <= RESIDENT_BODY_BUDGET_BYTES,
        "composed rust-engineer is over the {RESIDENT_BODY_BUDGET_BYTES}-byte \
         resident budget (#7723) — move detail into a skill rather than growing \
         the chain. Ledger: {}",
        composed_body_ledger("rust-engineer", composed.len(), RESIDENT_BODY_BUDGET_BYTES)
    );
}

/// 🔴 #7915 REGRESSION: the budget assertion reported a single total with 14
/// bytes of headroom, so any addition to BASE-AGENT.md or a bundled skill
/// turned it red with no pointer to the file that grew.
#[test]
fn composed_body_ledger_names_every_chain_link_7915() {
    use crate::core::agent_builder::{compose_agent, source_chain};

    let composed = compose_agent("rust-engineer", agent_assets_dir())
        .expect("compose_agent(rust-engineer) must succeed");
    let ledger = composed_body_ledger("rust-engineer", composed.len(), RESIDENT_BODY_BUDGET_BYTES);

    let chain = source_chain("rust-engineer", agent_assets_dir())
        .expect("source_chain(rust-engineer) must succeed");
    assert!(
        chain.len() >= 3,
        "rust-engineer must inherit through BASE-AGENT and BASE-ENGINEER, got {chain:?}"
    );
    for link in &chain {
        assert!(
            ledger.contains(&format!("{link}.md = ")),
            "ledger must name chain link {link:?} and its byte count, got {ledger:?}"
        );
        assert!(
            !ledger.contains(&format!("{link}.md = <source not found>")),
            "ledger failed to resolve the source file for {link:?}: {ledger:?}"
        );
    }
    assert!(
        ledger.contains(&format!("composed = {} bytes", composed.len())),
        "ledger must report the composed total: {ledger:?}"
    );
    assert!(
        ledger.contains("headroom") || ledger.contains("OVER budget"),
        "ledger must report headroom or the overrun: {ledger:?}"
    );
}

/// 🔴 #7825 REGRESSION: the resident-body budget covered rust-engineer alone,
/// so four other deployed bodies sat over 42,000 bytes undetected.
#[test]
fn every_deployed_agent_composed_body_stays_within_its_resident_budget() {
    use crate::core::agent_builder::compose_agent;

    let stems = deployed_agent_stems();
    let mut over: Vec<String> = Vec::new();
    let mut stale: Vec<String> = Vec::new();

    for stem in &stems {
        let composed = compose_agent(stem, agent_assets_dir())
            .unwrap_or_else(|e| panic!("compose_agent({stem}): {e}"));
        let baseline = OVER_BUDGET_BODY_BASELINES
            .iter()
            .find(|(name, _, _)| name == stem);
        let (budget, tracker) = match baseline {
            Some((_, ceiling, issue)) => (*ceiling, Some(*issue)),
            None => (RESIDENT_BODY_BUDGET_BYTES, None),
        };
        if composed.len() > budget {
            let ledger = composed_body_ledger(stem, composed.len(), budget);
            over.push(match tracker {
                Some(issue) => format!("{stem} (ratchet, {issue}): {ledger}"),
                None => format!("{stem}: {ledger}"),
            });
        }
        if tracker.is_some() && composed.len() <= RESIDENT_BODY_BUDGET_BYTES {
            stale.push(stem.clone());
        }
    }

    assert!(
        over.is_empty(),
        "composed agent bodies exceed their resident budget (#7825) — move \
         detail into a skill rather than growing the chain: {over:#?}"
    );
    assert!(
        stale.is_empty(),
        "these bodies are back under the {RESIDENT_BODY_BUDGET_BYTES}-byte \
         default budget — drop their OVER_BUDGET_BODY_BASELINES entries (#7825): \
         {stale:?}"
    );
    for (name, _, _) in OVER_BUDGET_BODY_BASELINES {
        assert!(
            stems.iter().any(|stem| stem == name),
            "OVER_BUDGET_BODY_BASELINES names {name:?}, which is not a deployed \
             bundled agent — the entry is stale (#7825)"
        );
    }
}

#[test]
fn base_agent_prose_rules_survive_composition() {
    // Output styles do NOT apply to subagents (they run their own system
    // prompt), so the prose rules have to reach agents through BASE-AGENT.md
    // composition instead. #7423 trimmed that section to one line per rule and
    // pointed it at the same skill the output style points at, so assert the
    // heading, the pointer, and one anchor per rule — plus the sparse-on-success
    // rule and the raw-output evidence floor it must not weaken.
    use crate::core::agent_builder::compose_agent;

    let assets_dir = agent_assets_dir();

    let composed =
        compose_agent("version-control", assets_dir).expect("compose_agent must succeed");

    // The agent-facing variant is kept in step with the output style, so it
    // states the same rules under a heading naming the same standard.
    // #7683: the pointer is PROSE, not a modelled `Skill(...)` call — most
    // agents' `tools:` allowlist no longer carries `Skill`, so an instruction
    // to invoke it would name a tool the agent does not have. The PM's own
    // output style still models the call (it keeps the tool); that pin lives in
    // `claude_md_sections_tests.rs`.
    for needle in [
        "Write Plainly",
        "`tm-prose-style` skill",
        "concrete referent",
        "closing aphorisms",
        "**Do not embellish.**",
        "**Don't justify the restraint**",
        "trailing emphatic negation",
        "**No praise for the user.**",
        "**If you are saying it, its worth is implied.**",
        "**Banned word — \"honest\"**",
        "**No borrowed-metaphor jargon.**",
        "ASD-STE-100",
        "**Ticket and PR bodies you draft**",
        "never whether it is said",
    ] {
        // #7709: whitespace-insensitive, so a rewrap is not a regression.
        assert!(
            contains_prose_anchor(&composed, needle),
            "composed agent is missing prose rule anchor {needle:?} (#7423)"
        );
    }

    // #7683: BASE-AGENT is the `extends` root of every roster agent, and most
    // of their `tools:` allowlists omit `Skill`. Compose one of those and
    // assert the base template models no `Skill(...)` call at all — an agent
    // must never be told to invoke a tool it does not carry.
    let no_skill_tool =
        compose_agent("code-critic", assets_dir).expect("compose_agent must succeed");
    assert!(
        !no_skill_tool.contains("Skill(skill="),
        "an agent whose tools: omits Skill must inherit no modelled Skill(...) call (#7683)"
    );

    assert!(
        composed.contains("Verbosity scales with what went wrong"),
        "composed agent is missing the graduated-verbosity rule"
    );
    assert!(
        composed.contains("A long report about a clean run"),
        "composed agent is missing the sparse-on-success rule"
    );
    // The evidence floor must survive verbatim next to it.
    assert!(
        composed.contains("Show raw output. Never summarise test results in your own words."),
        "graduated verbosity must not weaken the raw-output rule"
    );
    assert!(
        composed.contains("Sparse-on-success governs the"),
        "composed agent is missing the evidence-rule carve-out"
    );
    // "Caveman" is taken: hooks/optimizer.toml uses it for an unrelated
    // tool-output compression level. The prose rule must not collide with it.
    assert!(
        !composed.contains("Caveman"),
        "graduated-verbosity rule must not reuse the optimizer's `Caveman` term"
    );
}

/// 🔴 #7612 REGRESSION: `local-ops` parked on a narrated wait twice in one
/// session — once on a reachability poll, once after starting a deploy script —
/// despite BASE-AGENT's inherited rule, and a 600s bounded loop overran the
/// Bash tool's 600000ms ceiling. #2501/#2610 closed the same class on
/// version-control; the persona text must name the blocking verb for ITS task
/// shapes and the margin a bounded loop owes.
#[test]
fn local_ops_names_tm_wait_for_deploys_and_a_loop_margin_7612() {
    use crate::core::agent_builder::compose_agent;

    let assets_dir = agent_assets_dir();
    let local_ops =
        compose_agent("local-ops", assets_dir).expect("compose_agent(local-ops) must succeed");

    for needle in [
        "A deploy script and a reachability poll are your commands too",
        "`tm wait --for run`",
        "tm wait --for run --pid <pid> --timeout 480",
        "tm wait --for file --path <sentinel>",
        "10-15% under the harness's foreground ceiling",
        "600000ms",
    ] {
        assert!(
            local_ops.contains(needle),
            "composed local-ops is missing the #7612 blocking-wait guidance: {needle:?}"
        );
    }
}

/// 🔴 #7558 REGRESSION: `git pull --ff-only` aborts naming only the colliding
/// path, so the recovery gets improvised — once by hand-diffing two copies of
/// an untracked research doc. The bundled `git-workflow` skill must state the
/// pre-pull check and BOTH of its outcomes, so the identical-content case
/// resolves itself and the differing-content case is reported rather than
/// deleted.
#[test]
fn git_workflow_skill_states_the_pre_pull_untracked_collision_check_7558() {
    for needle in [
        "### Pulling After a Merge — Check Untracked Collisions First",
        "git status --porcelain",
        "git show origin/<base>:<path>",
        "**Identical content**",
        "**Differing content**",
        "Never delete an untracked path to clear the abort without diffing it",
    ] {
        assert!(
            skill_text("skills/git-workflow.md").contains(needle),
            "git-workflow skill is missing the #7558 pre-pull untracked-collision \
             guidance: {needle:?}"
        );
    }
}

/// #8630: adaptive-crm spent its org's Actions cap and every job failed after.
/// The deployed `git-workflow` entry must carry the four-check heading, each
/// check, the run-spend rule and the billing-blocker phrase, and the composed
/// `version-control` body must point at that section.
#[test]
fn deployed_git_workflow_skill_carries_the_actions_spend_checks_8630() {
    let deployed = deployed()
        .into_iter()
        .find(|a| a.rel_path == "skills/git-workflow.md")
        .expect("git-workflow must be in the ALL bundle table")
        .contents;
    for needle in [
        "### Four Checks Before a Workflow Edit or a PR on a Billed Repo",
        "branches: [main]",
        "cancel-in-progress: ${{ github.ref != format(",
        "timeout-minutes: 20",
        "if: needs.changes.outputs.db == 'true'",
        "Never re-run a green run.",
        "recent account payments have failed or your spending limit",
        "19,667 Linux minutes",
    ] {
        assert!(
            deployed.contains(needle),
            "deployed git-workflow skill is missing the #8630 Actions-spend text: {needle:?}"
        );
    }
    let composed = crate::core::agent_builder::compose_agent("version-control", agent_assets_dir())
        .expect("compose_agent(version-control) must succeed");
    assert!(
        composed.contains("git-workflow/SKILL.md`, \"GitHub Actions Spend\""),
        "composed version-control must point at the #8630 section"
    );
}

/// 🔴 #7558 REGRESSION, second home: `tm-workflow` owns the main-checkout
/// `pull --ff-only` refresh and already names ONE cause of its failure
/// (another session's uncommitted work). The untracked-path collision is a
/// second cause of the same command failing, so the refresh instructions must
/// point at the check rather than leaving the reader to improvise — a
/// cross-reference, not a second copy of the block.
#[test]
fn tm_workflow_points_at_the_pre_pull_untracked_collision_check_7558() {
    for needle in [
        "untracked path the incoming commits also add",
        "Pulling After a Merge — Check Untracked Collisions First",
        "#7558",
    ] {
        assert!(
            skill_text("skills/tm-workflow.md").contains(needle),
            "tm-workflow is missing the #7558 cross-reference to the pre-pull \
             untracked-collision check: {needle:?}"
        );
    }
    // A pointer, not a duplicate: the procedure itself stays in one place.
    assert!(
        !skill_text("skills/tm-workflow.md")
            .contains("git show origin/<base>:<path> | diff - <path>"),
        "tm-workflow must cross-reference the check, not restate its commands (#7558)"
    );
}

/// 🔴 #7561 REGRESSION: a `kill <pid>` the agent issued itself surfaced four
/// times as "failed with exit code 143", because a `128 + signal` exit shares
/// the numeric range of a real failure. `verification-before-completion` owns
/// the "check exit code" step, so the signal reading must live beside it —
/// including the one `128 + N` value that IS a failure (137 nobody killed).
#[test]
fn verification_skill_reads_128_plus_signal_as_terminated_not_failed_7561() {
    for needle in [
        "## Reading an Exit Code",
        "`128 + N`",
        "`143` (128+15)",
        "`SIGTERM` — the ordinary `kill <pid>`",
        "**terminated by signal N**",
        "never as \"failed with exit code 143\"",
        "The one exception is `137`",
    ] {
        assert!(
            skill_text("skills/verification-before-completion.md").contains(needle),
            "verification-before-completion skill is missing the #7561 \
             signal-exit reading: {needle:?}"
        );
    }
}

/// #7739: a local gate proves only the tree it ran against. `version-control`
/// reproduced this on an external repo (adaptive-crm PR #393) — the gate
/// passed against a working tree that held an uncommitted edit, the pushed
/// ref lacked it, and CI failed a `2 !== 3` assertion the gate never saw.
/// Both the agent and the workflow skill must state the clean-tree check.
#[test]
fn version_control_gate_requires_a_clean_tree_before_push_7739() {
    assert!(
        agent("version-control.md").contains("git status --porcelain")
            && agent("version-control.md").contains("#7739"),
        "version-control.md is missing the #7739 clean-tree-before-gate rule"
    );
    assert!(
        skill_text("skills/tm-workflow.md").contains("git status --porcelain")
            && skill_text("skills/tm-workflow.md").contains("#7739"),
        "tm-workflow.md is missing the #7739 clean-tree-before-gate rule"
    );
}

/// #7871: the ticketing agent reported that a repository carried no `done`
/// lifecycle label without listing the repository's labels first —
/// adaptive-crm carried `unicorn:done` the whole time. The asset must send the
/// agent to the live list before any absence claim, and say what to do with
/// each answer the list can give.
#[test]
fn ticketing_reads_the_live_label_list_before_claiming_a_label_is_absent_7871() {
    for needle in [
        "#7871",
        "never call a label absent without `gh label list` in front of you",
        "gh label list -R <owner>/<repo> --limit 200",
        "`gh label create <name>` and report what you created",
    ] {
        assert!(
            agent("ticketing.md").contains(needle),
            "ticketing.md is missing the #7871 list-before-asserting-absence \
             rule: {needle:?}"
        );
    }
}

/// #8013: a 5xx or timeout from a mutating `gh` call is not proof the call
/// failed — `version-control` retried `gh pr merge` after a 502 without
/// checking whether the merge had already landed, and the retry's side
/// effects (a dropped `--delete-branch`, a missed webhook) went unnoticed.
#[test]
fn version_control_verifies_before_retrying_a_5xx_8013() {
    assert!(
        agent("version-control.md").contains("5xx")
            && agent("version-control.md").contains("#8013"),
        "version-control.md is missing the #8013 verify-before-retry rule"
    );
    assert!(
        agent("version-control.md").contains("gh pr view --json state,mergeCommit"),
        "version-control.md must name the state-read command that gates a retry (#8013)"
    );
}

/// #8014: `version-control` took a PM brief's `e.g.` example commit subject
/// literally instead of deriving the real subject from the change, so the
/// squash-merge commit subject didn't match its own PR's title.
#[test]
fn version_control_treats_brief_examples_as_shapes_8014() {
    assert!(
        agent("version-control.md").contains("is a shape, not a literal")
            && agent("version-control.md").contains("#8014"),
        "version-control.md is missing the #8014 brief-example-is-a-shape rule"
    );
}

/// #8015: asked to store findings AND report them, the research agent's final
/// report was only a memory-drawer pointer, so the PM had to load
/// `memory_recall` to read the actual conclusion.
#[test]
fn research_report_carries_findings_not_just_a_memory_pointer_8015() {
    assert!(
        agent("research.md").contains("never replaces the report")
            && agent("research.md").contains("#8015"),
        "research.md is missing the #8015 report-carries-findings rule"
    );
}

/// #8022: closing a sibling tab dropped the web-qa agent's MCP tab group,
/// and the agent had no recovery step — a `computer` call on a still-open
/// tab in that group then failed with a stale cross-extension error.
#[test]
fn web_qa_recovers_a_dropped_tab_group_8022() {
    assert!(
        agent("web-qa.md").contains("Never close the last other tab")
            && agent("web-qa.md").contains("#8022"),
        "web-qa.md is missing the #8022 tab-group-recovery rule"
    );
    assert!(
        agent("web-qa.md").contains("tabs_context_mcp"),
        "web-qa.md must name `tabs_context_mcp` as the recovery check (#8022)"
    );
}

/// #8023: vercel-ops guidance named no source of truth for confirming which
/// commit a deployment serves, and no recovery path for a dropped webhook —
/// the agent lost a round-trip re-deriving both by hand.
#[test]
fn vercel_ops_names_commit_verification_and_webhook_recovery_8023() {
    assert!(
        agent("vercel-ops.md").contains("meta.githubCommitSha")
            && agent("vercel-ops.md").contains("#8023"),
        "vercel-ops.md is missing the #8023 commit-verification source"
    );
    assert!(
        agent("vercel-ops.md").contains("POST /v13/deployments"),
        "vercel-ops.md must name the git-sourced redeploy path for a dropped webhook (#8023)"
    );
}

/// #8027: local-ops ignored a diagnose-only brief's restrictions and cited a
/// stale log (last written before the incident window) as root cause.
#[test]
fn local_ops_honours_diagnose_only_briefs_8027() {
    assert!(
        agent("local-ops.md").contains("A diagnose-only brief overrides this playbook")
            && agent("local-ops.md").contains("#8027"),
        "local-ops.md is missing the #8027 diagnose-only-overrides-playbook rule"
    );
    assert!(
        agent("local-ops.md").contains("check its mtime against"),
        "local-ops.md must state the log-mtime check before citing root cause (#8027)"
    );
}

/// #8017: the resume skill's CLI fallback named `tm session catchup`, a verb
/// `main.rs` answers with `warning: 'session' is deprecated; use 'sessions'`,
/// and said nothing about the CLI having neither JSON nor paged output — so a
/// session that lost the MCP server fell back to an unbounded markdown blob
/// (163 KB for 23 sessions) without knowing a paged read existed.
///
/// Why: the skill is the only thing the PM reads before shelling out; a
/// deprecated verb there is a warning on every fallback, and an unnamed paging
/// knob is a paging knob nobody uses.
/// What: asserts the singular verb is gone from the skill and that the paged
/// and JSON forms are named — the MCP tool's and, since #8017's CLI half, the
/// CLI's `--json --sessions-offset`.
/// Test: this test.
#[test]
fn session_resume_skill_cites_live_verbs_and_paged_forms_8017() {
    assert!(
        !skill_text("skills/tm-session-resume.md").contains("tm session catchup"),
        "tm-session-resume.md still cites the deprecated singular `tm session catchup`; \
         the live verb is `tm sessions catchup` (#2116)"
    );
    for needle in [
        "tm sessions catchup",
        "--all-projects",
        "--full",
        "sessions_offset",
        "sessions_next_offset",
        "--json --sessions-offset",
        "#8017",
    ] {
        assert!(
            skill_text("skills/tm-session-resume.md").contains(needle),
            "tm-session-resume.md is missing the #8017 CLI-fallback correction: {needle:?}"
        );
    }
}

/// Why (#8408): every relaunch recreates the tmux window, so the skill's old
/// "select the recorded `@id`" step pointed a resumed PM at a window that no
/// longer existed.
/// What: the skill gives no `tmux select-window` step and names the
/// `tmux_session` resolution route.
/// Test: this test.
#[test]
fn session_resume_skill_does_not_realign_to_a_dead_window_8408() {
    assert!(
        !skill_text("skills/tm-session-resume.md").contains("tmux select-window"),
        "tm-session-resume.md must not tell a resumed PM to select the recorded window"
    );
    assert!(
        skill_text("skills/tm-session-resume.md").contains("\"tmux_session\""),
        "tm-session-resume.md must list the `tmux_session` resolved_via value"
    );
}