mlua-swarm-schema 0.19.0

Blueprint schema types for mlua-swarm — Swarm IF SoT (Blueprint / AgentDef / AgentKind / Hints / Strategy / Metadata).
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
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
//! Blueprint schema — Swarm IF SoT (= the core type set that defines "how a Blueprint object is written").
//!
//! This crate provides **schema types + serde derives only** as a pure IF crate. Execution
//! layers (SpawnerFactory / EngineDispatcher / Compiler) are not included here; consumers
//! (the `mlua-swarm` crate) own them. External consumers, sibling worktrees, and
//! future bundles can read/write Blueprints by depending on this single crate.
//!
//! # Versioning contract
//!
//! `Blueprint.schema_version` is tied to this crate's semver. It is fixed at 0.1.0 for now;
//! during 0.x breaking changes are free, and 1.0 will freeze the schema.
//!
//! # IN-immutability (extension discipline)
//!
//! This crate is the IN side of the swarm layering and stays **plain serde
//! data**: no compile pass, no field the engine macro-expands, no DSL
//! dialect. Flow conds are written literally against the Flow.ir Expr set
//! (`Eq($.<step>.verdict, Lit("blocked"))` — domain verdicts are plain
//! strings in step output). Authoring sugar (builders) lives OUT on the
//! consumer side; runtime behavior extension lives in the engine's
//! `SpawnerLayer` middleware.
//!
//! # AgentKind handling (= internal SoT)
//!
//! [`AgentKind`] is the SoT for the SpawnerAdapter offering axis. It is a closed enum managed
//! inside Swarm, extended by variant addition through **explicit maintenance**. String lookup
//! or a `Custom` escape hatch is deliberately avoided (= structurally eliminates the "silly
//! runtime typos" class of failures).
//!
//! # Examples
//!
//! Build a minimal [`Blueprint`] with a single [`AgentDef`] via struct literal:
//!
//! ```
//! use mlua_swarm_schema::{
//!     AgentDef, AgentKind, Blueprint, current_schema_version,
//! };
//! use mlua_flow_ir::{Expr, Node};
//! use serde_json::json;
//!
//! let bp = Blueprint {
//!     schema_version: current_schema_version(),
//!     id: "hello".into(),
//!     flow: Node::Step {
//!         ref_: "greeter".into(),
//!         in_: Expr::Lit { value: json!({"name": "world"}) },
//!         out: Expr::Path { at: "$.greeting".parse().unwrap() },
//!     },
//!     agents: vec![AgentDef {
//!         name: "greeter".into(),
//!         kind: AgentKind::RustFn,
//!         spec: json!({"fn_id": "hello_world"}),
//!         profile: None,
//!         meta: None,
//!         runner: None,
//!         runner_ref: None,
//!         verdict: None,
//!     }],
//!     operators: vec![],
//!     metas: vec![],
//!     hints: Default::default(),
//!     strategy: Default::default(),
//!     metadata: Default::default(),
//!     spawner_hints: Default::default(),
//!     default_agent_kind: AgentKind::Operator,
//!     default_operator_kind: None,
//!     default_init_ctx: None,
//!     default_agent_ctx: None,
//!     default_context_policy: None,
//!     projection_placement: None,
//!     audits: vec![],
//!     degradation_policy: None,
//!     runners: vec![],
//!     default_runner: None,
//!     subprocesses: vec![],
//!     check_policy: None,
//!     blueprint_ref_includes: vec![],
//! };
//!
//! assert_eq!(bp.id.as_str(), "hello");
//! assert_eq!(bp.agents.len(), 1);
//! assert_eq!(bp.strategy.strict_refs, true);
//! ```
//!
//! Round-trip a [`Blueprint`] through JSON (= confirms `serde` derives and the
//! `deny_unknown_fields` contract):
//!
//! ```
//! use mlua_swarm_schema::{AgentKind, Blueprint, BlueprintMetadata};
//! use mlua_flow_ir::{Expr, Node};
//! use serde_json::json;
//!
//! let bp = Blueprint {
//!     schema_version: mlua_swarm_schema::current_schema_version(),
//!     id: "roundtrip".into(),
//!     flow: Node::Seq { children: vec![] },
//!     agents: vec![],
//!     operators: vec![],
//!     metas: vec![],
//!     hints: Default::default(),
//!     strategy: Default::default(),
//!     metadata: BlueprintMetadata {
//!         description: Some("roundtrip smoke".into()),
//!         default_run_ttl_secs: Some(1800),
//!         ..Default::default()
//!     },
//!     spawner_hints: Default::default(),
//!     default_agent_kind: AgentKind::Operator,
//!     default_operator_kind: None,
//!     default_init_ctx: None,
//!     default_agent_ctx: None,
//!     default_context_policy: None,
//!     projection_placement: None,
//!     audits: vec![],
//!     degradation_policy: None,
//!     runners: vec![],
//!     default_runner: None,
//!     subprocesses: vec![],
//!     check_policy: None,
//!     blueprint_ref_includes: vec![],
//! };
//!
//! let json = serde_json::to_string(&bp).unwrap();
//! let back: Blueprint = serde_json::from_str(&json).unwrap();
//! assert_eq!(bp, back);
//! assert_eq!(back.metadata.default_run_ttl_secs, Some(1800));
//! ```

#![warn(missing_docs)]

use mlua_flow_ir::Node as FlowNode;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;

// ──────────────────────────────────────────────────────────────────────────
// Versioning
// ──────────────────────────────────────────────────────────────────────────

/// Current Blueprint schema version. Tied to this crate's semver.
pub const CURRENT_SCHEMA_VERSION: &str = "0.1.0";

fn default_schema_version() -> semver::Version {
    current_schema_version()
}

/// Blueprint construction helper: returns the semver of the current schema version.
/// Callers can write `schema_version: current_schema_version(),`.
pub fn current_schema_version() -> semver::Version {
    semver::Version::parse(CURRENT_SCHEMA_VERSION)
        .expect("CURRENT_SCHEMA_VERSION must be valid semver")
}

// ──────────────────────────────────────────────────────────────────────────
// BlueprintId (human-facing ID newtype)
// ──────────────────────────────────────────────────────────────────────────

/// Identifier for a Blueprint series — the domain name (`coding`,
/// `design`, `testing`, etc.). Default: [`BlueprintId::main`].
///
/// One representation across the workspace (issue #14): this type is
/// shared by the schema's [`Blueprint::id`] and the engine's store-layer
/// keys (`mlua-swarm` re-exports it at the old
/// `blueprint::store::types::BlueprintId` path). The value is
/// user-supplied — there is no prefix convention to validate, unlike the
/// engine's minted `T-` / `R-` / `ST-` ids — so construction is
/// infallible; the inner string is private so call sites go through
/// [`BlueprintId::new`] and the accessors. `#[serde(transparent)]` keeps
/// both the JSON wire shape and the generated JSON Schema a plain string.
#[derive(
    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
)]
#[serde(transparent)]
pub struct BlueprintId(String);

impl BlueprintId {
    /// The default series name used when a caller doesn't pick one.
    pub const MAIN: &'static str = "main";

    /// Shorthand for `BlueprintId::new(BlueprintId::MAIN)`.
    pub fn main() -> Self {
        Self(Self::MAIN.to_string())
    }

    /// Wrap any string-like value as a `BlueprintId` (user-supplied key;
    /// nothing to validate).
    pub fn new(s: impl Into<String>) -> Self {
        Self(s.into())
    }

    /// Borrow the inner series name.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consume the id and return the inner series name.
    pub fn into_string(self) -> String {
        self.0
    }
}

impl std::fmt::Display for BlueprintId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl From<String> for BlueprintId {
    fn from(s: String) -> Self {
        Self(s)
    }
}

impl From<&str> for BlueprintId {
    fn from(s: &str) -> Self {
        Self(s.to_string())
    }
}

#[cfg(test)]
mod blueprint_id_tests {
    use super::*;

    /// issue #14 convergence guard: `Blueprint.id` becoming a newtype must
    /// not change the generated JSON Schema — the property stays an inline
    /// plain string (no `$ref`), byte-compatible with the `String` era.
    #[test]
    fn blueprint_id_field_schema_stays_a_plain_inline_string() {
        let schema = schemars::schema_for!(Blueprint);
        let v = serde_json::to_value(&schema).expect("schema serializes");
        let id = &v["properties"]["id"];
        assert_eq!(id["type"], "string", "id must stay a plain string: {id}");
        assert!(id.get("$ref").is_none(), "id must not become a $ref: {id}");
    }

    /// The JSON wire shape of the newtype is the bare string.
    #[test]
    fn blueprint_id_serde_is_transparent() {
        let id = BlueprintId::new("coding");
        assert_eq!(
            serde_json::to_value(&id).unwrap(),
            serde_json::json!("coding")
        );
        let back: BlueprintId = serde_json::from_value(serde_json::json!("coding")).unwrap();
        assert_eq!(back, id);
    }
}

// ──────────────────────────────────────────────────────────────────────────
// Blueprint (top-level package)
// ──────────────────────────────────────────────────────────────────────────

/// Unified package of flow.ir + Swarm extension layers. The entry-point type of Swarm.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Blueprint {
    /// Schema version (= tied to this crate's semver). Default = `CURRENT_SCHEMA_VERSION`.
    /// Serialized as a semver string (e.g. `"0.1.0"`).
    #[serde(default = "default_schema_version")]
    #[schemars(with = "String")]
    pub schema_version: semver::Version,
    /// Blueprint identifier (= unique key within the caller's namespace).
    #[schemars(with = "String")]
    pub id: BlueprintId,
    /// Embeds the flow.ir Node verbatim (= keeps flow.ir side unpolluted).
    /// Opaque in the JSON Schema (the Node shape is owned by the `mlua-flow-ir`
    /// crate, a separate repo; see its docs for the Node / Expr grammar).
    #[schemars(with = "Value")]
    pub flow: FlowNode,
    /// Swarm extension layer: agent → backend mapping.
    #[serde(default)]
    pub agents: Vec<AgentDef>,
    /// Swarm extension layer: **design-time definition** of Operator roles (first-class).
    ///
    /// `AgentDef.spec.operator_ref` references an `OperatorDef.name` (logical role name) in
    /// this vec. Embedding runtime-generated IDs such as sid into the BP is forbidden
    /// (= collapses the design-time vs runtime boundary). Runtime backend bindings are
    /// established via the attach / register path; the BP side holds only logical names.
    ///
    /// Every `kind = Operator` agent must have its `spec.operator_ref` present in this
    /// list — the compiler validates it at `compile()` time. May be `[]` only when the
    /// Blueprint declares no Operator agents.
    #[serde(default)]
    pub operators: Vec<OperatorDef>,
    /// GH #21 Phase 2 — named, BP-scoped pool of [`MetaDef`] entries. Two
    /// independent consumers resolve names against this pool: a
    /// `$step_meta.ref` envelope embedded in a Step's evaluated `in`
    /// value (the Step tier — resolved by `EngineDispatcher` in the
    /// `mlua-swarm` core crate at dispatch time), and
    /// [`AgentMeta::meta_ref`] (the Agent tier — resolved at launch
    /// time). The pool lets multiple Steps and/or Agents share one
    /// declarative context object by name instead of repeating it
    /// inline. `[]` = no named `MetaDef`s declared (pre-#21-Phase-2
    /// Blueprints unaffected).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub metas: Vec<MetaDef>,
    /// Swarm extension layer: per-agent hints (interpreted by the Compiler).
    #[serde(default)]
    pub hints: CompilerHints,
    /// Swarm extension layer: Compiler behavior strategy (strict / lenient).
    #[serde(default)]
    pub strategy: CompilerStrategy,
    /// Blueprint metadata (description / origin / tags / ttl / version label / alias).
    #[serde(default)]
    pub metadata: BlueprintMetadata,
    /// Swarm extension layer: hint keys of the layers to wrap around the SpawnerStack.
    /// Resolved by the LayerRegistry at engine bind time (= unregistered keys are silently
    /// skipped). Flow / Blueprint do not hold middleware implementations (e.g. MainAIMiddleware)
    /// directly; they only declare required capabilities as string keys (= implementations
    /// live in the engine-side LayerRegistry).
    #[serde(default)]
    pub spawner_hints: SpawnerHints,
    /// BP-wide default `AgentKind` (= fallback when `AgentDef.kind` is omitted).
    /// Four-layer cascade: (1) Schema impl Default = Operator, (2) CLI
    /// `--default-agent-kind`, (3) this field (BP JSON literal), (4) `AgentDef.kind`
    /// (per-agent literal). (5) `CompilerHints.kind_override` allows runtime override.
    /// All default resolution flows through this path.
    #[serde(default = "default_global_agent_kind")]
    pub default_agent_kind: AgentKind,
    /// BP-wide default `OperatorKind` (= the "BP Global" tier of the 4-tier
    /// `OperatorKind` cascade). `None` when the Blueprint author does not
    /// declare a default; the caller-side resolver then falls through to
    /// the hardcoded `OperatorKind::default()` (Automate).
    ///
    /// # 4-tier cascade (highest to lowest priority)
    ///
    /// 1. Runtime Agent-level (per-agent override supplied at task-launch time)
    /// 2. Runtime Global (the launch-time `operator_kind` request)
    /// 3. BP Agent-level (`OperatorDef.kind`, resolved via `AgentDef.spec.operator_ref`)
    /// 4. BP Global (this field)
    /// 5. Default Fallback (`OperatorKind::default()` = Automate)
    ///
    /// The collapse itself is implemented once on the engine side and consumed
    /// per-agent when resolving operator info.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_operator_kind: Option<OperatorKind>,
    /// Blueprint-level default initial `ctx` for flow-ir eval.
    /// `TaskLaunchService::launch` shallow-merges this with the
    /// Task-level `init_ctx` (Task wins on key collision when both
    /// are `Object`; if Task's `init_ctx` is not an `Object`, it
    /// full-replaces the default). `None` — no default is merged;
    /// backward-compat with pre-#19 Blueprints.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(with = "Option<Value>")]
    pub default_init_ctx: Option<Value>,
    /// GH #21 Phase 1 — "BP Global" tier of the agent-context supply axis:
    /// a declarative object merged into `ctx.meta.runtime` (and, for
    /// unnamed keys, `AgentContextView.extra`) targeting every agent's
    /// runtime materialization. Contrast with [`Self::default_init_ctx`]:
    /// that field seeds the flow-ir eval `ctx` once at flow start, while
    /// this one is consumed per-spawn by
    /// `AgentContextMiddleware`/`AgentContextView` (Contract C, GH #20) —
    /// a pure flow-ir eval seed vs. an Agent/LLM-boundary runtime default.
    /// `None` = no BP-global default (pre-#21 Blueprints unaffected).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(with = "Option<Value>")]
    pub default_agent_ctx: Option<Value>,
    /// GH #21 Phase 1 — "BP Global" tier of the [`ContextPolicy`] cascade:
    /// the default filter applied to the materialized `AgentContextView`
    /// when the targeted agent declares no `AgentMeta.context_policy` of
    /// its own. `None` = pass-all (the pre-#21 behavior).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_context_policy: Option<ContextPolicy>,
    /// GH #27 (follow-up to #23) — Blueprint-declared override of the
    /// `mlua-swarm` core crate's projection placement resolver (root
    /// preference + target directory template for materialized step
    /// OUTPUT files). `None` = the resolver's byte-compat default (root =
    /// `work_dir` falling back to `project_root`; dir_template =
    /// `"workspace/tasks/{task_id}/ctx"`) — every pre-#27 Blueprint is
    /// unaffected. See [`ProjectionPlacementSpec`]'s doc for field detail.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub projection_placement: Option<ProjectionPlacementSpec>,
    /// GH #34 — Blueprint-declared after-run audit hooks: the engine
    /// auto-kicks each listed [`AuditDef`]'s agent once a matching Step
    /// settles, and persists its findings as an `OutputEvent::Artifact`
    /// named `"audit:<step_ref>"` on the AUDITED step's own output tail
    /// (see `mlua-swarm` core's `AfterRunAuditMiddleware` for the
    /// dispatch mechanics). `audits[].agent` is validated at
    /// `Compiler::compile` time against `Blueprint.agents[].name`
    /// (mirrors the `operator_ref` validation). `[]` (the default) = no
    /// audit hooks declared — every pre-#34 Blueprint is unaffected,
    /// byte-for-byte.
    ///
    /// **Binding invariant**: an audit's verdict, findings, or even its
    /// own failure NEVER change the audited step's outcome or gate the
    /// flow — audits are purely observational.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub audits: Vec<AuditDef>,
    /// GH #32 — Blueprint-declared policy for worker-reported degradations
    /// (see `mlua-swarm` core's `RunRecord.degradations` /
    /// `DegradationEntry`). `None` (the default) is schema-only for now:
    /// [`DegradationPolicy::Warn`] and [`DegradationPolicy::Fail`] carry the
    /// same observational behavior at this point — degradations are always
    /// persisted, never gate the flow. Engine enforcement of `Fail`
    /// (terminating a Run on any reported degradation) is a follow-up; this
    /// field only declares author intent today. Every pre-#32 Blueprint is
    /// unaffected.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub degradation_policy: Option<DegradationPolicy>,
    /// GH #46 M2 — named registry of [`RunnerDef`] entries (Tier 1 of the
    /// 3-tier Worker model: Runner / Agent / Context). Referenced by
    /// `AgentDef.runner_ref` and [`Self::default_runner`] by name.
    /// Same registry shape as [`Self::metas`] (GH #21 Phase 2). `[]` (the
    /// default) = no Runner registry declared — every pre-#46 Blueprint
    /// is unaffected, byte-for-byte.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub runners: Vec<RunnerDef>,
    /// GH #46 M2 — the "BP Global" tier of the [`resolve_runner`] cascade:
    /// a [`RunnerDef::name`] reference into [`Self::runners`] (inline
    /// `Runner` values are not accepted here — registry names only,
    /// mirroring [`Self::default_agent_ctx`]'s design). Ranks BELOW an
    /// agent's own inline `runner` / `runner_ref` / legacy
    /// `profile.worker_binding` declaration (see [`resolve_runner`]'s
    /// cascade doc for the full precedence). `None` = no BP-wide default
    /// declared — every pre-#46 Blueprint is unaffected.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_runner: Option<String>,
    /// GH #83 — named registry of [`SubprocessDef`] CLI invocation
    /// templates, referenced by `Runner::Subprocess { template }` by
    /// name. Same registry shape as [`Self::metas`] / [`Self::runners`].
    /// `[]` (the default) = no templates declared — every pre-#83
    /// Blueprint is unaffected, byte-for-byte.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub subprocesses: Vec<SubprocessDef>,
    /// "Blueprint" tier (tier 2) of the `check_policy`
    /// cascade: `launch request > blueprint > server config` (highest to
    /// lowest priority). The launch entry point resolves
    /// `launch.check_policy.or(blueprint.check_policy)` exactly once and
    /// threads the result into every spawned step's `TaskSpec.check_policy`;
    /// `None` here (the default) is a no declaration — resolution falls
    /// through to the launch-request tier and, absent that, to the
    /// server-wide `EngineCfg.check_policy` default. Every pre-cascade
    /// Blueprint is unaffected, byte-for-byte. See [`CheckPolicy`] for the
    /// three fail-open reaction modes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub check_policy: Option<CheckPolicy>,
    /// Authoring-time include list consumed by the compile-side linker
    /// (tier 2 of the include cascade — see `mlua-swarm-compile`'s
    /// `ResolveConfig`). Each entry is a directory path resolved
    /// relative to the bp.lua parent that `$agent_md` / `$file` refs
    /// will search after the parent dir itself. Bare list; the schema
    /// carries the field only so `deny_unknown_fields` won't reject a
    /// bp.lua that declares it. `[]` (the default) — no in-bp includes;
    /// every pre-cascade Blueprint is unaffected.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[schemars(with = "Vec<String>")]
    pub blueprint_ref_includes: Vec<std::path::PathBuf>,
}

