warble 0.15.4

Warble front-end compiler: parse/resolve/validate a behavior profile into language-neutral IR (sans-IO).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
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
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
use std::collections::HashMap;
use std::fs;
use std::path::Path;

use warble::{
    Additivity, BindingFile, ComponentFile, ContextLoader, DimensionInfo, LineageGraph, MetricInfo,
    ModelInfo, ProfileFile,
};

/// A controllable in-test [`ContextLoader`] so the core compile tests can drive precondition
/// evaluation without resolving a binding at all. Defaults to a parseable, empty context; builder
/// methods add metrics/dimensions. End-to-end compilation against a real bound layer is covered by
/// the golden tests in the `warble-cli` crate.
#[derive(Default)]
struct FakeContext {
    parseable_flag: bool,
    metrics: Vec<MetricInfo>,
    dimensions: Vec<DimensionInfo>,
    time_dimensions: Vec<DimensionInfo>,
    models: Vec<ModelInfo>,
    lineage: LineageGraph,
}

impl FakeContext {
    fn parseable() -> Self {
        Self {
            parseable_flag: true,
            ..Default::default()
        }
    }
    fn unparseable() -> Self {
        Self::default()
    }
    fn with_metric(mut self, name: &str, declared: bool, additivity: Option<Additivity>) -> Self {
        self.metrics.push(MetricInfo {
            name: name.into(),
            owner: "m".into(),
            declared,
            additivity,
        });
        self
    }
    fn with_dimension(mut self, name: &str, temporal: bool) -> Self {
        let dim = DimensionInfo {
            name: name.into(),
            owner: "m".into(),
            is_temporal: temporal,
        };
        if temporal {
            self.time_dimensions.push(dim.clone());
        }
        self.dimensions.push(dim);
        self
    }
    fn with_model(mut self, name: &str, has_timestamp: bool) -> Self {
        self.models.push(ModelInfo {
            name: name.into(),
            has_timestamp,
            columns: Vec::new(),
        });
        self
    }
}

impl ContextLoader for FakeContext {
    fn is_parseable(&self) -> bool {
        self.parseable_flag
    }
    fn metrics(&self) -> &[MetricInfo] {
        &self.metrics
    }
    fn dimensions(&self) -> &[DimensionInfo] {
        &self.dimensions
    }
    fn time_dimensions(&self) -> &[DimensionInfo] {
        &self.time_dimensions
    }
    fn models(&self) -> &[ModelInfo] {
        &self.models
    }
    fn lineage(&self) -> &LineageGraph {
        &self.lineage
    }
}

/// Compile a fixture project with a default parseable, empty context. Mechanical tests (bind,
/// guardrail, param, vocab) don't touch preconditions, so an empty context suffices.
fn compile_project(project_dir: &Path) -> Result<serde_json::Value, String> {
    compile_project_with(project_dir, &FakeContext::parseable())
}

/// Compile a fixture project with an explicit injected context (for precondition-evaluation tests).
fn compile_project_with(
    project_dir: &Path,
    context: &dyn ContextLoader,
) -> Result<serde_json::Value, String> {
    let profile: ProfileFile =
        serde_yaml::from_str(&fs::read_to_string(project_dir.join("profile.yml")).unwrap())
            .unwrap();

    let binding_path = project_dir.join(&profile.context.project);
    let binding: BindingFile =
        serde_yaml::from_str(&fs::read_to_string(&binding_path).unwrap()).unwrap();

    let mut components: HashMap<String, ComponentFile> = HashMap::new();
    let mut step_contents: HashMap<String, HashMap<String, String>> = HashMap::new();
    let mut slot_contents = warble::SlotContents::default();
    for slot in &profile.slots {
        let mut variants: HashMap<String, String> = HashMap::new();
        for (key, reference) in &slot.variants {
            let content = fs::read_to_string(project_dir.join(reference)).unwrap();
            variants.insert(key.clone(), content);
        }
        slot_contents.profile.insert(slot.name.clone(), variants);
    }

    for mount in &profile.components {
        let component_dir = project_dir.join("components").join(&mount.use_id);
        let component: ComponentFile =
            serde_yaml::from_str(&fs::read_to_string(component_dir.join("component.yml")).unwrap())
                .unwrap();

        let mut steps = HashMap::new();
        for step in &component.llm_steps {
            let content = fs::read_to_string(component_dir.join(&step.prompt_ref)).unwrap();
            steps.insert(step.name.clone(), content);
        }
        step_contents.insert(component.id.clone(), steps);

        let mut slots: HashMap<String, HashMap<String, String>> = HashMap::new();
        for slot in &component.slots {
            let mut variants: HashMap<String, String> = HashMap::new();
            for (key, reference) in &slot.variants {
                let content = fs::read_to_string(component_dir.join(reference)).unwrap();
                variants.insert(key.clone(), content);
            }
            slots.insert(slot.name.clone(), variants);
        }
        if !slots.is_empty() {
            slot_contents.components.insert(component.id.clone(), slots);
        }

        components.insert(component.id.clone(), component);
    }

    warble::compile(
        &profile,
        &components,
        &binding.project,
        context,
        &step_contents,
        &slot_contents,
    )
    .map_err(|e| e.to_string())
}

/// Writes a minimal Warble project into `dir` with one component whose single param has
/// `bind: required`. `bind_block` is inlined verbatim under the profile's component mount
/// entry (empty string omits the `bind:` map entirely, exercising the missing-bind case).
fn write_required_bind_fixture(dir: &Path, bind_block: &str) {
    fs::create_dir_all(dir.join("context")).unwrap();
    fs::create_dir_all(dir.join("components/needs_bind/steps")).unwrap();
    fs::create_dir_all(dir.join("wren_project")).unwrap();
    fs::write(
        dir.join("wren_project/wren_project.yml"),
        "schema_version: 2\n",
    )
    .unwrap();

    fs::write(
        dir.join("profile.yml"),
        format!(
            "profile: fixture\ncontext:\n  project: ./context/binding.yml\ncomponents:\n  - use: needs_bind\n{bind_block}"
        ),
    )
    .unwrap();
    fs::write(
        dir.join("context/binding.yml"),
        // These fixtures inject their own `ContextLoader`, so no resolver ever reads this
        // binding — but `kind` is a required field, so it still has to be declared. `external`
        // is the kind that reads nothing, which is the truthful description of a binding
        // whose context arrives by injection.
        "kind: external\nproject: ./wren_project\n",
    )
    .unwrap();
    fs::write(
        dir.join("components/needs_bind/component.yml"),
        r#"
id: needs_bind
verb: needs_bind
type: analytical
realization_kind: skill
binding_mode: runtime_selected
params:
  - { name: topic, bind: required }
llm_steps:
  - { name: only_step, tier: cheap, prompt_ref: steps/only_step.md }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution, locked: true }
required_capabilities: []
borrowed_actions: []
effect:
  render_blocks: []
  outcome: { kind: none }
"#,
    )
    .unwrap();
    fs::write(
        dir.join("components/needs_bind/steps/only_step.md"),
        "Do the thing.\n",
    )
    .unwrap();
}

/// Same fixture with the selector-facing fields appended to the component, so their authoring rules
/// can be exercised without a shipped profile.
fn write_selector_field_fixture(dir: &Path, selector_block: &str) {
    write_required_bind_fixture(dir, "    bind:\n      topic: \"orders\"\n");
    let path = dir.join("components/needs_bind/component.yml");
    let existing = fs::read_to_string(&path).unwrap();
    fs::write(path, format!("{existing}{selector_block}")).unwrap();
}

/// Every consumer reaches the examples through the description, so examples alone would be dropped
/// with nothing said — the failure mode this project rejects everywhere else.
#[test]
fn examples_without_a_description_fail_loudly() {
    let dir = tempfile::tempdir().unwrap();
    write_selector_field_fixture(dir.path(), "examples:\n  - \"Why did revenue drop?\"\n");

    let err = compile_project(dir.path()).expect_err("examples with no description must fail");
    assert!(
        err.contains("authors 'examples' without a 'description'"),
        "unexpected error: {err}"
    );
}

/// These fields take no placeholder substitution, deliberately: they describe the component to
/// readers with no bound project. A placeholder would therefore ship unrendered.
#[test]
fn a_placeholder_in_a_selector_field_fails_loudly() {
    for block in [
        "description: \"Survey {{project}} and report.\"\n",
        "description: \"Survey the model.\"\nexamples:\n  - \"What is in {{project_name}}?\"\n",
    ] {
        let dir = tempfile::tempdir().unwrap();
        write_selector_field_fixture(dir.path(), block);

        let err = compile_project(dir.path()).expect_err("an unrendered placeholder must fail");
        assert!(
            err.contains("placeholder") && err.contains("would never be rendered"),
            "unexpected error: {err}"
        );
    }
}

/// The paired, placeholder-free form is what authors are expected to write.
#[test]
fn a_description_with_examples_compiles() {
    let dir = tempfile::tempdir().unwrap();
    write_selector_field_fixture(
        dir.path(),
        "description: \"Answer one question about the bound model.\"\nexamples:\n  - \"How many orders?\"\n",
    );

    let ir = compile_project(dir.path()).expect("the paired form must compile");
    let node = &ir["components"][0];
    assert_eq!(
        node["description"], "Answer one question about the bound model.",
        "the authored description is emitted verbatim"
    );
    assert_eq!(node["examples"][0], "How many orders?");
}

#[test]
fn missing_required_bind_fails_loudly() {
    let dir = tempfile::tempdir().unwrap();
    write_required_bind_fixture(dir.path(), "");

    let err = compile_project(dir.path()).expect_err("missing required bind must fail");
    assert!(
        err.contains("missing required bind 'topic' for component 'needs_bind'"),
        "unexpected error: {err}"
    );
}

#[test]
fn supplied_required_bind_compiles() {
    let dir = tempfile::tempdir().unwrap();
    write_required_bind_fixture(dir.path(), "    bind:\n      topic: \"orders\"\n");

    compile_project(dir.path()).expect("bind is supplied, compile should succeed");
}

#[test]
fn locked_guardrail_override_fails_loudly() {
    let dir = tempfile::tempdir().unwrap();
    write_required_bind_fixture(
        dir.path(),
        "    bind:\n      topic: \"orders\"\n    guardrails:\n      read_only_execution:\n        locked: false\n",
    );

    let err = compile_project(dir.path()).expect_err("locked guardrail override must fail");
    assert!(
        err.contains(
            "cannot override locked guardrail 'read_only_execution' on component 'needs_bind'"
        ),
        "unexpected error: {err}"
    );
}

#[test]
fn unparseable_context_fails_loudly() {
    // The coarse floor: an unparseable bound project loud-fails before any per-component work.
    let dir = tempfile::tempdir().unwrap();
    write_required_bind_fixture(dir.path(), "    bind:\n      topic: \"orders\"\n");

    let err = compile_project_with(dir.path(), &FakeContext::unparseable())
        .expect_err("unparseable context must fail");
    assert!(
        err.contains("is not a parseable wren project"),
        "unexpected error: {err}"
    );
}

/// Writes a minimal Warble project into `dir` mounting a single component whose `component.yml`
/// body is exactly `component_yaml`. Mirrors `write_required_bind_fixture`'s scaffolding but lets
/// each test control the full component body (id/verb/params/guardrails/etc.) directly. Every
/// `llm_steps` entry must reference `steps/only_step.md`, which this fixture always writes.
fn write_component_fixture(dir: &Path, component_id: &str, component_yaml: &str) {
    write_component_fixture_with_profile(dir, component_id, component_yaml, "", "");
}

/// The one fixture writer the other two delegate to. `profile_extra` is spliced in as extra
/// top-level `profile.yml` keys (e.g. a `system_prompt:` line) and `bind_block` as extra lines
/// under the component's mount entry; either may be empty. Every `llm_steps` entry must reference
/// `steps/only_step.md`, which this fixture always writes.
fn write_component_fixture_with_profile(
    dir: &Path,
    component_id: &str,
    component_yaml: &str,
    profile_extra: &str,
    bind_block: &str,
) {
    fs::create_dir_all(dir.join("context")).unwrap();
    fs::create_dir_all(dir.join(format!("components/{component_id}/steps"))).unwrap();
    fs::create_dir_all(dir.join("wren_project")).unwrap();
    fs::write(
        dir.join("wren_project/wren_project.yml"),
        "schema_version: 2\n",
    )
    .unwrap();
    fs::write(
        dir.join("profile.yml"),
        format!(
            "profile: fixture\ncontext:\n  project: ./context/binding.yml\n{profile_extra}components:\n  - use: {component_id}\n{bind_block}"
        ),
    )
    .unwrap();
    fs::write(
        dir.join("context/binding.yml"),
        // These fixtures inject their own `ContextLoader`, so no resolver ever reads this
        // binding — but `kind` is a required field, so it still has to be declared. `external`
        // is the kind that reads nothing, which is the truthful description of a binding
        // whose context arrives by injection.
        "kind: external\nproject: ./wren_project\n",
    )
    .unwrap();
    fs::write(
        dir.join(format!("components/{component_id}/component.yml")),
        component_yaml,
    )
    .unwrap();
    fs::write(
        dir.join(format!("components/{component_id}/steps/only_step.md")),
        "Do the thing.\n",
    )
    .unwrap();
}

/// Like `write_component_fixture`, but lets the caller supply a `bind:` block on the profile's
/// mount entry (empty string omits `bind:` entirely) — for tests exercising `$param:` resolution
/// against a mount-supplied or defaulted value.
fn write_component_fixture_with_bind(
    dir: &Path,
    component_id: &str,
    component_yaml: &str,
    bind_block: &str,
) {
    write_component_fixture_with_profile(dir, component_id, component_yaml, "", bind_block);
}

/// A `monitor_freshness`-style component body: a single `model` param (`bind: required` unless
/// `param_block` overrides it) and a `model_has_timestamp` precondition pinned to it via
/// `$param:model` — the exact shape this bug fix targets (see `hub/components/monitor_freshness`).
fn monitor_style_component(id: &str, param_block: &str) -> String {
    format!(
        r#"
id: {id}
verb: {id}
type: analytical
realization_kind: skill
binding_mode: pinned
context_precondition:
  - {{ predicate: model_has_timestamp, args: {{ model: "$param:model" }} }}
params:
{param_block}
llm_steps:
  - {{ name: only_step, tier: cheap, prompt_ref: steps/only_step.md }}
trigger: {{ kind: one_shot }}
guardrails:
  - {{ name: read_only_execution, locked: true }}
effect:
  render_blocks: []
  outcome: {{ kind: none }}
"#
    )
}

/// Builds a single-component fixture body declaring exactly the given `context_precondition` block
/// (inlined verbatim), so precondition-evaluation tests can control the predicates.
fn precondition_component(id: &str, precondition_block: &str) -> String {
    format!(
        r#"
id: {id}
verb: {id}
type: analytical
realization_kind: skill
binding_mode: runtime_selected
context_precondition:
{precondition_block}
llm_steps:
  - {{ name: only_step, tier: cheap, prompt_ref: steps/only_step.md }}
trigger: {{ kind: one_shot }}
guardrails:
  - {{ name: read_only_execution, locked: true }}
effect:
  render_blocks: []
  outcome: {{ kind: none }}
"#
    )
}

#[test]
fn precondition_pass_records_structured_check() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "needs_metric",
        &precondition_component("needs_metric", "  - { predicate: has_metric }"),
    );

    let ctx =
        FakeContext::parseable().with_metric("total_revenue", true, Some(Additivity::Additive));
    let ir = compile_project_with(dir.path(), &ctx).expect("has_metric is satisfied");
    assert_eq!(
        ir["components"][0]["precondition_result"]["checks"],
        serde_json::json!([{ "predicate": "has_metric", "outcome": "pass" }]),
        "a satisfied precondition is recorded as a structured pass check"
    );
    // Current IR version + fine-grained resolved binding present.
    assert_eq!(ir["warble_ir_version"], "0.8");
    assert_eq!(
        ir["context_binding"]["resolved"]["metrics"][0]["name"],
        "total_revenue"
    );
}

#[test]
fn precondition_false_fails_loudly() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "needs_metric",
        &precondition_component("needs_metric", "  - { predicate: has_metric }"),
    );

    // Empty context: no metrics ⇒ has_metric is answerable but false.
    let err = compile_project_with(dir.path(), &FakeContext::parseable())
        .expect_err("has_metric must fail on a project with no metrics");
    assert!(err.contains("not satisfied"), "unexpected error: {err}");
}

#[test]
fn metric_additive_unanswerable_fails_loudly() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "needs_additive",
        &precondition_component("needs_additive", "  - { predicate: metric_additive }"),
    );

    // Only an implicit (undeclared) metric: additivity is not expressible ⇒ can_answer=false.
    let ctx = FakeContext::parseable().with_metric("amount", false, None);
    let err = compile_project_with(dir.path(), &ctx)
        .expect_err("metric_additive must be unanswerable without a declared metric");
    assert!(
        err.contains("cannot be evaluated") && err.contains("additivity"),
        "unexpected error (expected the can_answer=false loud-fail): {err}"
    );
}

#[test]
fn metric_additive_existential_passes_with_an_additive_metric() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "needs_additive",
        &precondition_component("needs_additive", "  - { predicate: metric_additive }"),
    );

    // A declared additive measure exists (plus a non-additive one) ⇒ existential pass.
    let ctx = FakeContext::parseable()
        .with_metric("total_revenue", true, Some(Additivity::Additive))
        .with_metric("avg_order", true, Some(Additivity::NonAdditive));
    compile_project_with(dir.path(), &ctx).expect("an additive declared metric satisfies it");
}

#[test]
fn metric_additive_pinned_to_nonadditive_metric_fails() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "needs_additive",
        &precondition_component(
            "needs_additive",
            "  - { predicate: metric_additive, args: { metric: avg_order } }",
        ),
    );

    // Pinned to a declared but non-additive metric ⇒ answerable-and-false loud-fail.
    let ctx =
        FakeContext::parseable().with_metric("avg_order", true, Some(Additivity::NonAdditive));
    let err =
        compile_project_with(dir.path(), &ctx).expect_err("a non-additive pinned metric must fail");
    assert!(err.contains("not satisfied"), "unexpected error: {err}");
}

#[test]
fn bind_value_resolves_into_precondition_args() {
    // A mount-supplied bind reaches the precondition's `$param:` reference, and the IR carries
    // the RESOLVED value, never the unresolved template.
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture_with_bind(
        dir.path(),
        "monitor_style",
        &monitor_style_component("monitor_style", "  - { name: model, bind: required }"),
        "    bind:\n      model: \"orders\"\n",
    );

    let ctx = FakeContext::parseable().with_model("orders", true);
    let ir = compile_project_with(dir.path(), &ctx).expect("bound model has a timestamp");
    assert_eq!(
        ir["components"][0]["context_precondition"],
        serde_json::json!([{ "predicate": "model_has_timestamp", "args": { "model": "orders" } }]),
        "the IR must carry the resolved bind value, not the '$param:model' template"
    );
}

#[test]
fn unsupplied_optional_bind_falls_back_to_default() {
    // An optional bind the mount doesn't supply falls back to the param's declared default.
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture_with_bind(
        dir.path(),
        "monitor_style",
        &monitor_style_component(
            "monitor_style",
            "  - { name: model, bind: optional, default: widgets }",
        ),
        "",
    );

    let ctx = FakeContext::parseable().with_model("widgets", true);
    let ir = compile_project_with(dir.path(), &ctx).expect("default model has a timestamp");
    assert_eq!(
        ir["components"][0]["context_precondition"][0]["args"]["model"],
        "widgets"
    );
    assert_eq!(ir["components"][0]["binds"]["model"], "widgets");
}

#[test]
fn unbound_optional_param_with_no_default_is_unanswerable() {
    // No mount-supplied bind and no declared default ⇒ the `$param:` reference resolves to
    // nothing, which is an unanswerable loud-fail, not a silent skip.
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture_with_bind(
        dir.path(),
        "monitor_style",
        &monitor_style_component("monitor_style", "  - { name: model, bind: optional }"),
        "",
    );

    let err = compile_project(dir.path())
        .expect_err("an unsupplied optional bind with no default must be unanswerable");
    assert!(
        err.contains("cannot be evaluated") && err.contains("no declared default"),
        "unexpected error: {err}"
    );
}

#[test]
fn dollar_param_referencing_undeclared_param_fails_loudly() {
    // `$param:<name>` naming a param the component does not declare is a structural compile
    // error (an authoring typo), not an unanswerable predicate.
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture_with_bind(
        dir.path(),
        "monitor_style",
        &precondition_component(
            "monitor_style",
            "  - { predicate: model_has_timestamp, args: { model: \"$param:ghost_param\" } }",
        ),
        "",
    );

    let err = compile_project(dir.path())
        .expect_err("a $param: reference to an undeclared param must loud-fail");
    assert!(
        err.contains("'ghost_param'") && err.contains("not a declared param"),
        "unexpected error: {err}"
    );
}

#[test]
fn binding_a_timestampless_model_fails_loudly_in_a_multi_model_project() {
    // The case the old existential check missed entirely — a multi-model project where the bound
    // model specifically lacks a timestamp must loud-fail, even though *some other* model in the
    // project has one.
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture_with_bind(
        dir.path(),
        "monitor_style",
        &monitor_style_component("monitor_style", "  - { name: model, bind: required }"),
        "    bind:\n      model: \"widgets\"\n",
    );

    let ctx = FakeContext::parseable()
        .with_model("orders", true)
        .with_model("widgets", false);
    let err = compile_project_with(dir.path(), &ctx)
        .expect_err("binding a timestampless model must fail even when another model has one");
    assert!(err.contains("not satisfied"), "unexpected error: {err}");
}

#[test]
fn binding_a_nonexistent_model_no_longer_silently_passes() {
    // Binding a model that doesn't exist in the project must loud-fail (unanswerable), not
    // silently pass because some *other* declared model happens to have a timestamp.
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture_with_bind(
        dir.path(),
        "monitor_style",
        &monitor_style_component("monitor_style", "  - { name: model, bind: required }"),
        "    bind:\n      model: \"ghost\"\n",
    );

    let ctx = FakeContext::parseable().with_model("orders", true);
    let err = compile_project_with(dir.path(), &ctx)
        .expect_err("binding a nonexistent model must fail, not silently pass");
    assert!(
        err.contains("cannot be evaluated") && err.contains("'ghost' is not a declared model"),
        "unexpected error: {err}"
    );
}

#[test]
fn model_has_timestamp_existential_fallback_is_unchanged() {
    // With no `args` at all (the pre-existing shape other profiles still use unmodified), the
    // predicate stays existential over every declared model.
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "existential_timestamp_test",
        &precondition_component(
            "existential_timestamp_test",
            "  - { predicate: model_has_timestamp }",
        ),
    );

    // No models with a timestamp ⇒ fail.
    let err = compile_project_with(
        dir.path(),
        &FakeContext::parseable().with_model("widgets", false),
    )
    .expect_err("existential model_has_timestamp must fail with no timestamped model");
    assert!(err.contains("not satisfied"), "unexpected error: {err}");

    // At least one model with a timestamp ⇒ pass, regardless of others.
    let ctx = FakeContext::parseable()
        .with_model("widgets", false)
        .with_model("orders", true);
    compile_project_with(dir.path(), &ctx)
        .expect("existential model_has_timestamp passes when any model has a timestamp");
}

#[test]
fn two_mounts_with_different_binds_produce_different_ir() {
    // Two mounts of the same component, differing only in their `bind:` value, must not produce
    // byte-identical IR.
    let dir_a = tempfile::tempdir().unwrap();
    write_component_fixture_with_bind(
        dir_a.path(),
        "monitor_style",
        &monitor_style_component("monitor_style", "  - { name: model, bind: required }"),
        "    bind:\n      model: \"orders\"\n",
    );
    let dir_b = tempfile::tempdir().unwrap();
    write_component_fixture_with_bind(
        dir_b.path(),
        "monitor_style",
        &monitor_style_component("monitor_style", "  - { name: model, bind: required }"),
        "    bind:\n      model: \"widgets\"\n",
    );

    let ctx = FakeContext::parseable()
        .with_model("orders", true)
        .with_model("widgets", true);
    let ir_a = compile_project_with(dir_a.path(), &ctx).expect("orders bind compiles");
    let ir_b = compile_project_with(dir_b.path(), &ctx).expect("widgets bind compiles");

    assert_ne!(
        ir_a["components"][0], ir_b["components"][0],
        "binding different models must produce different IR component nodes"
    );
    assert_eq!(ir_a["components"][0]["binds"]["model"], "orders");
    assert_eq!(ir_b["components"][0]["binds"]["model"], "widgets");
}

#[test]
fn runtime_injected_param_is_excluded_from_binds_facet() {
    // A `source: runtime-injected` param is never a bind — it's supplied by the runtime at
    // dispatch time, not by the profile at compile time — so it must not appear in the `binds` IR
    // facet even though it's a declared param.
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture_with_bind(
        dir.path(),
        "monitor_style",
        &monitor_style_component(
            "monitor_style",
            "  - { name: model, bind: required }\n  - { name: connection, source: runtime-injected }",
        ),
        "    bind:\n      model: \"orders\"\n",
    );

    let ctx = FakeContext::parseable().with_model("orders", true);
    let ir =
        compile_project_with(dir.path(), &ctx).expect("compiles with a runtime-injected param");
    let binds = ir["components"][0]["binds"].as_object().unwrap();
    assert_eq!(
        binds.len(),
        1,
        "runtime-injected params must not appear in the binds facet: {binds:?}"
    );
    assert_eq!(ir["components"][0]["binds"]["model"], "orders");
}