/// How a submit-time projection sink reacts when a fail-open condition
/// is encountered.
///
/// This is the Swarm IF SoT type for the `check_policy` axis; the
/// `mlua-swarm` core crate re-exports it as `crate::core::config::CheckPolicy`
/// so every existing path (`EngineCfg.check_policy`, `TaskSpec.check_policy`,
/// `apply_check_policy`) keeps its old type path unchanged.
///
/// Fail-open conditions include: `work_dir` / `project_root` unresolved,
/// `OutputStore` write error, `FileProjectionAdapter::materialize_submission`
/// error, and state lookup error. Each call site inside the engine's
/// `materialize_final_submission` / `materialize_artifact_submission`
/// currently logs a `tracing::warn!` and returns without materializing the
/// file / dual-write; `CheckPolicy` is the first-class knob that lets a
/// caller opt into a different reaction without changing that behaviour by
/// default.
///
/// The three modes are (a) [`CheckPolicy::Silent`] — no log, no error,
/// operation continues; (b) [`CheckPolicy::Warn`] — log warn (existing
/// message literal preserved), no error, operation continues (the
/// default = pre-existing behaviour); (c) [`CheckPolicy::Strict`] — log
/// the same warn AND return `EngineError::CheckPolicyStrict` (in the core
/// crate) so the caller can fail the step / launch fast. When Strict
/// returns an error, the underlying `OutputStore` may already have
/// appended (dual-write side-effect is not rolled back) — this "state
/// dirty on fail" semantics is intentional: the append happens **before**
/// the fail-open branch runs, so Strict surfaces the mismatch instead of
/// hiding it.
///
/// The wire form is snake_case (`"silent"` / `"warn"` / `"strict"`); the
/// default is [`CheckPolicy::Warn`].
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum CheckPolicy {
    /// Skip both the log warn and the error path — completely silent.
    /// The operation continues (fail-open is still in effect).
    Silent,
    /// Log a `tracing::warn!` with the call site's existing message and
    /// continue (fail-open). Default — byte-identical to the
    /// pre-`CheckPolicy` behaviour of every submit-time projection sink
    /// code path.
    #[default]
    Warn,
    /// Log the same warn AND return `EngineError::CheckPolicyStrict` (the
    /// core crate's error variant). A caller that has opted in can fail the
    /// step / launch fast instead of proceeding with a partially-realized
    /// submission. This mode also drives a launch-time pre-dispatch
    /// validation in `TaskLaunchService::launch` (the `mlua-swarm` core
    /// crate): a launch whose effective policy resolves to `Strict` and
    /// that supplies neither `project_root` nor `work_dir` is rejected
    /// with `TaskLaunchError::PreDispatch` before any step is dispatched,
    /// rather than dispatching a step that would deterministically hit
    /// this same error at its first submit-time file materialize.
    Strict,
}

/// GH #32 — Blueprint-declared policy for worker-reported degradations. See
/// [`Blueprint::degradation_policy`] for the (currently schema-only)
/// enforcement contract.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum DegradationPolicy {
    /// Observational only (today's only enforced behavior, regardless of
    /// which variant is declared): degradations are persisted to
    /// `RunRecord.degradations` and surfaced via `mse_doctor` /
    /// `GET /v1/runs/:id`, but never change the Run's outcome.
    Warn,
    /// Declares intent to terminate the Run on any reported degradation.
    /// Not yet enforced by the engine — schema-only until the follow-up
    /// lands.
    Fail,
}

/// GH #34 — one Blueprint-declared after-run audit hook. See
/// [`Blueprint::audits`] for the persistence / invariant contract.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct AuditDef {
    /// Name of the audit agent (must match a [`Blueprint::agents`] entry's
    /// `name`) the engine dispatches after a matched step settles.
    /// Validated at `Compiler::compile` time (mirrors
    /// `AgentDef.spec.operator_ref`'s `operator_ref` validation) — an
    /// unresolved name rejects compilation.
    pub agent: String,
    /// Step names this audit applies to, matched against the step's agent
    /// ref name. `None`, or a list containing the literal `"*"`, means
    /// "every step". `Some(vec![])` (an explicit empty list) audits no
    /// step. `None` is the default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub steps: Option<Vec<String>>,
    /// Dispatch timing for this audit's agent (see [`AuditMode`]).
    /// Defaults to [`AuditMode::Async`].
    #[serde(default)]
    pub mode: AuditMode,
}

/// GH #34 — dispatch timing for an [`AuditDef`]'s audit agent. Neither
/// variant ever changes the audited step's outcome (see
/// [`Blueprint::audits`]'s binding invariant).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum AuditMode {
    /// Fire-and-forget: the audit runs in the background after the
    /// audited step settles; the audited step's own spawn signal returns
    /// immediately, without waiting for the audit to finish.
    #[default]
    Async,
    /// Awaited before the audited step's spawn signal is returned to the
    /// engine — still never alters that signal or the step's recorded
    /// outcome.
    Sync,
}

/// Receptacle for a Blueprint-driven filter over the materialized
/// `AgentContextView` (GH #20/#21). Declared BP-side via
/// [`Blueprint::default_context_policy`] (BP-global) or
/// `AgentMeta::context_policy` (per-agent, outranks the BP-global tier) —
/// resolved and applied by `AgentContextMiddleware` in the `mlua-swarm`
/// core crate (this crate stays execution-free; see the crate doc).
/// Default (`include: None, exclude: vec![]`) is pass-all — [`Self::allows`]
/// returns `true` for every field name.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ContextPolicy {
    /// Field names to keep. `None` means "keep everything" (pass-all).
    /// Matched against the `AgentContextView` named-field strings
    /// (`"project_root"` / `"work_dir"` / `"task_metadata"` / `"run_id"` /
    /// `"project_name_alias"`) and `extra` keys by their own key string.
    /// Identity fields (`task_id` / `agent` / `attempt`) are never
    /// filtered regardless of `include`.
    #[serde(default)]
    pub include: Option<Vec<String>>,
    /// Field names to drop, applied AFTER `include` (exclude wins when a
    /// name appears in both). Same name-matching rule as `include`.
    #[serde(default)]
    pub exclude: Vec<String>,
    /// Which preceding steps' OUTPUT pointers a worker's fetch payload may
    /// see (`WorkerPayload.context.steps`, ST5 of the `projection-adapter`
    /// design). `None` = pass-all (every submitted step, the pre-ST5
    /// `ctx_step_dir` behavior); `Some(list)` = only the named steps;
    /// `Some(vec![])` = none. Evaluated by [`Self::allows_step`], a sibling
    /// of [`Self::allows`] with the same include/exclude precedence rule
    /// but a separate namespace (step names vs. `AgentContextView` field /
    /// `extra` key names never collide).
    #[serde(default)]
    pub steps: Option<Vec<String>>,
    /// Step names to drop, applied AFTER `steps` (exclude wins when a name
    /// appears in both). Same name-matching rule as `steps`.
    #[serde(default)]
    pub steps_exclude: Vec<String>,
}

impl ContextPolicy {
    /// Whether `name` survives this policy: `false` if `exclude` lists it;
    /// otherwise `true` when `include` is `None` (pass-all) or lists
    /// `name`. Shared by both the schema crate (tests) and the `mlua-swarm`
    /// core crate's `AgentContextView::apply_policy`, so the include/exclude
    /// evaluation rule has exactly one implementation.
    pub fn allows(&self, name: &str) -> bool {
        if self.exclude.iter().any(|excluded| excluded == name) {
            return false;
        }
        match &self.include {
            Some(list) => list.iter().any(|included| included == name),
            None => true,
        }
    }

    /// Whether the preceding step named `name` survives this policy for the
    /// worker fetch payload's `context.steps` pointer list: `false` if
    /// `steps_exclude` lists it; otherwise `true` when `steps` is `None`
    /// (pass-all) or lists `name`. Same precedence rule as [`Self::allows`],
    /// evaluated against the separate `steps` / `steps_exclude` fields.
    pub fn allows_step(&self, name: &str) -> bool {
        if self.steps_exclude.iter().any(|excluded| excluded == name) {
            return false;
        }
        match &self.steps {
            Some(list) => list.iter().any(|included| included == name),
            None => true,
        }
    }
}

/// Global default `AgentKind` at the Schema impl Default layer. Bottom of the 4-layer cascade.
pub fn default_global_agent_kind() -> AgentKind {
    AgentKind::Operator
}

/// Set of **capability hint keys** for the SpawnerLayer required by a Blueprint.
///
/// # Design rationale (= for the person who will reconstruct this later)
///
/// A Blueprint is a pure layer of flow.ir + agent name binding and holds no middleware
/// **implementation**. Nevertheless there are cases where the caller must be told the BP
/// needs certain **capabilities** — e.g. "MainAI hook required", "Operator delegate path
/// required", operator role mode switching, presence/absence of senior escalation, and
/// so on.
///
/// `spawner_hints.layers` is the place where those capabilities are declared as **string
/// keys**. The engine-side `LayerRegistry` (= consumer crate) resolves key → factory and
/// wraps the compiled routes with a `SpawnerStack`. The Blueprint does not import the
/// concrete `MainAIMiddleware` type; it exposes intent through strings such as `"main_ai"`
/// (= separates the pure Flow layer from implementation details).
///
/// # Canonical hint keys
///
/// - `"main_ai"` → `MainAIMiddleware` (= fires SpawnHook before/after when kind is MainAi/Composite)
/// - `"senior_escalation"` → `SeniorEscalationMiddleware` (= fires SeniorBridge.ask on worker ok=false)
/// - `"operator_delegate"` → `OperatorDelegateMiddleware` (= delegates the entire spawn to an external Operator.execute)
///
/// # Behavior of unregistered keys
///
/// If the engine-side LayerRegistry has no matching factory, the key is **silently skipped**
/// (= lenient default). This preserves Blueprint portability (= an unsupported capability in
/// another deployment falls back gracefully).
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct SpawnerHints {
    /// Ordered list of layer hint keys to wrap around the SpawnerStack.
    #[serde(default)]
    pub layers: Vec<String>,
}

// ──────────────────────────────────────────────────────────────────────────
// AgentDef / AgentKind / AgentProfile / AgentMeta
// ──────────────────────────────────────────────────────────────────────────

/// Maps an agent name to a Worker IMPL kind and its configuration. Referenced from flow.ir
/// `Step.ref` by name.
///
/// # Design
///
/// `AgentDef.kind` directly expresses the **Worker IMPL axis** (= not the old Spawner axis).
/// Dispatching to a host Spawner adapter (`InProcSpawner` / `ProcessSpawner` /
/// `OperatorSpawner`) is done by an internal Resolver on the compiler side. The design goal
/// is "do not make the caller aware of which Spawner hosts the Worker IMPL"; the caller
/// (Blueprint author) sees only the WorkerIMPL viewpoint.
///
/// A Spawner-axis hint (= "which adapter would you prefer running this Worker on", as a
/// priority list) will be added via a future `spawner_hint: Vec<Spawner>` field as a carry.
/// The current internal Resolver is a fixed 1:1 mapping, so the field is unnecessary today.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct AgentDef {
    /// Agent name (= referenced from flow.ir `Step.ref`).
    pub name: String,
    /// Worker IMPL kind (= see [`AgentKind`]).
    pub kind: AgentKind,
    /// Free-form schema per kind. Interpreted by the SpawnerFactory.
    ///
    /// Per-kind key contracts are documented on the [`AgentKind`] variants
    /// (`fn_id` for `Lua` / `RustFn`, `program` + `args` for `Subprocess`,
    /// `operator_ref` for `Operator`, and the `script_path` /
    /// `project_root` / `mcp_rpc_timeout_ms` / `mcp_servers` set for
    /// [`AgentKind::AgentBlock`]).
    #[serde(default)]
    pub spec: Value,
    /// Agent persona information (system_prompt / model / tools, etc.). Orthogonal to the
    /// backend kind and is a first-class field. Expected to be populated by
    /// `agent_md_loader` from the frontmatter + body of an `agent.md`. `None` = an agent
    /// without a profile (= backend built solely from `spec`).
    #[serde(default)]
    pub profile: Option<AgentProfile>,
    /// Agent-level metadata (description / version / tags).
    #[serde(default)]
    pub meta: Option<AgentMeta>,
    /// GH #46 M2 — inline [`Runner`] declaration: the highest-priority
    /// tier of the [`resolve_runner`] cascade. `None` = this agent
    /// declares no inline Runner (falls through to [`Self::runner_ref`],
    /// then the legacy `profile.worker_binding` fallback, then
    /// `Blueprint.default_runner`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub runner: Option<Runner>,
    /// GH #46 M2 — a [`RunnerDef::name`] reference into
    /// `Blueprint.runners` (second-priority tier of [`resolve_runner`]).
    /// `None` = this agent declares no Runner registry reference.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub runner_ref: Option<String>,
    /// GH #50 — opt-in declaration of which OUTPUT channel this agent's
    /// verdict token lives on, and the closed set of tokens it may emit
    /// through that channel (see [`VerdictContract`]). Consumed by the
    /// `mlua-swarm` core crate's `Compiler::compile` to lint
    /// `Branch`/`Loop` `Eq`/`Ne`/`In` conds against this agent's output at
    /// register time; a follow-up submit-time producer gate is a separate
    /// enforcement point. `None` (the default) — this agent declares no
    /// contract; a cond comparing its output to a literal is unchanged (at
    /// most a `tracing::warn!`, never rejected) — every pre-GH-#50
    /// Blueprint is unaffected, byte-for-byte.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub verdict: Option<VerdictContract>,
}