#[test]
fn binds_facet_is_absent_when_no_bind_params_exist() {
    // The `binds` facet follows the existing optional-facet pattern — emitted only when
    // non-empty, so components with no bind-family params (or none with an effective value) must
    // not carry an empty `binds: {}` in the IR (additive-only growth, invariant #3).
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "no_binds_test",
        &precondition_component("no_binds_test", "  - { predicate: has_metric }"),
    );

    let ctx =
        FakeContext::parseable().with_metric("total_revenue", true, Some(Additivity::Additive));
    let ir = compile_project_with(dir.path(), &ctx).expect("has_metric is satisfied");
    assert!(
        ir["components"][0].get("binds").is_none(),
        "binds facet must be absent (not an empty object) when there are no bind params: {:?}",
        ir["components"][0]
    );
}

#[test]
fn time_dimension_predicate_evaluates() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "needs_time",
        &precondition_component("needs_time", "  - { predicate: has_time_dimension }"),
    );

    // No time dimension ⇒ fail.
    let err = compile_project_with(dir.path(), &FakeContext::parseable())
        .expect_err("has_time_dimension must fail with no time dimension");
    assert!(err.contains("not satisfied"), "unexpected error: {err}");

    // With a temporal dimension ⇒ pass.
    let ctx = FakeContext::parseable().with_dimension("order_date", true);
    compile_project_with(dir.path(), &ctx).expect("a temporal dimension satisfies it");
}

#[test]
fn unknown_precondition_predicate_fails_loudly() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "precon_test",
        &precondition_component("precon_test", "  - { predicate: not_a_real_predicate }"),
    );

    let err = compile_project(dir.path()).expect_err("unknown precondition predicate must fail");
    assert!(
        err.contains("unknown context_precondition predicate"),
        "unexpected error: {err}"
    );
}

#[test]
fn source_param_is_carried_into_ir() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "source_param_test",
        r#"
id: source_param_test
verb: source_param_test
type: analytical
realization_kind: skill
binding_mode: runtime_selected
params:
  - { name: connection, source: runtime-injected }
llm_steps:
  - { name: only_step, tier: cheap, prompt_ref: steps/only_step.md }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution, locked: true }
effect:
  render_blocks: []
  outcome: { kind: none }
"#,
    );

    let ir = compile_project(dir.path()).expect("source param should compile");
    let params = ir["components"][0]["params"].as_array().unwrap();
    assert_eq!(
        params,
        &vec![serde_json::json!({ "name": "connection", "source": "runtime-injected" })],
        "source param must be carried into IR params verbatim: {params:?}"
    );
}

#[test]
fn param_with_both_bind_and_source_fails_loudly() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "both_test",
        r#"
id: both_test
verb: both_test
type: analytical
realization_kind: skill
binding_mode: runtime_selected
params:
  - { name: topic, bind: optional, source: runtime-injected }
llm_steps:
  - { name: only_step, tier: cheap, prompt_ref: steps/only_step.md }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution, locked: true }
effect:
  render_blocks: []
  outcome: { kind: none }
"#,
    );

    let err = compile_project(dir.path()).expect_err("bind + source must fail");
    assert!(err.contains("declares both"), "unexpected error: {err}");
}

#[test]
fn param_with_neither_bind_nor_source_fails_loudly() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "neither_test",
        r#"
id: neither_test
verb: neither_test
type: analytical
realization_kind: skill
binding_mode: runtime_selected
params:
  - { name: topic }
llm_steps:
  - { name: only_step, tier: cheap, prompt_ref: steps/only_step.md }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution, locked: true }
effect:
  render_blocks: []
  outcome: { kind: none }
"#,
    );

    let err = compile_project(dir.path()).expect_err("neither bind nor source must fail");
    assert!(err.contains("declares neither"), "unexpected error: {err}");
}

#[test]
fn param_with_unknown_source_fails_loudly() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "unknown_source_test",
        r#"
id: unknown_source_test
verb: unknown_source_test
type: analytical
realization_kind: skill
binding_mode: runtime_selected
params:
  - { name: topic, source: some-other-source }
llm_steps:
  - { name: only_step, tier: cheap, prompt_ref: steps/only_step.md }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution, locked: true }
effect:
  render_blocks: []
  outcome: { kind: none }
"#,
    );

    let err = compile_project(dir.path()).expect_err("unknown source value must fail");
    assert!(err.contains("unknown source"), "unexpected error: {err}");
}

#[test]
fn conditional_llm_step_is_carried_into_ir() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "conditional_test",
        r#"
id: conditional_test
verb: conditional_test
type: analytical
realization_kind: skill
binding_mode: runtime_selected
llm_steps:
  - { name: some_upstream_step, tier: cheap, prompt_ref: steps/only_step.md }
  - { name: only_step, tier: cheap, prompt_ref: steps/only_step.md, conditional: true,
      when: { guard: on_failure, target: some_upstream_step } }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution, locked: true }
effect:
  render_blocks: []
  outcome: { kind: none }
"#,
    );

    let ir =
        compile_project(dir.path()).expect("conditional step with a when guard should compile");
    assert_eq!(
        ir["components"][0]["llm_calls"][1]["conditional"],
        serde_json::json!(true)
    );
    assert_eq!(
        ir["components"][0]["llm_calls"][1]["when"],
        serde_json::json!({ "guard": "on_failure", "target": "some_upstream_step" })
    );
}

#[test]
fn bare_conditional_without_when_fails_loudly() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "bare_conditional_test",
        r#"
id: bare_conditional_test
verb: bare_conditional_test
type: analytical
realization_kind: skill
binding_mode: runtime_selected
llm_steps:
  - { name: only_step, tier: cheap, prompt_ref: steps/only_step.md, conditional: true }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution, locked: true }
effect:
  render_blocks: []
  outcome: { kind: none }
"#,
    );

    let err =
        compile_project(dir.path()).expect_err("bare conditional with no when must loud-fail");
    assert!(
        err.contains("has no 'when' guard"),
        "unexpected error: {err}"
    );
}

#[test]
fn when_guard_without_conditional_fails_loudly() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "when_without_conditional_test",
        r#"
id: when_without_conditional_test
verb: when_without_conditional_test
type: analytical
realization_kind: skill
binding_mode: runtime_selected
llm_steps:
  - { name: only_step, tier: cheap, prompt_ref: steps/only_step.md,
      when: { guard: on_failure, target: some_step } }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution, locked: true }
effect:
  render_blocks: []
  outcome: { kind: none }
"#,
    );

    let err =
        compile_project(dir.path()).expect_err("when guard without conditional must loud-fail");
    assert!(
        err.contains("is not 'conditional: true'"),
        "unexpected error: {err}"
    );
}

#[test]
fn unknown_guard_name_fails_loudly() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "unknown_guard_test",
        r#"
id: unknown_guard_test
verb: unknown_guard_test
type: analytical
realization_kind: skill
binding_mode: runtime_selected
llm_steps:
  - { name: only_step, tier: cheap, prompt_ref: steps/only_step.md, conditional: true,
      when: { guard: on_vibes, target: some_step } }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution, locked: true }
effect:
  render_blocks: []
  outcome: { kind: none }
"#,
    );

    let err = compile_project(dir.path()).expect_err("unknown guard name must loud-fail");
    assert!(
        err.contains("unknown guard 'on_vibes'"),
        "unexpected error: {err}"
    );
}

#[test]
fn on_flag_guard_requires_dotted_target() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "on_flag_bad_target_test",
        r#"
id: on_flag_bad_target_test
verb: on_flag_bad_target_test
type: analytical
realization_kind: skill
binding_mode: runtime_selected
llm_steps:
  - { name: only_step, tier: cheap, prompt_ref: steps/only_step.md, conditional: true,
      when: { guard: on_flag, target: no_dot_here } }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution, locked: true }
effect:
  render_blocks: []
  outcome: { kind: none }
"#,
    );

    let err =
        compile_project(dir.path()).expect_err("on_flag with a non-dotted target must loud-fail");
    assert!(err.contains("expects a dotted"), "unexpected error: {err}");
}

#[test]
fn on_missing_guard_is_valid() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "on_missing_test",
        r#"
id: on_missing_test
verb: on_missing_test
type: analytical
realization_kind: skill
binding_mode: runtime_selected
llm_steps:
  - { name: produce_it, tier: cheap, prompt_ref: steps/only_step.md, produces: some_artifact }
  - { name: only_step, tier: cheap, prompt_ref: steps/only_step.md, conditional: true,
      when: { guard: on_missing, target: some_artifact } }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution, locked: true }
effect:
  render_blocks: []
  outcome: { kind: none }
"#,
    );

    let ir = compile_project(dir.path()).expect("on_missing guard should compile");
    assert_eq!(
        ir["components"][0]["llm_calls"][1]["when"],
        serde_json::json!({ "guard": "on_missing", "target": "some_artifact" })
    );
}

#[test]
fn valid_cross_step_artifact_chain_compiles() {
    // A step consuming an artifact a strictly-earlier step produces must still compile — the
    // positive control for `check_step_dataflow`'s artifact-flow check.
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "valid_chain_test",
        r#"
id: valid_chain_test
verb: valid_chain_test
type: analytical
realization_kind: skill
binding_mode: runtime_selected
llm_steps:
  - { name: produce_it, tier: cheap, prompt_ref: steps/only_step.md, produces: some_artifact }
  - { name: consume_it, tier: cheap, prompt_ref: steps/only_step.md, consumes: [some_artifact] }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution, locked: true }
effect:
  render_blocks: []
  outcome: { kind: none }
"#,
    );

    let ir = compile_project(dir.path())
        .expect("a step consuming a strictly-earlier step's produced artifact must compile");
    assert_eq!(
        ir["components"][0]["llm_calls"][1]["consumes"],
        serde_json::json!(["some_artifact"])
    );
}

#[test]
fn step_consuming_its_own_produces_fails_loudly() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "self_consume_test",
        r#"
id: self_consume_test
verb: self_consume_test
type: analytical
realization_kind: skill
binding_mode: runtime_selected
llm_steps:
  - { name: only_step, tier: cheap, prompt_ref: steps/only_step.md, produces: some_artifact,
      consumes: [some_artifact] }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution, locked: true }
effect:
  render_blocks: []
  outcome: { kind: none }
"#,
    );

    let err = compile_project(dir.path())
        .expect_err("a step consuming its own 'produces' artifact must loud-fail");
    assert!(
        err.contains("step 'only_step'")
            && err.contains("component 'self_consume_test'")
            && err.contains("consumes 'some_artifact'")
            && err.contains("its own 'produces' artifact"),
        "unexpected error: {err}"
    );
}

#[test]
fn consuming_an_artifact_nobody_produces_fails_loudly() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "orphan_consume_test",
        r#"
id: orphan_consume_test
verb: orphan_consume_test
type: analytical
realization_kind: skill
binding_mode: runtime_selected
llm_steps:
  - { name: only_step, tier: cheap, prompt_ref: steps/only_step.md, consumes: [nobody_makes_this] }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution, locked: true }
effect:
  render_blocks: []
  outcome: { kind: none }
"#,
    );

    let err = compile_project(dir.path())
        .expect_err("consuming an artifact no step produces must loud-fail");
    assert!(
        err.contains("step 'only_step'")
            && err.contains("component 'orphan_consume_test'")
            && err.contains("consumes 'nobody_makes_this'")
            && err.contains("which no earlier step produces"),
        "unexpected error: {err}"
    );
}

#[test]
fn consuming_a_later_steps_artifact_fails_loudly() {
    // The artifact exists in the component, but only a *later* step produces it — still not
    // "earlier", so this must be refused exactly like the produced-by-nobody case.
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "forward_reference_test",
        r#"
id: forward_reference_test
verb: forward_reference_test
type: analytical
realization_kind: skill
binding_mode: runtime_selected
llm_steps:
  - { name: consume_it, tier: cheap, prompt_ref: steps/only_step.md, consumes: [some_artifact] }
  - { name: produce_it, tier: cheap, prompt_ref: steps/only_step.md, produces: some_artifact }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution, locked: true }
effect:
  render_blocks: []
  outcome: { kind: none }
"#,
    );

    let err = compile_project(dir.path())
        .expect_err("consuming a later step's produced artifact must loud-fail");
    assert!(
        err.contains("step 'consume_it'")
            && err.contains("consumes 'some_artifact'")
            && err.contains("which no earlier step produces"),
        "unexpected error: {err}"
    );
}