/// Agent persona information. Orthogonal to the backend kind (Shell / InProc / Operator).
///
/// Populated by `agent_md_loader::load_dir` from the frontmatter and Markdown body of
/// `agents/*.md` in agent-profiles. The backend (e.g. AgentBlockOperator) receives this
/// struct at construction / dispatch time and consumes `system_prompt` as the LLM API
/// system message and `model` / `tools` as configuration.
///
/// C-C-specific fields (`permissionMode` / `memory` / `abtest`, etc.) are dumped into
/// `extras: Value`, and consumers that need them read them out. This is the escape hatch
/// that keeps the schema future-proof rather than making it strict.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct AgentProfile {
    /// Markdown body (= system prompt content).
    #[serde(default)]
    pub system_prompt: String,
    /// LLM model identifier (e.g. `"sonnet"` / `"haiku"` / `"opus"`).
    #[serde(default)]
    pub model: Option<String>,
    /// Reasoning effort (e.g. `"low"` / `"medium"` / `"high"`).
    #[serde(default)]
    pub effort: Option<String>,
    /// List of available tool names (normalized from the CSV form in frontmatter).
    #[serde(default)]
    pub tools: Vec<String>,
    /// Frontmatter `description`. A short one-line description.
    #[serde(default)]
    pub description: Option<String>,
    /// C-C-specific / future-proof fields (permissionMode / memory / abtest / ...).
    /// Shape is the leftover keys of the agent.md frontmatter dumped as a JSON object.
    #[serde(default)]
    pub extras: Value,
    /// Content hash (blake3 32-byte hex) of the agent body (= `system_prompt`).
    ///
    /// # Purpose
    ///
    /// When the Enhance loop receives a Patch that replaces
    /// `/agents/N/profile/system_prompt`, the post-hook in `patch_applier.lua`
    /// recomputes this field (= new blake3 of the body) and updates it automatically.
    /// This is the field that structurally prevents a Blueprint carrying a stale hash
    /// from being committed.
    ///
    /// - `None` = hash not computed (= manually built agent, or a Blueprint predating this field)
    /// - `Some(hex)` = latest hash at agent-profiles seed time or after PatchApplier
    ///
    /// Planned to be used as the cache-index key in `AgentStore`.
    #[serde(default)]
    pub version_hash: Option<String>,
    /// Claude Code SubAgent definition name this agent binds to at spawn
    /// time (e.g. "code-worker"). Why: the Blueprint is the single
    /// source of truth for the declaration↔executor binding — an external
    /// registry would duplicate what `tools` already declares and drift.
    /// `None` is valid for agents whose operator backend never dispatches
    /// a SubAgent (direct-LLM operators); WS thin-path operators require
    /// it at compile time (see `Operator::requires_worker_binding`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub worker_binding: Option<String>,
}

/// SoT of the **Worker IMPL axis**. A closed enum managed inside Swarm and extended by
/// variant addition through **explicit maintenance**. String lookup / escape hatches are
/// deliberately not adopted.
///
/// This enum **expresses Worker IMPL directly**; dispatching to a host Spawner adapter is
/// resolved by an internal Resolver on the compiler side (= callers see only the Worker
/// IMPL viewpoint).
///
/// # Internal Resolver mapping (= currently a fixed 1:1, carry: priority list form)
///
/// | AgentKind | Host Spawner adapter |
/// |---|---|
/// | `Lua` | `InProcSpawner` (mlua VM eval) |
/// | `RustFn` | `InProcSpawner` (Rust closure) |
/// | `AgentBlock` | `InProcSpawner` (agent-block-core SDK in-process) |
/// | `Subprocess` | `ProcessSpawner` (child process launch) |
/// | `Operator` | `OperatorSpawner` (interactive role / Human-MainAI delegation) |
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum AgentKind {
    /// Lua script eval through the mlua VM (= factory-side registry looked up by `spec.fn_id`).
    Lua,
    /// Rust closure (= factory-side registry looked up by `spec.fn_id`).
    RustFn,
    /// Headless LLM agent via the agent-block-core SDK (in-process).
    ///
    /// Pairs with a [`Runner::AgentBlockInProcess`]. Its `spec` contract
    /// (GH #86 — every key optional):
    ///
    /// | key | meaning |
    /// |---|---|
    /// | `script_path` | Absent → **PromptBasedAgent** mode (the host embeds an invoker that calls the SDK's `agent` module). Present → **ScriptBasedAgent** mode (that Lua script runs instead). |
    /// | `project_root` | Compile-time fallback cwd. Overridden per launch by `init_ctx.work_dir` / `init_ctx.project_root`. |
    /// | `mcp_rpc_timeout_ms` | MCP RPC timeout; default `30000`. |
    /// | `mcp_servers` | `[{name, command, args}]` pool the tool grant selects from. |
    ///
    /// The step's evaluated `in` reaches the agent as the `_PROMPT` Lua
    /// global and `profile.system_prompt` as `_CONTEXT` — not through the
    /// server process env. A script returns its result by calling
    /// `bus.emit(<kind>, payload)`; the host reads `payload.content`, else
    /// `payload.response`, else the whole payload, as the step OUTPUT body
    /// (which is what a [`VerdictChannel::Body`] contract compares).
    AgentBlock,
    /// Child-process launch (= `spec.program` + `args`, via the ProcessSpawner path).
    Subprocess,
    /// Interactive Operator role (= MainAI / Human delegation, `spec.operator_ref`).
    Operator,
}

// ──────────────────────────────────────────────────────────────────────────
// VerdictContract / VerdictChannel (GH #50 — opt-in cond↔output-shape lint)
// ──────────────────────────────────────────────────────────────────────────

/// Opt-in per-agent declaration of the step OUTPUT shape a downstream
/// `Branch`/`Loop` `cond` is allowed to structurally compare against — see
/// the `blueprint-authoring.md` guide's "Returning verdicts to drive BP
/// flow" section for the Pattern A/B shapes this mirrors. Consumed by the
/// `mlua-swarm` core crate's `Compiler::compile` (a register-time,
/// read-only lint over `Branch`/`Loop` `Eq`/`Ne`/`In` conds — no `flow`
/// rewriting, no new `Expr` forms) and, as a follow-up, by the server's
/// submit-time producer gate. `None` on [`AgentDef::verdict`] (the
/// default) means neither enforcement point runs for that agent — the
/// pre-GH-#50 behavior, byte-for-byte.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct VerdictContract {
    /// Which OUTPUT channel carries the verdict token — see
    /// [`VerdictChannel`].
    pub channel: VerdictChannel,
    /// Closed set of the verdict tokens this agent may emit through the
    /// declared `channel` (e.g. `["PASS", "BLOCKED"]`). A `Branch`/`Loop`
    /// cond's `Lit` operand(s) compared against this agent's declared
    /// channel must be members of this set.
    pub values: Vec<String>,
}

/// Which step OUTPUT channel a [`VerdictContract`] addresses — the two
/// canonical submit shapes documented in the `blueprint-authoring.md`
/// guide's "Returning verdicts to drive BP flow" section.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum VerdictChannel {
    /// Pattern A — the plain step OUTPUT body IS the verdict scalar; a cond
    /// addresses it as the bare step output (`$.<step>`).
    Body,
    /// Pattern B — the verdict is staged as the named part `"verdict"`
    /// alongside a separate plain-body report; a cond addresses it as
    /// `$.<step>.parts.verdict` (equivalently `$.<step>.parts["verdict"]`
    /// — both forms normalize to the same canonical [`Path`](mlua_flow_ir::Path) `Display`).
    Part,
}

// ──────────────────────────────────────────────────────────────────────────
// Runner / RunnerDef / WorkerModel / resolve_runner (GH #46 Milestone 2)
// ──────────────────────────────────────────────────────────────────────────

/// The execution shell an agent's Worker IMPL runs inside — holding tool
/// grant, model selection, and runtime capabilities. Tier 1 of the GH #46
/// 3-tier Worker model (Runner / Agent / Context).
///
/// Runner here is broader than the ADK / OpenAI Agents SDK Runner (a loop
/// driver): it is the execution shell holding tool grant, model
/// selection, and runtime capabilities. Loop driving itself is the
/// backend's job (Claude Code harness / AgentBlock runtime).
///
/// Resolved per-agent by [`resolve_runner`]'s 5-step cascade; wiring the
/// resolved value into the launch path is Milestone 3 — this Milestone
/// only declares the shape and the pure resolver.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "backend", rename_all = "snake_case", deny_unknown_fields)]
pub enum Runner {
    /// Platform-neutral WebSocket Operator backend. The joined execution
    /// environment may be Claude Code, Codex, or another MainAI/plugin that
    /// implements the common binding and spawn contracts.
    WsOperator {
        /// Provider-defined launch variant selected by the execution environment.
        variant: String,
        /// Minimum tool grant the provider must enforce.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        tools: Vec<String>,
    },
    /// WS backend: Claude Code subagent wrapper. `variant` is the
    /// wrapper's subagent_type; `tools` mirrors the wrapper frontmatter =
    /// enforced grant.
    ///
    /// Kept as a compatibility backend for existing Blueprints. New
    /// platform-neutral declarations should use [`Self::WsOperator`].
    WsClaudeCode {
        /// The wrapper's `subagent_type` (= `WorkerBinding.variant` in the
        /// `mlua-swarm` core crate).
        variant: String,
        /// Declared (informational) tool list — mirrors the wrapper
        /// frontmatter; the actual grant is enforced by the wrapper file
        /// itself, not by this list.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        tools: Vec<String>,
    },
    /// In-process backend: agent-block runtime. `tools` is the effective
    /// (enforced) tool set for the in-process registry.
    ///
    /// Enforcement is per [`AgentKind::AgentBlock`] mode (GH #86) and is
    /// **server-granular**: PromptBasedAgent embeds only the
    /// `spec.mcp_servers` entries named by an `mcp__<server>__<tool>` entry
    /// of this list, so an unlisted server is unreachable — but every tool
    /// of a listed server is reachable. ScriptBasedAgent
    /// (`spec.script_path` present) cannot be enforced at all — the script
    /// drives its own `mcp.connect` — so declaring `mcp__` entries there is
    /// a compile error rather than a silent no-op.
    AgentBlockInProcess {
        /// Effective (enforced) tool set passed to the agent-block
        /// runtime's registry — unlike WebSocket Runner tool requests, this
        /// list is not merely informational.
        ///
        /// Declaring this Runner at all overrides `profile.tools`,
        /// **including when the list is empty**: an empty list is an
        /// enforced-empty grant (the way a Blueprint revokes an agent.md's
        /// inherited `tools:` line), not "unset". An agent that declares no
        /// Runner keeps `profile.tools` as its effective set. The override
        /// is applied once, when the Run's immutable `BoundAgent` snapshot
        /// is projected for the compiler, so it is pinned for resume.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        tools: Vec<String>,
    },
    /// GH #83 — Subprocess EmbedAgent backend: the step runs headless
    /// through the `ProcessSpawner` path, with the invocation described by
    /// a [`SubprocessDef`] template looked up by name in
    /// [`Blueprint::subprocesses`]. Name symmetry with
    /// `AgentKind::Subprocess` is deliberate (1:1 — this variant is the
    /// Runner-axis face of the same Worker IMPL kind).
    ///
    /// Per-agent overrides live HERE (not on `SubprocessDef`) so the
    /// template struct stays flat and shareable across agents.
    Subprocess {
        /// [`SubprocessDef::name`] reference into
        /// [`Blueprint::subprocesses`].
        template: String,
        /// Per-agent overrides applied on top of the referenced template
        /// and the agent profile. Empty (all defaults) is omitted on the
        /// wire.
        #[serde(default, skip_serializing_if = "SubprocessOverrides::is_empty")]
        overrides: SubprocessOverrides,
    },
}

/// Per-agent overrides for [`Runner::Subprocess`] — values that take
/// precedence over the agent's `profile.model` / `profile.tools` and the
/// spawn-time `{work_dir}` placeholder source when rendering the
/// [`SubprocessDef`] template. Lives on the Runner variant (not on
/// `SubprocessDef`) so the template itself stays flat (no per-agent
/// state, no variant axis).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct SubprocessOverrides {
    /// Overrides the `{model}` placeholder value (wins over
    /// `profile.model`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    /// Overrides the `{tools_csv}` placeholder value (wins over
    /// `profile.tools`).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tools: Vec<String>,
    /// Overrides the child process working directory (wins over the
    /// template's `cwd` and the spawn-time `{work_dir}` source).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cwd: Option<String>,
}

impl SubprocessOverrides {
    /// `true` when every field is at its default — used by
    /// `skip_serializing_if` so an empty overrides block stays off the
    /// wire (pre-#83 byte-compatibility for the `Runner` enum).
    pub fn is_empty(&self) -> bool {
        self.model.is_none() && self.tools.is_empty() && self.cwd.is_none()
    }
}

/// GH #83 — one declarative CLI invocation template: how a materialized
/// worker payload (system prompt + task + model/tools/cwd) is rendered
/// into a child-process invocation, and how its stdout is normalized back
/// into the worker-result shape.
///
/// Deliberately a **flat struct** — no internal variant/kind
/// discriminator. Adding support for a new CLI backend means adding one
/// more named entry to [`Blueprint::subprocesses`], never a new enum arm
/// or spawner branch (the `AgentKind` closed enum already owns the kind
/// axis; nesting a second "backend" hierarchy under it is the exact
/// complexity this shape refuses).
///
/// `argv` / `stdin` / `env` values / `cwd` may contain `{placeholder}`
/// tokens drawn from a closed, logic-free set (`{system}` /
/// `{system_file}` / `{prompt}` / `{model}` / `{tools_csv}` /
/// `{work_dir}` / `{task_id}` / `{attempt}`). Rendering is pure string
/// substitution — no conditionals, no loops, no expression language; the
/// engine-side consumer validates tokens against the closed set at
/// compile time. This crate stores the templates as plain strings only
/// (IN-immutability: no execution logic here).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct SubprocessDef {
    /// Registry key, referenced by `Runner::Subprocess { template }`.
    pub name: String,
    /// Program + arguments. `argv[0]` is the binary; every element may
    /// carry placeholder tokens.
    pub argv: Vec<String>,
    /// Rendered and piped to the child's stdin when `Some`; `None` = no
    /// stdin write (EOF immediately).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stdin: Option<String>,
    /// Extra environment variables (appended to the engine's `MSE_*`
    /// token exports). Values may carry placeholder tokens. `BTreeMap`
    /// for a deterministic wire order.
    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    pub env: std::collections::BTreeMap<String, String>,
    /// Child working directory (may carry placeholder tokens). `None` =
    /// the spawn-time `{work_dir}` source decides (or the engine default
    /// when no source exists).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cwd: Option<String>,
    /// stdout normalization declaration. `None` = the engine's historical
    /// JSON-or-raw behavior, byte-for-byte.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub output: Option<SubprocessOutput>,
    /// Streaming wire protocol for stdout (`"ndjson_lines"` /
    /// `"sse_events"` / `"length_prefixed"` — same vocabulary as the
    /// spec-based Subprocess path). `None` = plain mode.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stream_mode: Option<String>,
}

/// GH #83 — declarative stdout → worker-result normalization for a
/// [`SubprocessDef`] (plain mode only; streaming modes keep their event
/// protocol untouched).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct SubprocessOutput {
    /// Expected stdout format. `Some("json")` = stdout MUST parse as
    /// JSON (an unparsable stdout is a failed step). `None` = the
    /// historical lenient JSON-or-raw wrap.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub format: Option<String>,
    /// JSON Pointer (RFC 6901) selecting the worker-result value out of
    /// the parsed stdout (e.g. `"/result"`). `None` = the whole parsed
    /// value.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub result_ptr: Option<String>,
    /// Where the ok/failure signal comes from: `"exit_code"` (default
    /// behavior) or a JSON Pointer into the parsed stdout whose value
    /// must be boolean `true` for ok.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ok_from: Option<String>,
    /// Declarative stdout → per-step worker-stats mapping (token usage
    /// / model / num_turns), applied by the engine after a successful
    /// JSON parse. `None` = no stats extraction (the engine still
    /// records exit code + declared model as baseline stats).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stats: Option<SubprocessStats>,
}

/// Declarative stats extraction for a [`SubprocessOutput`] — JSON
/// Pointers (RFC 6901) into the parsed stdout, mirroring the
/// `result_ptr` idiom. Lets a declared CLI backend (e.g. `claude -p
/// --output-format json`, `codex exec --json`) surface token usage
/// without any engine-side backend branch. Same IN-immutability
/// discipline as the rest of this crate: pointers only, no logic.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct SubprocessStats {
    /// JSON Pointer selecting a usage OBJECT out of the parsed stdout.
    /// The engine reads `input_tokens`/`output_tokens` (falling back to
    /// the OpenAI-style `prompt_tokens`/`completion_tokens` spelling)
    /// and an optional `total_tokens` from it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub usage_ptr: Option<String>,
    /// JSON Pointer selecting the model name STRING that actually
    /// served the run (overrides the template's declared `{model}`
    /// value in the recorded stats when present).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model_ptr: Option<String>,
    /// JSON Pointer selecting the number of LLM turns (a JSON number).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub num_turns_ptr: Option<String>,
}

/// One [`Blueprint::runners`] registry entry — a named [`Runner`]
/// declaration referenced by `AgentDef.runner_ref` /
/// [`Blueprint::default_runner`]. Same registry shape as [`MetaDef`] (GH
/// #21 Phase 2).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RunnerDef {
    /// Registry key, referenced by `AgentDef.runner_ref` /
    /// `Blueprint.default_runner`.
    pub name: String,
    /// The declared Runner.
    pub runner: Runner,
}

/// Canonical GH #46 Worker unit: a resolved [`Runner`] paired with the
/// [`AgentDef`] it backs. The Milestone 4 adapter is the consumer that
/// turns this into a runtime spawn; this crate only declares the shape
/// (no execution logic lives here — see the crate doc's IN-immutability
/// discipline).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct WorkerModel {
    /// The resolved Runner.
    pub runner: Runner,
    /// The agent this Runner backs.
    pub agent: AgentDef,
}

/// Everything [`resolve_runner`] can fail with: an `AgentDef.runner_ref`
/// / `Blueprint.default_runner` reference that names no entry in
/// `Blueprint.runners`.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum RunnerResolveError {
    /// `AgentDef.runner_ref` names a [`RunnerDef::name`] absent from
    /// `Blueprint.runners`.
    #[error(
        "agent '{agent}' runner_ref '{ref_name}' does not match any RunnerDef.name in \
         Blueprint.runners (defined: {available:?})"
    )]
    UnknownRunnerRef {
        /// The agent whose `runner_ref` didn't resolve.
        agent: String,
        /// The `runner_ref` value that was looked up.
        ref_name: String,
        /// The `RunnerDef.name`s that *are* declared, for the error message.
        available: Vec<String>,
    },
    /// `Blueprint.default_runner` names a [`RunnerDef::name`] absent from
    /// `Blueprint.runners`.
    #[error(
        "default_runner '{ref_name}' does not match any RunnerDef.name in Blueprint.runners \
         (defined: {available:?})"
    )]
    UnknownDefaultRunner {
        /// The `default_runner` value that was looked up.
        ref_name: String,
        /// The `RunnerDef.name`s that *are* declared, for the error message.
        available: Vec<String>,
    },
}

/// Resolve `agent`'s effective [`Runner`] against `bp`, in cascade order
/// (highest priority first):
///
/// 1. `agent.runner` (inline declaration) — wins unconditionally.
/// 2. `agent.runner_ref`, resolved against `bp.runners` (an unresolved
///    name is [`RunnerResolveError::UnknownRunnerRef`]).
/// 3. Legacy fallback (agent-level): `agent.profile.worker_binding =
///    Some(variant)` becomes `Runner::WsClaudeCode { variant,
///    tools: profile.tools.clone() }` — the same synthesis
///    `crate::service::task_launch::derive_worker_bindings` (in the
///    `mlua-swarm` core crate) performs at launch time today.
/// 4. `bp.default_runner`, resolved against `bp.runners` (an unresolved
///    name is [`RunnerResolveError::UnknownDefaultRunner`]).
/// 5. `Ok(None)` — no Runner declared through any tier.
///
/// **Legacy (agent-level) beats `default_runner` (BP-global)**: tier 3
/// outranks tier 4, the same "agent-level wins over BP-global" rule the
/// ctx cascade (`AgentInline > MetaRef > BpGlobal`, see
/// `mlua-swarm`'s `core::explain::CtxTier`) already follows.
///
/// Pure and read-only: this Milestone does not wire the result into the
/// launch / compile path (Milestone 3 scope) — it only declares the
/// resolver.
pub fn resolve_runner(
    bp: &Blueprint,
    agent: &AgentDef,
) -> Result<Option<Runner>, RunnerResolveError> {
    // 1. inline — wins unconditionally.
    if let Some(runner) = &agent.runner {
        return Ok(Some(runner.clone()));
    }

    // 2. runner_ref → bp.runners lookup.
    if let Some(ref_name) = &agent.runner_ref {
        return match bp.runners.iter().find(|def| &def.name == ref_name) {
            Some(def) => Ok(Some(def.runner.clone())),
            None => Err(RunnerResolveError::UnknownRunnerRef {
                agent: agent.name.clone(),
                ref_name: ref_name.clone(),
                available: bp.runners.iter().map(|d| d.name.clone()).collect(),
            }),
        };
    }

    // 3. legacy fallback (agent-level `profile.worker_binding`) — outranks
    // `bp.default_runner` (tier 4).
    if let Some(variant) = agent
        .profile
        .as_ref()
        .and_then(|p| p.worker_binding.as_ref())
    {
        let tools = agent
            .profile
            .as_ref()
            .map(|p| p.tools.clone())
            .unwrap_or_default();
        return Ok(Some(Runner::WsClaudeCode {
            variant: variant.clone(),
            tools,
        }));
    }

    // 4. bp.default_runner → bp.runners lookup.
    if let Some(ref_name) = &bp.default_runner {
        return match bp.runners.iter().find(|def| &def.name == ref_name) {
            Some(def) => Ok(Some(def.runner.clone())),
            None => Err(RunnerResolveError::UnknownDefaultRunner {
                ref_name: ref_name.clone(),
                available: bp.runners.iter().map(|d| d.name.clone()).collect(),
            }),
        };
    }

    // 5. nothing declared through any tier.
    Ok(None)
}

/// Which declaration tier supplied a [`BoundAgent`]'s resolved Runner.
/// Kept in the immutable snapshot so explain surfaces can distinguish a
/// first-class binding from the Claude Code compatibility fallback.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RunnerResolutionSource {
    /// `AgentDef.runner`.
    AgentInline,
    /// `AgentDef.runner_ref` resolved through `Blueprint.runners`.
    AgentRef,
    /// Deprecated `AgentProfile.worker_binding` compatibility path.
    LegacyWorkerBinding,
    /// `Blueprint.default_runner` resolved through `Blueprint.runners`.
    BlueprintDefault,
    /// No Runner applies to this in-process or otherwise unbound agent.
    None,
}

/// Strongly typed identity of one immutable [`BoundAgent`] snapshot.
/// Transparent serde keeps the public JSON wire form a plain string.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, JsonSchema)]
#[serde(transparent)]
pub struct BindingDigest(String);

impl BindingDigest {
    /// Compute the canonical `sha256:<lowercase-hex>` digest of `bytes`.
    pub fn sha256(bytes: impl AsRef<[u8]>) -> Self {
        use sha2::Digest as _;
        Self(format!(
            "sha256:{}",
            hex::encode(sha2::Sha256::digest(bytes.as_ref()))
        ))
    }

    /// Borrow the stable wire representation.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for BindingDigest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::str::FromStr for BindingDigest {
    type Err = BindingDigestParseError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let Some(hex_part) = value.strip_prefix("sha256:") else {
            return Err(BindingDigestParseError::InvalidFormat(value.to_string()));
        };
        let canonical = hex_part.len() == 64
            && hex_part
                .bytes()
                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
        if !canonical {
            return Err(BindingDigestParseError::InvalidFormat(value.to_string()));
        }
        Ok(Self(value.to_string()))
    }
}

impl<'de> Deserialize<'de> for BindingDigest {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use std::str::FromStr as _;
        let value = String::deserialize(deserializer)?;
        Self::from_str(&value).map_err(serde::de::Error::custom)
    }
}

/// Rejection returned when an external binding digest is not in canonical
/// `sha256:<64 lowercase hex>` form.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum BindingDigestParseError {
    /// Unsupported algorithm prefix, wrong length, uppercase, or non-hex.
    #[error("invalid binding digest '{0}'; expected sha256:<64 lowercase hex>")]
    InvalidFormat(String),
}

/// Platform-neutral request sent to an [`AgentBindingProvider`](https://docs.rs/mlua-swarm)
/// before a Run is dispatched.
///
/// The request contains only Swarm declarations. A provider may resolve
/// platform aliases or inspect its own execution environment, but Swarm
/// validates the returned [`BindReceipt`] before accepting it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct BindRequest {
    /// Logical agent name; the receipt correlation key.
    pub agent: String,
    /// Digest of the declaration-only [`BoundAgent`] snapshot.
    pub request_digest: BindingDigest,
    /// Runner backend family Core resolved for this agent.
    pub backend: BindingBackend,
    /// Provider-specific routing key. For Operator-backed runners this is
    /// the logical `operator_ref`, never a runtime session id.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub binding_target: Option<String>,
    /// Requested model name or tier from [`AgentProfile::model`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub requested_model: Option<String>,
    /// Minimum tool grant declared by the resolved [`Runner`].
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub requested_tools: Vec<String>,
    /// Platform launch variant requested by the resolved [`Runner`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub launch_variant: Option<String>,
}

/// Backend family a binding provider must resolve.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum BindingBackend {
    /// Platform-neutral Operator/MainAI WebSocket execution.
    WsOperator,
    /// Claude Code wrapper dispatched through an Operator WebSocket.
    WsClaudeCode,
    /// AgentBlock registry enforced in the Server process.
    AgentBlockInProcess,
}

/// Provider report describing the effective runtime binding for one agent.
/// This value is untrusted until Swarm validates it against [`BindRequest`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct BindReceipt {
    /// Logical agent name copied from the request.
    pub agent: String,
    /// Declaration digest copied from the request. Core rejects stale or
    /// cross-request receipts even when the logical agent name matches.
    pub request_digest: BindingDigest,
    /// Stable provider implementation identifier.
    pub provider_id: String,
    /// Provider or adapter revision used to resolve the binding.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider_revision: Option<String>,
    /// Effective model after platform alias/tier resolution.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resolved_model: Option<String>,
    /// Effective tool grant enforced by the execution environment.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub effective_tools: Vec<String>,
    /// Effective platform launch variant.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub launch_variant: Option<String>,
    /// Optional digest of the provider-observed capability snapshot. This is
    /// a drift/lint correlation key, not independent security evidence.
    #[serde(
        default,
        alias = "evidence_digest",
        skip_serializing_if = "Option::is_none"
    )]
    pub capability_snapshot_digest: Option<BindingDigest>,
}

/// One provider outcome for a single [`BindRequest`].
///
/// A provider reports exactly one outcome per requested agent. `Bound`
/// carries an (untrusted) [`BindReceipt`] Core still validates; `Unbound`
/// records that the execution environment currently offers no capability for
/// the request (e.g. the role has not joined, or the manifest declares no
/// matching launch variant). Whether an `Unbound` outcome fails the launch
/// or is merely observed is decided by
/// [`CompilerStrategy::strict_binding`] — not by the provider.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "outcome", rename_all = "snake_case", deny_unknown_fields)]
pub enum BindOutcome {
    /// The provider resolved a receipt for the agent. Still untrusted until
    /// Core validates it against the originating [`BindRequest`].
    Bound {
        /// Provider-reported binding, validated by Core before acceptance.
        receipt: BindReceipt,
    },
    /// The provider offers no capability for the request right now. The
    /// `reason` is human-facing diagnostic text only; it never enters the
    /// [`BoundAgent`] snapshot or its digest lineage.
    Unbound {
        /// Logical agent name copied from the request.
        agent: String,
        /// Why the provider could not bind the agent.
        reason: String,
    },
}

/// Core-validated capability statement pinned into a [`BoundAgent`].
///
/// It deliberately omits the logical agent name because the containing
/// snapshot already supplies that identity.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct BindingAttestation {
    /// Declaration-only digest the provider attested.
    pub request_digest: BindingDigest,
    /// Stable provider implementation identifier.
    pub provider_id: String,
    /// Provider or adapter revision used to resolve the binding.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider_revision: Option<String>,
    /// Effective model after platform alias/tier resolution.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resolved_model: Option<String>,
    /// Effective tool grant, canonicalized by Swarm.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub effective_tools: Vec<String>,
    /// Effective platform launch variant.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub launch_variant: Option<String>,
    /// Optional digest of the provider-observed capability snapshot.
    #[serde(
        default,
        alias = "evidence_digest",
        skip_serializing_if = "Option::is_none"
    )]
    pub capability_snapshot_digest: Option<BindingDigest>,
}

/// One effective capability advertised by an execution-environment
/// provider. Operator manifests normally publish one entry per wrapper
/// variant.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct AgentProviderCapability {
    /// Platform launch variant this capability serves. `None` is reserved
    /// for backends without a variant axis.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub launch_variant: Option<String>,
    /// Effective model selected by the provider.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resolved_model: Option<String>,
    /// Effective tool grant enforced by the provider.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub effective_tools: Vec<String>,
    /// Optional digest of the provider-observed capability snapshot.
    #[serde(
        default,
        alias = "evidence_digest",
        skip_serializing_if = "Option::is_none"
    )]
    pub capability_snapshot_digest: Option<BindingDigest>,
}

/// Capability manifest supplied by an Operator/MainAI or an official
/// execution-platform plugin when joining the Server.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct AgentProviderManifest {
    /// Stable provider implementation identifier.
    pub provider_id: String,
    /// Provider or adapter revision used to inspect capabilities.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider_revision: Option<String>,
    /// Effective capabilities available through this provider instance.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub capabilities: Vec<AgentProviderCapability>,
}

/// Immutable, Run-scoped result of binding the Runner / Agent / Context
/// layers for one logical agent.
///
/// This is derived state, not a fourth authoring source of truth. The full
/// [`AgentDef`] is retained deliberately: resume/replay must not re-read a
/// changed role prompt or result contract from a mutable Blueprint registry.
/// Capability attestation is adapter-owned and is therefore not guessed here;
/// the resolved [`Runner`] remains a declaration until an adapter records its
/// requested/effective comparison.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct BoundAgent {
    /// Logical agent definition pinned for the Run.
    pub agent: AgentDef,
    /// Runner selected by [`resolve_runner`], if this agent needs one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub runner: Option<Runner>,
    /// Effective static Context policy (`AgentMeta.context_policy` wins over
    /// `Blueprint.default_context_policy`). Runtime context values are not
    /// embedded here.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub context_policy: Option<ContextPolicy>,
    /// Declaration tier that supplied `runner`.
    pub runner_source: RunnerResolutionSource,
    /// Effective capability statement accepted from the injected binding
    /// provider. `None` preserves the declaration-only compatibility path.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attestation: Option<BindingAttestation>,
    /// SHA-256 over the other fields of this snapshot, prefixed with
    /// `sha256:`. This is replay identity and an observability correlation
    /// key, not a signature.
    pub binding_digest: BindingDigest,
}

/// Failure while constructing immutable [`BoundAgent`] snapshots.
#[derive(Debug, thiserror::Error)]
pub enum BoundAgentResolveError {
    /// A Runner reference did not resolve.
    #[error(transparent)]
    Runner(#[from] RunnerResolveError),
    /// The snapshot input could not be serialized for deterministic hashing.
    #[error("bound agent '{agent}' could not be serialized for digest: {source}")]
    Digest {
        /// Logical agent name.
        agent: String,
        /// Serialization failure.
        source: serde_json::Error,
    },
    /// Strict binding rejected the deprecated Claude Code compatibility
    /// declaration instead of silently accepting it.
    #[error(
        "agent '{agent}' uses deprecated profile.worker_binding; strict binding requires runner or runner_ref"
    )]
    LegacyWorkerBindingDisabled {
        /// Logical agent that must be migrated.
        agent: String,
    },
}

#[derive(Serialize)]
struct BoundAgentDigestInput<'a> {
    agent: &'a AgentDef,
    runner: &'a Option<Runner>,
    context_policy: &'a Option<ContextPolicy>,
    runner_source: RunnerResolutionSource,
    attestation: &'a Option<BindingAttestation>,
}

impl BoundAgent {
    /// Replace the effective capability attestation and recompute replay
    /// identity over the complete immutable snapshot.
    pub fn set_attestation(
        &mut self,
        attestation: BindingAttestation,
    ) -> Result<(), BoundAgentResolveError> {
        self.attestation = Some(attestation);
        self.recompute_binding_digest()
    }

    /// Recompute `binding_digest` after a trusted snapshot mutation.
    pub fn recompute_binding_digest(&mut self) -> Result<(), BoundAgentResolveError> {
        let digest_input = BoundAgentDigestInput {
            agent: &self.agent,
            runner: &self.runner,
            context_policy: &self.context_policy,
            runner_source: self.runner_source,
            attestation: &self.attestation,
        };
        let bytes =
            serde_json::to_vec(&digest_input).map_err(|source| BoundAgentResolveError::Digest {
                agent: self.agent.name.clone(),
                source,
            })?;
        self.binding_digest = BindingDigest::sha256(bytes);
        Ok(())
    }
}

/// Resolve every `Blueprint.agents` entry into an immutable Run snapshot.
/// Output order follows `Blueprint.agents`, making persistence and explain
/// responses stable without a second sort.
pub fn resolve_bound_agents(bp: &Blueprint) -> Result<Vec<BoundAgent>, BoundAgentResolveError> {
    resolve_bound_agents_with_legacy(bp, true)
}

/// Strict counterpart to [`resolve_bound_agents`]: rejects the deprecated
/// `profile.worker_binding` fallback. This is the migration gate for callers
/// that require every binding to use the platform-neutral Runner contract.
pub fn resolve_bound_agents_strict(
    bp: &Blueprint,
) -> Result<Vec<BoundAgent>, BoundAgentResolveError> {
    resolve_bound_agents_with_legacy(bp, false)
}