#[test]
fn duplicate_step_names_fail_loudly() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "duplicate_step_name_test",
        r#"
id: duplicate_step_name_test
verb: duplicate_step_name_test
type: analytical
realization_kind: skill
binding_mode: runtime_selected
llm_steps:
  - { name: only_step, tier: cheap, prompt_ref: steps/only_step.md }
  - { name: only_step, tier: cheap, prompt_ref: steps/only_step.md }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution, locked: true }
effect:
  render_blocks: []
  outcome: { kind: none }
"#,
    );

    let err = compile_project(dir.path()).expect_err("duplicate step names must loud-fail");
    assert!(
        err.contains("duplicate step name 'only_step'")
            && err.contains("component 'duplicate_step_name_test'"),
        "unexpected error: {err}"
    );
}

#[test]
fn duplicate_produces_artifact_names_fail_loudly() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "duplicate_produces_test",
        r#"
id: duplicate_produces_test
verb: duplicate_produces_test
type: analytical
realization_kind: skill
binding_mode: runtime_selected
llm_steps:
  - { name: first_producer, tier: cheap, prompt_ref: steps/only_step.md, produces: some_artifact }
  - { name: second_producer, tier: cheap, prompt_ref: steps/only_step.md, produces: some_artifact }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution, locked: true }
effect:
  render_blocks: []
  outcome: { kind: none }
"#,
    );

    let err = compile_project(dir.path())
        .expect_err("duplicate 'produces' artifact names must loud-fail");
    assert!(
        err.contains("duplicate 'produces' artifact 'some_artifact'")
            && err.contains("component 'duplicate_produces_test'")
            && err.contains("second_producer"),
        "unexpected error: {err}"
    );
}

#[test]
fn on_failure_guard_targeting_a_non_earlier_step_fails_loudly() {
    // `on_failure` targeting the step's own name (not a strictly-earlier step) — the same
    // permanently-dead-guard failure mode as an artifact-flow forward reference.
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "on_failure_not_earlier_test",
        r#"
id: on_failure_not_earlier_test
verb: on_failure_not_earlier_test
type: analytical
realization_kind: skill
binding_mode: runtime_selected
llm_steps:
  - { name: only_step, tier: cheap, prompt_ref: steps/only_step.md, conditional: true,
      when: { guard: on_failure, target: only_step } }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution, locked: true }
effect:
  render_blocks: []
  outcome: { kind: none }
"#,
    );

    let err = compile_project(dir.path())
        .expect_err("on_failure targeting a non-strictly-earlier step must loud-fail");
    assert!(
        err.contains("guard 'on_failure'")
            && err.contains("step 'only_step'")
            && err.contains("component 'on_failure_not_earlier_test'")
            && err.contains("targets step 'only_step'")
            && err.contains("not a strictly-earlier step"),
        "unexpected error: {err}"
    );
}

#[test]
fn on_missing_guard_targeting_an_unproduced_artifact_fails_loudly() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "on_missing_unproduced_test",
        r#"
id: on_missing_unproduced_test
verb: on_missing_unproduced_test
type: analytical
realization_kind: skill
binding_mode: runtime_selected
llm_steps:
  - { name: only_step, tier: cheap, prompt_ref: steps/only_step.md, conditional: true,
      when: { guard: on_missing, target: nobody_makes_this } }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution, locked: true }
effect:
  render_blocks: []
  outcome: { kind: none }
"#,
    );

    let err = compile_project(dir.path())
        .expect_err("on_missing targeting an artifact no earlier step produces must loud-fail");
    assert!(
        err.contains("guard 'on_missing'")
            && err.contains("step 'only_step'")
            && err.contains("targets artifact 'nobody_makes_this'")
            && err.contains("which no earlier step produces"),
        "unexpected error: {err}"
    );
}

#[test]
fn on_flag_guard_targeting_an_unproduced_artifact_fails_loudly() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "on_flag_unproduced_test",
        r#"
id: on_flag_unproduced_test
verb: on_flag_unproduced_test
type: analytical
realization_kind: skill
binding_mode: runtime_selected
llm_steps:
  - { name: only_step, tier: cheap, prompt_ref: steps/only_step.md, conditional: true,
      when: { guard: on_flag, target: nobody_makes_this.stale } }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution, locked: true }
effect:
  render_blocks: []
  outcome: { kind: none }
"#,
    );

    let err = compile_project(dir.path())
        .expect_err("on_flag targeting an artifact no earlier step produces must loud-fail");
    assert!(
        err.contains("guard 'on_flag'")
            && err.contains("step 'only_step'")
            && err.contains("targets 'nobody_makes_this.stale'")
            && err.contains("artifact 'nobody_makes_this' is not produced by any earlier step"),
        "unexpected error: {err}"
    );
}

#[test]
fn on_flag_guard_targeting_a_produced_artifact_compiles() {
    // Positive control for the `on_flag` guard-target check, mirroring the shape of the shipped
    // `monitor_freshness` component (`read_freshness` produces `freshness_reading`;
    // `assess_severity` guards `on_flag: freshness_reading.stale`).
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "on_flag_produced_test",
        r#"
id: on_flag_produced_test
verb: on_flag_produced_test
type: analytical
realization_kind: skill
binding_mode: runtime_selected
llm_steps:
  - { name: produce_it, tier: cheap, prompt_ref: steps/only_step.md, produces: some_artifact }
  - { name: only_step, tier: cheap, prompt_ref: steps/only_step.md, conditional: true,
      when: { guard: on_flag, target: some_artifact.stale } }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution, locked: true }
effect:
  render_blocks: []
  outcome: { kind: none }
"#,
    );

    let ir =
        compile_project(dir.path()).expect("on_flag targeting a produced artifact should compile");
    assert_eq!(
        ir["components"][0]["llm_calls"][1]["when"],
        serde_json::json!({ "guard": "on_flag", "target": "some_artifact.stale" })
    );
}

#[test]
fn unconditional_step_emits_null_when() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "unconditional_when_test",
        r#"
id: unconditional_when_test
verb: unconditional_when_test
type: analytical
realization_kind: skill
binding_mode: runtime_selected
llm_steps:
  - { name: only_step, tier: cheap, prompt_ref: steps/only_step.md }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution, locked: true }
effect:
  render_blocks: []
  outcome: { kind: none }
"#,
    );

    let ir = compile_project(dir.path()).expect("unconditional step with no when should compile");
    assert_eq!(
        ir["components"][0]["llm_calls"][0]["when"],
        serde_json::json!(null)
    );
}

#[test]
fn authored_eval_block_is_carried_into_ir() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "eval_test",
        r#"
id: eval_test
verb: eval_test
type: analytical
realization_kind: skill
binding_mode: runtime_selected
llm_steps:
  - { name: only_step, tier: cheap, prompt_ref: steps/only_step.md }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution, locked: true }
effect:
  render_blocks: []
  outcome: { kind: none }
eval:
  template_ref: eval/
  metrics: [accuracy]
"#,
    );

    let ir = compile_project(dir.path()).expect("component with eval should compile");
    assert_eq!(
        ir["components"][0]["eval"],
        serde_json::json!({ "template_ref": "eval/", "metrics": ["accuracy"] })
    );
}

#[test]
fn component_file_rejects_unknown_fields() {
    let yaml = r#"
id: bad
verb: bad
type: analytical
realization_kind: skill
binding_mode: runtime_selected
llm_steps:
  - { name: only_step, tier: cheap, prompt_ref: steps/only_step.md }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution, locked: true }
effect:
  render_blocks: []
  outcome: { kind: none }
totally_unknown_field: true
"#;

    let err = serde_yaml::from_str::<ComponentFile>(yaml)
        .expect_err("unknown field must be rejected at parse time");
    assert!(
        err.to_string().contains("unknown field"),
        "unexpected error: {err}"
    );
}

#[test]
fn overridable_guardrail_normalizes_to_locked_false() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "overridable_test",
        r#"
id: overridable_test
verb: overridable_test
type: analytical
realization_kind: skill
binding_mode: runtime_selected
llm_steps:
  - { name: only_step, tier: cheap, prompt_ref: steps/only_step.md }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution, overridable: true }
effect:
  render_blocks: []
  outcome: { kind: none }
"#,
    );

    let ir = compile_project(dir.path()).expect("overridable guardrail should compile");
    assert_eq!(
        ir["components"][0]["guardrails"][0],
        serde_json::json!({ "name": "read_only_execution", "locked": false })
    );
}

#[test]
fn contradictory_locked_and_overridable_fails_loudly() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "contradictory_test",
        r#"
id: contradictory_test
verb: contradictory_test
type: analytical
realization_kind: skill
binding_mode: runtime_selected
llm_steps:
  - { name: only_step, tier: cheap, prompt_ref: steps/only_step.md }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution, locked: true, overridable: true }
effect:
  render_blocks: []
  outcome: { kind: none }
"#,
    );

    let err = compile_project(dir.path()).expect_err("contradictory locked/overridable must fail");
    assert!(err.contains("contradictory"), "unexpected error: {err}");
}

#[test]
fn guardrail_with_neither_locked_nor_overridable_fails_loudly() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "no_lock_decl_test",
        r#"
id: no_lock_decl_test
verb: no_lock_decl_test
type: analytical
realization_kind: skill
binding_mode: runtime_selected
llm_steps:
  - { name: only_step, tier: cheap, prompt_ref: steps/only_step.md }
trigger: { kind: one_shot }
guardrails:
  - { name: read_only_execution }
effect:
  render_blocks: []
  outcome: { kind: none }
"#,
    );

    let err = compile_project(dir.path()).expect_err("missing locked/overridable must fail");
    assert!(err.contains("must declare"), "unexpected error: {err}");
}

/// A context carrying the data to answer `has_metric` but declaring it does not answer it — the
/// shape of an adapter bound to a semantic layer the host cannot introspect where it stands.
struct DeclinesSchemaProbes(FakeContext);

impl ContextLoader for DeclinesSchemaProbes {
    fn is_parseable(&self) -> bool {
        self.0.is_parseable()
    }
    fn metrics(&self) -> &[MetricInfo] {
        self.0.metrics()
    }
    fn dimensions(&self) -> &[DimensionInfo] {
        self.0.dimensions()
    }
    fn time_dimensions(&self) -> &[DimensionInfo] {
        self.0.time_dimensions()
    }
    fn models(&self) -> &[ModelInfo] {
        self.0.models()
    }
    fn lineage(&self) -> &LineageGraph {
        self.0.lineage()
    }
    fn can_answer(&self, predicate: &str) -> bool {
        !matches!(predicate, "has_metric")
    }
}

/// `can_answer` is the documented hook for an adapter with its own answerable set, so the compiler
/// has to consult it — otherwise the override is silently ignored and an existence predicate is
/// reported as an answerable `Fail` ("not satisfied") when the truth is that the context does not
/// know. The metric below exists, which is exactly what makes this a test of the gate rather than of
/// emptiness.
#[test]
fn a_declined_predicate_is_unanswerable_even_when_the_data_is_present() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "needs_metric",
        &precondition_component("needs_metric", "  - { predicate: has_metric }"),
    );

    let ctx = DeclinesSchemaProbes(FakeContext::parseable().with_metric("revenue", true, None));
    let err = compile_project_with(dir.path(), &ctx)
        .expect_err("a declined predicate must refuse rather than be evaluated anyway");
    assert!(
        err.contains("cannot be evaluated") && !err.contains("not satisfied"),
        "expected the unanswerable loud-fail, not an answerable false: {err}"
    );
}

// --- component-level `brief` ---------------------------------------------------------------------

/// A minimal single-step component body, optionally carrying an authored `brief:` (empty string
/// omits the field entirely — the "no brief authored" case).
fn brief_component(id: &str, brief_line: &str) -> String {
    format!(
        r#"
id: {id}
verb: {id}
type: analytical
realization_kind: skill
binding_mode: runtime_selected
llm_steps:
  - {{ name: only_step, tier: cheap, prompt_ref: steps/only_step.md }}
trigger: {{ kind: one_shot }}
guardrails:
  - {{ name: read_only_execution, locked: true }}
effect:
  render_blocks: []
  outcome: {{ kind: none }}
{brief_line}
"#
    )
}

#[test]
fn absent_brief_produces_no_brief_key_in_ir() {
    // A component that authors no `brief` at all must not gain a `brief` key in its IR node —
    // the unit-level half of the byte-identical-IR guarantee (the full before/after diff of an
    // unchanged example is checked separately, not as a unit test).
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(dir.path(), "no_brief", &brief_component("no_brief", ""));

    let ir = compile_project(dir.path()).expect("component with no brief should compile");
    assert!(
        ir["components"][0].get("brief").is_none(),
        "a component with no authored brief must not gain a 'brief' key: {:?}",
        ir["components"][0]
    );
}