fn resolve_bound_agents_with_legacy(
    bp: &Blueprint,
    allow_legacy: bool,
) -> Result<Vec<BoundAgent>, BoundAgentResolveError> {
    bp.agents
        .iter()
        .map(|agent| {
            let runner = resolve_runner(bp, agent)?;
            let runner_source = if agent.runner.is_some() {
                RunnerResolutionSource::AgentInline
            } else if agent.runner_ref.is_some() {
                RunnerResolutionSource::AgentRef
            } else if agent
                .profile
                .as_ref()
                .and_then(|p| p.worker_binding.as_ref())
                .is_some()
            {
                RunnerResolutionSource::LegacyWorkerBinding
            } else if bp.default_runner.is_some() {
                RunnerResolutionSource::BlueprintDefault
            } else {
                RunnerResolutionSource::None
            };
            if !allow_legacy && runner_source == RunnerResolutionSource::LegacyWorkerBinding {
                return Err(BoundAgentResolveError::LegacyWorkerBindingDisabled {
                    agent: agent.name.clone(),
                });
            }
            let context_policy = agent
                .meta
                .as_ref()
                .and_then(|m| m.context_policy.clone())
                .or_else(|| bp.default_context_policy.clone());
            let digest_input = BoundAgentDigestInput {
                agent,
                runner: &runner,
                context_policy: &context_policy,
                runner_source,
                attestation: &None,
            };
            let bytes = serde_json::to_vec(&digest_input).map_err(|source| {
                BoundAgentResolveError::Digest {
                    agent: agent.name.clone(),
                    source,
                }
            })?;
            let binding_digest = BindingDigest::sha256(bytes);
            Ok(BoundAgent {
                agent: agent.clone(),
                runner,
                context_policy,
                runner_source,
                attestation: None,
                binding_digest,
            })
        })
        .collect()
}

// ──────────────────────────────────────────────────────────────────────────
// OperatorDef / OperatorKind
// ──────────────────────────────────────────────────────────────────────────

/// Kind axis of an Operator role (= "in which mode does this Operator run").
/// Corresponds 1:1 with the engine's runtime `OperatorKind`. Kept as a schema
/// duplicate so that BPs can be authored while depending only on this crate.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum OperatorKind {
    /// MainAI (= interactive AI Operator via WS client or SDK).
    MainAi,
    /// Automate (= normal spawn path, without human interception).
    #[default]
    Automate,
    /// Composite (= MainAi + Automate running side by side).
    Composite,
}

/// Design-time definition of an Operator role (first-class).
///
/// `AgentDef.spec.operator_ref` references this struct's `name` as a logical role name.
/// Binding to a runtime backend (WS session / SDK / pool, etc.) is established via the
/// attach path; the BP side only declares "under this logical name we expect an Operator
/// of this Kind".
///
/// `spec` is an escape hatch for kind-specific config (WS endpoint / SDK profile / pool
/// binding, etc.). Even when empty, declaring `name` + `kind` alone is enough for
/// compile-time validation to succeed (= it guarantees that agent `operator_ref` values
/// reference an existing definition).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct OperatorDef {
    /// Logical role name (= design-time symbol referenced from `AgentDef.spec.operator_ref`).
    pub name: String,
    /// Display name for UI / docs (optional).
    #[serde(default)]
    pub display_name: Option<String>,
    /// Kind axis of the Operator (MainAi / Automate / Composite) — the "BP
    /// Agent-level" tier of the 4-tier `OperatorKind` cascade (see
    /// `Blueprint.default_operator_kind` for the full tier list). `None`
    /// when this `OperatorDef` does not declare a kind; the resolver then
    /// falls through to BP Global / Default Fallback for agents referencing
    /// this role via `AgentDef.spec.operator_ref`.
    #[serde(default)]
    pub kind: Option<OperatorKind>,
    /// Kind-specific config (WS endpoint / SDK profile / pool binding, etc.). Interpreted
    /// by the factory.
    #[serde(default)]
    pub spec: Value,
    /// Operator persona information (e.g. system_prompt template). Same shape as
    /// `AgentDef.profile`. Used as a template when the Operator itself plays a "role".
    /// If `None`, the agent-side profile is used instead.
    #[serde(default)]
    pub profile: Option<AgentProfile>,
    /// Operator-level metadata (description / version / tags).
    #[serde(default)]
    pub meta: Option<AgentMeta>,
}

/// Named, multi-step-shared declarative context payload (GH #21 Phase 2).
///
/// Lives in the [`Blueprint::metas`] pool and is referenced by name from
/// two independent consumers: a `$step_meta.ref` envelope embedded in a
/// Step's evaluated `in` value (the Step tier, resolved by
/// `EngineDispatcher::dispatch` in the `mlua-swarm` core crate at
/// dispatch time — see `EngineDispatcher::with_step_metas`), and
/// [`AgentMeta::meta_ref`] (the Agent tier, resolved at launch time and
/// merged UNDER the agent's inline `AgentMeta::ctx`). The pool lets
/// multiple Steps and/or Agents share one declarative context object by
/// name instead of repeating it inline.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct MetaDef {
    /// Logical name (= referenced by `$step_meta.ref` and
    /// `AgentMeta.meta_ref`; unique within [`Blueprint::metas`]).
    pub name: String,
    /// Declarative context payload. Consumers expect a JSON `Object` so
    /// it can be shallow-merged with an `inline` override / an agent's
    /// own `ctx` (a non-`Object` value is rejected — loudly at dispatch
    /// time for the Step tier, defensively (warn + skip) at launch time
    /// for the Agent tier); the shape is otherwise free-form.
    pub ctx: Value,
}

/// GH #27 (follow-up to #23) — Blueprint-declared override of the
/// `mlua-swarm` core crate's placement resolver
/// (`mlua_swarm::core::projection_placement::ProjectionPlacement`), which
/// decides where a Step's materialized OUTPUT file (submit-time sink,
/// server read-back, and spawn-time `ctx_projection` pointer — the "3
/// path" convergence point) is written on disk. Both fields are
/// independently optional and validated (`dir_template`) at
/// `Compiler::compile` time — see that resolver's `from_spec` doc for the
/// full rejection rules.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ProjectionPlacementSpec {
    /// Which of the spawn-time `work_dir` / `project_root` to prefer as
    /// the materialize root, falling back to the other when the
    /// preferred one is absent. `"work_dir"` (default, current
    /// byte-compat behavior) | `"project_root"`. `None` = the default
    /// (`"work_dir"`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub root: Option<String>,
    /// Target directory template, relative to the resolved root, with a
    /// `{task_id}` placeholder substituted at materialize time. `None` =
    /// the default (`"workspace/tasks/{task_id}/ctx"`, current byte-compat
    /// behavior). Must be non-empty, contain the `{task_id}` placeholder,
    /// stay relative, and not contain any `..` path segment — rejected at
    /// `Compiler::compile` time otherwise.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dir_template: Option<String>,
}

/// Agent / Operator level metadata (description / version / tags).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct AgentMeta {
    /// Short human-readable description.
    #[serde(default)]
    pub description: Option<String>,
    /// Free-form version label.
    #[serde(default)]
    pub version: Option<String>,
    /// Tag list for classification / routing.
    #[serde(default)]
    pub tags: Vec<String>,
    /// GH #21 Phase 1 — "BP Agent-level" tier of the agent-context supply
    /// axis: a declarative object merged into `ctx.meta.runtime` for this
    /// agent's spawns, on top of (and winning over)
    /// [`Blueprint::default_agent_ctx`]. See that field's doc for the
    /// contrast with `default_init_ctx`. `None` = this agent declares no
    /// per-agent context (the BP-global tier alone applies, if any).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(with = "Option<Value>")]
    pub ctx: Option<Value>,
    /// GH #21 Phase 1 — "BP Agent-level" tier of the [`ContextPolicy`]
    /// cascade: outranks [`Blueprint::default_context_policy`] for this
    /// agent. `None` = fall through to the BP-global policy (or pass-all
    /// if that is also `None`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub context_policy: Option<ContextPolicy>,
    /// GH #21 Phase 2 — "BP Agent-level" tier of the [`MetaDef`] pool:
    /// resolves against [`Blueprint::metas`] by name. The resolved
    /// `ctx` sits UNDER this agent's inline [`Self::ctx`] (inline wins
    /// on key collision). `None` = this agent declares no shared
    /// `MetaDef` reference.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub meta_ref: Option<String>,
    /// GH #23 — the step-projection canonical name this agent's dispatched
    /// Steps should be addressed by (data-plane submit / `ContextPolicy`
    /// filter / `StepPointer`/`StepSummary` `name` / REST `:step` path /
    /// materialized file stem — see `mlua-swarm` core's
    /// `core::step_naming::StepNaming` for the table this field feeds).
    /// `None` = this agent declares no projection name; the canonical
    /// name falls back to the Step's `ref` (the flow.ir data-plane
    /// producer name), matching pre-GH-#23 behavior byte-for-byte.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub projection_name: Option<String>,
}

// ──────────────────────────────────────────────────────────────────────────
// Compiler hints / strategy
// ──────────────────────────────────────────────────────────────────────────

/// Per-agent overrides / hints. Interpreted by the Compiler / SpawnerFactory; not required.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct CompilerHints {
    /// Agent name → per-agent hint (= passed to `SpawnerFactory.build`).
    #[serde(default)]
    pub per_agent: HashMap<String, Value>,
    /// Global hints (= e.g. parallel limit, default timeout, ...).
    #[serde(default)]
    pub global: Value,
}

/// Compiler behavior rules. Controls strict / lenient handling and default fallback.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct CompilerStrategy {
    /// If `true` (default), an unresolved `Step.ref` is an error; if `false`, it falls
    /// through to the default Spawner.
    #[serde(default = "default_true")]
    pub strict_refs: bool,
    /// If `true` (default), an `AgentKind` missing from the registry is an error; if
    /// `false`, it is skipped.
    #[serde(default = "default_true")]
    pub strict_kind: bool,
    /// If `true`, every Runner-backed agent must obtain a Core-validated
    /// attestation at launch (a binding provider is required, and any agent
    /// the provider leaves `Unbound` fails the launch). If `false` (default),
    /// an unattested agent runs `DeclarationOnly` and the gap is only
    /// observed (tracing warn + a `RunRecord.degradations` entry).
    ///
    /// This default is deliberately the opposite of `strict_refs` /
    /// `strict_kind` (both default `true`): those two guard *structural
    /// integrity* of the Blueprint itself (an unresolved ref or unknown kind
    /// is always a Blueprint bug), whereas binding attestation is an
    /// *execution-assurance opt-in* — it depends on an execution environment
    /// being present to attest against, which is not available for embed-only
    /// or manifest-less launches. Requiring it by default would break every
    /// launch that has no provider, so it is opt-in per Blueprint.
    #[serde(default)]
    pub strict_binding: bool,
}

fn default_true() -> bool {
    true
}

impl Default for CompilerStrategy {
    fn default() -> Self {
        Self {
            strict_refs: true,
            strict_kind: true,
            strict_binding: false,
        }
    }
}

// ──────────────────────────────────────────────────────────────────────────
// Blueprint metadata / origin
// ──────────────────────────────────────────────────────────────────────────

/// Blueprint-level metadata (description / origin / tags / ttl / version label / alias).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct BlueprintMetadata {
    /// Short human-readable description of the Blueprint.
    #[serde(default)]
    pub description: Option<String>,
    /// Provenance record (inline / file / algocline).
    #[serde(default)]
    pub origin: BlueprintOrigin,
    /// Tag list for classification / routing.
    #[serde(default)]
    pub tags: Vec<String>,
    /// Optional SemVer label (= match target for `TaskPipeline VersionSelector::SemVerReq`).
    /// Example: `"1.2.3"`. Rewritten by `EnhanceAdapter` on PATCH/MINOR/MAJOR bumps.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version_label: Option<String>,
    /// Optional LDS session alias label. The Swarm engine itself does not apply this
    /// (= it is free-form content); the value is expanded into the Spawn directive and
    /// reaches the MainAI. The MainAI is expected to establish a task session via
    /// `mcp__lds__session_create(root=..., alias=<this>)`, and to inject
    /// `LDS Session Alias: <this>` verbatim into the SubAgent dispatch prompt body.
    /// The SubAgent body then calls `mcp__lds__session_start(alias=<this>)` with the
    /// received alias. Worktree ownership is thereby unified under a single session, and
    /// cross-SubAgent / cross-worktree ownership blocks (= `not owned by this session`)
    /// cannot fire structurally.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub project_name_alias: Option<String>,
    /// Optional default TTL (seconds) for tasks dispatched via this BP. Estimated by the
    /// Blueprint author from the flow shape (agent count × expected duration per agent).
    /// If `POST /v1/tasks` supplies `ttl_secs` explicitly, the body value wins; otherwise
    /// this metadata field is used as the default; if both are absent, the server global
    /// default (`default_run_ttl()` = 1800s) applies. Not needed for short chains (~5 min);
    /// recommended for long chains (14 agents × several minutes = 30-60 min).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_run_ttl_secs: Option<u64>,
    /// GH #50 follow-up (issue `33bc825b`): promote `VerdictValueUnhandled`
    /// compile-time lint to a hard error. When `false` (or absent), a
    /// declared `AgentDef.verdict.values` entry that no downstream cond
    /// references is only surfaced via `tracing::warn!` (informational);
    /// when `true`, `Compiler::compile` rejects the Blueprint with
    /// `CompileError::VerdictValueUnhandled`. Opt-in so existing Blueprints
    /// that intentionally leave some verdict values as silent-pass
    /// informational tokens keep compiling unchanged.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub strict_verdict_handling: Option<bool>,
}

/// Provenance record of a Blueprint.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum BlueprintOrigin {
    /// Inline construction, e.g. via a Rust struct literal or test code.
    #[default]
    Inline,
    /// Loaded from a file.
    File {
        /// Source file path.
        path: String,
    },
    /// Emitted by an algocline strategy (traced by `session_id`).
    Algo {
        /// Algocline session identifier.
        session_id: String,
    },
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn schema_version_default_parses() {
        let v = default_schema_version();
        assert_eq!(v.to_string(), "0.1.0");
    }

    #[test]
    fn current_schema_version_const_matches() {
        assert_eq!(CURRENT_SCHEMA_VERSION, "0.1.0");
    }

    #[test]
    fn blueprint_json_schema_exports_key_properties() {
        let schema = schemars::schema_for!(Blueprint);
        let v = serde_json::to_value(&schema).expect("schema serializes");
        let props = v["properties"].as_object().expect("object schema");
        for key in [
            "schema_version",
            "id",
            "flow",
            "agents",
            "operators",
            "metas",
            "hints",
            "strategy",
            "metadata",
            "spawner_hints",
            "default_agent_kind",
            "default_operator_kind",
            "default_init_ctx",
            "default_agent_ctx",
            "default_context_policy",
            "projection_placement",
            "audits",
            "runners",
            "default_runner",
            "check_policy",
        ] {
            assert!(props.contains_key(key), "missing property: {key}");
        }
        // semver override lands as a plain string
        assert_eq!(v["properties"]["schema_version"]["type"], "string");
        // enum variants (snake_case) survive into the schema (LLM author axis)
        let dump = v.to_string();
        assert!(dump.contains("agent_block"), "AgentKind variants in schema");
        assert!(dump.contains("main_ai"), "OperatorKind variants in schema");
        // nested defs are referenced (AgentDef reachable from agents[])
        assert!(dump.contains("AgentDef"), "AgentDef definition in schema");
    }

    #[test]
    fn agent_profile_worker_binding_roundtrips_when_some() {
        let profile = AgentProfile {
            worker_binding: Some("code-worker".to_string()),
            ..Default::default()
        };
        let json = serde_json::to_value(&profile).expect("serializes");
        assert_eq!(json["worker_binding"], "code-worker");
        let back: AgentProfile = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back.worker_binding.as_deref(), Some("code-worker"));
    }

    #[test]
    fn agent_profile_worker_binding_omitted_when_none() {
        let profile = AgentProfile::default();
        let json = serde_json::to_value(&profile).expect("serializes");
        // `skip_serializing_if = "Option::is_none"` — the key must not appear at all.
        assert!(
            json.as_object().unwrap().get("worker_binding").is_none(),
            "worker_binding key must be absent when None: {json}"
        );
        let back: AgentProfile = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back.worker_binding, None);
    }

    // ──────────────────────────────────────────────────────────────
    // issue #19 ST3: `Blueprint.default_init_ctx`
    // ──────────────────────────────────────────────────────────────

    fn minimal_bp(default_init_ctx: Option<Value>) -> Blueprint {
        Blueprint {
            schema_version: current_schema_version(),
            id: "bp-init-ctx-ut".into(),
            flow: FlowNode::Seq { children: vec![] },
            agents: vec![],
            operators: vec![],
            metas: vec![],
            hints: Default::default(),
            strategy: Default::default(),
            metadata: Default::default(),
            spawner_hints: Default::default(),
            default_agent_kind: AgentKind::Operator,
            default_operator_kind: None,
            default_init_ctx,
            default_agent_ctx: None,
            default_context_policy: None,
            projection_placement: None,
            audits: vec![],
            degradation_policy: None,
            runners: vec![],
            default_runner: None,
            subprocesses: vec![],
            check_policy: None,
            blueprint_ref_includes: Vec::new(),
        }
    }

    #[test]
    fn blueprint_default_init_ctx_roundtrips_when_some() {
        let bp = minimal_bp(Some(serde_json::json!({ "seeded": true })));
        let json = serde_json::to_string(&bp).expect("serializes");
        let back: Blueprint = serde_json::from_str(&json).expect("deserializes");
        assert_eq!(
            back.default_init_ctx,
            Some(serde_json::json!({ "seeded": true }))
        );
        assert_eq!(bp, back);
    }

    #[test]
    fn blueprint_default_init_ctx_omitted_when_none() {
        let bp = minimal_bp(None);
        let json = serde_json::to_value(&bp).expect("serializes");
        // `skip_serializing_if = "Option::is_none"` — the key must not appear at all
        // (pre-#19 Blueprints round-trip byte-identical through this path).
        assert!(
            json.as_object().unwrap().get("default_init_ctx").is_none(),
            "default_init_ctx key must be absent when None: {json}"
        );
        let back: Blueprint = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back.default_init_ctx, None);
        assert_eq!(bp, back);
    }

    #[test]
    fn blueprint_json_schema_exports_default_init_ctx_as_nullable_value() {
        let schema = schemars::schema_for!(Blueprint);
        let v = serde_json::to_value(&schema).expect("schema serializes");
        assert!(
            v["properties"]["default_init_ctx"].is_object(),
            "default_init_ctx must appear in the exported schema: {v}"
        );
    }

    // ──────────────────────────────────────────────────────────────
    // issue #21 Phase 1: `Blueprint.default_agent_ctx` /
    // `default_context_policy`, `AgentMeta.ctx` / `context_policy`,
    // `ContextPolicy`
    // ──────────────────────────────────────────────────────────────

    #[test]
    fn blueprint_default_agent_ctx_and_context_policy_roundtrip_when_some() {
        let mut bp = minimal_bp(None);
        bp.default_agent_ctx = Some(serde_json::json!({ "org_conventions": "x" }));
        bp.default_context_policy = Some(ContextPolicy {
            include: Some(vec!["project_root".to_string()]),
            exclude: vec!["work_dir".to_string()],
            ..Default::default()
        });
        let json = serde_json::to_string(&bp).expect("serializes");
        let back: Blueprint = serde_json::from_str(&json).expect("deserializes");
        assert_eq!(bp, back);
        assert_eq!(
            back.default_agent_ctx,
            Some(serde_json::json!({ "org_conventions": "x" }))
        );
        assert_eq!(
            back.default_context_policy,
            Some(ContextPolicy {
                include: Some(vec!["project_root".to_string()]),
                exclude: vec!["work_dir".to_string()],
                ..Default::default()
            })
        );
    }

    #[test]
    fn blueprint_default_agent_ctx_and_context_policy_omitted_when_none() {
        let bp = minimal_bp(None);
        let json = serde_json::to_value(&bp).expect("serializes");
        let obj = json.as_object().unwrap();
        assert!(
            obj.get("default_agent_ctx").is_none(),
            "default_agent_ctx key must be absent when None: {json}"
        );
        assert!(
            obj.get("default_context_policy").is_none(),
            "default_context_policy key must be absent when None: {json}"
        );
        let back: Blueprint = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back.default_agent_ctx, None);
        assert_eq!(back.default_context_policy, None);
        assert_eq!(bp, back);
    }

    #[test]
    fn blueprint_json_schema_exports_agent_ctx_and_context_policy() {
        let schema = schemars::schema_for!(Blueprint);
        let v = serde_json::to_value(&schema).expect("schema serializes");
        assert!(
            v["properties"]["default_agent_ctx"].is_object(),
            "default_agent_ctx must appear in the exported schema: {v}"
        );
        assert!(
            v["properties"]["default_context_policy"].is_object(),
            "default_context_policy must appear in the exported schema: {v}"
        );
    }

    // ──────────────────────────────────────────────────────────────
    // GH #27 (follow-up to #23): `Blueprint.projection_placement` /
    // `ProjectionPlacementSpec`
    // ──────────────────────────────────────────────────────────────

    #[test]
    fn blueprint_projection_placement_roundtrips_when_some() {
        let mut bp = minimal_bp(None);
        bp.projection_placement = Some(ProjectionPlacementSpec {
            root: Some("project_root".to_string()),
            dir_template: Some("custom/{task_id}/out".to_string()),
        });
        let json = serde_json::to_string(&bp).expect("serializes");
        let back: Blueprint = serde_json::from_str(&json).expect("deserializes");
        assert_eq!(bp, back);
        assert_eq!(
            back.projection_placement,
            Some(ProjectionPlacementSpec {
                root: Some("project_root".to_string()),
                dir_template: Some("custom/{task_id}/out".to_string()),
            })
        );
    }

    #[test]
    fn blueprint_projection_placement_omitted_when_none() {
        let bp = minimal_bp(None);
        let json = serde_json::to_value(&bp).expect("serializes");
        assert!(
            json.as_object()
                .unwrap()
                .get("projection_placement")
                .is_none(),
            "projection_placement key must be absent when None: {json}"
        );
        let back: Blueprint = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back.projection_placement, None);
        assert_eq!(bp, back);
    }

    #[test]
    fn blueprint_json_schema_exports_projection_placement() {
        let schema = schemars::schema_for!(Blueprint);
        let v = serde_json::to_value(&schema).expect("schema serializes");
        assert!(
            v["properties"]["projection_placement"].is_object(),
            "projection_placement must appear in the exported schema: {v}"
        );
    }

    #[test]
    fn agent_meta_ctx_and_context_policy_roundtrip_when_some() {
        let meta = AgentMeta {
            ctx: Some(serde_json::json!({ "k": "v" })),
            context_policy: Some(ContextPolicy {
                include: None,
                exclude: vec!["run_id".to_string()],
                ..Default::default()
            }),
            ..Default::default()
        };
        let json = serde_json::to_value(&meta).expect("serializes");
        let back: AgentMeta = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back, meta);
    }

    #[test]
    fn agent_meta_ctx_and_context_policy_omitted_when_none() {
        let meta = AgentMeta::default();
        let json = serde_json::to_value(&meta).expect("serializes");
        let obj = json.as_object().unwrap();
        assert!(
            obj.get("ctx").is_none(),
            "ctx key must be absent when None: {json}"
        );
        assert!(
            obj.get("context_policy").is_none(),
            "context_policy key must be absent when None: {json}"
        );
    }

    #[test]
    fn agent_meta_json_schema_exports_ctx_context_policy_and_meta_ref() {
        let schema = schemars::schema_for!(AgentMeta);
        let v = serde_json::to_value(&schema).expect("schema serializes");
        let props = v["properties"].as_object().expect("object schema");
        for key in [
            "description",
            "version",
            "tags",
            "ctx",
            "context_policy",
            "meta_ref",
            "projection_name",
        ] {
            assert!(props.contains_key(key), "missing property: {key}");
        }
    }

    // ──────────────────────────────────────────────────────────────
    // issue #21 Phase 2: `MetaDef`, `Blueprint.metas`, `AgentMeta.meta_ref`
    // ──────────────────────────────────────────────────────────────

    #[test]
    fn meta_def_roundtrips_through_json() {
        let def = MetaDef {
            name: "heavy-scan".to_string(),
            ctx: serde_json::json!({ "work_dir": "/x" }),
        };
        let json = serde_json::to_value(&def).expect("serializes");
        let back: MetaDef = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back, def);
    }

    #[test]
    fn blueprint_metas_omitted_when_empty() {
        let bp = minimal_bp(None);
        let json = serde_json::to_value(&bp).expect("serializes");
        assert!(
            json.as_object().unwrap().get("metas").is_none(),
            "metas key must be absent when empty: {json}"
        );
        let back: Blueprint = serde_json::from_value(json).expect("deserializes");
        assert!(back.metas.is_empty());
        assert_eq!(bp, back);
    }

    #[test]
    fn blueprint_metas_roundtrips_when_non_empty() {
        let mut bp = minimal_bp(None);
        bp.metas = vec![MetaDef {
            name: "heavy-scan".to_string(),
            ctx: serde_json::json!({ "work_dir": "/x" }),
        }];
        let json = serde_json::to_string(&bp).expect("serializes");
        let back: Blueprint = serde_json::from_str(&json).expect("deserializes");
        assert_eq!(bp, back);
        assert_eq!(back.metas.len(), 1);
        assert_eq!(back.metas[0].name, "heavy-scan");
    }

    #[test]
    fn blueprint_json_schema_exports_metas() {
        let schema = schemars::schema_for!(Blueprint);
        let v = serde_json::to_value(&schema).expect("schema serializes");
        assert!(
            v["properties"]["metas"].is_object(),
            "metas must appear in the exported schema: {v}"
        );
        let dump = v.to_string();
        assert!(dump.contains("MetaDef"), "MetaDef definition in schema");
    }

    #[test]
    fn agent_meta_meta_ref_roundtrips_when_some() {
        let meta = AgentMeta {
            meta_ref: Some("heavy-scan".to_string()),
            ..Default::default()
        };
        let json = serde_json::to_value(&meta).expect("serializes");
        assert_eq!(json["meta_ref"], "heavy-scan");
        let back: AgentMeta = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back, meta);
    }

    #[test]
    fn agent_meta_meta_ref_omitted_when_none() {
        let meta = AgentMeta::default();
        let json = serde_json::to_value(&meta).expect("serializes");
        assert!(
            json.as_object().unwrap().get("meta_ref").is_none(),
            "meta_ref key must be absent when None: {json}"
        );
        let back: AgentMeta = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back.meta_ref, None);
    }

    // ──────────────────────────────────────────────────────────────
    // GH #23: `AgentMeta.projection_name`
    // ──────────────────────────────────────────────────────────────

    #[test]
    fn agent_meta_projection_name_roundtrips_when_some() {
        let meta = AgentMeta {
            projection_name: Some("plan".to_string()),
            ..Default::default()
        };
        let json = serde_json::to_value(&meta).expect("serializes");
        assert_eq!(json["projection_name"], "plan");
        let back: AgentMeta = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back, meta);
    }

    #[test]
    fn agent_meta_projection_name_omitted_when_none() {
        let meta = AgentMeta::default();
        let json = serde_json::to_value(&meta).expect("serializes");
        assert!(
            json.as_object().unwrap().get("projection_name").is_none(),
            "projection_name key must be absent when None: {json}"
        );
        let back: AgentMeta = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back.projection_name, None);
        assert_eq!(back, meta);
    }

    #[test]
    fn agent_meta_rejects_unknown_field_with_projection_name_present() {
        // `deny_unknown_fields` must still reject an unrelated stray key
        // even when `projection_name` is present alongside it (regression
        // guard: adding the field must not accidentally loosen the
        // contract for the rest of the struct).
        let json = serde_json::json!({
            "projection_name": "plan",
            "not_a_real_field": true
        });
        let err = serde_json::from_value::<AgentMeta>(json).unwrap_err();
        assert!(
            err.to_string().contains("not_a_real_field")
                || err.to_string().contains("unknown field"),
            "expected an unknown-field rejection, got: {err}"
        );
    }

    #[test]
    fn context_policy_default_allows_everything() {
        let policy = ContextPolicy::default();
        assert!(policy.allows("project_root"));
        assert!(policy.allows("anything"));
    }

    #[test]
    fn context_policy_include_only_allows_listed_names() {
        let policy = ContextPolicy {
            include: Some(vec!["project_root".to_string()]),
            exclude: vec![],
            ..Default::default()
        };
        assert!(policy.allows("project_root"));
        assert!(!policy.allows("work_dir"));
    }

    #[test]
    fn context_policy_exclude_wins_over_include() {
        let policy = ContextPolicy {
            include: Some(vec!["project_root".to_string()]),
            exclude: vec!["project_root".to_string()],
            ..Default::default()
        };
        assert!(!policy.allows("project_root"));
    }

    #[test]
    fn context_policy_roundtrips_through_json() {
        let policy = ContextPolicy {
            include: Some(vec!["a".to_string(), "b".to_string()]),
            exclude: vec!["c".to_string()],
            ..Default::default()
        };
        let json = serde_json::to_value(&policy).expect("serializes");
        let back: ContextPolicy = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back, policy);
    }

    #[test]
    fn context_policy_default_roundtrips_as_empty_object() {
        let policy = ContextPolicy::default();
        let json = serde_json::to_value(&policy).expect("serializes");
        assert_eq!(
            json,
            serde_json::json!({
                "include": null,
                "exclude": [],
                "steps": null,
                "steps_exclude": [],
            })
        );
        let back: ContextPolicy = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back, policy);
    }

    // ──────────────────────────────────────────────────────────────
    // ST5 (`projection-adapter`): `ContextPolicy.steps` / `steps_exclude`
    // ──────────────────────────────────────────────────────────────

    #[test]
    fn context_policy_steps_default_allows_every_step() {
        let policy = ContextPolicy::default();
        assert!(policy.allows_step("planner"));
        assert!(policy.allows_step("anything"));
    }

    #[test]
    fn context_policy_steps_include_only_allows_listed_names() {
        let policy = ContextPolicy {
            steps: Some(vec!["planner".to_string()]),
            ..Default::default()
        };
        assert!(policy.allows_step("planner"));
        assert!(!policy.allows_step("coder"));
    }

    #[test]
    fn context_policy_steps_empty_list_allows_none() {
        let policy = ContextPolicy {
            steps: Some(vec![]),
            ..Default::default()
        };
        assert!(!policy.allows_step("planner"));
    }

    #[test]
    fn context_policy_steps_exclude_wins_over_steps() {
        let policy = ContextPolicy {
            steps: Some(vec!["planner".to_string()]),
            steps_exclude: vec!["planner".to_string()],
            ..Default::default()
        };
        assert!(!policy.allows_step("planner"));
    }

    #[test]
    fn context_policy_steps_roundtrips_through_json() {
        let policy = ContextPolicy {
            steps: Some(vec!["planner".to_string(), "coder".to_string()]),
            steps_exclude: vec!["reviewer".to_string()],
            ..Default::default()
        };
        let json = serde_json::to_value(&policy).expect("serializes");
        let back: ContextPolicy = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back, policy);
    }

    // ──────────────────────────────────────────────────────────────
    // GH #34: `AuditDef`, `AuditMode`, `Blueprint.audits`
    // ──────────────────────────────────────────────────────────────

    #[test]
    fn blueprint_audits_omitted_when_empty() {
        let bp = minimal_bp(None);
        let json = serde_json::to_value(&bp).expect("serializes");
        assert!(
            json.as_object().unwrap().get("audits").is_none(),
            "audits key must be absent when empty: {json}"
        );
        let back: Blueprint = serde_json::from_value(json).expect("deserializes");
        assert!(back.audits.is_empty());
        assert_eq!(bp, back);
    }

    #[test]
    fn blueprint_audits_roundtrips_when_non_empty() {
        let mut bp = minimal_bp(None);
        bp.audits = vec![AuditDef {
            agent: "auditor".to_string(),
            steps: Some(vec!["worker".to_string()]),
            mode: AuditMode::Sync,
        }];
        let json = serde_json::to_string(&bp).expect("serializes");
        let back: Blueprint = serde_json::from_str(&json).expect("deserializes");
        assert_eq!(bp, back);
        assert_eq!(back.audits.len(), 1);
        assert_eq!(back.audits[0].agent, "auditor");
        assert_eq!(back.audits[0].mode, AuditMode::Sync);
    }

    #[test]
    fn audit_def_steps_none_and_mode_default_when_omitted() {
        let json = serde_json::json!({ "agent": "auditor" });
        let def: AuditDef = serde_json::from_value(json).expect("deserializes");
        assert_eq!(def.steps, None);
        assert_eq!(def.mode, AuditMode::Async);
    }

    #[test]
    fn audit_def_rejects_unknown_field() {
        let json = serde_json::json!({ "agent": "auditor", "not_a_real_field": true });
        let err = serde_json::from_value::<AuditDef>(json).unwrap_err();
        assert!(
            err.to_string().contains("not_a_real_field")
                || err.to_string().contains("unknown field"),
            "expected an unknown-field rejection, got: {err}"
        );
    }

    #[test]
    fn audit_mode_serializes_snake_case() {
        assert_eq!(
            serde_json::to_value(AuditMode::Async).unwrap(),
            serde_json::json!("async")
        );
        assert_eq!(
            serde_json::to_value(AuditMode::Sync).unwrap(),
            serde_json::json!("sync")
        );
    }

    #[test]
    fn blueprint_json_schema_exports_audits_and_audit_def() {
        let schema = schemars::schema_for!(Blueprint);
        let v = serde_json::to_value(&schema).expect("schema serializes");
        assert!(
            v["properties"]["audits"].is_object(),
            "audits must appear in the exported schema: {v}"
        );
        let dump = v.to_string();
        assert!(dump.contains("AuditDef"), "AuditDef definition in schema");
    }

    // ──────────────────────────────────────────────────────────────
    // GH #32: `Blueprint.degradation_policy`, `DegradationPolicy`
    // ──────────────────────────────────────────────────────────────

    #[test]
    fn blueprint_without_degradation_policy_deserializes_to_none() {
        let json = serde_json::json!({
            "schema_version": current_schema_version(),
            "id": "no-degradation-policy-ut",
            "flow": { "kind": "seq", "children": [] },
        });
        let bp: Blueprint = serde_json::from_value(json).expect("deserializes");
        assert_eq!(bp.degradation_policy, None);
    }

    #[test]
    fn blueprint_degradation_policy_omitted_when_none() {
        let bp = minimal_bp(None);
        let json = serde_json::to_value(&bp).expect("serializes");
        assert!(
            json.as_object()
                .unwrap()
                .get("degradation_policy")
                .is_none(),
            "degradation_policy key must be absent when None: {json}"
        );
    }

    #[test]
    fn blueprint_degradation_policy_warn_and_fail_roundtrip() {
        for (label, expected) in [
            ("warn", DegradationPolicy::Warn),
            ("fail", DegradationPolicy::Fail),
        ] {
            let mut bp = minimal_bp(None);
            bp.degradation_policy = Some(expected);
            let json = serde_json::to_string(&bp).expect("serializes");
            assert!(json.contains(&format!("\"degradation_policy\":\"{label}\"")));
            let back: Blueprint = serde_json::from_str(&json).expect("deserializes");
            assert_eq!(back.degradation_policy, Some(expected));
        }
    }

    #[test]
    fn degradation_policy_rejects_unknown_variant() {
        let json = serde_json::json!({
            "schema_version": current_schema_version(),
            "id": "degradation-policy-unknown-variant-ut",
            "flow": { "kind": "seq", "children": [] },
            "degradation_policy": "ignore",
        });
        let err = serde_json::from_value::<Blueprint>(json).unwrap_err();
        assert!(
            err.to_string().contains("unknown variant"),
            "expected an unknown-variant rejection, got: {err}"
        );
    }

    // ──────────────────────────────────────────────────────────────
    // GH #46 Milestone 2: `Runner`, `RunnerDef`, `WorkerModel`,
    // `Blueprint.runners` / `default_runner`, `AgentDef.runner` /
    // `runner_ref`, `resolve_runner`
    // ──────────────────────────────────────────────────────────────

    fn agent_with_runner(
        name: &str,
        profile: Option<AgentProfile>,
        runner: Option<Runner>,
        runner_ref: Option<String>,
    ) -> AgentDef {
        AgentDef {
            name: name.to_string(),
            kind: AgentKind::RustFn,
            spec: serde_json::json!({ "fn_id": name }),
            profile,
            meta: None,
            runner,
            runner_ref,
            verdict: None,
        }
    }

    fn ws_runner(variant: &str, tools: Vec<&str>) -> Runner {
        Runner::WsClaudeCode {
            variant: variant.to_string(),
            tools: tools.into_iter().map(str::to_string).collect(),
        }
    }

    fn agent_block_runner(tools: Vec<&str>) -> Runner {
        Runner::AgentBlockInProcess {
            tools: tools.into_iter().map(str::to_string).collect(),
        }
    }

    // ─── round-trip byte-compat ─────────────────────────────────────

    #[test]
    fn blueprint_without_runners_or_default_runner_deserializes_to_defaults() {
        let json = serde_json::json!({
            "schema_version": current_schema_version(),
            "id": "no-runners-ut",
            "flow": { "kind": "seq", "children": [] },
        });
        let bp: Blueprint = serde_json::from_value(json).expect("deserializes");
        assert!(bp.runners.is_empty());
        assert_eq!(bp.default_runner, None);
    }

    #[test]
    fn blueprint_runners_omitted_when_empty() {
        let bp = minimal_bp(None);
        let json = serde_json::to_value(&bp).expect("serializes");
        assert!(
            json.as_object().unwrap().get("runners").is_none(),
            "runners key must be absent when empty: {json}"
        );
        let back: Blueprint = serde_json::from_value(json).expect("deserializes");
        assert!(back.runners.is_empty());
        assert_eq!(bp, back);
    }

    #[test]
    fn blueprint_runners_roundtrips_when_non_empty() {
        let mut bp = minimal_bp(None);
        bp.runners = vec![RunnerDef {
            name: "claude-worker".to_string(),
            runner: ws_runner("code-worker", vec!["Read", "Grep"]),
        }];
        let json = serde_json::to_string(&bp).expect("serializes");
        let back: Blueprint = serde_json::from_str(&json).expect("deserializes");
        assert_eq!(bp, back);
        assert_eq!(back.runners.len(), 1);
        assert_eq!(back.runners[0].name, "claude-worker");
    }

    #[test]
    fn blueprint_default_runner_roundtrips_when_some() {
        let mut bp = minimal_bp(None);
        bp.default_runner = Some("claude-worker".to_string());
        let json = serde_json::to_value(&bp).expect("serializes");
        assert_eq!(json["default_runner"], "claude-worker");
        let back: Blueprint = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back, bp);
    }

    #[test]
    fn blueprint_default_runner_omitted_when_none() {
        let bp = minimal_bp(None);
        let json = serde_json::to_value(&bp).expect("serializes");
        assert!(
            json.as_object().unwrap().get("default_runner").is_none(),
            "default_runner key must be absent when None: {json}"
        );
        let back: Blueprint = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back, bp);
    }

    #[test]
    fn blueprint_json_schema_exports_runners_and_default_runner() {
        let schema = schemars::schema_for!(Blueprint);
        let v = serde_json::to_value(&schema).expect("schema serializes");
        assert!(
            v["properties"]["runners"].is_object(),
            "runners must appear in the exported schema: {v}"
        );
        assert!(
            v["properties"]["default_runner"].is_object(),
            "default_runner must appear in the exported schema: {v}"
        );
        let dump = v.to_string();
        assert!(dump.contains("RunnerDef"), "RunnerDef definition in schema");
        assert!(dump.contains("Runner"), "Runner definition in schema");
    }

    #[test]
    fn agent_def_runner_and_runner_ref_omitted_when_none() {
        let agent = agent_with_runner("scout", None, None, None);
        let json = serde_json::to_value(&agent).expect("serializes");
        let obj = json.as_object().unwrap();
        assert!(
            obj.get("runner").is_none(),
            "runner key must be absent when None: {json}"
        );
        assert!(
            obj.get("runner_ref").is_none(),
            "runner_ref key must be absent when None: {json}"
        );
        let back: AgentDef = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back, agent);
    }

    #[test]
    fn agent_def_runner_inline_roundtrips_when_some() {
        let agent = agent_with_runner("coder", None, Some(agent_block_runner(vec!["Bash"])), None);
        let json = serde_json::to_string(&agent).expect("serializes");
        let back: AgentDef = serde_json::from_str(&json).expect("deserializes");
        assert_eq!(back, agent);
    }

    #[test]
    fn agent_def_runner_ref_roundtrips_when_some() {
        let agent = agent_with_runner("coder", None, None, Some("claude-worker".to_string()));
        let json = serde_json::to_value(&agent).expect("serializes");
        assert_eq!(json["runner_ref"], "claude-worker");
        let back: AgentDef = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back, agent);
    }

    #[test]
    fn agent_def_json_schema_exports_runner_and_runner_ref() {
        let schema = schemars::schema_for!(AgentDef);
        let v = serde_json::to_value(&schema).expect("schema serializes");
        let props = v["properties"].as_object().expect("object schema");
        for key in ["runner", "runner_ref"] {
            assert!(props.contains_key(key), "missing property: {key}");
        }
    }

    #[test]
    fn runner_ws_claude_code_roundtrips_through_json_and_tags_backend() {
        let runner = ws_runner("code-worker", vec!["Read", "Grep"]);
        let json = serde_json::to_value(&runner).expect("serializes");
        assert_eq!(json["backend"], "ws_claude_code");
        assert_eq!(json["variant"], "code-worker");
        assert_eq!(json["tools"], serde_json::json!(["Read", "Grep"]));
        let back: Runner = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back, runner);
    }

    #[test]
    fn runner_ws_operator_roundtrips_through_json_and_tags_backend() {
        let runner = Runner::WsOperator {
            variant: "mse-worker-reviewer".to_string(),
            tools: vec!["Read".to_string(), "Grep".to_string()],
        };
        let json = serde_json::to_value(&runner).expect("serializes");
        assert_eq!(json["backend"], "ws_operator");
        assert_eq!(json["variant"], "mse-worker-reviewer");
        assert_eq!(json["tools"], serde_json::json!(["Read", "Grep"]));
        let back: Runner = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back, runner);
    }

    #[test]
    fn runner_agent_block_in_process_roundtrips_through_json_and_tags_backend() {
        let runner = agent_block_runner(vec!["Bash"]);
        let json = serde_json::to_value(&runner).expect("serializes");
        assert_eq!(json["backend"], "agent_block_in_process");
        assert_eq!(json["tools"], serde_json::json!(["Bash"]));
        let back: Runner = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back, runner);
    }

    #[test]
    fn runner_tools_omitted_when_empty() {
        let runner = ws_runner("code-worker", vec![]);
        let json = serde_json::to_value(&runner).expect("serializes");
        assert!(
            json.as_object().unwrap().get("tools").is_none(),
            "tools key must be absent when empty: {json}"
        );
        let back: Runner = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back, runner);
    }

    #[test]
    fn runner_rejects_unknown_field() {
        let json = serde_json::json!({
            "backend": "ws_claude_code",
            "variant": "x",
            "not_a_real_field": true,
        });
        let err = serde_json::from_value::<Runner>(json).unwrap_err();
        assert!(
            err.to_string().contains("not_a_real_field")
                || err.to_string().contains("unknown field"),
            "expected an unknown-field rejection, got: {err}"
        );
    }

    #[test]
    fn runner_def_roundtrips_through_json() {
        let def = RunnerDef {
            name: "claude-worker".to_string(),
            runner: ws_runner("code-worker", vec!["Read"]),
        };
        let json = serde_json::to_value(&def).expect("serializes");
        let back: RunnerDef = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back, def);
    }

    // ─── GH #83: SubprocessDef / Runner::Subprocess ────────────────

    fn sample_subprocess_def(name: &str) -> SubprocessDef {
        SubprocessDef {
            name: name.to_string(),
            argv: vec![
                "sh".to_string(),
                "-c".to_string(),
                "echo '{\"result\": \"ok\"}'".to_string(),
            ],
            stdin: Some("{prompt}".to_string()),
            env: std::collections::BTreeMap::from([("EXTRA".to_string(), "{task_id}".to_string())]),
            cwd: Some("{work_dir}".to_string()),
            output: Some(SubprocessOutput {
                format: Some("json".to_string()),
                result_ptr: Some("/result".to_string()),
                ok_from: Some("exit_code".to_string()),
                stats: None,
            }),
            stream_mode: None,
        }
    }

    #[test]
    fn subprocess_def_roundtrips_through_json() {
        let def = sample_subprocess_def("echo-json");
        let json = serde_json::to_value(&def).expect("serializes");
        let back: SubprocessDef = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back, def);
    }

    #[test]
    fn subprocess_def_optional_fields_omitted_when_default() {
        let def = SubprocessDef {
            name: "min".to_string(),
            argv: vec!["cat".to_string()],
            stdin: None,
            env: Default::default(),
            cwd: None,
            output: None,
            stream_mode: None,
        };
        let json = serde_json::to_value(&def).expect("serializes");
        let obj = json.as_object().unwrap();
        for absent in ["stdin", "env", "cwd", "output", "stream_mode"] {
            assert!(
                !obj.contains_key(absent),
                "{absent} key must be absent when default: {json}"
            );
        }
        let back: SubprocessDef = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back, def);
    }

    #[test]
    fn subprocess_def_rejects_unknown_field() {
        let json = serde_json::json!({
            "name": "x",
            "argv": ["cat"],
            "not_a_real_field": true,
        });
        let err = serde_json::from_value::<SubprocessDef>(json).unwrap_err();
        assert!(
            err.to_string().contains("unknown field"),
            "expected an unknown-field rejection, got: {err}"
        );
    }

    #[test]
    fn blueprint_subprocesses_defaults_to_empty_and_stays_off_the_wire() {
        // Pre-#83 BP JSON (no `subprocesses` key) deserializes to an empty registry.
        let bp = minimal_bp(None);
        let json = serde_json::to_value(&bp).expect("serializes");
        assert!(
            json.as_object().unwrap().get("subprocesses").is_none(),
            "subprocesses key must be absent when empty: {json}"
        );
        let back: Blueprint = serde_json::from_value(json).expect("deserializes");
        assert!(back.subprocesses.is_empty());
    }

    #[test]
    fn blueprint_subprocesses_roundtrips_when_declared() {
        let mut bp = minimal_bp(None);
        bp.subprocesses = vec![sample_subprocess_def("echo-json")];
        let json = serde_json::to_value(&bp).expect("serializes");
        assert_eq!(json["subprocesses"][0]["name"], "echo-json");
        let back: Blueprint = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back.subprocesses, bp.subprocesses);
    }

    #[test]
    fn runner_subprocess_roundtrips_through_json_and_tags_backend() {
        // 1:1 name symmetry with AgentKind::Subprocess — tag must be "subprocess".
        let runner = Runner::Subprocess {
            template: "echo-json".to_string(),
            overrides: SubprocessOverrides {
                model: Some("small".to_string()),
                tools: vec!["Read".to_string()],
                cwd: Some("/tmp/wd".to_string()),
            },
        };
        let json = serde_json::to_value(&runner).expect("serializes");
        assert_eq!(json["backend"], "subprocess");
        assert_eq!(json["template"], "echo-json");
        assert_eq!(json["overrides"]["model"], "small");
        let back: Runner = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back, runner);
    }

    #[test]
    fn runner_subprocess_overrides_omitted_when_empty() {
        let runner = Runner::Subprocess {
            template: "echo-json".to_string(),
            overrides: SubprocessOverrides::default(),
        };
        let json = serde_json::to_value(&runner).expect("serializes");
        assert!(
            json.as_object().unwrap().get("overrides").is_none(),
            "overrides key must be absent when all-default: {json}"
        );
        let back: Runner = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back, runner);
    }

    #[test]
    fn resolve_runner_inline_subprocess_variant_resolves() {
        let inline = Runner::Subprocess {
            template: "echo-json".to_string(),
            overrides: SubprocessOverrides::default(),
        };
        let agent = agent_with_runner("headless", None, Some(inline.clone()), None);
        let mut bp = minimal_bp(None);
        bp.agents = vec![agent.clone()];

        let resolved = resolve_runner(&bp, &agent).expect("resolves");
        assert_eq!(resolved, Some(inline));
    }

    #[test]
    fn resolve_runner_registry_and_default_tiers_resolve_subprocess_variant() {
        let registry_runner = Runner::Subprocess {
            template: "echo-json".to_string(),
            overrides: SubprocessOverrides::default(),
        };
        // Tier 2: runner_ref → registry.
        let agent = agent_with_runner("headless", None, None, Some("proc-entry".to_string()));
        let mut bp = minimal_bp(None);
        bp.runners = vec![RunnerDef {
            name: "proc-entry".to_string(),
            runner: registry_runner.clone(),
        }];
        bp.agents = vec![agent.clone()];
        let resolved = resolve_runner(&bp, &agent).expect("resolves");
        assert_eq!(resolved, Some(registry_runner.clone()));

        // Tier 4: default_runner alone.
        let bare = agent_with_runner("headless", None, None, None);
        bp.agents = vec![bare.clone()];
        bp.default_runner = Some("proc-entry".to_string());
        let resolved = resolve_runner(&bp, &bare).expect("resolves");
        assert_eq!(resolved, Some(registry_runner));
    }

    #[test]
    fn bind_outcome_bound_roundtrips_through_json_and_tags_outcome() {
        let outcome = BindOutcome::Bound {
            receipt: BindReceipt {
                agent: "coder".to_string(),
                request_digest: BindingDigest::sha256("req"),
                provider_id: "mse-provider".to_string(),
                provider_revision: Some("1".to_string()),
                resolved_model: Some("claude-sonnet-4".to_string()),
                effective_tools: vec!["Read".to_string(), "Write".to_string()],
                launch_variant: Some("mse-coder".to_string()),
                capability_snapshot_digest: None,
            },
        };
        let json = serde_json::to_value(&outcome).expect("serializes");
        assert_eq!(json["outcome"], "bound");
        assert_eq!(json["receipt"]["agent"], "coder");
        let back: BindOutcome = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back, outcome);
    }

    #[test]
    fn bind_outcome_unbound_roundtrips_through_json_and_tags_outcome() {
        let outcome = BindOutcome::Unbound {
            agent: "coder".to_string(),
            reason: "no capability for launch variant".to_string(),
        };
        let json = serde_json::to_value(&outcome).expect("serializes");
        assert_eq!(json["outcome"], "unbound");
        assert_eq!(json["agent"], "coder");
        assert_eq!(json["reason"], "no capability for launch variant");
        let back: BindOutcome = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back, outcome);
    }

    #[test]
    fn bind_outcome_rejects_unknown_field() {
        let json = serde_json::json!({
            "outcome": "unbound",
            "agent": "coder",
            "reason": "gone",
            "not_a_real_field": true,
        });
        let err = serde_json::from_value::<BindOutcome>(json).unwrap_err();
        assert!(
            err.to_string().contains("not_a_real_field")
                || err.to_string().contains("unknown field"),
            "expected an unknown-field rejection, got: {err}"
        );
    }

    #[test]
    fn compiler_strategy_strict_binding_defaults_false_and_omitted() {
        let strategy = CompilerStrategy::default();
        assert!(!strategy.strict_binding);
        // Absent in JSON deserializes back to false.
        let back: CompilerStrategy = serde_json::from_value(serde_json::json!({
            "strict_refs": true,
            "strict_kind": true,
        }))
        .expect("deserializes without strict_binding");
        assert!(!back.strict_binding);
    }

    #[test]
    fn worker_model_roundtrips_through_json() {
        let model = WorkerModel {
            runner: agent_block_runner(vec!["Bash"]),
            agent: agent_with_runner("coder", None, None, None),
        };
        let json = serde_json::to_value(&model).expect("serializes");
        let back: WorkerModel = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back, model);
    }

    // ─── resolve_runner cascade precedence ─────────────────────────

    #[test]
    fn resolve_runner_inline_wins_over_everything() {
        let inline = agent_block_runner(vec!["Bash"]);
        let profile = AgentProfile {
            worker_binding: Some("legacy-variant".to_string()),
            tools: vec!["Read".to_string()],
            ..Default::default()
        };
        let agent = agent_with_runner(
            "coder",
            Some(profile),
            Some(inline.clone()),
            Some("registry-entry".to_string()),
        );
        let mut bp = minimal_bp(None);
        bp.default_runner = Some("registry-entry".to_string());
        bp.runners = vec![RunnerDef {
            name: "registry-entry".to_string(),
            runner: ws_runner("other-variant", vec![]),
        }];
        bp.agents = vec![agent.clone()];

        let resolved = resolve_runner(&bp, &agent).expect("resolves");
        assert_eq!(resolved, Some(inline));
    }

    #[test]
    fn resolve_runner_runner_ref_wins_over_legacy_fallback() {
        let profile = AgentProfile {
            worker_binding: Some("legacy-variant".to_string()),
            tools: vec!["Read".to_string()],
            ..Default::default()
        };
        let registry_runner = ws_runner("registry-variant", vec!["Grep"]);
        let agent = agent_with_runner(
            "coder",
            Some(profile),
            None,
            Some("registry-entry".to_string()),
        );
        let mut bp = minimal_bp(None);
        bp.runners = vec![RunnerDef {
            name: "registry-entry".to_string(),
            runner: registry_runner.clone(),
        }];
        bp.agents = vec![agent.clone()];

        let resolved = resolve_runner(&bp, &agent).expect("resolves");
        assert_eq!(resolved, Some(registry_runner));
    }

    #[test]
    fn resolve_runner_legacy_fallback_wins_over_default_runner() {
        let profile = AgentProfile {
            worker_binding: Some("legacy-variant".to_string()),
            tools: vec!["Read".to_string(), "Grep".to_string()],
            ..Default::default()
        };
        let agent = agent_with_runner("coder", Some(profile), None, None);
        let mut bp = minimal_bp(None);
        bp.default_runner = Some("registry-entry".to_string());
        bp.runners = vec![RunnerDef {
            name: "registry-entry".to_string(),
            runner: agent_block_runner(vec!["Bash"]),
        }];
        bp.agents = vec![agent.clone()];

        let resolved = resolve_runner(&bp, &agent).expect("resolves");
        assert_eq!(
            resolved,
            Some(ws_runner("legacy-variant", vec!["Read", "Grep"]))
        );
    }

    #[test]
    fn resolve_runner_default_runner_alone_when_no_agent_level_declaration() {
        let agent = agent_with_runner("coder", None, None, None);
        let mut bp = minimal_bp(None);
        bp.default_runner = Some("registry-entry".to_string());
        bp.runners = vec![RunnerDef {
            name: "registry-entry".to_string(),
            runner: agent_block_runner(vec!["Bash"]),
        }];
        bp.agents = vec![agent.clone()];

        let resolved = resolve_runner(&bp, &agent).expect("resolves");
        assert_eq!(resolved, Some(agent_block_runner(vec!["Bash"])));
    }

    #[test]
    fn resolve_runner_none_when_nothing_declared_through_any_tier() {
        let agent = agent_with_runner("coder", None, None, None);
        let bp = minimal_bp(None);

        let resolved = resolve_runner(&bp, &agent).expect("resolves");
        assert_eq!(resolved, None);
    }

    #[test]
    fn resolve_runner_unknown_runner_ref_errs() {
        let agent = agent_with_runner("coder", None, None, Some("no-such-entry".to_string()));
        let mut bp = minimal_bp(None);
        bp.runners = vec![RunnerDef {
            name: "registry-entry".to_string(),
            runner: agent_block_runner(vec![]),
        }];
        bp.agents = vec![agent.clone()];

        let err = resolve_runner(&bp, &agent).expect_err("unresolved runner_ref");
        assert_eq!(
            err,
            RunnerResolveError::UnknownRunnerRef {
                agent: "coder".to_string(),
                ref_name: "no-such-entry".to_string(),
                available: vec!["registry-entry".to_string()],
            }
        );
    }

    #[test]
    fn resolve_runner_unknown_default_runner_errs() {
        let agent = agent_with_runner("coder", None, None, None);
        let mut bp = minimal_bp(None);
        bp.default_runner = Some("no-such-entry".to_string());
        bp.runners = vec![RunnerDef {
            name: "registry-entry".to_string(),
            runner: agent_block_runner(vec![]),
        }];
        bp.agents = vec![agent.clone()];

        let err = resolve_runner(&bp, &agent).expect_err("unresolved default_runner");
        assert_eq!(
            err,
            RunnerResolveError::UnknownDefaultRunner {
                ref_name: "no-such-entry".to_string(),
                available: vec!["registry-entry".to_string()],
            }
        );
    }

    #[test]
    fn bound_agent_digest_is_stable_and_tracks_runner_changes() {
        let agent = agent_with_runner(
            "coder",
            None,
            Some(ws_runner("worker-a", vec!["Read"])),
            None,
        );
        let mut bp = minimal_bp(None);
        bp.agents = vec![agent];

        let first = resolve_bound_agents(&bp).expect("binds");
        let second = resolve_bound_agents(&bp).expect("binds again");
        assert_eq!(first[0].binding_digest, second[0].binding_digest);
        assert!(first[0].binding_digest.as_str().starts_with("sha256:"));
        assert_eq!(first[0].binding_digest.as_str().len(), 71);
        assert_eq!(first[0].runner_source, RunnerResolutionSource::AgentInline);

        bp.agents[0].runner = Some(ws_runner("worker-b", vec!["Read"]));
        let changed = resolve_bound_agents(&bp).expect("binds changed runner");
        assert_ne!(first[0].binding_digest, changed[0].binding_digest);
    }

    #[test]
    fn bound_agent_pins_effective_context_policy_and_full_agent() {
        let mut agent = agent_with_runner("scout", None, None, None);
        agent.profile = Some(AgentProfile {
            system_prompt: "inspect carefully".to_string(),
            ..Default::default()
        });
        let mut bp = minimal_bp(None);
        bp.default_context_policy = Some(ContextPolicy {
            include: Some(vec!["task".to_string()]),
            ..Default::default()
        });
        bp.agents = vec![agent];

        let bound = resolve_bound_agents(&bp).expect("binds").remove(0);
        assert_eq!(
            bound.agent.profile.unwrap().system_prompt,
            "inspect carefully"
        );
        assert_eq!(
            bound.context_policy.unwrap().include,
            Some(vec!["task".to_string()])
        );
        assert_eq!(bound.runner_source, RunnerResolutionSource::None);
    }

    #[test]
    fn strict_bound_agent_resolution_rejects_legacy_worker_binding() {
        let profile = AgentProfile {
            worker_binding: Some("legacy-worker".to_string()),
            ..Default::default()
        };
        let mut bp = minimal_bp(None);
        bp.agents = vec![agent_with_runner("coder", Some(profile), None, None)];

        let err = resolve_bound_agents_strict(&bp).expect_err("legacy must fail closed");
        assert!(matches!(
            err,
            BoundAgentResolveError::LegacyWorkerBindingDisabled { agent } if agent == "coder"
        ));
    }

    #[test]
    fn binding_digest_is_a_validated_transparent_string() {
        use std::str::FromStr as _;

        let digest = BindingDigest::sha256(b"same snapshot");
        let json = serde_json::to_value(&digest).expect("serializes");
        assert_eq!(json, serde_json::Value::String(digest.to_string()));
        assert_eq!(
            serde_json::from_value::<BindingDigest>(json).expect("deserializes"),
            digest
        );
        for invalid in [
            "deadbeef",
            "sha256:abc",
            "sha256:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
            "blake3:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        ] {
            assert!(
                BindingDigest::from_str(invalid).is_err(),
                "accepted {invalid}"
            );
        }
    }

    #[test]
    fn capability_snapshot_digest_accepts_the_legacy_wire_name() {
        let digest = BindingDigest::sha256("capabilities");
        let capability: AgentProviderCapability = serde_json::from_value(serde_json::json!({
            "launch_variant": "coder",
            "effective_tools": ["Read"],
            "evidence_digest": digest,
        }))
        .expect("legacy manifest remains readable");
        assert_eq!(capability.capability_snapshot_digest, Some(digest.clone()));

        let serialized = serde_json::to_value(capability).expect("serialize new wire shape");
        assert_eq!(serialized["capability_snapshot_digest"], digest.to_string());
        assert!(serialized.get("evidence_digest").is_none());
    }

    // ──────────────────────────────────────────────────────────────
    // GH #50: `AgentDef.verdict` / `VerdictContract` / `VerdictChannel`
    // ──────────────────────────────────────────────────────────────

    #[test]
    fn verdict_contract_roundtrips_body_channel() {
        let json = serde_json::json!({"channel": "body", "values": ["PASS", "BLOCKED"]});
        let contract: VerdictContract = serde_json::from_value(json.clone()).expect("deserializes");
        assert_eq!(contract.channel, VerdictChannel::Body);
        assert_eq!(
            contract.values,
            vec!["PASS".to_string(), "BLOCKED".to_string()]
        );
        assert_eq!(serde_json::to_value(&contract).expect("serializes"), json);
    }

    #[test]
    fn verdict_contract_roundtrips_part_channel() {
        let json = serde_json::json!({"channel": "part", "values": ["ALLOW"]});
        let contract: VerdictContract = serde_json::from_value(json.clone()).expect("deserializes");
        assert_eq!(contract.channel, VerdictChannel::Part);
        assert_eq!(serde_json::to_value(&contract).expect("serializes"), json);
    }

    #[test]
    fn agent_def_verdict_omitted_when_none() {
        let agent = agent_with_runner("gate", None, None, None);
        let json = serde_json::to_value(&agent).expect("serializes");
        assert!(
            json.as_object().unwrap().get("verdict").is_none(),
            "verdict key must be absent when None: {json}"
        );
        let back: AgentDef = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back.verdict, None);
    }

    #[test]
    fn agent_def_verdict_roundtrips_when_some() {
        let mut agent = agent_with_runner("gate", None, None, None);
        agent.verdict = Some(VerdictContract {
            channel: VerdictChannel::Body,
            values: vec!["PASS".to_string(), "BLOCKED".to_string()],
        });
        let json = serde_json::to_value(&agent).expect("serializes");
        let back: AgentDef = serde_json::from_value(json).expect("deserializes");
        assert_eq!(back.verdict, agent.verdict);
    }

    /// Acceptance criterion #2: the `02-verdict-loop.json` sample (no
    /// `verdict` field on any of its agents) must still deserialize
    /// unchanged under the new `#[serde(deny_unknown_fields)]`-constrained
    /// `AgentDef` — `verdict` is `#[serde(default)]`, so its absence is not
    /// an error.
    #[test]
    fn existing_verdict_loop_sample_deserializes_with_verdict_omitted() {
        const SAMPLE: &str =
            include_str!("../../mlua-swarm-cli/src/mcp/resources/samples/02-verdict-loop.json");
        let bp: Blueprint = serde_json::from_str(SAMPLE).expect("sample deserializes");
        assert_eq!(bp.agents.len(), 6);
        assert!(
            bp.agents.iter().all(|a| a.verdict.is_none()),
            "no agent in the sample declares a verdict contract"
        );
    }

    // ──────────────────────────────────────────────────────────────
    // CheckPolicy enum relocation + Blueprint.check_policy
    // (T1: schema round-trip / omit→None / invalid→error)
    // ──────────────────────────────────────────────────────────────

    /// The wire form is snake_case and byte-identical to the pre-relocation
    /// enum (`"silent"` / `"warn"` / `"strict"`), round-tripping in both
    /// directions — the relocation must not change the serde surface.
    #[test]
    fn check_policy_wire_form_round_trips() {
        for (variant, wire) in [
            (CheckPolicy::Silent, "silent"),
            (CheckPolicy::Warn, "warn"),
            (CheckPolicy::Strict, "strict"),
        ] {
            let json = serde_json::to_value(variant).expect("serializes");
            assert_eq!(json, serde_json::json!(wire), "wire form for {variant:?}");
            let back: CheckPolicy = serde_json::from_value(json).expect("deserializes");
            assert_eq!(back, variant, "round-trip for {variant:?}");
        }
    }

    /// The default is `Warn` (preserves the pre-CheckPolicy fail-open
    /// behaviour of every submit-time projection sink).
    #[test]
    fn check_policy_default_is_warn() {
        assert_eq!(CheckPolicy::default(), CheckPolicy::Warn);
    }

    /// A Blueprint that declares `check_policy: "strict"` parses to
    /// `Some(Strict)` and re-serializes with the same snake_case literal.
    #[test]
    fn blueprint_check_policy_strict_round_trips() {
        let json = serde_json::json!({
            "schema_version": current_schema_version(),
            "id": "check-policy-strict-ut",
            "flow": { "kind": "seq", "children": [] },
            "check_policy": "strict",
        });
        let bp: Blueprint = serde_json::from_value(json).expect("deserializes");
        assert_eq!(bp.check_policy, Some(CheckPolicy::Strict));
        let re = serde_json::to_string(&bp).expect("serializes");
        assert!(
            re.contains("\"check_policy\":\"strict\""),
            "re-serialized BP must preserve the snake_case wire literal: {re}"
        );
    }

    /// An omitted `check_policy` parses to `None` and is skipped on
    /// serialize (backward-compat with every pre-cascade Blueprint).
    #[test]
    fn blueprint_check_policy_omitted_is_none() {
        let json = serde_json::json!({
            "schema_version": current_schema_version(),
            "id": "check-policy-omitted-ut",
            "flow": { "kind": "seq", "children": [] },
        });
        let bp: Blueprint = serde_json::from_value(json).expect("deserializes");
        assert_eq!(bp.check_policy, None);

        let out = serde_json::to_value(&bp).expect("serializes");
        assert!(
            out.as_object().unwrap().get("check_policy").is_none(),
            "check_policy key must be absent when None: {out}"
        );
    }

    /// An invalid `check_policy` value is a hard parse error (not silently
    /// dropped) — the enum is closed to the three snake_case variants. This
    /// also confirms `deny_unknown_fields` is not the gate here: the field
    /// IS known, only its value is invalid.
    #[test]
    fn blueprint_check_policy_invalid_value_errors() {
        let json = serde_json::json!({
            "schema_version": current_schema_version(),
            "id": "check-policy-invalid-ut",
            "flow": { "kind": "seq", "children": [] },
            "check_policy": "loud",
        });
        let err = serde_json::from_value::<Blueprint>(json)
            .expect_err("an unknown check_policy value must be rejected");
        let msg = err.to_string();
        assert!(
            msg.contains("check_policy") || msg.contains("loud") || msg.contains("variant"),
            "error should point at the bad check_policy value: {msg}"
        );
    }

    #[test]
    fn agent_provider_manifest_round_trips_and_rejects_unknown_fields() {
        let json = serde_json::json!({
            "provider_id": "main-ai-self-report",
            "provider_revision": "1",
            "capabilities": [{
                "launch_variant": "mse-coder",
                "resolved_model": "claude-sonnet-4",
                "effective_tools": ["Read", "Edit"]
            }]
        });
        let manifest: AgentProviderManifest =
            serde_json::from_value(json.clone()).expect("manifest deserializes");
        assert_eq!(serde_json::to_value(manifest).unwrap(), json);

        let invalid = serde_json::json!({
            "provider_id": "main-ai-self-report",
            "capabilities": [],
            "platform_secret": true
        });
        assert!(serde_json::from_value::<AgentProviderManifest>(invalid).is_err());
    }
}