#[test]
fn component_brief_is_rendered_with_placeholders_and_carried_into_ir() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "with_brief",
        &brief_component(
            "with_brief",
            r#"brief: "Shared framing for {{project_name}} at {{project}}.""#,
        ),
    );

    let ir = compile_project(dir.path()).expect("component with brief should compile");
    assert_eq!(
        ir["components"][0]["brief"],
        serde_json::json!("Shared framing for wren_project at ./wren_project."),
        "brief must have its {{{{project}}}}/{{{{project_name}}}} placeholders substituted, \
same as a step body: {:?}",
        ir["components"][0]["brief"]
    );
}

#[test]
fn profile_mount_brief_replaces_component_brief_wholesale() {
    // A profile-mount brief is a full replacement, never a merge — the IR must carry only the
    // mount's text, with no trace of the component's own brief.
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture_with_bind(
        dir.path(),
        "overridden_brief",
        &brief_component(
            "overridden_brief",
            r#"brief: "Component's own framing, must not appear.""#,
        ),
        "    brief: \"Mount-level framing for {{project_name}}.\"\n",
    );

    let ir = compile_project(dir.path()).expect("component with overridden brief should compile");
    assert_eq!(
        ir["components"][0]["brief"],
        serde_json::json!("Mount-level framing for wren_project."),
        "a profile-mount brief must replace the component's brief entirely: {:?}",
        ir["components"][0]["brief"]
    );
}

#[test]
fn profile_system_prompt_becomes_the_brief_when_the_component_has_none() {
    // The profile-level `system_prompt` reaches every mounted component, including one that
    // authors no `brief` of its own — that is the whole point of authoring it once on the profile
    // instead of repeating it in every mount.
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture_with_profile(
        dir.path(),
        "no_brief",
        &brief_component("no_brief", ""),
        "system_prompt: \"House rules every behavior follows.\"\n",
        "",
    );

    let ir = compile_project(dir.path()).expect("profile system_prompt should compile");
    assert_eq!(
        ir["components"][0]["brief"],
        serde_json::json!("House rules every behavior follows."),
        "a profile system_prompt must reach a component that authors no brief: {:?}",
        ir["components"][0]
    );
}

#[test]
fn profile_system_prompt_precedes_the_component_brief() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture_with_profile(
        dir.path(),
        "with_brief",
        &brief_component("with_brief", r#"brief: "Framing for this one behavior.""#),
        "system_prompt: \"House rules every behavior follows.\"\n",
        "",
    );

    let ir = compile_project(dir.path()).expect("profile system_prompt should compile");
    assert_eq!(
        ir["components"][0]["brief"],
        serde_json::json!("House rules every behavior follows.\n\nFraming for this one behavior."),
        "the shared system_prompt must come first, then the component's own brief: {:?}",
        ir["components"][0]["brief"]
    );
}

#[test]
fn profile_system_prompt_survives_a_mount_brief_replacement() {
    // A mount `brief` replaces the *component's* brief wholesale, but it does not stand in for the
    // profile's shared framing — the two are separate layers, so the system_prompt is still there.
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture_with_profile(
        dir.path(),
        "overridden_brief",
        &brief_component(
            "overridden_brief",
            r#"brief: "Component's own framing, must not appear.""#,
        ),
        "system_prompt: \"House rules every behavior follows.\"\n",
        "    brief: \"Mount-level framing.\"\n",
    );

    let ir = compile_project(dir.path()).expect("profile system_prompt should compile");
    assert_eq!(
        ir["components"][0]["brief"],
        serde_json::json!("House rules every behavior follows.\n\nMount-level framing."),
        "a mount brief replaces the component's brief but not the profile system_prompt: {:?}",
        ir["components"][0]["brief"]
    );
}

#[test]
fn profile_system_prompt_is_rendered_with_placeholders() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture_with_profile(
        dir.path(),
        "no_brief",
        &brief_component("no_brief", ""),
        "system_prompt: \"Answer about {{project_name}} at {{project}}.\"\n",
        "",
    );

    let ir = compile_project(dir.path()).expect("profile system_prompt should compile");
    assert_eq!(
        ir["components"][0]["brief"],
        serde_json::json!("Answer about wren_project at ./wren_project."),
        "system_prompt must take the same placeholder substitution as a brief or a step body: {:?}",
        ir["components"][0]["brief"]
    );
}

#[test]
fn empty_profile_system_prompt_does_not_conjure_a_brief() {
    // An empty system_prompt contributes nothing. Without this, authoring `system_prompt: ""`
    // would put `"brief": ""` onto every component that has no brief — inventing a key where the
    // no-brief guarantee says there must not be one.
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture_with_profile(
        dir.path(),
        "no_brief",
        &brief_component("no_brief", ""),
        "system_prompt: \"\"\n",
        "",
    );

    let ir = compile_project(dir.path()).expect("empty system_prompt should compile");
    assert!(
        ir["components"][0].get("brief").is_none(),
        "an empty system_prompt must not add a 'brief' key: {:?}",
        ir["components"][0]
    );
}

#[test]
fn empty_mount_brief_still_blanks_the_component_brief_under_a_system_prompt() {
    // `brief: ""` on a mount is the documented way to blank a component's own framing. That must
    // keep working with a profile system_prompt above it: the result is the shared framing alone,
    // with no trailing separator and no trace of the component's text.
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture_with_profile(
        dir.path(),
        "overridden_brief",
        &brief_component(
            "overridden_brief",
            r#"brief: "Component's own framing, must not appear.""#,
        ),
        "system_prompt: \"House rules every behavior follows.\"\n",
        "    brief: \"\"\n",
    );

    let ir = compile_project(dir.path()).expect("profile system_prompt should compile");
    assert_eq!(
        ir["components"][0]["brief"],
        serde_json::json!("House rules every behavior follows."),
        "blanking the component brief must leave the shared framing alone, unpadded: {:?}",
        ir["components"][0]["brief"]
    );
}

/// A component whose `required_capabilities` is exactly `capabilities` (flow-style YAML, e.g.
/// `"[sql_execution]"` or `"[]"`) — used to exercise the `config.capability_ceiling` gate without
/// dragging in params or preconditions the ceiling check does not care about.
fn capability_component(id: &str, capabilities: &str) -> String {
    format!(
        r#"
id: {id}
verb: {id}
type: analytical
realization_kind: skill
binding_mode: runtime_selected
llm_steps:
  - {{ name: only_step, tier: cheap, prompt_ref: steps/only_step.md }}
trigger: {{ kind: one_shot }}
guardrails:
  - {{ name: read_only_execution, locked: true }}
required_capabilities: {capabilities}
effect:
  render_blocks: []
  outcome: {{ kind: none }}
"#
    )
}

#[test]
fn capability_within_ceiling_compiles_and_the_ceiling_appears_in_the_ir() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture_with_profile(
        dir.path(),
        "needs_sql",
        &capability_component("needs_sql", "[sql_execution]"),
        "config:\n  capability_ceiling:\n    - sql_execution\n",
        "",
    );

    let ir = compile_project(dir.path()).expect("a capability within the ceiling must compile");
    assert_eq!(
        ir["config"]["capability_ceiling"],
        serde_json::json!(["sql_execution"]),
        "a declared ceiling must be carried into the IR's config block: {:?}",
        ir["config"]
    );
}

#[test]
fn capability_outside_ceiling_fails_compile_naming_both_values() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture_with_profile(
        dir.path(),
        "needs_write",
        &capability_component("needs_write", "[filesystem_write]"),
        "config:\n  capability_ceiling:\n    - sql_execution\n",
        "",
    );

    let err = compile_project(dir.path())
        .expect_err("a capability outside the declared ceiling must fail compile");
    assert!(
        err.contains("needs_write")
            && err.contains("filesystem_write")
            && err.contains("sql_execution"),
        "error must name the component, the offending capability, and the declared ceiling: {err}"
    );
}

#[test]
fn absent_capability_ceiling_leaves_config_exactly_empty() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture_with_profile(
        dir.path(),
        "needs_anything",
        &capability_component("needs_anything", "[whatever_capability_it_wants]"),
        "",
        "",
    );

    let ir = compile_project(dir.path()).expect("with no declared ceiling, any capability is fine");
    assert_eq!(
        ir["config"],
        serde_json::json!({}),
        "a profile with no declared ceiling must still emit an empty config block: {:?}",
        ir["config"]
    );
}

#[test]
fn capability_ceiling_does_not_admit_a_more_specific_qualifier() {
    // A ceiling of `sql_execution` must not be read as covering `sql_execution:read_only` — the
    // `:` qualifier is not a hierarchy. This pins exact-string-set containment down explicitly.
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture_with_profile(
        dir.path(),
        "needs_read_only_sql",
        &capability_component("needs_read_only_sql", "[sql_execution:read_only]"),
        "config:\n  capability_ceiling:\n    - sql_execution\n",
        "",
    );

    let err = compile_project(dir.path()).expect_err(
        "a ceiling of 'sql_execution' must not admit 'sql_execution:read_only' by prefix",
    );
    assert!(
        err.contains("sql_execution:read_only") && err.contains("sql_execution"),
        "unexpected error: {err}"
    );
}

/// A component body with a populated `required_capabilities` list and a single `llm_steps` entry,
/// so capability-subset tests can vary just the step's own `capabilities`/`produces_exclusive`
/// lines (`step_extra`, inlined verbatim under the step's `prompt_ref` line) without duplicating
/// the rest of a minimal component.
fn step_capability_component(
    id: &str,
    required_capabilities_block: &str,
    step_extra: &str,
) -> String {
    format!(
        r#"
id: {id}
verb: {id}
type: analytical
realization_kind: skill
binding_mode: runtime_selected
llm_steps:
  - name: only_step
    tier: cheap
    prompt_ref: steps/only_step.md
{step_extra}
trigger: {{ kind: one_shot }}
guardrails:
  - {{ name: read_only_execution, locked: true }}
required_capabilities:
{required_capabilities_block}
effect:
  render_blocks: []
  outcome: {{ kind: none }}
"#
    )
}

#[test]
fn step_capabilities_subset_of_required_reaches_ir() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "capped_step",
        &step_capability_component(
            "capped_step",
            "  - sql_execution:read_only\n  - render_contract\n",
            "    capabilities:\n      - sql_execution:read_only\n",
        ),
    );

    let ir = compile_project(dir.path()).expect("a capability that is a subset must compile");
    assert_eq!(
        ir["components"][0]["llm_calls"][0]["capabilities"],
        serde_json::json!(["sql_execution:read_only"]),
        "the step's narrowed capabilities must reach the matching llm_calls entry verbatim"
    );
}

#[test]
fn step_capability_outside_required_set_fails_loudly() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "capped_step",
        &step_capability_component(
            "capped_step",
            "  - render_contract\n",
            "    capabilities:\n      - sql_execution:read_only\n",
        ),
    );

    let err = compile_project(dir.path())
        .expect_err("a capability outside required_capabilities must fail");
    assert!(
        err.contains("step 'only_step'")
            && err.contains("component 'capped_step'")
            && err.contains("capability 'sql_execution:read_only'"),
        "error must name both the offending step and capability: {err}"
    );
}

#[test]
fn step_produces_exclusive_reaches_ir() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "exclusive_step",
        &step_capability_component(
            "exclusive_step",
            "  - render_contract\n",
            "    produces: draft\n    produces_exclusive: true\n",
        ),
    );

    let ir = compile_project(dir.path()).expect("produces_exclusive must compile");
    assert_eq!(
        ir["components"][0]["llm_calls"][0]["produces_exclusive"],
        serde_json::json!(true),
        "an authored produces_exclusive: true must reach the matching llm_calls entry"
    );
}

#[test]
fn unauthored_capabilities_and_produces_exclusive_are_absent_from_ir() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture(
        dir.path(),
        "plain_step",
        &step_capability_component("plain_step", "  - render_contract\n", ""),
    );

    let ir = compile_project(dir.path()).expect("a step with neither field must compile");
    let call = ir["components"][0]["llm_calls"][0]
        .as_object()
        .expect("llm_calls entry must be an object");
    assert!(
        !call.contains_key("capabilities"),
        "an unauthored 'capabilities' must be absent as a key, not null: {call:?}"
    );
    assert!(
        !call.contains_key("produces_exclusive"),
        "an unauthored 'produces_exclusive' must be absent as a key, not null: {call:?}"
    );
}

fn composition_component(id: &str, steps: &str) -> String {
    format!(
        r#"
id: {id}
verb: {id}
type: analytical
realization_kind: skill
binding_mode: runtime_selected
llm_steps:
{steps}
trigger: {{ kind: one_shot }}
guardrails:
  - {{ name: read_only_execution, locked: true }}
required_capabilities: [llm:cheap]
borrowed_actions: []
effect:
  render_blocks: []
  outcome: {{ kind: none }}
"#
    )
}

fn write_composition_fixture(
    dir: &Path,
    profile_prefix: &str,
    mounts: &str,
    components: &[(&str, String)],
) {
    fs::create_dir_all(dir.join("context")).unwrap();
    fs::create_dir_all(dir.join("wren_project")).unwrap();
    fs::write(
        dir.join("wren_project/wren_project.yml"),
        "schema_version: 2\n",
    )
    .unwrap();
    fs::write(
        dir.join("context/binding.yml"),
        // These fixtures inject their own `ContextLoader`, so no resolver ever reads this
        // binding — but `kind` is a required field, so it still has to be declared. `external`
        // is the kind that reads nothing, which is the truthful description of a binding
        // whose context arrives by injection.
        "kind: external\nproject: ./wren_project\n",
    )
    .unwrap();
    fs::write(
        dir.join("profile.yml"),
        format!(
            "profile: composition\ncontext:\n  project: ./context/binding.yml\n{profile_prefix}components:\n{mounts}"
        ),
    )
    .unwrap();
    for (id, component) in components {
        let component_dir = dir.join("components").join(id);
        fs::create_dir_all(component_dir.join("steps")).unwrap();
        fs::write(component_dir.join("component.yml"), component).unwrap();
        fs::write(component_dir.join("steps/only_step.md"), "Do the thing.\n").unwrap();
    }
}

fn one_step(name: &str, component_calls: &str) -> String {
    format!(
        "  - name: {name}\n    tier: cheap\n    prompt_ref: steps/only_step.md\n{component_calls}"
    )
}

#[test]
fn component_call_authorization_reaches_ir_without_reshaping_artifact_flow() {
    let dir = tempfile::tempdir().unwrap();
    let caller_steps = r#"  - name: plan
    tier: cheap
    prompt_ref: steps/only_step.md
    produces: plan
  - name: compose
    tier: cheap
    prompt_ref: steps/only_step.md
    consumes: [plan]
    produces: answer
    capabilities: [llm:cheap]
    component_calls:
      - { alias: answer, component: callee }
"#;
    write_composition_fixture(
        dir.path(),
        "",
        "  - use: caller\n  - use: callee\n    entrypoint: false\n",
        &[
            ("caller", composition_component("caller", caller_steps)),
            (
                "callee",
                composition_component("callee", &one_step("answer", "")),
            ),
        ],
    );

    let ir = compile_project(dir.path()).expect("a valid same-profile call graph must compile");
    let caller = &ir["components"][0];
    let call = &caller["llm_calls"][1];
    assert_eq!(caller["entrypoint"], true);
    assert_eq!(ir["components"][1]["entrypoint"], false);
    assert_eq!(call["consumes"], serde_json::json!(["plan"]));
    assert_eq!(call["produces"], "answer");
    assert_eq!(
        call["component_calls"],
        serde_json::json!([{ "alias": "answer", "component": "callee" }])
    );
    assert_eq!(
        caller["required_capabilities"],
        serde_json::json!(["llm:cheap", "component_invocation"])
    );
    assert_eq!(
        call["capabilities"],
        serde_json::json!(["llm:cheap", "component_invocation"])
    );
}

#[test]
fn component_invocation_is_checked_against_the_profile_capability_ceiling() {
    let dir = tempfile::tempdir().unwrap();
    write_composition_fixture(
        dir.path(),
        "config:\n  capability_ceiling: [llm:cheap]\n",
        "  - use: caller\n  - use: callee\n",
        &[
            (
                "caller",
                composition_component(
                    "caller",
                    &one_step(
                        "invoke",
                        "    component_calls:\n      - { alias: answer, component: callee }\n",
                    ),
                ),
            ),
            (
                "callee",
                composition_component("callee", &one_step("answer", "")),
            ),
        ],
    );

    let error = compile_project(dir.path())
        .expect_err("the implied invocation capability must not bypass the ceiling");
    assert!(
        error.contains("caller")
            && error.contains("component_invocation")
            && error.contains("capability_ceiling"),
        "unexpected error: {error}"
    );
}

#[test]
fn component_call_without_step_capabilities_keeps_inherited_requirement_semantics() {
    let dir = tempfile::tempdir().unwrap();
    write_composition_fixture(
        dir.path(),
        "",
        "  - use: caller\n  - use: callee\n",
        &[
            (
                "caller",
                composition_component(
                    "caller",
                    &one_step(
                        "invoke",
                        "    component_calls:\n      - { alias: answer, component: callee }\n",
                    ),
                ),
            ),
            (
                "callee",
                composition_component("callee", &one_step("answer", "")),
            ),
        ],
    );

    let ir = compile_project(dir.path()).expect("an inherited-capability call must compile");
    let caller = &ir["components"][0];
    assert_eq!(
        caller["required_capabilities"],
        serde_json::json!(["llm:cheap", "component_invocation"])
    );
    assert!(
        caller["llm_calls"][0].get("capabilities").is_none(),
        "an unauthored step capability list must remain omitted so the step inherits the full component requirements"
    );
}

#[test]
fn duplicate_mount_identity_is_rejected_as_an_ambiguous_call_target() {
    let dir = tempfile::tempdir().unwrap();
    write_composition_fixture(
        dir.path(),
        "",
        "  - use: caller\n  - use: callee\n  - use: callee\n",
        &[
            (
                "caller",
                composition_component(
                    "caller",
                    &one_step(
                        "invoke",
                        "    component_calls:\n      - { alias: answer, component: callee }\n",
                    ),
                ),
            ),
            (
                "callee",
                composition_component("callee", &one_step("answer", "")),
            ),
        ],
    );

    let error = compile_project(dir.path()).expect_err("duplicate mounts must fail");
    assert!(
        error.contains("callee")
            && error.contains("more than once")
            && error.contains("unambiguously"),
        "unexpected error: {error}"
    );
}

#[test]
fn missing_duplicate_and_invalid_component_call_names_fail_with_local_diagnostics() {
    let cases = [
        (
            "missing target",
            "      - { alias: answer, component: absent }\n",
            &["caller", "invoke", "answer", "absent", "missing mount"][..],
        ),
        (
            "duplicate alias",
            "      - { alias: answer, component: callee }\n      - { alias: answer, component: other }\n",
            &["caller", "invoke", "answer", "duplicate"][..],
        ),
        (
            "invalid alias",
            "      - { alias: Answer-Now, component: callee }\n",
            &["caller", "invoke", "Answer-Now", "[a-z_][a-z0-9_]*"][..],
        ),
        (
            "invalid component",
            "      - { alias: answer, component: Bad-Target }\n",
            &["caller", "invoke", "answer", "Bad-Target", "[a-z_][a-z0-9_]*"][..],
        ),
    ];

    for (label, declarations, expected) in cases {
        let dir = tempfile::tempdir().unwrap();
        write_composition_fixture(
            dir.path(),
            "",
            "  - use: caller\n  - use: callee\n  - use: other\n",
            &[
                (
                    "caller",
                    composition_component(
                        "caller",
                        &one_step("invoke", &format!("    component_calls:\n{declarations}")),
                    ),
                ),
                (
                    "callee",
                    composition_component("callee", &one_step("answer", "")),
                ),
                (
                    "other",
                    composition_component("other", &one_step("answer", "")),
                ),
            ],
        );
        let error = compile_project(dir.path()).expect_err(label);
        for fragment in expected {
            assert!(
                error.contains(fragment),
                "{label}: missing {fragment:?} in {error}"
            );
        }
    }
}

#[test]
fn self_calls_fail_before_general_cycle_detection() {
    let dir = tempfile::tempdir().unwrap();
    write_composition_fixture(
        dir.path(),
        "",
        "  - use: caller\n",
        &[(
            "caller",
            composition_component(
                "caller",
                &one_step(
                    "invoke",
                    "    component_calls:\n      - { alias: again, component: caller }\n",
                ),
            ),
        )],
    );

    let error = compile_project(dir.path()).expect_err("self-calls must fail");
    assert!(
        error.contains("caller") && error.contains("invoke") && error.contains("self-call"),
        "unexpected error: {error}"
    );
}

#[test]
fn direct_and_indirect_cycles_report_a_complete_closed_path() {
    for (mounts, components, expected_path) in [
        (
            "  - use: a\n  - use: b\n",
            vec![
                (
                    "a",
                    composition_component(
                        "a",
                        &one_step(
                            "call_b",
                            "    component_calls:\n      - { alias: b, component: b }\n",
                        ),
                    ),
                ),
                (
                    "b",
                    composition_component(
                        "b",
                        &one_step(
                            "call_a",
                            "    component_calls:\n      - { alias: a, component: a }\n",
                        ),
                    ),
                ),
            ],
            "a -> b -> a",
        ),
        (
            "  - use: a\n  - use: b\n  - use: c\n",
            vec![
                (
                    "a",
                    composition_component(
                        "a",
                        &one_step(
                            "call_b",
                            "    component_calls:\n      - { alias: b, component: b }\n",
                        ),
                    ),
                ),
                (
                    "b",
                    composition_component(
                        "b",
                        &one_step(
                            "call_c",
                            "    component_calls:\n      - { alias: c, component: c }\n",
                        ),
                    ),
                ),
                (
                    "c",
                    composition_component(
                        "c",
                        &one_step(
                            "call_a",
                            "    conditional: true\n    when: { guard: on_missing, target: result }\n    component_calls:\n      - { alias: a, component: a }\n",
                        ),
                    ),
                ),
            ],
            "a -> b -> c -> a",
        ),
    ] {
        let dir = tempfile::tempdir().unwrap();
        write_composition_fixture(dir.path(), "", mounts, &components);
        let error = compile_project(dir.path()).expect_err("cyclic authorization must fail");
        assert!(
            error.contains(expected_path),
            "expected complete path {expected_path:?}, got {error}"
        );
    }
}

#[test]
fn diamond_shared_callees_and_repeated_static_edges_are_not_cycles() {
    let dir = tempfile::tempdir().unwrap();
    write_composition_fixture(
        dir.path(),
        "",
        "  - use: a\n  - use: b\n  - use: c\n  - use: d\n",
        &[
            (
                "a",
                composition_component(
                    "a",
                    &one_step(
                        "fan_out",
                        "    component_calls:\n      - { alias: first_b, component: b }\n      - { alias: second_b, component: b }\n      - { alias: c, component: c }\n",
                    ),
                ),
            ),
            (
                "b",
                composition_component(
                    "b",
                    &one_step(
                        "shared",
                        "    component_calls:\n      - { alias: d, component: d }\n",
                    ),
                ),
            ),
            (
                "c",
                composition_component(
                    "c",
                    &one_step(
                        "shared",
                        "    component_calls:\n      - { alias: d, component: d }\n",
                    ),
                ),
            ),
            ("d", composition_component("d", &one_step("leaf", ""))),
        ],
    );

    let ir = compile_project(dir.path())
        .expect("diamonds, shared leaves, and several aliases to one callee are acyclic");
    assert_eq!(
        ir["components"][0]["llm_calls"][0]["component_calls"]
            .as_array()
            .unwrap()
            .len(),
        3
    );
}

/// Writes a one-component fixture whose slot variants live on disk, for the `slots:` tests.
///
/// Helper names in this file carry a feature prefix deliberately: two parallel branches once
/// landed different `capability_component` helpers and had to be merged by hand.
fn slot_write_fixture(
    dir: &Path,
    component_yaml: &str,
    step_body: &str,
    variant_files: &[(&str, &str)],
) {
    write_component_fixture_with_profile(dir, "slotted", component_yaml, "", "");
    fs::write(dir.join("components/slotted/steps/only_step.md"), step_body).unwrap();
    for (rel, content) in variant_files {
        let path = dir.join("components/slotted").join(rel);
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(path, content).unwrap();
    }
}

/// A component body with an arbitrary `slots:` block and a single step.
fn slot_component(slots_block: &str) -> String {
    format!(
        r#"
id: slotted
verb: slotted
type: analytical
realization_kind: skill
binding_mode: pinned
description: A component that carries slots.
examples:
  - Do the slotted thing.
llm_steps:
  - name: only_step
    tier: strong
    prompt_ref: steps/only_step.md
trigger: {{ kind: one_shot }}
guardrails: []
effect:
  render_blocks: []
  outcome: {{ kind: none }}
{slots_block}"#
    )
}

#[test]
fn slot_variants_reach_the_ir_with_placeholders_substituted() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_fixture(
        dir.path(),
        &slot_component(
            "slots:\n  - name: verification\n    variants:\n      base: fragments/base.md\n      terse: fragments/terse.md\n    default: base\n",
        ),
        "Answer, then: {{ slot.verification }}\n",
        &[
            ("fragments/base.md", "Verify against {{project_name}}.\n"),
            ("fragments/terse.md", "Verify.\n"),
        ],
    );

    let ir = compile_project(dir.path()).expect("a declared and referenced slot must compile");
    let slots = ir["components"][0]["slots"].as_array().unwrap();
    assert_eq!(slots.len(), 1);
    assert_eq!(slots[0]["name"], "verification");
    assert_eq!(slots[0]["default"], "base");
    // Every variant travels; compile selects none of them.
    assert_eq!(slots[0]["variants"]["base"], "Verify against wren_project.");
    assert_eq!(slots[0]["variants"]["terse"], "Verify.");
    // `present_when` is absent, not null, when unauthored.
    assert!(slots[0].get("present_when").is_none());
}

#[test]
fn slot_present_when_reaches_the_ir_when_authored() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_fixture(
        dir.path(),
        &slot_component(
            "slots:\n  - name: plan_mode\n    variants:\n      on: fragments/on.md\n    default: on\n    present_when: plan_mode_enabled\n",
        ),
        "{{ slot.plan_mode }}\n",
        &[("fragments/on.md", "Draft a plan first.\n")],
    );

    let ir = compile_project(dir.path()).expect("present_when must compile");
    assert_eq!(
        ir["components"][0]["slots"][0]["present_when"],
        "plan_mode_enabled"
    );
}

#[test]
fn a_component_without_slots_emits_no_slots_key() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_fixture(dir.path(), &slot_component(""), "Just answer.\n", &[]);

    let ir = compile_project(dir.path()).expect("no slots must compile");
    assert!(
        ir["components"][0].get("slots").is_none(),
        "the field must be absent, not an empty array — that is what keeps existing goldens byte-identical"
    );
}

#[test]
fn a_referenced_but_undeclared_slot_fails_compile() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_fixture(
        dir.path(),
        &slot_component(
            "slots:\n  - name: verification\n    variants:\n      base: fragments/base.md\n    default: base\n",
        ),
        "{{ slot.verification }} and {{ slot.verifcation }}\n",
        &[("fragments/base.md", "Verify.\n")],
    );

    let err = compile_project(dir.path()).expect_err("a mistyped slot name must fail");
    assert!(
        err.contains("verifcation") && err.contains("does not \n                 declare")
            || err.contains("verifcation"),
        "error must name the offending slot: {err}"
    );
}

#[test]
fn referencing_a_slot_when_none_are_declared_fails_compile() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_fixture(
        dir.path(),
        &slot_component(""),
        "{{ slot.verification }}\n",
        &[],
    );

    let err =
        compile_project(dir.path()).expect_err("a slot reference with no declarations must fail");
    assert!(err.contains("verification"), "{err}");
    assert!(err.contains("declares no slots"), "{err}");
}

#[test]
fn a_declared_but_unreferenced_slot_fails_compile() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_fixture(
        dir.path(),
        &slot_component(
            "slots:\n  - name: verification\n    variants:\n      base: fragments/base.md\n    default: base\n",
        ),
        "No slot reference here.\n",
        &[("fragments/base.md", "Verify.\n")],
    );

    let err = compile_project(dir.path()).expect_err("an unreferenced slot must fail");
    assert!(err.contains("verification"), "{err}");
}

#[test]
fn a_slot_default_outside_its_variants_fails_compile() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_fixture(
        dir.path(),
        &slot_component(
            "slots:\n  - name: verification\n    variants:\n      base: fragments/base.md\n    default: terse\n",
        ),
        "{{ slot.verification }}\n",
        &[("fragments/base.md", "Verify.\n")],
    );

    let err = compile_project(dir.path()).expect_err("a default naming no variant must fail");
    assert!(err.contains("terse"), "{err}");
    assert!(err.contains("base"), "the allowed set must be named: {err}");
}

#[test]
fn a_slot_with_no_variants_fails_compile() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_fixture(
        dir.path(),
        &slot_component("slots:\n  - name: verification\n    variants: {}\n    default: base\n"),
        "{{ slot.verification }}\n",
        &[],
    );

    let err = compile_project(dir.path()).expect_err("a slot with no variants must fail");
    assert!(err.contains("no variants"), "{err}");
}

#[test]
fn a_duplicate_slot_declaration_fails_compile() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_fixture(
        dir.path(),
        &slot_component(
            "slots:\n  - name: verification\n    variants:\n      base: fragments/base.md\n    default: base\n  - name: verification\n    variants:\n      terse: fragments/terse.md\n    default: terse\n",
        ),
        "{{ slot.verification }}\n",
        &[
            ("fragments/base.md", "Verify.\n"),
            ("fragments/terse.md", "Verify briefly.\n"),
        ],
    );

    let err = compile_project(dir.path()).expect_err("a duplicate slot name must fail");
    assert!(err.contains("more than once"), "{err}");
}

#[test]
fn a_slot_referenced_only_from_a_brief_counts_as_used() {
    let dir = tempfile::tempdir().unwrap();
    let component = format!(
        "{}\nbrief: |\n  Framing. {{{{ slot.verification }}}}\n",
        slot_component(
            "slots:\n  - name: verification\n    variants:\n      base: fragments/base.md\n    default: base\n",
        )
    );
    slot_write_fixture(
        dir.path(),
        &component,
        "No slot reference in the step.\n",
        &[("fragments/base.md", "Verify.\n")],
    );

    let ir = compile_project(dir.path()).expect("a brief reference must satisfy the usage check");
    assert_eq!(ir["components"][0]["slots"][0]["name"], "verification");
}

#[test]
fn a_slot_reference_inside_a_variant_counts_as_used() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_fixture(
        dir.path(),
        &slot_component(
            "slots:\n  - name: outer\n    variants:\n      base: fragments/outer.md\n    default: base\n  - name: inner\n    variants:\n      base: fragments/inner.md\n    default: base\n",
        ),
        "{{ slot.outer }}\n",
        &[
            ("fragments/outer.md", "Outer, then {{ slot.inner }}.\n"),
            ("fragments/inner.md", "Inner.\n"),
        ],
    );

    let ir = compile_project(dir.path())
        .expect("a slot referenced from another slot's variant must count as used");
    let slots = ir["components"][0]["slots"].as_array().unwrap();
    assert_eq!(slots.len(), 2);
    // Carried verbatim — nesting is not expanded at compile; dispatch does the choosing.
    assert_eq!(
        slots[0]["variants"]["base"],
        "Outer, then {{ slot.inner }}."
    );
}

#[test]
fn a_malformed_slot_reference_is_rejected_as_unrecognised_syntax() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_fixture(
        dir.path(),
        &slot_component(""),
        "Literal {{ slot.Verification }} would reach the model as text.\n",
        &[],
    );

    // The inverse of this test used to assert the reference was left verbatim, which is what
    // compile did before unrecognised template syntax became a compile error. A malformed slot
    // name is the case that motivated the change: it is too close to a real reference to be worth
    // passing through to a model as literal text.
    let err = compile_project(dir.path())
        .expect_err("a malformed slot reference must be rejected, not passed through");
    assert!(
        err.contains("unrecognised template syntax"),
        "the error must say what kind of problem this is: {err}"
    );
    assert!(
        err.contains("slot.Verification"),
        "the error must quote the offending reference: {err}"
    );
    assert!(
        err.contains("step 'only_step' of component 'slotted'"),
        "the error must name the surface the author has to open: {err}"
    );
}

/// Writes a fixture whose *profile* declares slots. `profile_extra` is inlined into `profile.yml`
/// above `components:`, and `profile_variant_files` are written relative to the project dir —
/// which is what a profile-level slot reference resolves against.
fn slot_write_profile_fixture(
    dir: &Path,
    profile_extra: &str,
    component_yaml: &str,
    step_body: &str,
    component_variant_files: &[(&str, &str)],
    profile_variant_files: &[(&str, &str)],
) {
    write_component_fixture_with_profile(dir, "slotted", component_yaml, profile_extra, "");
    fs::write(dir.join("components/slotted/steps/only_step.md"), step_body).unwrap();
    for (rel, content) in component_variant_files {
        let path = dir.join("components/slotted").join(rel);
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(path, content).unwrap();
    }
    for (rel, content) in profile_variant_files {
        let path = dir.join(rel);
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(path, content).unwrap();
    }
}

#[test]
fn profile_slots_reach_the_top_level_ir() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_profile_fixture(
        dir.path(),
        "system_prompt: |\n  You are a fixture. {{ slot.plan_mode }}\nslots:\n  - name: plan_mode\n    variants:\n      on: fragments/plan_on.md\n      off: fragments/plan_off.md\n    default: off\n    present_when: plan_mode_enabled\n",
        &slot_component(""),
        "Just answer.\n",
        &[],
        &[
            ("fragments/plan_on.md", "Draft a plan for {{project_name}} first.\n"),
            ("fragments/plan_off.md", "Act directly.\n"),
        ],
    );

    let ir = compile_project(dir.path()).expect("a profile-level slot must compile");

    // This assertion is the point of the test: `profile.yml` is NOT parsed with
    // `deny_unknown_fields`, so a field placed at the wrong level would be dropped in silence and
    // the compile would still succeed. Asserting on the emitted IR is the only way to know the
    // declaration was actually read.
    let slots = ir["slots"]
        .as_array()
        .expect("top-level slots must be emitted");
    assert_eq!(slots.len(), 1);
    assert_eq!(slots[0]["name"], "plan_mode");
    assert_eq!(slots[0]["default"], "off");
    assert_eq!(slots[0]["present_when"], "plan_mode_enabled");
    assert_eq!(
        slots[0]["variants"]["on"],
        "Draft a plan for wren_project first."
    );
    // Profile slots are not copied onto component nodes — each layer is addressed where declared.
    assert!(ir["components"][0].get("slots").is_none());
}

#[test]
fn a_profile_without_slots_emits_no_top_level_slots_key() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_profile_fixture(
        dir.path(),
        "",
        &slot_component(""),
        "Just answer.\n",
        &[],
        &[],
    );

    let ir = compile_project(dir.path()).expect("no profile slots must compile");
    assert!(
        ir.get("slots").is_none(),
        "absent, not empty — this is what keeps existing goldens byte-identical"
    );
}

#[test]
fn a_profile_slot_colliding_with_a_component_slot_fails_compile() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_profile_fixture(
        dir.path(),
        "system_prompt: |\n  Framing. {{ slot.verification }}\nslots:\n  - name: verification\n    variants:\n      loose: fragments/loose.md\n    default: loose\n",
        &slot_component(
            "slots:\n  - name: verification\n    variants:\n      base: fragments/base.md\n    default: base\n",
        ),
        "{{ slot.verification }}\n",
        &[("fragments/base.md", "Verify.\n")],
        &[("fragments/loose.md", "Verify loosely.\n")],
    );

    let err = compile_project(dir.path())
        .expect_err("the same slot name on both layers must fail rather than shadow");
    assert!(err.contains("verification"), "{err}");
    assert!(
        err.contains("slotted"),
        "the error must name the colliding component: {err}"
    );
}

#[test]
fn a_profile_slot_unreferenced_by_the_system_prompt_fails_compile() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_profile_fixture(
        dir.path(),
        "system_prompt: |\n  Framing with no slot reference.\nslots:\n  - name: plan_mode\n    variants:\n      on: fragments/plan_on.md\n    default: on\n",
        &slot_component(""),
        "Just answer.\n",
        &[],
        &[("fragments/plan_on.md", "Plan first.\n")],
    );

    let err = compile_project(dir.path()).expect_err("an unreferenced profile slot must fail");
    assert!(err.contains("plan_mode"), "{err}");
    // Pins the scope the check actually has. Asserting only the slot name — or only
    // "system_prompt", which the corrected message still contains — cannot tell this message from
    // the older one that claimed the check looked at `system_prompt` alone.
    assert!(
        err.contains("a declared slot's variant content"),
        "the message must name every surface the check draws references from: {err}"
    );
}

#[test]
fn a_system_prompt_referencing_an_undeclared_slot_fails_compile() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_profile_fixture(
        dir.path(),
        "system_prompt: |\n  Framing. {{ slot.plan_mode }}\n",
        &slot_component(""),
        "Just answer.\n",
        &[],
        &[],
    );

    let err = compile_project(dir.path())
        .expect_err("a system_prompt slot reference with no profile declaration must fail");
    assert!(err.contains("plan_mode"), "{err}");
    // `contains("system_prompt")` was the previous assertion and is no longer discriminating: the
    // corrected message names system_prompt as one of two surfaces, so the old wording — which
    // asserted the reference was in system_prompt specifically — satisfies it too.
    assert!(
        err.contains("a declared slot's variant content"),
        "the message must not claim the reference is in system_prompt specifically: {err}"
    );
}

#[test]
fn a_component_slot_is_not_satisfied_by_a_system_prompt_reference() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_profile_fixture(
        dir.path(),
        "system_prompt: |\n  Framing. {{ slot.verification }}\n",
        &slot_component(
            "slots:\n  - name: verification\n    variants:\n      base: fragments/base.md\n    default: base\n",
        ),
        "No slot reference in the step.\n",
        &[("fragments/base.md", "Verify.\n")],
        &[],
    );

    // The layers are checked against their own text. A component slot referenced only from the
    // profile's `system_prompt` is unused as far as the component is concerned, and the
    // system_prompt's reference is undeclared as far as the profile is concerned — either error is
    // correct, and both are better than accepting a cross-layer reference the name space forbids.
    let err = compile_project(dir.path())
        .expect_err("a cross-layer slot reference must not satisfy either layer's check");
    assert!(err.contains("verification"), "{err}");
}

#[test]
fn a_duplicate_profile_slot_declaration_fails_compile() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_profile_fixture(
        dir.path(),
        "system_prompt: |\n  Framing. {{ slot.plan_mode }}\nslots:\n  - name: plan_mode\n    variants:\n      on: fragments/plan_on.md\n    default: on\n  - name: plan_mode\n    variants:\n      off: fragments/plan_off.md\n    default: off\n",
        &slot_component(""),
        "Just answer.\n",
        &[],
        &[
            ("fragments/plan_on.md", "Plan first.\n"),
            ("fragments/plan_off.md", "Act directly.\n"),
        ],
    );

    let err = compile_project(dir.path()).expect_err("a duplicate profile slot name must fail");
    assert!(err.contains("more than once"), "{err}");
}

#[test]
fn a_profile_slot_default_outside_its_variants_fails_compile() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_profile_fixture(
        dir.path(),
        "system_prompt: |\n  Framing. {{ slot.plan_mode }}\nslots:\n  - name: plan_mode\n    variants:\n      on: fragments/plan_on.md\n    default: off\n",
        &slot_component(""),
        "Just answer.\n",
        &[],
        &[("fragments/plan_on.md", "Plan first.\n")],
    );

    let err =
        compile_project(dir.path()).expect_err("a profile default naming no variant must fail");
    assert!(err.contains("off"), "{err}");
    assert!(
        err.contains("profile 'fixture'"),
        "the owner must be named: {err}"
    );
}

/// Writes a one-component fixture with an arbitrary `assets:` block and the asset files on disk.
/// Prefixed `asset_` per this file's helper-naming convention.
fn asset_write_fixture(dir: &Path, assets_block: &str, asset_files: &[(&str, &[u8])]) {
    let component_yaml = format!(
        r#"
id: assetted
verb: assetted
type: analytical
realization_kind: skill
binding_mode: pinned
description: A component that carries files.
examples:
  - Do the thing with files.
llm_steps:
  - name: only_step
    tier: strong
    prompt_ref: steps/only_step.md
trigger: {{ kind: one_shot }}
guardrails: []
effect:
  render_blocks: []
  outcome: {{ kind: none }}
{assets_block}"#
    );
    write_component_fixture_with_profile(dir, "assetted", &component_yaml, "", "");
    for (rel, content) in asset_files {
        let path = dir.join("components/assetted").join(rel);
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(path, content).unwrap();
    }
}

#[test]
fn a_component_without_assets_emits_no_assets_key() {
    let dir = tempfile::tempdir().unwrap();
    asset_write_fixture(dir.path(), "", &[]);

    let ir = compile_project(dir.path()).expect("no assets must compile");
    assert!(
        ir["components"][0].get("assets").is_none(),
        "absent, not empty — this is what keeps existing goldens byte-identical"
    );
}

// ── unrecognised template syntax ────────────────────────────────────────────────────────────────
//
// One test per prompt-text surface, because the check lives in the single shared substitution
// function and the value of these tests is proving every surface actually routes through it.

#[test]
fn an_unknown_placeholder_in_a_step_body_fails_compile() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_fixture(
        dir.path(),
        &slot_component(""),
        "Answer about {{ topic }}.\n",
        &[],
    );

    let err = compile_project(dir.path()).expect_err("an unknown placeholder must fail");
    assert!(err.contains("unrecognised template syntax"), "{err}");
    assert!(
        err.contains("{{ topic }}"),
        "the error must quote it: {err}"
    );
    assert!(
        err.contains("step 'only_step' of component 'slotted'"),
        "{err}"
    );
    assert!(
        err.contains("literal one"),
        "the message must tell the author how to write a literal brace: {err}"
    );
}

#[test]
fn an_unknown_placeholder_in_a_component_brief_fails_compile() {
    let dir = tempfile::tempdir().unwrap();
    let component = format!(
        "{}\nbrief: |\n  Framing about {{{{ topic }}}}.\n",
        slot_component("")
    );
    slot_write_fixture(dir.path(), &component, "Just answer.\n", &[]);

    let err = compile_project(dir.path()).expect_err("an unknown placeholder in a brief must fail");
    assert!(err.contains("unrecognised template syntax"), "{err}");
    assert!(
        err.contains("the brief of component 'slotted'"),
        "the error must name the brief, not the step: {err}"
    );
}

#[test]
fn an_unknown_placeholder_in_a_mount_brief_names_the_mount() {
    let dir = tempfile::tempdir().unwrap();
    write_component_fixture_with_profile(
        dir.path(),
        "slotted",
        &slot_component(""),
        "",
        "    brief: |\n      Mount framing about {{ topic }}.\n",
    );

    let err =
        compile_project(dir.path()).expect_err("an unknown placeholder in a mount brief must fail");
    assert!(
        err.contains("the mount brief for component 'slotted'"),
        "a profile-supplied brief must be named as such, since that is the file to edit: {err}"
    );
}

#[test]
fn an_unknown_placeholder_in_a_system_prompt_fails_compile() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_profile_fixture(
        dir.path(),
        "system_prompt: |\n  You work on {{ topic }}.\n",
        &slot_component(""),
        "Just answer.\n",
        &[],
        &[],
    );

    let err =
        compile_project(dir.path()).expect_err("an unknown placeholder in system_prompt must fail");
    assert!(err.contains("the profile's system_prompt"), "{err}");
}

#[test]
fn an_unknown_placeholder_in_a_slot_variant_fails_compile() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_fixture(
        dir.path(),
        &slot_component(
            "slots:\n  - name: verification\n    variants:\n      base: fragments/base.md\n    default: base\n",
        ),
        "{{ slot.verification }}\n",
        &[("fragments/base.md", "Verify using {{ tool }}.\n")],
    );

    let err =
        compile_project(dir.path()).expect_err("an unknown placeholder in a variant must fail");
    assert!(
        err.contains("variant 'base' of slot 'verification'"),
        "{err}"
    );
}

#[test]
fn a_jinja_statement_delimiter_fails_compile() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_fixture(
        dir.path(),
        &slot_component(""),
        "{% if verbose %}Say more.{% endif %}\n",
        &[],
    );

    let err = compile_project(dir.path()).expect_err("a statement delimiter must fail");
    assert!(err.contains("unrecognised template syntax"), "{err}");
    assert!(
        err.contains("'{%'"),
        "the error must quote the delimiter it found: {err}"
    );
}

#[test]
fn a_jinja_comment_delimiter_fails_compile() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_fixture(
        dir.path(),
        &slot_component(""),
        "Answer. {# a note to nobody #}\n",
        &[],
    );

    let err = compile_project(dir.path()).expect_err("a comment delimiter must fail");
    assert!(err.contains("'{#'"), "{err}");
}

#[test]
fn the_known_placeholders_and_slot_references_still_compile() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_fixture(
        dir.path(),
        &slot_component(
            "slots:\n  - name: verification\n    variants:\n      base: fragments/base.md\n    default: base\n",
        ),
        "Work on {{project}} ({{ project_name }}). {{ slot.verification }}\n",
        &[("fragments/base.md", "Verify against {{project_name}}.\n")],
    );

    let ir = compile_project(dir.path())
        .expect("the recognised forms must still compile, spacing variants included");
    let prompt = ir["components"][0]["prompt_fragment"].as_str().unwrap();
    assert!(
        prompt.contains("wren_project"),
        "substitution still happens: {prompt}"
    );
    // A slot reference is deliberately NOT substituted at compile — dispatch chooses the variant.
    assert!(prompt.contains("{{ slot.verification }}"), "{prompt}");
}

#[test]
fn a_single_brace_is_left_alone() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_fixture(
        dir.path(),
        &slot_component(""),
        "Reply with JSON: { \"answer\": 1, \"nested\": { \"ok\": true } }\n",
        &[],
    );

    // The in-repo prompts that teach a model to emit JSON use single braces, which is why this
    // check could be added with a measured blast radius of zero. If single braces ever started
    // failing, every such prompt would break at once.
    let ir = compile_project(dir.path()).expect("single braces must not trip the check");
    let prompt = ir["components"][0]["prompt_fragment"].as_str().unwrap();
    assert!(prompt.contains("{ \"answer\": 1"), "{prompt}");
}

#[test]
fn an_unterminated_double_brace_is_not_reported_as_a_reference() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_fixture(
        dir.path(),
        &slot_component(""),
        "An unclosed {{ thing without a closing delimiter\n",
        &[],
    );

    // Nothing here can be read as a reference, and guessing at where the author meant it to end
    // would invent an error message about text they did not write. Left alone, exactly as today.
    compile_project(dir.path()).expect("an unterminated '{{' must not be reported as a reference");
}

#[test]
fn a_slot_name_that_cannot_be_referenced_fails_compile_on_the_declaration() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_fixture(
        dir.path(),
        &slot_component(
            "slots:\n  - name: Verification\n    variants:\n      base: fragments/base.md\n    default: base\n",
        ),
        "Answer, then: {{ slot.Verification }}\n",
        &[("fragments/base.md", "Verify.\n")],
    );

    // The author wrote both halves consistently, so the useful complaint is about the name, not
    // about the reference. Before this check the name was accepted, no reference to it was ever
    // recognised, and the error told the author to add prompt text they had already written.
    let err = compile_project(dir.path())
        .expect_err("a slot name that cannot appear in a reference must fail");
    assert!(
        err.contains("not a usable slot name"),
        "the error must name the real problem, not report the slot as unreferenced: {err}"
    );
    assert!(err.contains("Verification"), "{err}");
}

#[test]
fn produces_exclusive_without_a_produced_artifact_fails_compile() {
    let dir = tempfile::tempdir().unwrap();
    let component = r#"
id: exclusive_nothing
verb: exclusive_nothing
type: analytical
realization_kind: skill
binding_mode: pinned
description: A component whose step claims exclusivity over nothing.
examples:
  - Claim nothing.
llm_steps:
  - name: only_step
    tier: strong
    prompt_ref: steps/only_step.md
    produces_exclusive: true
trigger: { kind: one_shot }
guardrails: []
effect:
  render_blocks: []
  outcome: { kind: none }
"#;
    write_component_fixture(dir.path(), "exclusive_nothing", component);

    // Exclusivity is provenance on a `produces` name. With no artifact it marks nothing, so
    // accepting it would emit a marker no consumer can act on while the author believes they
    // constrained who may write something.
    let err = compile_project(dir.path())
        .expect_err("exclusivity over no artifact must fail rather than compile to a no-op");
    assert!(
        err.contains("produces no \n                 artifact") || err.contains("produces no"),
        "{err}"
    );
    assert!(
        err.contains("only_step"),
        "the error must name the step: {err}"
    );
}

#[test]
fn a_profile_slot_referenced_only_from_another_slots_variant_compiles() {
    let dir = tempfile::tempdir().unwrap();
    slot_write_profile_fixture(
        dir.path(),
        "system_prompt: |\n  Framing. {{ slot.verification }}\nslots:\n  - name: verification\n    variants:\n      base: fragments/verification.md\n    default: base\n  - name: plan_mode\n    variants:\n      on: fragments/plan_on.md\n    default: on\n",
        &slot_component(""),
        "Just answer.\n",
        &[],
        &[
            // `plan_mode` is referenced from here, not from system_prompt.
            ("fragments/verification.md", "Verify, then {{ slot.plan_mode }}.\n"),
            ("fragments/plan_on.md", "Plan first.\n"),
        ],
    );

    // The profile-level counterpart of `a_slot_reference_inside_a_variant_counts_as_used`, which
    // covers only the component layer. Nothing exercised this path before: if profile slots
    // stopped honouring references from variant content, every existing profile-slot test would
    // still pass, because they all assert failures.
    let ir = compile_project(dir.path())
        .expect("a profile slot referenced from another declared slot's variant must compile");
    let slots = ir["slots"].as_array().unwrap();
    assert_eq!(slots.len(), 2);
    // Carried verbatim — compile does not resolve a nested reference, dispatch selects.
    assert_eq!(
        slots[0]["variants"]["base"],
        "Verify, then {{ slot.plan_mode }}."
    );
}