mlua-swarm-server 0.23.1

HTTP + WebSocket server for mlua-swarm (task API, Blueprint store, Operator WS sessions).
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
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
//! HTTP `/v1/worker/*` endpoints (SubAgent self-fetch path).
//!
//! # 7-Entry pointer #6 (Output Event design)
//!
//! **This endpoint accesses `OutputStore` directly and does NOT go through the engine.**
//! It is one of the seven entry points enumerated in project `CLAUDE.md` §"Output Event
//! Design SoT". For the canonical description, see the crate root doc of
//! `mlua-swarm-output-store` (`cargo doc -p mlua-swarm-output-store`).
//!
//! # Path
//!
//! A thin-payload path where a SubAgent (= worker process launched by a MainAI) uses
//! the capability token it received via WS Spawn to self-fetch its prompt and
//! submit its result — putting the token in `Authorization: Bearer <encoded CapToken>`.
//!
//! ## Routes
//!
//! - `GET /v1/worker/prompt?task_id=<tid>` — via `engine.fetch_worker_payload`,
//!   returns `{task_id, attempt, agent, system?, prompt, context?}`.
//!   `context.steps` (`projection-adapter` ST5, [`assemble_step_pointers`])
//!   is assembled fresh on every fetch: a `ContextPolicy.steps`-filtered
//!   pointer list to preceding steps' OUTPUT, resolved through
//!   `crate::projection::McpQueryAdapter`'s Data-plane + `result_ref`
//!   enumeration — no separate MCP tool call needed to discover a prior
//!   step's OUTPUT.
//! - `POST /v1/worker/result` with body `{task_id, value, ok}` — appends one `Final`
//!   to the output tail via `engine.submit_output(Final)` (= the canonical path
//!   through which the dispatch layer decides Pass/Blocked) and updates
//!   `task.last_result` via `engine.post_result`.
//! - `POST /v1/worker/artifact?name=<name>` (GH #36 ST1) — stages one named
//!   part per POST via `engine.stage_worker_artifact_trusted`. Completing the
//!   attempt is still `POST /v1/worker/submit` / `/v1/worker/result` — this
//!   route only stages; the dispatch layer's Final-pull folds every staged
//!   part into `{"out": <final>, "parts": {<name>: <value>, ...}}`. At
//!   staging time the submit-time projection sink also materializes the part
//!   raw to `<ctx-dir>/<name>` (the IN file the next Agent step reads;
//!   fail-open skip when no `work_dir` / `project_root` resolves).
//! - `GET /v1/worker/prompt/system?task_id=<tid>&attempt=<n>` (GH #31) —
//!   raw baked `system` bytes for `(task_id, attempt)`, the `Http`-mode
//!   fetch target for `system_ref.uri`. Same Bearer flow as
//!   `/v1/worker/prompt`; body is `text/plain`, not JSON.
//! - `GET /v1/agents/:name/render-size` (GH #31) — no Bearer required, same
//!   trust tier as `GET /v1/blueprints/:id/head`. Live per-agent most-recently
//!   observed render size, backing `bp_doctor`'s post-render check.
//! - `POST /v1/worker/degradation` (GH #32) — structured JSON `{tool, error,
//!   fallback, note?}`, same Bearer flow as [`worker_submit`]. An
//!   **independent channel**: entries are appended to `RunRecord.degradations`
//!   via `RunStore::append_degradation` directly and never touch
//!   `OutputStore` / the fold path (Crux invariant 2 — a degradation must
//!   never surface as step OUTPUT). `step_ref` / `attempt` / `at` are
//!   server-injected, never trusted from the client. Silent `204` (no
//!   append) when the dispatch task carries no Run linkage — same
//!   fail-open contract as [`reject_if_run_terminal`]'s own resolution
//!   steps, since a pre-run-tracking dispatch has nowhere to record a
//!   degradation and that must not become a client-visible error.
//!
//! ## Bearer authentication
//!
//! The Bearer value is the string produced by `CapToken::encode()` (= URL-safe
//! base64 of serde_json). The server decodes it with `CapToken::decode` and then,
//! inside the engine, verifies HMAC sig + role × verb gate + TTL via
//! `verify_token_for_task` (= self-contained capability token; no server-side
//! store lookup required).
//!
//! Tokens are minted during the "2) mint outside the lock" phase of
//! `engine.dispatch_attempt` (`Role::Worker`, 600s TTL, `scopes=["*"]`).
//! The verb gate covers `FetchPrompt` / `EmitOutput` / `PostResult` — the worker
//! leaf capability set (`crate::types::WORKER_LEAF_VERBS`).

use axum::{
    extract::{Query, State},
    http::{header, header::AUTHORIZATION, HeaderMap, StatusCode},
    Json,
};
use mlua_swarm::core::agent_context::StepPointer;
use mlua_swarm::core::state::SubmitOutcome;
use mlua_swarm::core::step_naming::StepNaming;
use mlua_swarm::store::run::{DegradationEntry, RunStatus, RunStoreError};
use mlua_swarm::{CapToken, ContentRef, EngineError, OutputEvent, RunId, StepId, WorkerPayload};
use mlua_swarm_schema::{ContextPolicy, VerdictChannel};
use serde::Deserialize;
use serde_json::Value;

use crate::projection::McpQueryAdapter;
use crate::{ApiError, AppState};

/// Query params for `GET /v1/worker/prompt`.
#[derive(Debug, Deserialize)]
pub struct PromptQuery {
    /// Task the fetched prompt belongs to; cross-checked against the Bearer
    /// handle/token. Typed [`StepId`] since issue #14 — the wire shape stays
    /// a plain string; a bad prefix is rejected at deserialize.
    pub task_id: StepId,
}

/// `GET /v1/worker/prompt?task_id=<tid>`. Bearer = encoded `CapToken` or short `wh-` handle.
/// Thin HTTP wrapper over `engine.fetch_worker_payload` / `fetch_worker_payload_trusted`.
/// Short-handle path (recommended for SubAgents): handle → task_id
/// cross-check → trusted fetch.
/// Full-`CapToken` path: token decode → verify → fetch.
pub async fn worker_prompt(
    State(state): State<AppState>,
    headers: HeaderMap,
    Query(q): Query<PromptQuery>,
) -> Result<Json<WorkerPayload>, ApiError> {
    let task_id = q.task_id;
    let bearer = extract_bearer_raw(&headers)?;
    let mut payload = if let Some(handle) = parse_worker_handle(&bearer) {
        // Short-handle path: verify handle → task_id (security: confirm the handle is bound to this task).
        let resolved = state
            .engine
            .task_id_from_handle(handle)
            .await
            .map_err(map_handle_lookup_err)?;
        if resolved != task_id {
            return Err(ApiError::bad_request(format!(
                "handle {handle} is bound to task {resolved}, not {task_id}"
            )));
        }
        state
            .engine
            .fetch_worker_payload_trusted(&task_id)
            .await
            .map_err(|e| ApiError::engine(format!("fetch_worker_payload_trusted: {e}")))?
    } else {
        // Full CapToken path (the alternate Bearer form).
        let token = CapToken::decode(bearer.trim())
            .map_err(|e| ApiError::bad_request(format!("invalid token: {e}")))?;
        state
            .engine
            .fetch_worker_payload(&token, &task_id)
            .await
            .map_err(|e| ApiError::engine(format!("fetch_worker_payload: {e}")))?
    };
    assemble_step_pointers(&state, &mut payload).await;
    Ok(Json(payload))
}

/// Assembles `payload.context.steps` — the `ContextPolicy.steps`-filtered
/// pointer list to preceding steps' OUTPUT (`projection-adapter` ST5's
/// Worker axis; see `mlua_swarm::core::agent_context`'s module doc).
/// Resolved fresh on every fetch (not baked at spawn time), so a step
/// submitted after this agent spawned — but before it fetches its prompt
/// — is still visible.
///
/// GH #23 subtask-3: `resolved_steps` (from
/// `McpQueryAdapter::list_steps_by_run_id`) always reports the CANONICAL
/// name (see `crate::projection`'s module doc), so both the self-exclusion
/// check and the `ContextPolicy` match are done against canonical names —
/// `payload.agent` (the raw `Step.ref` this fetching agent was dispatched
/// under) is canonicalized via `Engine::step_naming_for(&payload.task_id)`
/// (the FETCHING agent's own dispatch id — the same `StepNaming` `Arc`
/// every step of this Blueprint launch shares, see [`StepNaming`]'s module
/// doc), and `policy.allows_step` itself is left untouched (schema crate
/// stays name-agnostic) — [`allows_step_canonical`] is the caller-side seam
/// that resolves each policy-declared name through the table before
/// comparing.
///
/// No-op (`context.steps` stays empty) when: the payload carries no
/// `context` at all; the context has no `run_id` (a spawn that never
/// threaded one through — pre-run-tracking callers, or a spawner stack
/// without the Run-tracking layer); or the addressed Run cannot be
/// resolved. All three are fail-open, matching this crate's other
/// best-effort projection hooks (a missing pointer list must never turn a
/// would-have-succeeded fetch into a failure).
async fn assemble_step_pointers(state: &AppState, payload: &mut WorkerPayload) {
    let Some(context) = payload.context.as_mut() else {
        return;
    };
    let Some(run_id_str) = context.run_id.clone() else {
        return;
    };
    let Ok(run_id) = RunId::parse(run_id_str) else {
        return;
    };

    let adapter = McpQueryAdapter::new(
        state.data_store.clone(),
        state.run_store.clone(),
        state.engine.clone(),
    );
    let Ok((run, resolved_steps)) = adapter.list_steps_by_run_id(&run_id).await else {
        return;
    };

    let naming = state.engine.step_naming_for(&payload.task_id).await;
    let policy = state
        .engine
        .context_policy_for(&payload.task_id, payload.attempt)
        .await;
    let self_canonical = naming
        .as_deref()
        .and_then(|n| n.canonical_of_producer(&payload.agent))
        .map(str::to_string)
        .unwrap_or_else(|| payload.agent.clone());

    let mut pointers = Vec::new();
    for step in &resolved_steps {
        if step.name == self_canonical
            || !allows_step_canonical(&policy, naming.as_deref(), &step.name)
        {
            continue;
        }
        if let Some((size_bytes, file_path, content_url, sha256)) =
            crate::projection::resolve_step_pointer_fields(state, &run, step).await
        {
            pointers.push(StepPointer {
                name: step.name.clone(),
                size_bytes,
                file_path,
                content_url,
                sha256,
            });
        }
    }
    context.steps = pointers;
}

/// GH #23 subtask-3: caller-side canonical/alias expansion for
/// `ContextPolicy.allows_step` — same precedence as
/// `ContextPolicy::allows_step` itself (`steps_exclude` wins; `steps:
/// None` = pass-all, `Some(list)` = named-only), but each
/// policy-declared name is resolved through the Blueprint's `StepNaming`
/// table before comparison, so a Blueprint author's `steps: [...]` entry
/// naming either the canonical projection name OR any alias (`Step.ref` /
/// the `out` ctx-path's top-level segment) matches the same step.
/// `ContextPolicy::allows_step` (schema crate) is untouched — this is the
/// GH #23 seam, kept out of the name-agnostic schema type. `naming: None`
/// degrades to a literal string comparison, byte-identical to
/// `ContextPolicy::allows_step` itself (defensive-only fallback, matching
/// `crate::projection::McpQueryAdapter::step_naming_for_run`'s own
/// contract).
fn allows_step_canonical(
    policy: &ContextPolicy,
    naming: Option<&StepNaming>,
    canonical_name: &str,
) -> bool {
    let resolves_to = |raw: &str| -> bool {
        match naming {
            Some(n) => n
                .resolve(raw)
                .map(|c| c == canonical_name)
                .unwrap_or(raw == canonical_name),
            None => raw == canonical_name,
        }
    };
    if policy
        .steps_exclude
        .iter()
        .any(|excluded| resolves_to(excluded))
    {
        return false;
    }
    match &policy.steps {
        None => true,
        Some(list) => list.iter().any(|included| resolves_to(included)),
    }
}

/// Body for `POST /v1/worker/result`.
#[derive(Debug, Deserialize)]
pub struct WorkerResultReq {
    /// Task this result belongs to (looked up together with the Bearer
    /// token). Typed [`StepId`] since issue #14 (see [`PromptQuery`]).
    pub task_id: StepId,
    /// `WorkerResult.value` (= the value returned by the Operator: LLM inference result or tool execution result).
    pub value: Value,
    /// `WorkerResult.ok`. `false` makes the dispatch path decide Blocked
    /// (= same semantics as `OutputEvent::Final { ok: false, .. }` from a
    /// `SpawnerAdapter`). Defaults to `true`.
    #[serde(default = "default_ok_true")]
    pub ok: bool,
    /// Optional explicit attempt. Normally omitted (= the server looks up `task.attempt`).
    /// A carry for race-condition tests that need to write to a fixed attempt.
    #[serde(default)]
    pub attempt: Option<u32>,
}

fn default_ok_true() -> bool {
    true
}

/// `POST /v1/worker/result`. Bearer = encoded `CapToken`.
/// Fires `engine.submit_output(Final)` + `engine.post_result`.
pub async fn worker_result(
    State(state): State<AppState>,
    headers: HeaderMap,
    Json(req): Json<WorkerResultReq>,
) -> Result<StatusCode, ApiError> {
    let token = decode_worker_bearer(&headers)?;
    let task_id = req.task_id.clone();

    // Use body-explicit attempt if provided; otherwise the current task.attempt.
    let attempt = match req.attempt {
        Some(n) => n,
        None => state
            .engine
            .task_attempt(&task_id)
            .await
            .map_err(|e| ApiError::engine(format!("task_attempt: {e}")))?,
    };

    let event = OutputEvent::Final {
        content: ContentRef::Inline {
            value: req.value.clone(),
        },
        ok: req.ok,
    };
    // GH #51: completion-time verdict-contract enforcement now runs
    // inside `Engine::submit_output` itself (see
    // `map_completion_result`'s doc) — this route previously called no
    // gate at all.
    map_completion_result(
        state
            .engine
            .submit_output(&token, &task_id, attempt, event)
            .await,
        "submit_output",
    )?;
    state
        .engine
        .post_result(&token, &task_id, req.value)
        .await
        .map_err(|e| ApiError::engine(format!("post_result: {e}")))?;
    Ok(StatusCode::NO_CONTENT)
}

/// Body-level protocol prefix recognized by [`worker_submit`] and
/// [`worker_artifact`] (GH #42). When the trimmed request body starts with
/// this sentinel, the rest is treated as an absolute path; the file is
/// read and its contents replace the submitted body. Non-sentinel bodies
/// are unchanged.
///
/// See [`resolve_file_sentinel`] for the resolution rules and guards.
const FILE_SENTINEL_PREFIX: &str = "@file:";

/// Byte ceiling on the resolved-file body, matching the HTTP
/// `DefaultBodyLimit` applied to inline bodies at the router (2 MiB, see
/// the `/v1/worker/submit` layer in `crate::app_router`). Sentinel
/// bodies bypass that axum body layer (the request itself is small), so
/// the guard is checked in [`resolve_file_sentinel`] instead.
const FILE_SENTINEL_MAX_BYTES: u64 = 2 * 1024 * 1024;

/// `AgentContextView.extra` key that opts a step into `@file:` sentinel
/// resolution (GH #43). Declared through the GH #21 meta channels
/// (`Blueprint.metas` / `AgentMeta.ctx` / step-level `$step_meta`) and
/// folded into the view at spawn time by `AgentContextMiddleware`.
///
/// Default-deny: absent, or any value other than the strict boolean
/// `true` (a string `"true"` does not count), rejects the sentinel with
/// `400`. The v0.9.x line has no sentinel at all, so deny-by-default is
/// the released-behavior-compatible default; a step whose output
/// contract legitimately needs file submission opts in with one
/// declaration.
const FILE_SENTINEL_ALLOW_KEY: &str = "allow_file_submit";

/// `AgentContextView.extra` key carrying a step's declared submit format.
/// Declared through the same GH #21 meta channels as
/// [`FILE_SENTINEL_ALLOW_KEY`] (`Blueprint.metas` / `AgentMeta.ctx` /
/// step-level `$step_meta`) and folded into the view at spawn time by
/// `AgentContextMiddleware`. Same string as the engine-side fold's key
/// (`mlua_swarm::core::engine::SUBMIT_FORMAT_KEY`) — this route and the
/// fold are the two halves of one contract.
///
/// Absent (the overwhelming majority of steps): this route stages the
/// body as `Value::String`, byte-for-byte — the engine's Final-pull fold
/// then applies the default LENIENT container parse (a body that parses
/// as a JSON object / array folds structured into the flow ctx; scalars
/// and prose stay strings — see `mlua_swarm::core::engine::FoldParse`).
/// The recognized values are [`SUBMIT_FORMAT_JSON`] (strict parse-or-422
/// here at submit time) and [`SUBMIT_FORMAT_TEXT`] (fold-side opt-out);
/// see [`resolve_submit_value`].
const SUBMIT_FORMAT_KEY: &str = mlua_swarm::core::engine::SUBMIT_FORMAT_KEY;

/// Strict [`SUBMIT_FORMAT_KEY`] value: parse the final submit body as
/// JSON — any JSON value, scalars included, unlike the fold's
/// containers-only lenient default — and fold the parsed [`Value`], with
/// an unparseable body rejected `422` at submit time. The opt-in for "the
/// worker PROMISES JSON" (fail loud, retry-able) rather than "parse it if
/// it happens to be JSON".
const SUBMIT_FORMAT_JSON: &str = "json";

/// Opt-out [`SUBMIT_FORMAT_KEY`] value: the body stages as a string here
/// AND the engine-side fold skips its lenient container parse for the
/// step (final body and staged parts alike), so a JSON-container-looking
/// text reaches the flow ctx as raw text
/// (`mlua_swarm::core::engine::SUBMIT_FORMAT_TEXT`).
const SUBMIT_FORMAT_TEXT: &str = mlua_swarm::core::engine::SUBMIT_FORMAT_TEXT;

/// How many leading characters of an unparseable body the `422` echoes
/// back, so the failure is diagnosable from the HTTP response alone
/// without dumping a multi-KB payload into the error message.
const SUBMIT_FORMAT_PREVIEW_CHARS: usize = 80;

/// Resolves the `@file:<abs-path>` sentinel (GH #42) when present at the
/// start of `body_str`. When absent, returns `body_str` unchanged — this
/// is the byte-for-byte compatible path for all pre-#42 workers.
///
/// # Sentinel form
///
/// The trimmed body is `@file:<abs-path>` on a single line — a worker
/// materializes the large payload to a file under its task's `work_dir`
/// with its existing `Write` capability, then submits the sentinel body
/// instead of streaming the payload back through the LLM.
///
/// # Guards
///
/// - Empty / multi-line path → `400`.
/// - Relative path → `400` (the allowlist works only in
///   canonicalized-absolute form).
/// - `AgentContextView` not materialized for `(task_id, attempt)` → `400`
///   (spawn must have run through `AgentContextMiddleware`; without a
///   view there is no allowlist root to check against).
/// - `view.extra[`[`FILE_SENTINEL_ALLOW_KEY`]`]` is not boolean `true` →
///   `400` (GH #43 — file submission is opt-in per step; default-deny).
/// - `view.work_dir` is `None` → `400`.
/// - Canonicalized path is not under canonicalized `work_dir` → `400`
///   (blocks `..`-escapes and symlinks pointing outside the allowlist).
/// - File does not exist → `404`.
/// - File size > [`FILE_SENTINEL_MAX_BYTES`] → `413`.
/// - Any other I/O / canonicalize error → `500`.
///
/// The resolved contents are `trim_end()`-ed to match the inline path's
/// own trailing-whitespace strip, so the downstream `Value::String` is
/// observationally identical whether the body arrived inline or via
/// sentinel.
async fn resolve_file_sentinel(
    state: &AppState,
    task_id: &StepId,
    attempt: u32,
    body_str: String,
) -> Result<String, ApiError> {
    let Some(rest) = body_str.strip_prefix(FILE_SENTINEL_PREFIX) else {
        return Ok(body_str);
    };
    let path_str = rest.trim();
    if path_str.is_empty() {
        return Err(ApiError::bad_request(
            "@file: sentinel: empty path".to_string(),
        ));
    }
    if path_str.contains('\n') || path_str.contains('\r') {
        return Err(ApiError::bad_request(
            "@file: sentinel: path must be a single line".to_string(),
        ));
    }
    let path = std::path::Path::new(path_str);
    if !path.is_absolute() {
        return Err(ApiError::bad_request(format!(
            "@file: sentinel: path must be absolute (got {path_str:?})"
        )));
    }
    let view = state
        .engine
        .agent_context_for(task_id, attempt)
        .await
        .ok_or_else(|| {
            ApiError::bad_request(
                "@file: sentinel: no AgentContextView for this task/attempt \
                 (spawn must run through AgentContextMiddleware to enable \
                 sentinel resolution)"
                    .to_string(),
            )
        })?;
    // GH #43: file submission is opt-in per step (default-deny). Strict
    // boolean `true` only — folded from the Blueprint meta channels by
    // `AgentContextMiddleware` at spawn time.
    if view.extra.get(FILE_SENTINEL_ALLOW_KEY) != Some(&Value::Bool(true)) {
        return Err(ApiError::bad_request(format!(
            "@file: sentinel: file submission is not allowed for this step \
             (declare `{FILE_SENTINEL_ALLOW_KEY}: true` via `$step_meta` / \
             `AgentMeta.ctx` / `Blueprint.metas`; strict boolean `true` \
             required)"
        )));
    }
    let work_dir = view.work_dir.ok_or_else(|| {
        ApiError::bad_request("@file: sentinel: task has no resolved work_dir".to_string())
    })?;
    let work_dir_canon = tokio::fs::canonicalize(&work_dir).await.map_err(|e| {
        ApiError::engine(format!(
            "@file: sentinel: canonicalize work_dir {work_dir:?}: {e}"
        ))
    })?;
    let path_canon = match tokio::fs::canonicalize(path).await {
        Ok(p) => p,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            return Err(ApiError::not_found(format!(
                "@file: sentinel: file not found: {path_str}"
            )));
        }
        Err(e) => {
            return Err(ApiError::engine(format!(
                "@file: sentinel: canonicalize {path_str:?}: {e}"
            )));
        }
    };
    if !path_canon.starts_with(&work_dir_canon) {
        return Err(ApiError::bad_request(format!(
            "@file: sentinel: path {} is not under work_dir {} (canonicalized: {} vs {})",
            path_str,
            work_dir,
            path_canon.display(),
            work_dir_canon.display(),
        )));
    }
    let meta = tokio::fs::metadata(&path_canon)
        .await
        .map_err(|e| ApiError::engine(format!("@file: sentinel: metadata {path_str:?}: {e}")))?;
    if meta.len() > FILE_SENTINEL_MAX_BYTES {
        return Err(ApiError::payload_too_large(format!(
            "@file: sentinel: file size {} exceeds limit {}",
            meta.len(),
            FILE_SENTINEL_MAX_BYTES
        )));
    }
    let bytes = tokio::fs::read(&path_canon)
        .await
        .map_err(|e| ApiError::engine(format!("@file: sentinel: read {path_str:?}: {e}")))?;
    // Match the `trim_end()` the inline path applies (see `worker_submit`).
    Ok(String::from_utf8_lossy(&bytes).trim_end().to_string())
}

/// Resolves the final submit body into the [`Value`] folded into the flow
/// ctx, honoring the [`SUBMIT_FORMAT_KEY`] opt-in.
///
/// Called by [`worker_submit`] AFTER [`resolve_file_sentinel`], so a
/// declared step may combine both: the sentinel resolves the file first
/// and the parse then applies to the file's contents, exactly as if the
/// same bytes had been posted inline.
///
/// Outcomes:
///
/// - No `AgentContextView` for `(task_id, attempt)`, or no
///   [`SUBMIT_FORMAT_KEY`] in `view.extra` → `Value::String(body_str)`,
///   staged unchanged down to the byte. (The engine's Final-pull fold
///   later applies its default lenient container parse to this string —
///   see [`SUBMIT_FORMAT_KEY`]'s doc; this route itself never sniffs.)
/// - `submit_format: "json"` and the body parses → the parsed [`Value`]
///   (object, array, or any other JSON value — scalars included, unlike
///   the fold's containers-only lenient default).
/// - `submit_format: "json"` and the body does NOT parse → `422`
///   (declared-strict, the same posture as the verdict contract: a
///   declared output contract the worker breaks is rejected rather than
///   silently degraded). The message names the agent and echoes the
///   first [`SUBMIT_FORMAT_PREVIEW_CHARS`] characters of the body.
/// - `submit_format: "text"` → `Value::String(body_str)`, no warn. The
///   declaration's real effect lives in the engine fold
///   (`FoldParse::Raw`); here it is simply a recognized no-op.
/// - Any other declared value (`"yaml"`, `true`, a typo) → the body folds
///   as `Value::String` and a `tracing::warn!` records the unrecognized
///   declaration. An unknown value is not a client error: the strict lane
///   belongs to the recognized formats, and a future kind-agnostic output
///   contract is the place to type this key.
///
/// The verdict contract is deliberately NOT consulted here — the
/// completion-time check lives inside
/// `Engine::submit_worker_result_trusted` and runs on the value this
/// function returns, so an undeclared agent's bare token reaches it as
/// the same `Value::String` as before.
async fn resolve_submit_value(
    state: &AppState,
    task_id: &StepId,
    attempt: u32,
    body_str: String,
) -> Result<Value, ApiError> {
    let declared = state
        .engine
        .agent_context_for(task_id, attempt)
        .await
        .and_then(|view| {
            view.extra
                .get(SUBMIT_FORMAT_KEY)
                .cloned()
                .map(|declared| (view.agent, declared))
        });
    let Some((agent, declared)) = declared else {
        return Ok(Value::String(body_str));
    };
    match declared.as_str() {
        Some(SUBMIT_FORMAT_JSON) => serde_json::from_str::<Value>(&body_str).map_err(|e| {
            let preview: String = body_str.chars().take(SUBMIT_FORMAT_PREVIEW_CHARS).collect();
            ApiError::unprocessable(format!(
                "submit_format violation: agent {agent:?} declared \
                     `{SUBMIT_FORMAT_KEY}: {SUBMIT_FORMAT_JSON:?}`, but the submitted body is \
                     not valid JSON: {e} (body starts with: {preview:?})"
            ))
        }),
        Some(SUBMIT_FORMAT_TEXT) => Ok(Value::String(body_str)),
        _ => {
            tracing::warn!(
                agent = %agent,
                declared = %declared,
                "unknown `{SUBMIT_FORMAT_KEY}` value; folding the body as a string \
                 (recognized values: {SUBMIT_FORMAT_JSON:?}, {SUBMIT_FORMAT_TEXT:?})"
            );
            Ok(Value::String(body_str))
        }
    }
}

/// GH #50 (Subtask 2) — submit-time verdict contract gate, shared by
/// [`worker_submit`] (`channel = Body`) and [`worker_artifact`]
/// (`channel = Part`, only when `name == "verdict"`). Enforcement Point 2
/// (the submit-time complement to `Compiler::compile`'s register-time lint
/// in `mlua_swarm::blueprint::compiler`, Enforcement Point 1) — called
/// after the final value string is resolved and BEFORE it is handed to
/// `submit_worker_result_trusted` / `stage_worker_artifact_trusted`, so a
/// rejected value never reaches the flow ctx.
///
/// No-op (`Ok(())`) in every case that must preserve pre-GH-#50 behavior
/// byte-for-byte:
/// - the dispatching agent declared no `VerdictContract` at all (opt-in).
/// - the agent's declared contract addresses the OTHER channel — a
///   channel/shape mismatch is the compile-time lint's job (Enforcement
///   Point 1); this gate only validates value membership for the channel
///   it was called for.
/// - `value` IS a member of the contract's declared `values`.
///
/// `Err(ApiError::unprocessable(..))` (HTTP 422) otherwise, echoing the
/// expected token set.
async fn check_verdict_contract(
    state: &AppState,
    task_id: &StepId,
    channel: VerdictChannel,
    value: &str,
) -> Result<(), ApiError> {
    let Some(contract) = state.engine.verdict_contract_for_task(task_id).await else {
        return Ok(());
    };
    if contract.channel != channel {
        return Ok(());
    }
    if contract.values.iter().any(|v| v == value) {
        return Ok(());
    }
    Err(ApiError::unprocessable(format!(
        "verdict contract violation: {value:?} is not a member of the declared values {:?}",
        contract.values
    )))
}

/// GH #51 — maps the 2 completion-time verdict-contract `EngineError`
/// variants (raised by the embedded choke point inside
/// `Engine::submit_worker_result_trusted` / `Engine::submit_output`) to
/// their `422` HTTP shape; every other `EngineError` variant falls back
/// to the pre-existing generic `500` `ApiError::engine` wrapping,
/// unchanged. Shared by [`worker_submit`] and [`worker_result`] — both
/// routes surface the SAME embedded engine-side check, so their
/// HTTP-layer error translation is identical too (this is HTTP
/// status-code translation, not the verdict-contract logic itself, which
/// stays the single engine-side choke point per GH #51's "not duplicated
/// into each route handler" constraint).
///
/// `context` labels the wrapped `EngineError`'s `Display` text for the
/// fallback `500` case only, matching the pre-existing
/// `format!("<call>: {e}")` style each call site used before this
/// helper.
fn map_completion_result<T>(result: Result<T, EngineError>, context: &str) -> Result<T, ApiError> {
    result.map_err(|e| match e {
        EngineError::VerdictValueRejected { value, allowed } => ApiError::unprocessable(format!(
            "verdict contract violation: {value:?} is not a member of the declared values {allowed:?}"
        )),
        EngineError::VerdictPartMissing { allowed } => ApiError::unprocessable(format!(
            "verdict contract violation: no staged \"verdict\" part found for this attempt; declared values {allowed:?}"
        )),
        other => ApiError::engine(format!("{context}: {other}")),
    })
}

/// `POST /v1/worker/submit`. Bearer = encoded `CapToken`. Body = raw text/octet.
///
/// Simplification-axis endpoint for SubAgents. Removes the JSON construction,
/// duplicated `task_id`, and JSON-escape burden of `/v1/worker/result` — the
/// worker completes a POST with just token + raw body. Origin: the recent clean-up
/// of the SubAgent contract drift (fewer IDs to pass around, multi-line escape
/// accidents eliminated).
///
/// **GH #42 `@file:` sentinel**: workers whose result body is too large to
/// re-emit inline (multi-KB structured output) may `Write` the payload to
/// a file under their task's `work_dir` and submit the body
/// `@file:<abs-path>` instead — see [`resolve_file_sentinel`].
/// Non-sentinel bodies pass through unchanged. The step must opt in via
/// `allow_file_submit: true` (GH #43, default-deny — see
/// [`FILE_SENTINEL_ALLOW_KEY`]).
///
/// **`submit_format: "json"` opt-in**: a step whose meta channel declares
/// [`SUBMIT_FORMAT_KEY`] as `"json"` gets its final body parsed into a
/// structured [`Value`] before it is folded into the flow ctx, so a
/// downstream `fanout` / `branch` can address fields inside it. Applied
/// after sentinel resolution (so the two combine), declared-strict
/// (unparseable → `422`), default-deny for every undeclared step — see
/// [`resolve_submit_value`].
///
/// Behavior:
/// - `task_id` is auto-looked-up server-side from the token (already bound to the `CapToken`).
/// - Body raw bytes go as-is into `Value::String` for `submit_output` + `post_result`
///   (unless the step declared `submit_format: "json"`, above).
/// - `ok=true` fixed (= the submit endpoint is success-path only). For the error
///   path, use `/v1/worker/result` with an explicit `ok=false`.
#[derive(Debug, Deserialize, Default)]
pub struct SubmitQuery {
    /// Optional. `ok=false` signals failure (= `DispatchOutcome::Blocked`, caught
    /// by the flow.ir Try path). Unspecified (`None`) is treated as `ok=true`
    /// (= normal success).
    #[serde(default)]
    pub ok: Option<bool>,
    /// GH #76 HTTP wire: opt-in verdict tier selector. When absent, `ok` alone
    /// drives the tier (pre-#76 byte-for-byte behavior:
    /// `ok=true|absent → Pass`, `ok=false → Blocked`). When present, must
    /// be one of `"pass"`, `"blocked"`, `"skip"` — anything else returns
    /// 400. `verdict=skip` requires `ok` to be absent or `true`: an
    /// explicit `verdict=skip&ok=false` is a conflicting signal and also
    /// returns 400. `verdict=pass` / `verdict=blocked` semantics match
    /// the corresponding `ok` boolean; a `verdict=pass&ok=false` or
    /// `verdict=blocked&ok=true` combination is also a conflict → 400.
    #[serde(default)]
    pub verdict: Option<String>,
}

/// GH #76 HTTP wire: resolve the `(ok, verdict)` query-param pair into the
/// [`SubmitOutcome`] the engine call takes. Kept as a plain free function
/// (not a method on `SubmitQuery`) so the exhaustive match is unit-testable
/// from `#[cfg(test)]` without threading an `AppState` through.
///
/// - `verdict` absent: `ok=true|None → Pass`, `ok=false → Blocked` (=
///   pre-#76 wire, byte-for-byte).
/// - `verdict=pass`: allowed with `ok=true|None`; conflicts with `ok=false`.
/// - `verdict=blocked`: allowed with `ok=false|None`; conflicts with `ok=true`.
/// - `verdict=skip`: allowed with `ok=true|None`; conflicts with `ok=false`.
/// - `verdict` = anything else: `Err` with a message naming the valid set.
fn resolve_submit_outcome(
    verdict: Option<&str>,
    ok: Option<bool>,
) -> Result<SubmitOutcome, String> {
    match verdict {
        None => Ok(if ok.unwrap_or(true) {
            SubmitOutcome::Pass
        } else {
            SubmitOutcome::Blocked
        }),
        Some(v) => match v {
            "pass" => {
                if ok == Some(false) {
                    Err(
                        "conflicting signal: verdict=pass with ok=false; drop one of them"
                            .to_string(),
                    )
                } else {
                    Ok(SubmitOutcome::Pass)
                }
            }
            "blocked" => {
                if ok == Some(true) {
                    Err(
                        "conflicting signal: verdict=blocked with ok=true; drop one of them"
                            .to_string(),
                    )
                } else {
                    Ok(SubmitOutcome::Blocked)
                }
            }
            "skip" => {
                if ok == Some(false) {
                    Err(
                        "conflicting signal: verdict=skip with ok=false; drop one of them"
                            .to_string(),
                    )
                } else {
                    Ok(SubmitOutcome::Skip)
                }
            }
            other => Err(format!(
                "verdict must be one of: pass, blocked, skip (got {other:?})"
            )),
        },
    }
}

/// `POST /v1/worker/submit`. Simplified counterpart of [`worker_result`]:
/// the caller sends only the raw result body, `task_id` is resolved
/// server-side from the Bearer handle/token, and `ok` defaults to `true`
/// unless overridden via [`SubmitQuery::ok`]. See the module doc for the
/// short-handle vs full-`CapToken` Bearer forms.
pub async fn worker_submit(
    State(state): State<AppState>,
    headers: HeaderMap,
    Query(q): Query<SubmitQuery>,
    body: axum::body::Bytes,
) -> Result<StatusCode, ApiError> {
    // Bearer accepts either (a) `wh-<8 hex>` short handle (recommended for
    // SubAgents) or (b) base64-wrapped CapToken JSON (the full-token form).
    let bearer = extract_bearer_raw(&headers)?;
    let task_id = if let Some(handle) = parse_worker_handle(&bearer) {
        state
            .engine
            .task_id_from_handle(handle)
            .await
            .map_err(map_handle_lookup_err)?
    } else {
        let token = CapToken::decode(bearer.trim())
            .map_err(|e| ApiError::bad_request(format!("invalid token: {e}")))?;
        state
            .engine
            .task_id_from_token(&token)
            .await
            .map_err(|e| ApiError::engine(format!("task_id_from_token: {e}")))?
    };
    let attempt = state
        .engine
        .task_attempt(&task_id)
        .await
        .map_err(|e| ApiError::engine(format!("task_attempt: {e}")))?;
    // GH #37: fail loud (410) instead of silently accepting a submit whose
    // addressed Run is already terminal — see `reject_if_run_terminal`.
    reject_if_run_terminal(&state, &task_id, attempt).await?;
    // Strip trailing whitespace (newlines, etc.) so flow.ir `Eq` string matches
    // don't drift on `"BLOCKED\n" == "BLOCKED"` false results. Origin: the recent clean-up
    // verdict_loop smoke — sharp-edge removal. Internal `\n` inside the raw bytes
    // is preserved (= only trailing).
    let body_str = String::from_utf8_lossy(&body).trim_end().to_string();
    // GH #42: `@file:<abs-path>` sentinel — pass through unchanged when
    // absent (byte-for-byte compat with pre-#42 callers).
    let body_str = resolve_file_sentinel(&state, &task_id, attempt, body_str).await?;
    // GH #51: the `channel: "body"` submit-time check formerly performed
    // here (`check_verdict_contract(&state, &task_id, VerdictChannel::Body,
    // ..)`) is now performed inside `Engine::submit_worker_result_trusted`
    // itself — the single completion-time choke point shared by all 3
    // completion routes (see `map_completion_result`'s doc). No separate
    // call is needed here; `check_verdict_contract` remains in use by
    // `worker_artifact`'s staging-time `name == "verdict"` early
    // validation, unchanged.
    //
    // `submit_format` handling: `"json"` (strict) parses here or 422s;
    // `"text"` and undeclared stage the raw string byte-for-byte (see
    // `resolve_submit_value`) — for undeclared steps the engine's
    // Final-pull fold later applies its default lenient container parse
    // (`FoldParse::Lenient`). The verdict-contract check still runs
    // downstream (inside the engine) on whatever value this produces, so
    // an undeclared gate agent's bare token is compared exactly as before
    // (a bare token is scalar, never touched by the lenient fold).
    let value = resolve_submit_value(&state, &task_id, attempt, body_str).await?;

    // GH #76 HTTP wire: resolve the `(ok, verdict)` query-param pair into the
    // `SubmitOutcome` the engine call takes. The handle path = trusted
    // internal API (= the server-minted handle is validated by the earlier
    // lookup); the full-token path = existing verify-by-token API. Both are
    // reflected identically into final + last_result. Absent `verdict`
    // preserves the pre-#76 wire byte-for-byte (`ok=true|absent → Pass`,
    // `ok=false → Blocked`); `verdict=skip` is the new opt-in third tier
    // (see [`resolve_submit_outcome`] for the full truth table).
    let outcome =
        resolve_submit_outcome(q.verdict.as_deref(), q.ok).map_err(ApiError::bad_request)?;
    let submit_result = state
        .engine
        .submit_worker_result_trusted(&task_id, attempt, value, outcome)
        .await;
    map_completion_result(submit_result, "submit_worker_result_trusted")?;
    Ok(StatusCode::NO_CONTENT)
}

/// Query params for `POST /v1/worker/artifact`.
#[derive(Debug, Deserialize)]
pub struct ArtifactQuery {
    /// Artifact name (GH #36 ST1: named multi-part worker output). Required
    /// and non-empty (400 otherwise) — becomes the object key
    /// `Engine::dispatch_attempt_with`'s Final-pull folds this part under
    /// (`{"out": <final>, "parts": {<name>: <value>, ...}}`, see that
    /// method's doc). No character restriction is enforced here (a BP
    /// author references it via bracket notation, e.g. `$.out.parts["a.b"]`).
    pub name: String,
}

/// `POST /v1/worker/artifact?name=<name>`. Bearer = same short-handle /
/// full-`CapToken` forms as [`worker_submit`]. Body = raw text/octet.
///
/// Simplification-axis sibling of [`worker_submit`] (GH #36 ST1): lets a
/// worker with more than one named result POST each part independently —
/// same 1-part-per-POST simplicity as `/v1/worker/submit`, no Single Big
/// JSON the worker has to construct/escape itself — then complete the
/// attempt with an ordinary `/v1/worker/submit` (unchanged). Staging alone
/// never completes the attempt; `dispatch_attempt_with` only pulls the
/// tail's `Final` (whichever endpoint submits it) and folds every staged
/// `Artifact` into `"parts"` at that point.
///
/// Behavior:
/// - `task_id` is auto-looked-up server-side from the token/handle, same as
///   [`worker_submit`].
/// - `name` is required and non-empty; missing or blank → 400.
/// - Body raw bytes go as-is into `Value::String` (same trailing-whitespace
///   trim as `worker_submit`) and are staged via
///   [`mlua_swarm::core::engine::Engine::stage_worker_artifact_trusted`] —
///   which is also what `materialize_part` writes, so the part FILE is
///   always the submitted bytes verbatim. The engine's Final-pull fold
///   applies its default lenient container parse to the part's ctx value
///   (a JSON object / array part becomes addressable, e.g.
///   `$.<step>.parts["plan-meta.json"].lanes`); `submit_format: "text"`
///   on the step opts its parts (and body) out of that parse.
/// - Staging the same `name` twice within one attempt: last write wins (the
///   Final-pull fold walks the tail in event order — see its doc).
pub async fn worker_artifact(
    State(state): State<AppState>,
    headers: HeaderMap,
    Query(q): Query<ArtifactQuery>,
    body: axum::body::Bytes,
) -> Result<StatusCode, ApiError> {
    let name = q.name.trim();
    if name.is_empty() {
        return Err(ApiError::bad_request("name must not be empty".into()));
    }
    let name = name.to_string();

    let bearer = extract_bearer_raw(&headers)?;
    let task_id = if let Some(handle) = parse_worker_handle(&bearer) {
        state
            .engine
            .task_id_from_handle(handle)
            .await
            .map_err(map_handle_lookup_err)?
    } else {
        let token = CapToken::decode(bearer.trim())
            .map_err(|e| ApiError::bad_request(format!("invalid token: {e}")))?;
        state
            .engine
            .task_id_from_token(&token)
            .await
            .map_err(|e| ApiError::engine(format!("task_id_from_token: {e}")))?
    };
    let attempt = state
        .engine
        .task_attempt(&task_id)
        .await
        .map_err(|e| ApiError::engine(format!("task_attempt: {e}")))?;
    // GH #37: fail loud (410) instead of silently staging a part whose
    // addressed Run is already terminal — see `reject_if_run_terminal`.
    reject_if_run_terminal(&state, &task_id, attempt).await?;
    let body_str = String::from_utf8_lossy(&body).trim_end().to_string();
    // GH #42: same `@file:<abs-path>` sentinel as `worker_submit`.
    let body_str = resolve_file_sentinel(&state, &task_id, attempt, body_str).await?;
    // GH #50: submit-time verdict contract gate (Enforcement Point 2),
    // ONLY for the literal `"verdict"` part name (Pattern B's staging
    // channel — see `blueprint-authoring.md`'s "Returning verdicts to
    // drive BP flow" section). Every other part name skips the gate
    // entirely, unchanged from pre-GH-#50 behavior.
    if name == "verdict" {
        check_verdict_contract(&state, &task_id, VerdictChannel::Part, &body_str).await?;
    }
    let value = Value::String(body_str);

    state
        .engine
        .stage_worker_artifact_trusted(&task_id, attempt, name, value)
        .await
        .map_err(|e| ApiError::engine(format!("stage_worker_artifact_trusted: {e}")))?;
    Ok(StatusCode::NO_CONTENT)
}

/// Body for `POST /v1/worker/degradation` (GH #32).
///
/// The persisted shape is [`DegradationEntry`], not this struct: the
/// server injects `step_ref` / `attempt` / `at` on the way in. `JsonSchema`
/// is derived because this body is hand-authored by worker harness
/// implementors, who read it from `mse://api/http-endpoints`.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct DegradationBody {
    /// The tool (or capability) the worker attempted to use.
    pub tool: String,
    /// The error that triggered the fallback, in the worker's own words.
    pub error: String,
    /// What the worker substituted instead of failing.
    pub fallback: String,
    /// Optional free-form context from the worker.
    #[serde(default)]
    pub note: Option<String>,
}

/// `POST /v1/worker/degradation` (GH #32). Bearer = same short-handle /
/// full-`CapToken` forms as [`worker_submit`]. Body = JSON, not raw bytes —
/// this endpoint carries structured data, unlike its raw-bytes siblings.
///
/// Independent channel: appends a [`DegradationEntry`] to
/// `RunRecord.degradations` via `RunStore::append_degradation` directly.
/// Never touches `OutputStore` / the fold path (Crux invariant 2 — a
/// degradation must not surface as step OUTPUT / `$.step.parts`).
///
/// Behavior:
/// - `task_id` is auto-looked-up server-side from the token/handle, same as
///   [`worker_submit`] / [`worker_artifact`].
/// - GH #37 terminal-run guard applies first — a degradation addressed at
///   an already-terminal Run is rejected with `410 Gone`
///   ([`reject_if_run_terminal`]), same as a submit/artifact would be.
/// - `step_ref` / `attempt` / `at` are server-injected — `step_ref` is the
///   fetching agent's resolved name (`AgentContextView.agent`, the best
///   proxy for `Step.ref` available at this layer), `attempt` is the
///   task's current attempt, `at` is now (Unix epoch seconds). The client
///   body never supplies any of the three.
/// - No Run linkage in `agent_ctx` (a pre-run-tracking dispatch), an
///   unparseable `run_id`, or an `append_degradation` call against a Run
///   the store doesn't actually hold (`RunStoreError::NotFound` — the same
///   condition [`reject_if_run_terminal`] itself fails open on) all take
///   the same silent `204 No Content` path, logged via `tracing::warn!` —
///   this is a legitimate no-tracking codepath, not a client error. Any
///   other `RunStore` failure propagates as `ApiError::engine`.
pub async fn worker_degradation(
    State(state): State<AppState>,
    headers: HeaderMap,
    Json(body): Json<DegradationBody>,
) -> Result<StatusCode, ApiError> {
    let bearer = extract_bearer_raw(&headers)?;
    let task_id = if let Some(handle) = parse_worker_handle(&bearer) {
        state
            .engine
            .task_id_from_handle(handle)
            .await
            .map_err(map_handle_lookup_err)?
    } else {
        let token = CapToken::decode(bearer.trim())
            .map_err(|e| ApiError::bad_request(format!("invalid token: {e}")))?;
        state
            .engine
            .task_id_from_token(&token)
            .await
            .map_err(|e| ApiError::engine(format!("task_id_from_token: {e}")))?
    };
    let attempt = state
        .engine
        .task_attempt(&task_id)
        .await
        .map_err(|e| ApiError::engine(format!("task_attempt: {e}")))?;
    // GH #37: the same terminal-run guard `worker_submit` / `worker_artifact`
    // apply — a dead Run must not accumulate signals.
    reject_if_run_terminal(&state, &task_id, attempt).await?;

    // Same `with_state` resolution pattern as `reject_if_run_terminal`: an
    // engine-level failure here is fail-open too (`_ => ...`), matching
    // that guard's own "every resolution step is fail-open" contract —
    // this lookup isn't a second, stricter gate on top of it.
    let tid = task_id.clone();
    let (run_id_str, agent) = match state
        .engine
        .with_state("worker_degradation_run_lookup", move |s| {
            s.agent_ctx.get(&(tid, attempt)).and_then(|e| {
                e.view
                    .run_id
                    .clone()
                    .map(|run_id| (run_id, e.view.agent.clone()))
            })
        })
        .await
    {
        Ok(Some(pair)) => pair,
        _ => {
            tracing::warn!(%task_id, "worker_degradation: no run linkage for this task; entry dropped");
            return Ok(StatusCode::NO_CONTENT);
        }
    };
    let Ok(run_id) = RunId::parse(run_id_str) else {
        tracing::warn!(%task_id, "worker_degradation: run_id failed to parse; entry dropped");
        return Ok(StatusCode::NO_CONTENT);
    };

    // RunTrace mirror: the degradation also lands on the per-Run trace
    // stream (`worker.degradation`) so the timeline is self-contained —
    // the authoritative record stays `RunRecord.degradations` below.
    mlua_swarm::store::trace::TraceHandle::new(run_id.clone(), state.run_trace_store.clone())
        .append(
            mlua_swarm::store::trace::kind::WORKER_DEGRADATION,
            Some(agent.as_str()),
            Some(attempt),
            serde_json::json!({
                "tool": body.tool.as_str(),
                "error": body.error.as_str(),
                "fallback": body.fallback.as_str(),
            }),
        )
        .await;

    let entry = DegradationEntry {
        tool: body.tool,
        error: body.error,
        fallback: body.fallback,
        note: body.note,
        step_ref: Some(agent),
        attempt: Some(attempt),
        at: crate::tasks::now_secs(),
    };
    match state.run_store.append_degradation(&run_id, entry).await {
        Ok(()) => Ok(StatusCode::NO_CONTENT),
        Err(RunStoreError::NotFound(_)) => {
            tracing::warn!(%task_id, %run_id, "worker_degradation: run not found in run_store; entry dropped");
            Ok(StatusCode::NO_CONTENT)
        }
        Err(e) => Err(ApiError::engine(format!("append_degradation: {e}"))),
    }
}

/// Request body for `POST /v1/worker/stats` — a worker's self-reported
/// per-attempt stats (per-step run stats, operator axis). Every field
/// optional; an all-empty body is accepted and dropped.
///
/// Field-for-field the wire twin of [`mlua_swarm::store::trace::WorkerStats`],
/// which is what the handler converts it into; the one difference is this
/// body's `worker_kind` default of `"operator"`. The property sets are
/// drift-locked by `stats_body_schema_matches_worker_stats_property_set`.
/// `JsonSchema` is derived because this body is hand-authored by worker
/// harness implementors, who read it from `mse://api/http-endpoints`.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct StatsBody {
    /// Worker kind label. Defaults to `"operator"` — this endpoint's
    /// primary caller is the WS-operator / SubAgent axis, whose spawn
    /// path has no in-process fold site to attach stats at.
    #[serde(default)]
    pub worker_kind: Option<String>,
    /// The model that served the attempt, self-reported.
    #[serde(default)]
    pub model: Option<String>,
    /// Normalized token usage.
    #[serde(default)]
    pub usage: Option<mlua_swarm::store::trace::TokenUsage>,
    /// Number of LLM turns the attempt ran.
    #[serde(default)]
    pub num_turns: Option<u32>,
    /// Free-form worker-specific detail (size-capped on fold).
    #[serde(default)]
    pub adapter_data: Option<Value>,
}

/// `POST /v1/worker/stats`. Bearer = same short-handle / full-`CapToken`
/// forms as [`worker_submit`]. Body = JSON ([`StatsBody`]).
///
/// Records normalized per-attempt worker stats via
/// `Engine::record_worker_stats`; the dispatcher's outcome fold drains
/// them into the terminal `StepEntry`. Sibling of
/// [`worker_degradation`] on the observational plane: never touches the
/// fold path / step OUTPUT, and SHOULD be called before the final
/// `/v1/worker/submit` (the dispatcher folds at outcome time — stats
/// arriving after the fold are dropped with the attempt's cleanup).
pub async fn worker_stats(
    State(state): State<AppState>,
    headers: HeaderMap,
    Json(body): Json<StatsBody>,
) -> Result<StatusCode, ApiError> {
    let bearer = extract_bearer_raw(&headers)?;
    let task_id = if let Some(handle) = parse_worker_handle(&bearer) {
        state
            .engine
            .task_id_from_handle(handle)
            .await
            .map_err(map_handle_lookup_err)?
    } else {
        let token = CapToken::decode(bearer.trim())
            .map_err(|e| ApiError::bad_request(format!("invalid token: {e}")))?;
        state
            .engine
            .task_id_from_token(&token)
            .await
            .map_err(|e| ApiError::engine(format!("task_id_from_token: {e}")))?
    };
    let attempt = state
        .engine
        .task_attempt(&task_id)
        .await
        .map_err(|e| ApiError::engine(format!("task_attempt: {e}")))?;
    // GH #37: the same terminal-run guard as the sibling worker routes —
    // a dead Run must not accumulate signals.
    reject_if_run_terminal(&state, &task_id, attempt).await?;

    let stats = mlua_swarm::store::trace::WorkerStats {
        worker_kind: Some(body.worker_kind.unwrap_or_else(|| "operator".to_string())),
        model: body.model,
        usage: body.usage,
        num_turns: body.num_turns,
        adapter_data: body.adapter_data,
    };
    state
        .engine
        .record_worker_stats(&task_id, attempt, stats)
        .await;
    Ok(StatusCode::NO_CONTENT)
}

/// GH #37: terminal-run guard shared by [`worker_submit`] / [`worker_artifact`].
///
/// Resolves the dispatch task's `AgentContextView.run_id` (threaded at
/// spawn time when a `RunContext` accompanied the launch) and rejects the
/// submit with `410 Gone` when the addressed Run has already reached a
/// terminal status (`Done` / `Failed` / `Interrupted`) — the flow-eval
/// driver for that Run is gone, so the staged/final value could never be
/// folded into a flow context. Before this guard, such a submit was
/// silently accepted with `204` and the worker's output orphaned — the
/// exact failure shape observed when a long-running worker outlived the
/// GH #33 sync launch ceiling.
///
/// Every resolution step is fail-open (missing agent-ctx entry / missing
/// `run_id` / unparseable id / unknown Run → `Ok(())`), matching this
/// crate's other best-effort projection hooks: a pre-run-tracking dispatch
/// must keep working exactly as before.
async fn reject_if_run_terminal(
    state: &AppState,
    task_id: &StepId,
    attempt: u32,
) -> Result<(), ApiError> {
    let tid = task_id.clone();
    let run_id_str = match state
        .engine
        .with_state("worker_terminal_run_guard", move |s| {
            s.agent_ctx
                .get(&(tid, attempt))
                .and_then(|e| e.view.run_id.clone())
        })
        .await
    {
        Ok(Some(rid)) => rid,
        _ => return Ok(()),
    };
    let Ok(run_id) = RunId::parse(run_id_str) else {
        return Ok(());
    };
    let Ok(rec) = state.run_store.get(&run_id).await else {
        return Ok(());
    };
    match rec.status {
        RunStatus::Done | RunStatus::Failed | RunStatus::Interrupted | RunStatus::Cancelled => {
            Err(ApiError::gone(format!(
                "run {run_id} is already terminal ({:?}): this attempt's output cannot be \
             delivered to a flow context; re-kick the task (POST /v1/tasks/:id/runs) and \
             fetch a fresh prompt",
                rec.status
            )))
        }
        RunStatus::Pending | RunStatus::Running => Ok(()),
    }
}

/// Query params for `GET /v1/worker/prompt/system`. Field names are fixed to
/// `task_id` / `attempt` — this is the exact shape the engine bakes into
/// `system_ref.uri`'s query string for `Http` mode (GH #31), so the names
/// here must match verbatim.
#[derive(Debug, Deserialize)]
pub struct PromptSystemQuery {
    /// Task the fetched raw system prompt belongs to; cross-checked
    /// against the Bearer handle/token, same as [`PromptQuery::task_id`].
    pub task_id: StepId,
    /// Attempt number the baked system prompt was recorded under.
    pub attempt: u32,
}

/// `GET /v1/worker/prompt/system?task_id=<tid>&attempt=<n>` (GH #31). The
/// `Http`-mode fetch target for `system_ref.uri`: serves the exact baked
/// `system` bytes for `(task_id, attempt)` as a raw `text/plain` body — not
/// JSON-wrapped, since `mse_worker_fetch` needs the precise byte sequence to
/// sha256-verify against `system_ref.sha256`.
///
/// Same Bearer auth flow as [`worker_prompt`] (short handle or full
/// `CapToken`); 404 via [`ApiError::not_found`] if no baked system exists for
/// that `(task_id, attempt)`.
pub async fn worker_prompt_system(
    State(state): State<AppState>,
    headers: HeaderMap,
    Query(q): Query<PromptSystemQuery>,
) -> Result<impl axum::response::IntoResponse, ApiError> {
    let task_id = q.task_id;
    let attempt = q.attempt;
    let bearer = extract_bearer_raw(&headers)?;
    if let Some(handle) = parse_worker_handle(&bearer) {
        let resolved = state
            .engine
            .task_id_from_handle(handle)
            .await
            .map_err(map_handle_lookup_err)?;
        if resolved != task_id {
            return Err(ApiError::bad_request(format!(
                "handle {handle} is bound to task {resolved}, not {task_id}"
            )));
        }
    } else {
        let token = CapToken::decode(bearer.trim())
            .map_err(|e| ApiError::bad_request(format!("invalid token: {e}")))?;
        state
            .engine
            .verify_token_for_task(&token, mlua_swarm::Verb::FetchPrompt, &task_id)
            .await
            .map_err(|e| ApiError::engine(format!("verify_token_for_task: {e}")))?;
    }
    let system = state
        .engine
        .raw_system_prompt(&task_id, attempt)
        .await
        .map_err(|e| ApiError::engine(format!("raw_system_prompt: {e}")))?
        .ok_or_else(|| {
            ApiError::not_found(format!(
                "no baked system prompt for task {task_id} attempt {attempt}"
            ))
        })?;
    Ok((
        [(header::CONTENT_TYPE, "text/plain; charset=utf-8")],
        system,
    ))
}

/// Response body for `GET /v1/agents/:name/render-size`.
#[derive(Debug, serde::Serialize)]
pub struct AgentRenderSizeResponse {
    /// The agent name looked up (echoed back verbatim from the path param).
    pub agent: String,
    /// Most-recently-baked `system_prompt` render size in bytes for this
    /// agent, or `None` if `bake_worker_system_prompt` has never recorded
    /// one (a freshly-added agent that has never been dispatched).
    pub last_rendered_bytes: Option<usize>,
}

/// `GET /v1/agents/:name/render-size` (GH #31). Live per-agent-name lookup
/// of the most-recently-baked `system_prompt` render size, backing
/// `bp_doctor`'s post-render size check. No Bearer required — same
/// unauthenticated trust tier as `GET /v1/blueprints/:id/head`
/// (`blueprints::get_head`), an operator-diagnostic route.
///
/// `last_rendered_bytes: null` is a normal, expected response (a
/// freshly-added agent that has never been dispatched yet) — always
/// `200 OK`, never a 404.
pub async fn agent_render_size(
    State(state): State<AppState>,
    axum::extract::Path(name): axum::extract::Path<String>,
) -> Json<AgentRenderSizeResponse> {
    let last_rendered_bytes = state.engine.agent_last_rendered_size(&name).await;
    Json(AgentRenderSizeResponse {
        agent: name,
        last_rendered_bytes,
    })
}

/// Extracts the raw string from the `Authorization` header (= strips the `Bearer `
/// prefix). To let `worker_submit` accept both short handles and full tokens, we
/// fetch the raw value before any decode.
fn extract_bearer_raw(headers: &HeaderMap) -> Result<String, ApiError> {
    let v = headers
        .get(AUTHORIZATION)
        .ok_or_else(|| ApiError::bad_request("missing Authorization header".into()))?
        .to_str()
        .map_err(|_| ApiError::bad_request("invalid Authorization header encoding".into()))?;
    let s = v
        .strip_prefix("Bearer ")
        .ok_or_else(|| ApiError::bad_request("Authorization must be 'Bearer <token>'".into()))?
        .trim();
    if s.is_empty() {
        return Err(ApiError::bad_request("Bearer is empty".into()));
    }
    Ok(s.to_string())
}

/// Maps a `task_id_from_handle` failure on the short-handle Bearer path. A
/// `wh-`-prefixed handle that parsed as well-formed (via
/// [`parse_worker_handle`]) but is unknown to the engine
/// (`EngineError::TokenNotFound`) is a handle that was minted before the
/// engine's in-memory state was wiped — typically a server restart. "Once
/// valid, now gone" is exactly `410 Gone`: the worker should re-kick its
/// task and fetch a fresh handle rather than treat this as a server fault.
/// Every other engine error stays a `500` (unchanged), same wrapping style
/// as the pre-existing call sites.
///
/// Only reached on the handle path (`parse_worker_handle` returned `Some`),
/// so it never re-labels a full-`CapToken` decode/verify failure.
fn map_handle_lookup_err(e: EngineError) -> ApiError {
    match e {
        EngineError::TokenNotFound(_) => ApiError::gone(
            "worker handle is no longer valid (the engine's in-flight state was reset, \
             e.g. by a server restart): re-kick the task (POST /v1/tasks/:id/runs) and \
             fetch a fresh prompt/handle"
                .to_string(),
        ),
        other => ApiError::engine(format!("task_id_from_handle: {other}")),
    }
}

/// Decides whether the Bearer is a short handle (`wh-XXXXXXXX`). Returns
/// `Some(handle)` on a match, `None` otherwise (= caller proceeds to try decoding
/// as full `CapToken` JSON).
fn parse_worker_handle(s: &str) -> Option<&str> {
    let s = s.trim();
    if s.starts_with("wh-")
        && s.len() >= 5
        && s.len() <= 64
        && s[3..].chars().all(|c| c.is_ascii_alphanumeric())
    {
        Some(s)
    } else {
        None
    }
}

/// Decodes an encoded `CapToken` from `Authorization: Bearer <encoded CapToken>`.
/// Kept separate from `extract_bearer` (sid-only) — kept as a distinct fn so
/// that sid strings and encoded tokens are not confused, distinguishing them by type.
fn decode_worker_bearer(headers: &HeaderMap) -> Result<CapToken, ApiError> {
    let v = headers
        .get(AUTHORIZATION)
        .ok_or_else(|| ApiError::bad_request("missing Authorization header".into()))?
        .to_str()
        .map_err(|_| ApiError::bad_request("invalid Authorization header encoding".into()))?;
    let encoded = v
        .strip_prefix("Bearer ")
        .ok_or_else(|| ApiError::bad_request("Authorization must be 'Bearer <token>'".into()))?
        .trim();
    if encoded.is_empty() {
        return Err(ApiError::bad_request("Bearer token is empty".into()));
    }
    CapToken::decode(encoded).map_err(|e| ApiError::bad_request(format!("invalid token: {e}")))
}

// ──────────────────────────────────────────────────────────────────────────
// UT — `assemble_step_pointers` (`projection-adapter` ST5 Worker axis)
// ──────────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use axum::response::IntoResponse;
    use mlua_swarm::core::agent_context::AgentContextView;
    use mlua_swarm::core::config::EngineCfg;
    use mlua_swarm::core::engine::Engine;
    use mlua_swarm::store::output::{InMemoryOutputStore, OutputStore};
    use mlua_swarm::store::run::{InMemoryRunStore, RunRecord, RunStatus, RunStore, StepEntry};
    use mlua_swarm::store::task::InMemoryTaskStore;
    use mlua_swarm::{RunId, StepId, TaskId};
    use serde_json::json;
    use std::collections::HashMap;
    use std::sync::Arc;
    use tokio::sync::Mutex;

    /// Per-module test-helper convention (this crate's established
    /// pattern — see e.g. `projection::tests::test_state`): a minimal
    /// `AppState` wired with the caller-supplied `data_store` / `run_store`
    /// so a test can seed both directly rather than driving a real
    /// dispatch through them.
    fn test_state(data_store: Arc<dyn OutputStore>, run_store: Arc<dyn RunStore>) -> AppState {
        let engine = Engine::new(EngineCfg::default());
        let compiler = mlua_swarm::Compiler::new(crate::default_registry());
        let launch = Arc::new(mlua_swarm::TaskLaunchService::new(engine.clone(), compiler));
        AppState {
            engine,
            sessions: Arc::new(Mutex::new(crate::SessionStore::default())),
            task_app: Arc::new(mlua_swarm::TaskApplication::new_inline_only(launch)),
            ws_operator_factory: None,
            data_store,
            operator_sessions: Arc::new(Mutex::new(HashMap::new())),
            roles_to_sid: Arc::new(Mutex::new(HashMap::new())),
            task_store: Arc::new(InMemoryTaskStore::new()),
            run_store,
            replay_store: Arc::new(mlua_swarm::store::replay::InMemoryReplayStore::new()),
            run_trace_store: Arc::new(mlua_swarm::store::trace::InMemoryRunTraceStore::new()),
            base_url: None,
            sync_timeout_secs: 300,
        }
    }

    // GH #76 HTTP wire — `resolve_submit_outcome` truth table. Guards the
    // exhaustive `(verdict, ok)` mapping against silent regressions when
    // future work adds new tiers under `#[non_exhaustive]` `SubmitOutcome`.
    #[test]
    fn resolve_submit_outcome_absent_verdict_preserves_pre_gh76_wire() {
        // ok=None / ok=true / ok=false without verdict → Pass / Pass / Blocked.
        assert!(matches!(
            resolve_submit_outcome(None, None),
            Ok(SubmitOutcome::Pass)
        ));
        assert!(matches!(
            resolve_submit_outcome(None, Some(true)),
            Ok(SubmitOutcome::Pass)
        ));
        assert!(matches!(
            resolve_submit_outcome(None, Some(false)),
            Ok(SubmitOutcome::Blocked)
        ));
    }

    #[test]
    fn resolve_submit_outcome_verdict_pass_and_blocked_match_ok_bool_or_default() {
        assert!(matches!(
            resolve_submit_outcome(Some("pass"), None),
            Ok(SubmitOutcome::Pass)
        ));
        assert!(matches!(
            resolve_submit_outcome(Some("pass"), Some(true)),
            Ok(SubmitOutcome::Pass)
        ));
        assert!(resolve_submit_outcome(Some("pass"), Some(false)).is_err());

        assert!(matches!(
            resolve_submit_outcome(Some("blocked"), None),
            Ok(SubmitOutcome::Blocked)
        ));
        assert!(matches!(
            resolve_submit_outcome(Some("blocked"), Some(false)),
            Ok(SubmitOutcome::Blocked)
        ));
        assert!(resolve_submit_outcome(Some("blocked"), Some(true)).is_err());
    }

    #[test]
    fn resolve_submit_outcome_verdict_skip_is_ok_true_only() {
        assert!(matches!(
            resolve_submit_outcome(Some("skip"), None),
            Ok(SubmitOutcome::Skip)
        ));
        assert!(matches!(
            resolve_submit_outcome(Some("skip"), Some(true)),
            Ok(SubmitOutcome::Skip)
        ));
        // The conflict case the HTTP wire HTTP handler surfaces as 400.
        let err = resolve_submit_outcome(Some("skip"), Some(false))
            .expect_err("skip + ok=false must be a conflict");
        assert!(
            err.contains("conflict") || err.contains("conflicting"),
            "err should name the conflict: {err}"
        );
    }

    #[test]
    fn resolve_submit_outcome_invalid_verdict_names_valid_set() {
        let err = resolve_submit_outcome(Some("bogus"), None)
            .expect_err("unknown verdict must be an error");
        assert!(
            err.contains("pass") && err.contains("blocked") && err.contains("skip"),
            "err should enumerate the valid tier set: {err}"
        );
    }

    /// Drift lock: [`StatsBody`] is the wire twin of
    /// [`mlua_swarm::store::trace::WorkerStats`] — the handler builds one
    /// from the other field by field. A field added to either side alone
    /// silently drops that field from `POST /v1/worker/stats` (or publishes
    /// one the endpoint cannot accept), so the two property sets are
    /// asserted equal rather than left to review.
    #[test]
    fn stats_body_schema_matches_worker_stats_property_set() {
        fn property_names<T: schemars::JsonSchema>() -> std::collections::BTreeSet<String> {
            let schema = serde_json::to_value(schemars::schema_for!(T))
                .expect("schema must serialize as JSON");
            schema
                .get("properties")
                .and_then(|p| p.as_object())
                .expect("schema must expose a properties object")
                .keys()
                .cloned()
                .collect()
        }

        assert_eq!(
            property_names::<StatsBody>(),
            property_names::<mlua_swarm::store::trace::WorkerStats>(),
            "StatsBody and WorkerStats must expose the same property set"
        );
    }

    async fn append_final(
        data_store: &Arc<dyn OutputStore>,
        task_id: &str,
        producer: &str,
        value: Value,
    ) {
        data_store
            .append(
                task_id,
                1,
                producer,
                OutputEvent::Final {
                    content: ContentRef::Inline { value },
                    ok: true,
                },
                vec![],
            )
            .await
            .expect("append final");
    }

    fn step_entry(step_id: &StepId, step_ref: &str) -> StepEntry {
        StepEntry::basic(
            step_id.clone(),
            Some(step_ref.to_string()),
            Some("passed".to_string()),
            None,
            0,
        )
    }

    fn run_record(task_id: &TaskId, run_id: &RunId, step_entries: Vec<StepEntry>) -> RunRecord {
        RunRecord {
            id: run_id.clone(),
            task_id: task_id.clone(),
            status: RunStatus::Running,
            step_entries,
            degradations: Vec::new(),
            operator_sid: None,
            result_ref: None,
            input_json: None,
            created_at: 0,
            updated_at: 0,
        }
    }

    fn consumer_payload(consumer_step_id: &StepId, run_id: &RunId) -> WorkerPayload {
        WorkerPayload {
            task_id: consumer_step_id.clone(),
            attempt: 1,
            agent: "consumer".to_string(),
            system: None,
            prompt: String::new(),
            context: Some(AgentContextView {
                task_id: consumer_step_id.to_string(),
                agent: "consumer".to_string(),
                attempt: 1,
                run_id: Some(run_id.to_string()),
                ..Default::default()
            }),
            system_ref: None,
        }
    }

    /// Test 1: `ContextPolicy.steps` unspecified (no policy seeded at all
    /// — `Engine::context_policy_for`'s "no entry" default is `None` /
    /// pass-all) → the fetch payload carries every submitted step's
    /// `StepPointer`.
    #[tokio::test]
    async fn context_policy_unspecified_yields_every_submitted_step() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let task_id = TaskId::new();
        let run_id = RunId::new();
        let planner_id = StepId::new();
        let coder_id = StepId::new();

        append_final(
            &data_store,
            planner_id.as_str(),
            "planner",
            json!({"plan": "x"}),
        )
        .await;
        append_final(
            &data_store,
            coder_id.as_str(),
            "coder",
            json!({"code": "y"}),
        )
        .await;
        run_store
            .create(run_record(
                &task_id,
                &run_id,
                vec![
                    step_entry(&planner_id, "planner"),
                    step_entry(&coder_id, "coder"),
                ],
            ))
            .await
            .expect("create run");

        let state = test_state(data_store, run_store);
        let consumer_id = StepId::new();
        let mut payload = consumer_payload(&consumer_id, &run_id);
        assemble_step_pointers(&state, &mut payload).await;

        let names: Vec<&str> = payload
            .context
            .as_ref()
            .expect("context")
            .steps
            .iter()
            .map(|p| p.name.as_str())
            .collect();
        assert!(names.contains(&"planner"), "names: {names:?}");
        assert!(names.contains(&"coder"), "names: {names:?}");
    }

    /// Test 2: `steps: ["planner"]` → only `planner`'s pointer is present.
    #[tokio::test]
    async fn context_policy_steps_include_list_filters_to_named_steps() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let task_id = TaskId::new();
        let run_id = RunId::new();
        let planner_id = StepId::new();
        let coder_id = StepId::new();
        append_final(&data_store, planner_id.as_str(), "planner", json!("x")).await;
        append_final(&data_store, coder_id.as_str(), "coder", json!("y")).await;
        run_store
            .create(run_record(
                &task_id,
                &run_id,
                vec![
                    step_entry(&planner_id, "planner"),
                    step_entry(&coder_id, "coder"),
                ],
            ))
            .await
            .expect("create run");

        let state = test_state(data_store, run_store);
        let consumer_id = StepId::new();
        state
            .engine
            .with_state("test.seed_policy", {
                let consumer_id = consumer_id.clone();
                move |s| {
                    s.agent_ctx.insert(
                        (consumer_id, 1),
                        mlua_swarm::core::state::AgentCtxEntry {
                            policy: mlua_swarm_schema::ContextPolicy {
                                steps: Some(vec!["planner".to_string()]),
                                ..Default::default()
                            },
                            ..Default::default()
                        },
                    );
                }
            })
            .await
            .expect("seed policy");

        let mut payload = consumer_payload(&consumer_id, &run_id);
        assemble_step_pointers(&state, &mut payload).await;

        let names: Vec<&str> = payload
            .context
            .as_ref()
            .expect("context")
            .steps
            .iter()
            .map(|p| p.name.as_str())
            .collect();
        assert_eq!(names, vec!["planner"], "names: {names:?}");
    }

    /// Test 3: `steps: []` → the pointer list is empty.
    #[tokio::test]
    async fn context_policy_steps_empty_list_yields_no_pointers() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let task_id = TaskId::new();
        let run_id = RunId::new();
        let planner_id = StepId::new();
        append_final(&data_store, planner_id.as_str(), "planner", json!("x")).await;
        run_store
            .create(run_record(
                &task_id,
                &run_id,
                vec![step_entry(&planner_id, "planner")],
            ))
            .await
            .expect("create run");

        let state = test_state(data_store, run_store);
        let consumer_id = StepId::new();
        state
            .engine
            .with_state("test.seed_policy", {
                let consumer_id = consumer_id.clone();
                move |s| {
                    s.agent_ctx.insert(
                        (consumer_id, 1),
                        mlua_swarm::core::state::AgentCtxEntry {
                            policy: mlua_swarm_schema::ContextPolicy {
                                steps: Some(vec![]),
                                ..Default::default()
                            },
                            ..Default::default()
                        },
                    );
                }
            })
            .await
            .expect("seed policy");

        let mut payload = consumer_payload(&consumer_id, &run_id);
        assemble_step_pointers(&state, &mut payload).await;

        assert!(payload.context.expect("context").steps.is_empty());
    }

    /// Test 4: `steps_exclude` wins over `steps` for a name in both.
    #[tokio::test]
    async fn context_policy_steps_exclude_wins_over_steps() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let task_id = TaskId::new();
        let run_id = RunId::new();
        let planner_id = StepId::new();
        let coder_id = StepId::new();
        append_final(&data_store, planner_id.as_str(), "planner", json!("x")).await;
        append_final(&data_store, coder_id.as_str(), "coder", json!("y")).await;
        run_store
            .create(run_record(
                &task_id,
                &run_id,
                vec![
                    step_entry(&planner_id, "planner"),
                    step_entry(&coder_id, "coder"),
                ],
            ))
            .await
            .expect("create run");

        let state = test_state(data_store, run_store);
        let consumer_id = StepId::new();
        state
            .engine
            .with_state("test.seed_policy", {
                let consumer_id = consumer_id.clone();
                move |s| {
                    s.agent_ctx.insert(
                        (consumer_id, 1),
                        mlua_swarm::core::state::AgentCtxEntry {
                            policy: mlua_swarm_schema::ContextPolicy {
                                steps: Some(vec!["planner".to_string(), "coder".to_string()]),
                                steps_exclude: vec!["planner".to_string()],
                                ..Default::default()
                            },
                            ..Default::default()
                        },
                    );
                }
            })
            .await
            .expect("seed policy");

        let mut payload = consumer_payload(&consumer_id, &run_id);
        assemble_step_pointers(&state, &mut payload).await;

        let names: Vec<&str> = payload
            .context
            .as_ref()
            .expect("context")
            .steps
            .iter()
            .map(|p| p.name.as_str())
            .collect();
        assert_eq!(names, vec!["coder"], "names: {names:?}");
    }

    /// Test 5 (in-flight window, subtask-4-style invariant): the Run has
    /// NOT finalized (`result_ref: None`, mirroring a Run still `Running`)
    /// yet the fetch payload still carries a `StepPointer` for a step
    /// already visible through the Data-plane store — the same mechanism
    /// `crates/mlua-swarm-server/src/projection.rs`'s
    /// `steps_list_returns_in_flight_step_output_before_run_completes`
    /// proves end-to-end through a real gated 2-step dispatch; this test
    /// isolates the same invariant at the `assemble_step_pointers` level.
    #[tokio::test]
    async fn in_flight_step_output_is_visible_before_run_finalizes() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let task_id = TaskId::new();
        let run_id = RunId::new();
        let step1_id = StepId::new();
        append_final(
            &data_store,
            step1_id.as_str(),
            "step1",
            json!({"step1_out": "hi"}),
        )
        .await;
        let mut run = run_record(&task_id, &run_id, vec![step_entry(&step1_id, "step1")]);
        run.status = RunStatus::Running;
        run.result_ref = None; // the in-flight window: not yet finalized.
        run_store.create(run).await.expect("create run");

        let state = test_state(data_store, run_store);
        let consumer_id = StepId::new();
        let mut payload = consumer_payload(&consumer_id, &run_id);
        assemble_step_pointers(&state, &mut payload).await;

        let steps = &payload.context.expect("context").steps;
        assert_eq!(steps.len(), 1);
        assert_eq!(steps[0].name, "step1");
    }

    /// Test 6: the fetching agent's own name is always excluded, even if
    /// (e.g. a loop re-dispatching the same agent) it also appears in
    /// `run.step_entries` with a resolvable Data-plane record.
    #[tokio::test]
    async fn self_agent_name_is_always_excluded() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let task_id = TaskId::new();
        let run_id = RunId::new();
        let planner_id = StepId::new();
        let consumer_prior_id = StepId::new();
        append_final(&data_store, planner_id.as_str(), "planner", json!("x")).await;
        append_final(
            &data_store,
            consumer_prior_id.as_str(),
            "consumer",
            json!("self"),
        )
        .await;
        run_store
            .create(run_record(
                &task_id,
                &run_id,
                vec![
                    step_entry(&planner_id, "planner"),
                    step_entry(&consumer_prior_id, "consumer"),
                ],
            ))
            .await
            .expect("create run");

        let state = test_state(data_store, run_store);
        let consumer_id = StepId::new();
        let mut payload = consumer_payload(&consumer_id, &run_id);
        assemble_step_pointers(&state, &mut payload).await;

        let names: Vec<&str> = payload
            .context
            .as_ref()
            .expect("context")
            .steps
            .iter()
            .map(|p| p.name.as_str())
            .collect();
        assert!(!names.contains(&"consumer"), "names: {names:?}");
        assert!(names.contains(&"planner"), "names: {names:?}");
    }

    /// Test 7 (pointer-only invariant): a `StepPointer`'s serialized JSON
    /// carries no preview / content-bytes field — only `name` /
    /// `size_bytes` / `file_path?` / `content_url` / `sha256`.
    #[tokio::test]
    async fn step_pointer_serializes_with_no_preview_or_content_bytes() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let task_id = TaskId::new();
        let run_id = RunId::new();
        let planner_id = StepId::new();
        append_final(
            &data_store,
            planner_id.as_str(),
            "planner",
            json!({"plan": "do the thing, at length".repeat(50)}),
        )
        .await;
        run_store
            .create(run_record(
                &task_id,
                &run_id,
                vec![step_entry(&planner_id, "planner")],
            ))
            .await
            .expect("create run");

        let state = test_state(data_store, run_store);
        let consumer_id = StepId::new();
        let mut payload = consumer_payload(&consumer_id, &run_id);
        assemble_step_pointers(&state, &mut payload).await;

        let steps = &payload.context.expect("context").steps;
        assert_eq!(steps.len(), 1);
        let json_value = serde_json::to_value(&steps[0]).expect("serialize StepPointer");
        let obj = json_value.as_object().expect("object");
        for forbidden in ["preview", "content", "value", "bytes"] {
            assert!(
                !obj.contains_key(forbidden),
                "StepPointer must not carry a {forbidden:?} field: {obj:?}"
            );
        }
        assert!(obj.contains_key("name"));
        assert!(obj.contains_key("size_bytes"));
        assert!(obj.contains_key("content_url"));
        assert!(obj.contains_key("sha256"));
    }

    /// A single-step Blueprint whose `planner` agent declares
    /// `AgentMeta.projection_name = "plan-out"` — the `StepNaming` fixture
    /// for [`declared_projection_name_pointer_name_is_canonical_and_policy_matches_it`],
    /// mirroring `crate::projection::tests`' own
    /// `declared_projection_name_blueprint` helper (duplicated here rather
    /// than shared — this crate's established per-module test-helper
    /// convention).
    fn declared_name_bp() -> mlua_swarm::blueprint::Blueprint {
        use mlua_flow_ir::{Expr, Node};
        use mlua_swarm::blueprint::{
            current_schema_version, AgentDef, AgentKind, AgentMeta, Blueprint, BlueprintMetadata,
            CompilerHints, CompilerStrategy,
        };
        Blueprint {
            schema_version: current_schema_version(),
            id: "worker-test-declared-name-bp".into(),
            flow: Node::Step {
                ref_: "planner".to_string(),
                in_: Expr::Path {
                    at: "$.in".parse().expect("literal test path: $.in"),
                },
                out: Expr::Path {
                    at: "$.plan".parse().expect("literal test path: $.plan"),
                },
            },
            agents: vec![AgentDef {
                name: "planner".to_string(),
                kind: AgentKind::RustFn,
                spec: json!({"fn_id": "planner"}),
                profile: None,
                meta: Some(AgentMeta {
                    projection_name: Some("plan-out".to_string()),
                    ..Default::default()
                }),
                runner: None,
                runner_ref: None,
                verdict: None,
                lints: None,
            }],
            operators: vec![],
            metas: vec![],
            hints: CompilerHints::default(),
            strategy: CompilerStrategy::default(),
            metadata: BlueprintMetadata::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::new(),
        }
    }

    /// Test 8 (GH #23 subtask-3, declared-name E2E — Worker axis half): a
    /// declared `projection_name` makes `StepPointer.name` the CANONICAL
    /// name (not the raw `Step.ref` the Data-plane / `step_entries` still
    /// index by), and `ContextPolicy.steps` naming the canonical name
    /// matches it.
    #[tokio::test]
    async fn declared_projection_name_pointer_name_is_canonical_and_policy_matches_it() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let task_id = TaskId::new();
        let run_id = RunId::new();
        let planner_id = StepId::new();

        // The Data-plane store is keyed by the CANONICAL name — GH #23
        // subtask-2's sink already writes it that way.
        append_final(
            &data_store,
            planner_id.as_str(),
            "plan-out",
            json!({"plan": "x"}),
        )
        .await;
        run_store
            .create(run_record(
                &task_id,
                &run_id,
                vec![step_entry(&planner_id, "planner")],
            ))
            .await
            .expect("create run");

        let state = test_state(data_store, run_store);

        // Seed the `StepNaming` table the way `Compiler::compile` +
        // `EngineDispatcher::dispatch` would have — the same `Arc` stashed
        // under every dispatched step's own id, including the FETCHING
        // agent's (`consumer_id`), which `assemble_step_pointers` looks up
        // via `Engine::step_naming_for(&payload.task_id)`.
        let (naming, _warnings) =
            mlua_swarm::core::step_naming::StepNaming::from_blueprint(&declared_name_bp())
                .expect("no collision");
        let naming = Arc::new(naming);
        let consumer_id = StepId::new();
        state
            .engine
            .with_state("test.seed_step_naming", {
                let naming = naming.clone();
                let planner_id = planner_id.clone();
                let consumer_id = consumer_id.clone();
                move |s| {
                    s.step_namings.insert(planner_id, naming.clone());
                    s.step_namings.insert(consumer_id, naming);
                }
            })
            .await
            .expect("seed step naming");
        state
            .engine
            .with_state("test.seed_policy", {
                let consumer_id = consumer_id.clone();
                move |s| {
                    s.agent_ctx.insert(
                        (consumer_id, 1),
                        mlua_swarm::core::state::AgentCtxEntry {
                            policy: mlua_swarm_schema::ContextPolicy {
                                steps: Some(vec!["plan-out".to_string()]),
                                ..Default::default()
                            },
                            ..Default::default()
                        },
                    );
                }
            })
            .await
            .expect("seed policy");

        let mut payload = consumer_payload(&consumer_id, &run_id);
        assemble_step_pointers(&state, &mut payload).await;

        let steps = &payload.context.expect("context").steps;
        assert_eq!(steps.len(), 1, "steps: {steps:?}");
        assert_eq!(
            steps[0].name, "plan-out",
            "StepPointer.name must be the canonical name"
        );
    }

    // ──────────────────────────────────────────────────────────────────────
    // GH #31 — `/v1/worker/prompt/system` + `/v1/agents/:name/render-size`
    // ──────────────────────────────────────────────────────────────────────

    /// Seeds a task + baked system prompt + a short worker handle bound to
    /// it, mirroring the shape `Engine::dispatch_attempt` would have
    /// produced (minus the parts these two routes don't touch: no real
    /// HMAC-signed `CapToken`, since `task_id_from_handle`'s handle → fp →
    /// task_id chain is what's under test, not signature verification).
    async fn seed_task_with_handle(
        state: &AppState,
        task_id: &StepId,
        agent: &str,
        attempt: u32,
        system: Option<String>,
    ) -> String {
        let handle = format!("wh-{}", mlua_swarm::types::secure_hex(4));
        let task_id = task_id.clone();
        let agent = agent.to_string();
        let handle_clone = handle.clone();
        state
            .engine
            .with_state("test.seed_task_with_handle", move |s| {
                let mut task = mlua_swarm::core::state::TaskState::new(
                    task_id.clone(),
                    mlua_swarm::core::state::TaskSpec {
                        agent: agent.clone(),
                        initial_directive: json!("x"),
                        step_ctx: None,
                        check_policy: None,
                    },
                );
                task.attempt = attempt;
                s.tasks.insert(task_id.clone(), task);
                s.systems.insert((task_id.clone(), attempt), system);
                let token = CapToken {
                    agent_id: agent,
                    role: mlua_swarm::Role::Worker,
                    scopes: vec!["*".to_string()],
                    issued_at: 0,
                    expire_at: u64::MAX,
                    max_uses: None,
                    nonce: format!("test-nonce-{task_id}"),
                    sig_hex: String::new(),
                };
                let fp = token.fingerprint();
                s.tokens.insert(
                    fp.clone(),
                    mlua_swarm::core::state::CapTokenRecord {
                        token,
                        uses_left: None,
                        revoked: false,
                        task_id: Some(task_id),
                    },
                );
                s.worker_handles.insert(handle_clone, fp);
            })
            .await
            .expect("seed_task_with_handle");
        handle
    }

    fn bearer_headers(handle: &str) -> HeaderMap {
        let mut headers = HeaderMap::new();
        headers.insert(
            AUTHORIZATION,
            format!("Bearer {handle}").parse().expect("header value"),
        );
        headers
    }

    /// `GET /v1/worker/prompt/system` returns the exact raw baked bytes
    /// (not JSON-wrapped) with `Content-Type: text/plain`, for the
    /// `(task_id, attempt)` the handle is bound to.
    #[tokio::test]
    async fn worker_prompt_system_returns_raw_bytes_for_baked_system() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);
        let task_id = StepId::new();
        let rendered = "# Hello\n\nThis is the baked system prompt.".to_string();
        let handle =
            seed_task_with_handle(&state, &task_id, "planner", 1, Some(rendered.clone())).await;

        let resp = worker_prompt_system(
            State(state.clone()),
            bearer_headers(&handle),
            Query(PromptSystemQuery {
                task_id: task_id.clone(),
                attempt: 1,
            }),
        )
        .await
        .expect("worker_prompt_system")
        .into_response();

        assert_eq!(resp.status(), StatusCode::OK);
        let content_type = resp
            .headers()
            .get(header::CONTENT_TYPE)
            .expect("content-type header")
            .to_str()
            .expect("ascii");
        assert_eq!(content_type, "text/plain; charset=utf-8");
        let body_bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .expect("body bytes");
        assert_eq!(body_bytes.as_ref(), rendered.as_bytes());
    }

    /// No baked system for the given `(task_id, attempt)` → 404, not a
    /// panic or a 200-with-empty-body.
    #[tokio::test]
    async fn worker_prompt_system_404s_when_no_baked_system() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "planner", 1, None).await;

        let result = worker_prompt_system(
            State(state.clone()),
            bearer_headers(&handle),
            Query(PromptSystemQuery {
                task_id: task_id.clone(),
                attempt: 1,
            }),
        )
        .await;
        let err = match result {
            Ok(_) => panic!("expected 404 ApiError, got Ok"),
            Err(e) => e,
        };
        assert_eq!(err.into_response().status(), StatusCode::NOT_FOUND);
    }

    /// A handle bound to a different task than the one requested must be
    /// rejected (400) — this is the same cross-check `worker_prompt` does.
    #[tokio::test]
    async fn worker_prompt_system_rejects_handle_task_mismatch() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);
        let task_id = StepId::new();
        let other_task_id = StepId::new();
        let handle =
            seed_task_with_handle(&state, &task_id, "planner", 1, Some("x".to_string())).await;

        let result = worker_prompt_system(
            State(state.clone()),
            bearer_headers(&handle),
            Query(PromptSystemQuery {
                task_id: other_task_id,
                attempt: 1,
            }),
        )
        .await;
        let err = match result {
            Ok(_) => panic!("expected 400 ApiError for task mismatch, got Ok"),
            Err(e) => e,
        };
        assert_eq!(err.into_response().status(), StatusCode::BAD_REQUEST);
    }

    /// `GET /v1/agents/:name/render-size` requires no auth, and reports
    /// `last_rendered_bytes: null` for an agent that has never had a
    /// `system_prompt` baked — a normal 200, not a 404.
    #[tokio::test]
    async fn agent_render_size_returns_null_for_unknown_agent() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);

        let Json(body) = agent_render_size(
            State(state.clone()),
            axum::extract::Path("never-dispatched".to_string()),
        )
        .await;
        assert_eq!(body.agent, "never-dispatched");
        assert_eq!(body.last_rendered_bytes, None);
    }

    /// Once `bake_worker_system_prompt` has recorded a render size for an
    /// agent, the route reports the most-recently-observed value.
    #[tokio::test]
    async fn agent_render_size_reports_last_rendered_bytes() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);
        let task_id = StepId::new();
        state
            .engine
            .with_state("test.seed_agent_ctx_for_bake", {
                let task_id = task_id.clone();
                move |s| {
                    s.tasks.insert(
                        task_id.clone(),
                        mlua_swarm::core::state::TaskState::new(
                            task_id,
                            mlua_swarm::core::state::TaskSpec {
                                agent: "coder".to_string(),
                                initial_directive: json!("x"),
                                step_ctx: None,
                                check_policy: None,
                            },
                        ),
                    );
                }
            })
            .await
            .expect("seed task");
        state
            .engine
            .bake_worker_system_prompt(&task_id, 1, Some("z".repeat(42)))
            .await
            .expect("bake_worker_system_prompt");

        let Json(body) = agent_render_size(
            State(state.clone()),
            axum::extract::Path("coder".to_string()),
        )
        .await;
        assert_eq!(body.agent, "coder");
        assert_eq!(body.last_rendered_bytes, Some(42));
    }

    // ──────────────────────────────────────────────────────────────────────
    // GH #36 ST1 — `POST /v1/worker/artifact`
    // ──────────────────────────────────────────────────────────────────────

    /// A valid `?name=` + short-handle Bearer stages the raw body (trailing
    /// whitespace trimmed, same as `worker_submit`) as an `Artifact` on the
    /// task's current-attempt tail, and returns `204 No Content`.
    #[tokio::test]
    async fn worker_artifact_stages_and_204s_for_valid_request() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "planner", 1, None).await;

        let status = worker_artifact(
            State(state.clone()),
            bearer_headers(&handle),
            Query(ArtifactQuery {
                name: "summary".to_string(),
            }),
            axum::body::Bytes::from_static(b"hello artifact\n"),
        )
        .await
        .expect("worker_artifact");
        assert_eq!(status, StatusCode::NO_CONTENT);

        let tail = state.engine.output_tail(&task_id, 1).await;
        assert_eq!(tail.len(), 1, "tail: {tail:?}");
        match &tail[0] {
            OutputEvent::Artifact { name, content } => {
                assert_eq!(name, "summary");
                match content {
                    ContentRef::Inline { value } => {
                        assert_eq!(value, &json!("hello artifact"));
                    }
                    other => panic!("expected Inline content, got {other:?}"),
                }
            }
            other => panic!("expected Artifact event, got {other:?}"),
        }
    }

    /// `?name=` missing entirely → axum's `Query` extractor rejection
    /// (400), not a panic. `Query<ArtifactQuery>` is constructed directly
    /// in this test (mirroring the other handlers' unit style, which call
    /// the handler fn with an already-extracted `Query`) — an empty `name`
    /// is exercised separately below since that case is NOT caught by the
    /// extractor and must be checked in the handler body.
    #[tokio::test]
    async fn worker_artifact_rejects_blank_name() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "planner", 1, None).await;

        let result = worker_artifact(
            State(state.clone()),
            bearer_headers(&handle),
            Query(ArtifactQuery {
                name: "   ".to_string(),
            }),
            axum::body::Bytes::from_static(b"x"),
        )
        .await;
        let err = match result {
            Ok(_) => panic!("expected 400 ApiError for blank name, got Ok"),
            Err(e) => e,
        };
        assert_eq!(err.into_response().status(), StatusCode::BAD_REQUEST);

        // Nothing was staged.
        assert!(state.engine.output_tail(&task_id, 1).await.is_empty());
    }

    /// Staging the same `name` twice within one attempt is last-write-wins
    /// on the folded value (`fold_final_and_parts` in `mlua_swarm::core::
    /// engine`) — this test only asserts the raw tail carries both events
    /// in order (the fold itself is covered by that crate's own unit
    /// tests); `Engine::stage_worker_artifact_trusted`'s doc.
    #[tokio::test]
    async fn worker_artifact_staging_same_name_twice_appends_both_events_in_order() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "planner", 1, None).await;

        for body in [b"first".as_slice(), b"second".as_slice()] {
            worker_artifact(
                State(state.clone()),
                bearer_headers(&handle),
                Query(ArtifactQuery {
                    name: "a".to_string(),
                }),
                axum::body::Bytes::copy_from_slice(body),
            )
            .await
            .expect("worker_artifact");
        }

        let tail = state.engine.output_tail(&task_id, 1).await;
        assert_eq!(tail.len(), 2, "tail: {tail:?}");
        let values: Vec<&str> = tail
            .iter()
            .map(|ev| match ev {
                OutputEvent::Artifact {
                    content: ContentRef::Inline { value },
                    ..
                } => value.as_str().expect("string value"),
                other => panic!("expected Artifact/Inline event, got {other:?}"),
            })
            .collect();
        assert_eq!(values, vec!["first", "second"]);
    }

    // ──────────────────────────────────────────────────────────────────
    // GH #37 — terminal-run guard (`reject_if_run_terminal`)
    // ──────────────────────────────────────────────────────────────────

    /// Links a seeded dispatch task to a Run the same way
    /// `AgentContextMiddleware` does at spawn time: an `agent_ctx` entry
    /// whose view carries the `run_id`.
    async fn link_task_to_run(state: &AppState, task_id: &StepId, attempt: u32, run_id: &RunId) {
        let tid = task_id.clone();
        let rid_str = run_id.to_string();
        state
            .engine
            .with_state("test.link_task_to_run", move |s| {
                let mut entry = mlua_swarm::core::state::AgentCtxEntry::default();
                entry.view.run_id = Some(rid_str);
                s.agent_ctx.insert((tid, attempt), entry);
            })
            .await
            .expect("link_task_to_run");
    }

    /// GH #37: a submit / artifact addressed at a Run that already
    /// reached a terminal status must be rejected with `410 Gone` — the
    /// flow-eval driver for that Run is gone, so a silent `204` here
    /// would orphan the worker's output.
    #[tokio::test]
    async fn submit_and_artifact_against_terminal_run_return_410() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store.clone());
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "planner", 1, None).await;

        let owner_task = TaskId::new();
        let run_id = RunId::new();
        let mut rec = run_record(&owner_task, &run_id, vec![]);
        rec.status = RunStatus::Failed;
        run_store.create(rec).await.expect("run create");
        link_task_to_run(&state, &task_id, 1, &run_id).await;

        let err = worker_submit(
            State(state.clone()),
            bearer_headers(&handle),
            Query(SubmitQuery {
                ok: None,
                verdict: None,
            }),
            axum::body::Bytes::from_static(b"LATE OUTPUT"),
        )
        .await
        .expect_err("a submit against a Failed run must be rejected");
        assert_eq!(err.status, StatusCode::GONE);
        assert!(
            err.message.contains(&run_id.to_string()),
            "the 410 must name the terminal run: {}",
            err.message
        );

        let err = worker_artifact(
            State(state.clone()),
            bearer_headers(&handle),
            Query(ArtifactQuery {
                name: "part.md".to_string(),
            }),
            axum::body::Bytes::from_static(b"LATE PART"),
        )
        .await
        .expect_err("an artifact staged against a Failed run must be rejected");
        assert_eq!(err.status, StatusCode::GONE);

        // The rejected values must not have reached the output tail.
        let tail = state.engine.output_tail(&task_id, 1).await;
        assert!(tail.is_empty(), "rejected submits must not land: {tail:?}");
    }

    /// GH #37 fail-open contract: the guard must never turn a
    /// would-have-succeeded submit into a failure — no run linkage at
    /// all, an unknown Run, and a live (`Running`) Run all pass.
    #[tokio::test]
    async fn terminal_run_guard_is_fail_open() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store.clone());
        let task_id = StepId::new();
        seed_task_with_handle(&state, &task_id, "planner", 1, None).await;

        // (a) No agent-ctx linkage at all (pre-run-tracking dispatch).
        reject_if_run_terminal(&state, &task_id, 1)
            .await
            .expect("no linkage must fail open");

        // (b) Linked to a Run the store does not know.
        let unknown_run = RunId::new();
        link_task_to_run(&state, &task_id, 1, &unknown_run).await;
        reject_if_run_terminal(&state, &task_id, 1)
            .await
            .expect("unknown run must fail open");

        // (c) Linked to a live Run.
        let owner_task = TaskId::new();
        let live_run = RunId::new();
        run_store
            .create(run_record(&owner_task, &live_run, vec![]))
            .await
            .expect("run create");
        link_task_to_run(&state, &task_id, 1, &live_run).await;
        reject_if_run_terminal(&state, &task_id, 1)
            .await
            .expect("a Running run must pass the guard");
    }

    // ──────────────────────────────────────────────────────────────────
    // GH #32 — `POST /v1/worker/degradation`
    // ──────────────────────────────────────────────────────────────────

    fn degradation_body(tool: &str, note: Option<&str>) -> DegradationBody {
        DegradationBody {
            tool: tool.to_string(),
            error: "boom".to_string(),
            fallback: "used cached value".to_string(),
            note: note.map(str::to_string),
        }
    }

    /// [`link_task_to_run`] plus the `view.agent` name — production's
    /// `AgentContextMiddleware` sets both fields on the same `agent_ctx`
    /// entry; the shared GH #37 helper only needed `run_id`, so this
    /// sibling fills in `agent` too for tests that assert on the
    /// server-injected `step_ref`.
    async fn link_task_to_run_with_agent(
        state: &AppState,
        task_id: &StepId,
        attempt: u32,
        run_id: &RunId,
        agent: &str,
    ) {
        let tid = task_id.clone();
        let rid_str = run_id.to_string();
        let agent = agent.to_string();
        state
            .engine
            .with_state("test.link_task_to_run_with_agent", move |s| {
                let mut entry = mlua_swarm::core::state::AgentCtxEntry::default();
                entry.view.run_id = Some(rid_str);
                entry.view.agent = agent;
                s.agent_ctx.insert((tid, attempt), entry);
            })
            .await
            .expect("link_task_to_run_with_agent");
    }

    /// A worker-reported degradation is persisted to the linked Run's
    /// `degradations` with the server-injected `step_ref` / `attempt` /
    /// `at` fields filled in — the client body never supplies any of the
    /// three.
    #[tokio::test]
    async fn worker_degradation_persists_entry_when_run_tracked() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store.clone());
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "planner", 1, None).await;

        let owner_task = TaskId::new();
        let run_id = RunId::new();
        run_store
            .create(run_record(&owner_task, &run_id, vec![]))
            .await
            .expect("run create");
        link_task_to_run_with_agent(&state, &task_id, 1, &run_id, "planner").await;

        let status = worker_degradation(
            State(state.clone()),
            bearer_headers(&handle),
            Json(degradation_body("web_search", Some("rate limited"))),
        )
        .await
        .expect("worker_degradation");
        assert_eq!(status, StatusCode::NO_CONTENT);

        let rec = run_store.get(&run_id).await.expect("run get");
        assert_eq!(
            rec.degradations.len(),
            1,
            "degradations: {:?}",
            rec.degradations
        );
        let entry = &rec.degradations[0];
        assert_eq!(entry.tool, "web_search");
        assert_eq!(entry.error, "boom");
        assert_eq!(entry.fallback, "used cached value");
        assert_eq!(entry.note.as_deref(), Some("rate limited"));
        assert_eq!(entry.step_ref.as_deref(), Some("planner"));
        assert_eq!(entry.attempt, Some(1));
        assert!(entry.at > 0, "at must be a real timestamp: {}", entry.at);
    }

    /// Two entries POSTed in sequence are appended in order.
    #[tokio::test]
    async fn worker_degradation_appends_in_order() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store.clone());
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "planner", 1, None).await;

        let owner_task = TaskId::new();
        let run_id = RunId::new();
        run_store
            .create(run_record(&owner_task, &run_id, vec![]))
            .await
            .expect("run create");
        link_task_to_run(&state, &task_id, 1, &run_id).await;

        for tool in ["first_tool", "second_tool"] {
            worker_degradation(
                State(state.clone()),
                bearer_headers(&handle),
                Json(degradation_body(tool, None)),
            )
            .await
            .expect("worker_degradation");
        }

        let rec = run_store.get(&run_id).await.expect("run get");
        let tools: Vec<&str> = rec.degradations.iter().map(|e| e.tool.as_str()).collect();
        assert_eq!(tools, vec!["first_tool", "second_tool"]);
    }

    /// A task whose `agent_ctx` carries no Run linkage (pre-run-tracking
    /// dispatch) silently 204s — nothing to append to, and this must not
    /// surface as a client error.
    #[tokio::test]
    async fn worker_degradation_silent_ok_when_no_run_tracked() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "planner", 1, None).await;

        let status = worker_degradation(
            State(state.clone()),
            bearer_headers(&handle),
            Json(degradation_body("some_tool", None)),
        )
        .await
        .expect("worker_degradation must not error on missing run linkage");
        assert_eq!(status, StatusCode::NO_CONTENT);
    }

    /// GH #37 terminal-run guard applies to the degradation channel too — a
    /// dead Run must not accumulate signals.
    #[tokio::test]
    async fn worker_degradation_rejects_terminal_run() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store.clone());
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "planner", 1, None).await;

        let owner_task = TaskId::new();
        let run_id = RunId::new();
        let mut rec = run_record(&owner_task, &run_id, vec![]);
        rec.status = RunStatus::Done;
        run_store.create(rec).await.expect("run create");
        link_task_to_run(&state, &task_id, 1, &run_id).await;

        let err = worker_degradation(
            State(state.clone()),
            bearer_headers(&handle),
            Json(degradation_body("some_tool", None)),
        )
        .await
        .expect_err("a degradation against a Done run must be rejected");
        assert_eq!(err.status, StatusCode::GONE);

        let rec = run_store.get(&run_id).await.expect("run get");
        assert!(
            rec.degradations.is_empty(),
            "rejected degradation must not land: {:?}",
            rec.degradations
        );
    }

    // ──────────────────────────────────────────────────────────────────
    // GH #42 — `@file:<abs-path>` sentinel resolution in `worker_submit`
    // / `worker_artifact`. Guards each verified independently: sentinel
    // resolves to the file's trimmed contents; path outside `work_dir`,
    // missing file, oversized file, and non-sentinel bodies each get the
    // documented behavior.
    // ──────────────────────────────────────────────────────────────────

    /// Seeds an `agent_ctx` entry whose view carries `work_dir` and, when
    /// `allow_file_submit` is `Some`, that value under the GH #43
    /// [`FILE_SENTINEL_ALLOW_KEY`] in `view.extra` — matching the shape
    /// `AgentContextMiddleware` writes at spawn time. Sentinel resolution
    /// requires both the `work_dir` and the strict `Bool(true)` opt-in.
    async fn seed_work_dir(
        state: &AppState,
        task_id: &StepId,
        attempt: u32,
        work_dir: &str,
        allow_file_submit: Option<Value>,
    ) {
        let tid = task_id.clone();
        let work_dir = work_dir.to_string();
        state
            .engine
            .with_state("test.seed_work_dir", move |s| {
                let mut entry = mlua_swarm::core::state::AgentCtxEntry::default();
                entry.view.work_dir = Some(work_dir);
                if let Some(v) = allow_file_submit {
                    entry
                        .view
                        .extra
                        .insert(FILE_SENTINEL_ALLOW_KEY.to_string(), v);
                }
                s.agent_ctx.insert((tid, attempt), entry);
            })
            .await
            .expect("seed_work_dir");
    }

    /// Sentinel body `@file:<abs-path>` resolves to the file's trimmed
    /// contents and reaches the `OutputStore` via the normal Final-append
    /// path — same 204 the inline path returns.
    #[tokio::test]
    async fn worker_submit_resolves_file_sentinel_under_work_dir() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store.clone(), run_store);
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "planner", 1, None).await;

        let tmp = tempfile::tempdir().expect("tempdir");
        let work_dir = tmp.path().to_path_buf();
        seed_work_dir(
            &state,
            &task_id,
            1,
            work_dir.to_str().expect("work_dir utf-8"),
            Some(Value::Bool(true)),
        )
        .await;

        let payload_path = work_dir.join("scout.md");
        let payload = "## Context Package (broad)\n\nlarge body content\n";
        tokio::fs::write(&payload_path, payload)
            .await
            .expect("write payload");
        let body = format!(
            "@file:{}",
            payload_path.to_str().expect("payload path utf-8")
        );

        let status = worker_submit(
            State(state.clone()),
            bearer_headers(&handle),
            Query(SubmitQuery {
                ok: None,
                verdict: None,
            }),
            axum::body::Bytes::from(body),
        )
        .await
        .expect("worker_submit sentinel");
        assert_eq!(status, StatusCode::NO_CONTENT);

        // Final event lands with the file's trimmed contents on
        // `EngineState.output_store` (the in-memory tail
        // `submit_worker_result_trusted` writes to).
        let tid = task_id.clone();
        let value = state
            .engine
            .with_state("test.inspect_output_store", move |s| {
                s.output_store.get(&(tid.clone(), 1)).and_then(|evs| {
                    evs.iter().find_map(|ev| match ev {
                        OutputEvent::Final {
                            content: ContentRef::Inline { value },
                            ..
                        } => Some(value.clone()),
                        _ => None,
                    })
                })
            })
            .await
            .expect("with_state")
            .expect("Final event present");
        assert_eq!(value, Value::String(payload.trim_end().to_string()));
    }

    /// A non-sentinel body is passed through byte-for-byte (pre-#42
    /// callers see zero behavior change).
    #[tokio::test]
    async fn worker_submit_passes_non_sentinel_body_unchanged() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store.clone(), run_store);
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "planner", 1, None).await;
        // No agent_ctx / work_dir seeded — the inline path must not
        // require one.

        let status = worker_submit(
            State(state.clone()),
            bearer_headers(&handle),
            Query(SubmitQuery {
                ok: None,
                verdict: None,
            }),
            axum::body::Bytes::from_static(b"DONE yes=1 maybe=0 no=0"),
        )
        .await
        .expect("worker_submit inline");
        assert_eq!(status, StatusCode::NO_CONTENT);

        let tid = task_id.clone();
        let value = state
            .engine
            .with_state("test.inspect_output_store", move |s| {
                s.output_store.get(&(tid.clone(), 1)).and_then(|evs| {
                    evs.iter().find_map(|ev| match ev {
                        OutputEvent::Final {
                            content: ContentRef::Inline { value },
                            ..
                        } => Some(value.clone()),
                        _ => None,
                    })
                })
            })
            .await
            .expect("with_state")
            .expect("Final event present");
        assert_eq!(value, Value::String("DONE yes=1 maybe=0 no=0".to_string()));
    }

    /// Sentinel with a path outside the task's `work_dir` (`..`-escape
    /// via a sibling tempdir) → `400`. `canonicalize` collapses the
    /// `..`, so a symlink pointing outside the allowlist would be caught
    /// by the same check.
    #[tokio::test]
    async fn worker_submit_rejects_sentinel_path_outside_work_dir() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "planner", 1, None).await;

        let allowed = tempfile::tempdir().expect("allowed tempdir");
        let outside = tempfile::tempdir().expect("outside tempdir");
        seed_work_dir(
            &state,
            &task_id,
            1,
            allowed.path().to_str().expect("utf-8"),
            Some(Value::Bool(true)),
        )
        .await;

        let outside_file = outside.path().join("leak.md");
        tokio::fs::write(&outside_file, b"outside content")
            .await
            .expect("write outside");
        let body = format!(
            "@file:{}",
            outside_file.to_str().expect("outside path utf-8")
        );

        let err = worker_submit(
            State(state.clone()),
            bearer_headers(&handle),
            Query(SubmitQuery {
                ok: None,
                verdict: None,
            }),
            axum::body::Bytes::from(body),
        )
        .await
        .expect_err("outside-work_dir sentinel must be rejected");
        assert_eq!(err.status, StatusCode::BAD_REQUEST);
    }

    /// Sentinel pointing at a non-existent file → `404`.
    #[tokio::test]
    async fn worker_submit_rejects_sentinel_missing_file() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "planner", 1, None).await;

        let tmp = tempfile::tempdir().expect("tempdir");
        seed_work_dir(
            &state,
            &task_id,
            1,
            tmp.path().to_str().expect("utf-8"),
            Some(Value::Bool(true)),
        )
        .await;
        let missing = tmp.path().join("does-not-exist.md");
        let body = format!("@file:{}", missing.to_str().expect("utf-8"));

        let err = worker_submit(
            State(state.clone()),
            bearer_headers(&handle),
            Query(SubmitQuery {
                ok: None,
                verdict: None,
            }),
            axum::body::Bytes::from(body),
        )
        .await
        .expect_err("missing-file sentinel must be rejected");
        assert_eq!(err.status, StatusCode::NOT_FOUND);
    }

    /// Sentinel body with a relative path → `400` before any FS lookup.
    #[tokio::test]
    async fn worker_submit_rejects_sentinel_relative_path() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "planner", 1, None).await;

        let err = worker_submit(
            State(state.clone()),
            bearer_headers(&handle),
            Query(SubmitQuery {
                ok: None,
                verdict: None,
            }),
            axum::body::Bytes::from_static(b"@file:relative/path.md"),
        )
        .await
        .expect_err("relative-path sentinel must be rejected");
        assert_eq!(err.status, StatusCode::BAD_REQUEST);
    }

    /// Sentinel body when the task has no `AgentContextView` (spawn
    /// didn't run through `AgentContextMiddleware`) → `400`. This is the
    /// documented pre-condition for sentinel use.
    #[tokio::test]
    async fn worker_submit_rejects_sentinel_without_agent_context_view() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "planner", 1, None).await;
        // No seed_work_dir — the agent_ctx map has no entry for this task.

        let err = worker_submit(
            State(state.clone()),
            bearer_headers(&handle),
            Query(SubmitQuery {
                ok: None,
                verdict: None,
            }),
            axum::body::Bytes::from_static(b"@file:/tmp/anywhere.md"),
        )
        .await
        .expect_err("missing AgentContextView must reject sentinel");
        assert_eq!(err.status, StatusCode::BAD_REQUEST);
    }

    /// The same sentinel form works on `POST /v1/worker/artifact` — the
    /// artifact endpoint shares the resolver with `worker_submit`, so the
    /// resolved file contents land under the artifact's `name` key.
    #[tokio::test]
    async fn worker_artifact_resolves_file_sentinel_under_work_dir() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "planner", 1, None).await;

        let tmp = tempfile::tempdir().expect("tempdir");
        seed_work_dir(
            &state,
            &task_id,
            1,
            tmp.path().to_str().expect("utf-8"),
            Some(Value::Bool(true)),
        )
        .await;

        let payload_path = tmp.path().join("part.md");
        let payload = "artifact part body\n";
        tokio::fs::write(&payload_path, payload)
            .await
            .expect("write payload");
        let body = format!("@file:{}", payload_path.to_str().expect("utf-8"));

        let status = worker_artifact(
            State(state.clone()),
            bearer_headers(&handle),
            Query(ArtifactQuery {
                name: "scout".to_string(),
            }),
            axum::body::Bytes::from(body),
        )
        .await
        .expect("worker_artifact sentinel");
        assert_eq!(status, StatusCode::NO_CONTENT);
    }

    /// GH #43 — sentinel with `work_dir` seeded but no
    /// `allow_file_submit` opt-in → `400` (default-deny). The file exists
    /// and sits under `work_dir`, so the rejection is attributable to the
    /// missing opt-in alone.
    #[tokio::test]
    async fn worker_submit_rejects_sentinel_without_allow_flag() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "planner", 1, None).await;

        let tmp = tempfile::tempdir().expect("tempdir");
        seed_work_dir(
            &state,
            &task_id,
            1,
            tmp.path().to_str().expect("utf-8"),
            None,
        )
        .await;

        let payload_path = tmp.path().join("out.md");
        tokio::fs::write(&payload_path, b"resolvable body")
            .await
            .expect("write payload");
        let body = format!("@file:{}", payload_path.to_str().expect("utf-8"));

        let err = worker_submit(
            State(state.clone()),
            bearer_headers(&handle),
            Query(SubmitQuery {
                ok: None,
                verdict: None,
            }),
            axum::body::Bytes::from(body),
        )
        .await
        .expect_err("missing opt-in must reject sentinel");
        assert_eq!(err.status, StatusCode::BAD_REQUEST);
        assert!(
            err.message.contains("not allowed"),
            "rejection must name the opt-in guard, got: {}",
            err.message
        );
    }

    /// GH #43 — the opt-in is the strict boolean `true`: `Bool(false)`
    /// and the string `"true"` are both rejected with `400`.
    #[tokio::test]
    async fn worker_submit_rejects_sentinel_with_non_true_allow_values() {
        for allow in [Value::Bool(false), Value::String("true".to_string())] {
            let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
            let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
            let state = test_state(data_store, run_store);
            let task_id = StepId::new();
            let handle = seed_task_with_handle(&state, &task_id, "planner", 1, None).await;

            let tmp = tempfile::tempdir().expect("tempdir");
            seed_work_dir(
                &state,
                &task_id,
                1,
                tmp.path().to_str().expect("utf-8"),
                Some(allow.clone()),
            )
            .await;

            let payload_path = tmp.path().join("out.md");
            tokio::fs::write(&payload_path, b"resolvable body")
                .await
                .expect("write payload");
            let body = format!("@file:{}", payload_path.to_str().expect("utf-8"));

            let err = worker_submit(
                State(state.clone()),
                bearer_headers(&handle),
                Query(SubmitQuery {
                    ok: None,
                    verdict: None,
                }),
                axum::body::Bytes::from(body),
            )
            .await
            .expect_err("non-true opt-in value must reject sentinel");
            assert_eq!(err.status, StatusCode::BAD_REQUEST, "value: {allow:?}");
        }
    }

    // ──────────────────────────────────────────────────────────────────
    // `submit_format` — the submit-route half of the contract. Default
    // (undeclared) STAGES `Value::String` exactly as before (the lenient
    // container parse is the engine fold's job, not this route's);
    // `"json"` parses here (any JSON value) and rejects `422` when the
    // body does not parse; `"text"` is a recognized no-op here whose
    // effect lives in the engine fold (`FoldParse::Raw`).
    // ──────────────────────────────────────────────────────────────────

    /// Seeds an `agent_ctx` entry carrying the agent name plus, when
    /// `submit_format` is `Some`, that value under [`SUBMIT_FORMAT_KEY`]
    /// in `view.extra` — the shape `AgentContextMiddleware` folds from
    /// the Blueprint meta channels at spawn time. `work_dir`, when given,
    /// also enables the `@file:` sentinel (`allow_file_submit: true`), so
    /// one helper covers the sentinel + parse combination.
    async fn seed_submit_format(
        state: &AppState,
        task_id: &StepId,
        attempt: u32,
        agent: &str,
        submit_format: Option<Value>,
        work_dir: Option<&str>,
    ) {
        let tid = task_id.clone();
        let agent = agent.to_string();
        let work_dir = work_dir.map(|w| w.to_string());
        state
            .engine
            .with_state("test.seed_submit_format", move |s| {
                let mut entry = mlua_swarm::core::state::AgentCtxEntry::default();
                entry.view.agent = agent;
                if let Some(w) = work_dir {
                    entry.view.work_dir = Some(w);
                    entry
                        .view
                        .extra
                        .insert(FILE_SENTINEL_ALLOW_KEY.to_string(), Value::Bool(true));
                }
                if let Some(v) = submit_format {
                    entry.view.extra.insert(SUBMIT_FORMAT_KEY.to_string(), v);
                }
                s.agent_ctx.insert((tid, attempt), entry);
            })
            .await
            .expect("seed_submit_format");
    }

    /// Reads back the `Final` event's value from the in-memory
    /// `output_store` tail `submit_worker_result_trusted` writes to.
    async fn final_value(state: &AppState, task_id: &StepId, attempt: u32) -> Option<Value> {
        let tid = task_id.clone();
        state
            .engine
            .with_state("test.inspect_output_store", move |s| {
                s.output_store.get(&(tid.clone(), attempt)).and_then(|evs| {
                    evs.iter().find_map(|ev| match ev {
                        OutputEvent::Final {
                            content: ContentRef::Inline { value },
                            ..
                        } => Some(value.clone()),
                        _ => None,
                    })
                })
            })
            .await
            .expect("with_state")
    }

    /// Route-level regression lock: a step with a materialized view but
    /// NO `submit_format` declaration STAGES its body as a string even
    /// when that body happens to be valid JSON — this route never sniffs
    /// the payload. (The default lenient container parse happens later,
    /// at the engine's Final-pull fold — `FoldParse::Lenient`, tested in
    /// `mlua_swarm::core::engine` — which is exactly why the staged bytes
    /// here must stay raw: they are what `materialize_final_submission` /
    /// `materialize_part` and the verdict-contract checks see.)
    #[tokio::test]
    async fn worker_submit_without_submit_format_stages_json_looking_body_as_string() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "planner", 1, None).await;
        seed_submit_format(&state, &task_id, 1, "planner", None, None).await;

        let body = r#"{"lanes":["a","b"]}"#;
        let status = worker_submit(
            State(state.clone()),
            bearer_headers(&handle),
            Query(SubmitQuery {
                ok: None,
                verdict: None,
            }),
            axum::body::Bytes::from(body),
        )
        .await
        .expect("undeclared submit must succeed");
        assert_eq!(status, StatusCode::NO_CONTENT);

        assert_eq!(
            final_value(&state, &task_id, 1).await,
            Some(Value::String(body.to_string())),
            "an undeclared step must keep the raw-string fold",
        );
    }

    /// `submit_format: "json"` + a parseable body → the folded value is
    /// the structured JSON, so a downstream path (`$.<step>.lanes`)
    /// resolves instead of hitting one opaque string.
    #[tokio::test]
    async fn worker_submit_declared_json_folds_structured_value() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "planner", 1, None).await;
        seed_submit_format(
            &state,
            &task_id,
            1,
            "planner",
            Some(Value::String(SUBMIT_FORMAT_JSON.to_string())),
            None,
        )
        .await;

        let status = worker_submit(
            State(state.clone()),
            bearer_headers(&handle),
            Query(SubmitQuery {
                ok: None,
                verdict: None,
            }),
            axum::body::Bytes::from(r#"{"lanes":["auth","billing"],"verdict":"PASS"}"#),
        )
        .await
        .expect("declared JSON submit must succeed");
        assert_eq!(status, StatusCode::NO_CONTENT);

        let value = final_value(&state, &task_id, 1)
            .await
            .expect("Final event present");
        assert_eq!(
            value,
            json!({"lanes": ["auth", "billing"], "verdict": "PASS"})
        );
        // The whole point of the opt-in: fields are addressable.
        assert_eq!(value["lanes"], json!(["auth", "billing"]));
        assert_eq!(value["verdict"], json!("PASS"));
    }

    /// Declared-strict: a declared step whose body does not parse is
    /// rejected with `422` (naming the agent and echoing the body head),
    /// and nothing reaches the flow ctx.
    #[tokio::test]
    async fn worker_submit_declared_json_rejects_unparseable_body_with_422() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "planner", 1, None).await;
        seed_submit_format(
            &state,
            &task_id,
            1,
            "planner",
            Some(Value::String(SUBMIT_FORMAT_JSON.to_string())),
            None,
        )
        .await;

        let err = worker_submit(
            State(state.clone()),
            bearer_headers(&handle),
            Query(SubmitQuery {
                ok: None,
                verdict: None,
            }),
            axum::body::Bytes::from("DONE — 3 lanes planned, see the report above"),
        )
        .await
        .expect_err("a declared step must not fold an unparseable body");
        assert_eq!(err.status, StatusCode::UNPROCESSABLE_ENTITY);
        assert!(
            err.message.contains("planner") && err.message.contains("DONE"),
            "the rejection must name the agent and echo the body head, got: {}",
            err.message
        );
        assert_eq!(
            final_value(&state, &task_id, 1).await,
            None,
            "a rejected submit must not reach the output tail",
        );
    }

    /// The `@file:` sentinel and the parse compose: the file is resolved
    /// first, then its contents are parsed, so a large structured payload
    /// can take the file lane without losing its shape.
    #[tokio::test]
    async fn worker_submit_declared_json_parses_file_sentinel_contents() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "planner", 1, None).await;

        let tmp = tempfile::tempdir().expect("tempdir");
        let work_dir = tmp.path().to_path_buf();
        seed_submit_format(
            &state,
            &task_id,
            1,
            "planner",
            Some(Value::String(SUBMIT_FORMAT_JSON.to_string())),
            Some(work_dir.to_str().expect("work_dir utf-8")),
        )
        .await;

        let payload_path = work_dir.join("plan.json");
        tokio::fs::write(&payload_path, "{\"lanes\": [\"auth\", \"billing\"]}\n")
            .await
            .expect("write payload");
        let body = format!(
            "@file:{}",
            payload_path.to_str().expect("payload path utf-8")
        );

        let status = worker_submit(
            State(state.clone()),
            bearer_headers(&handle),
            Query(SubmitQuery {
                ok: None,
                verdict: None,
            }),
            axum::body::Bytes::from(body),
        )
        .await
        .expect("sentinel + declared JSON submit must succeed");
        assert_eq!(status, StatusCode::NO_CONTENT);

        assert_eq!(
            final_value(&state, &task_id, 1).await,
            Some(json!({"lanes": ["auth", "billing"]})),
        );
    }

    /// An unrecognized declared value is not a client error: the body
    /// folds as a string (the default lane) and the server warns. Locks
    /// the fallback so a typo degrades visibly instead of 422-ing a
    /// worker that did nothing wrong.
    #[tokio::test]
    async fn worker_submit_unknown_submit_format_falls_back_to_string() {
        for declared in [
            Value::String("yaml".to_string()),
            Value::Bool(true),
            Value::Number(1.into()),
        ] {
            let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
            let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
            let state = test_state(data_store, run_store);
            let task_id = StepId::new();
            let handle = seed_task_with_handle(&state, &task_id, "planner", 1, None).await;
            seed_submit_format(&state, &task_id, 1, "planner", Some(declared.clone()), None).await;

            let status = worker_submit(
                State(state.clone()),
                bearer_headers(&handle),
                Query(SubmitQuery {
                    ok: None,
                    verdict: None,
                }),
                axum::body::Bytes::from(r#"{"lanes":["a"]}"#),
            )
            .await
            .unwrap_or_else(|e| panic!("unknown value must not reject ({declared}): {e:?}"));
            assert_eq!(status, StatusCode::NO_CONTENT);

            assert_eq!(
                final_value(&state, &task_id, 1).await,
                Some(Value::String(r#"{"lanes":["a"]}"#.to_string())),
                "unknown value {declared} must keep the string fold",
            );
        }
    }

    /// `submit_format: "text"` is a recognized value at this route: the
    /// body stages as a string (like undeclared), succeeds, and is NOT
    /// the unknown-value warn path. Its real effect — opting the step's
    /// fold out of the lenient container parse — is the engine fold's
    /// job (`FoldParse::Raw`, tested in `mlua_swarm::core::engine`).
    #[tokio::test]
    async fn worker_submit_declared_text_stages_string() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "planner", 1, None).await;
        seed_submit_format(
            &state,
            &task_id,
            1,
            "planner",
            Some(Value::String("text".to_string())),
            None,
        )
        .await;

        let body = r#"{"lanes":["a","b"]}"#;
        let status = worker_submit(
            State(state.clone()),
            bearer_headers(&handle),
            Query(SubmitQuery {
                ok: None,
                verdict: None,
            }),
            axum::body::Bytes::from(body),
        )
        .await
        .expect("text-declared submit must succeed");
        assert_eq!(status, StatusCode::NO_CONTENT);

        assert_eq!(
            final_value(&state, &task_id, 1).await,
            Some(Value::String(body.to_string())),
            "a text-declared step must stage the raw string",
        );
    }

    /// Order lock: the verdict contract still sees the pre-parse string
    /// for an undeclared gate agent — a `channel: "body"` contract keeps
    /// accepting its bare token and keeps rejecting a non-member value,
    /// byte-for-byte as before the opt-in existed.
    #[tokio::test]
    async fn worker_submit_verdict_contract_unchanged_without_submit_format() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);
        state.engine.register_verdict_contracts(HashMap::from([(
            "gate".to_string(),
            body_verdict_contract(&["PASS", "BLOCKED"]),
        )]));

        // Member value: accepted, folded as the same bare string.
        let accepted = StepId::new();
        let handle = seed_task_with_handle(&state, &accepted, "gate", 1, None).await;
        seed_submit_format(&state, &accepted, 1, "gate", None, None).await;
        let status = worker_submit(
            State(state.clone()),
            bearer_headers(&handle),
            Query(SubmitQuery {
                ok: None,
                verdict: None,
            }),
            axum::body::Bytes::from("BLOCKED"),
        )
        .await
        .expect("a declared verdict value must still pass");
        assert_eq!(status, StatusCode::NO_CONTENT);
        assert_eq!(
            final_value(&state, &accepted, 1).await,
            Some(Value::String("BLOCKED".to_string())),
        );

        // Non-member value: still the pre-existing 422 from the contract,
        // not a submit_format error.
        let rejected = StepId::new();
        let handle = seed_task_with_handle(&state, &rejected, "gate", 1, None).await;
        seed_submit_format(&state, &rejected, 1, "gate", None, None).await;
        let err = worker_submit(
            State(state.clone()),
            bearer_headers(&handle),
            Query(SubmitQuery {
                ok: None,
                verdict: None,
            }),
            axum::body::Bytes::from("UNKNOWN"),
        )
        .await
        .expect_err("a non-member verdict value must still be rejected");
        assert_eq!(err.status, StatusCode::UNPROCESSABLE_ENTITY);
        assert!(
            err.message.contains("verdict contract violation"),
            "the verdict contract must own this rejection, got: {}",
            err.message
        );
    }

    /// End-to-end of the motivating shape: a planner declares
    /// `submit_format: "json"`, submits `{"lanes": [...]}`, and a `fanout`
    /// whose `items` is `$.<step>.lanes` dispatches one lane per element.
    /// Before the opt-in the same submit folded as a string and the
    /// `items` path could not be resolved at all.
    #[tokio::test]
    async fn declared_json_submit_feeds_a_fanout_items_path() {
        use mlua_flow_ir::{EvalError, Expr, JoinMode, Node as FlowNode};

        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "planner", 1, None).await;
        seed_submit_format(
            &state,
            &task_id,
            1,
            "planner",
            Some(Value::String(SUBMIT_FORMAT_JSON.to_string())),
            None,
        )
        .await;

        worker_submit(
            State(state.clone()),
            bearer_headers(&handle),
            Query(SubmitQuery {
                ok: None,
                verdict: None,
            }),
            axum::body::Bytes::from(r#"{"lanes":["auth","billing","search"]}"#),
        )
        .await
        .expect("declared JSON submit must succeed");
        let planner_out = final_value(&state, &task_id, 1)
            .await
            .expect("Final event present");

        // The step's OUTPUT as the BP chain would see it, under `$.planner`.
        let path = |s: &str| Expr::Path {
            at: s.parse().expect("literal test path"),
        };
        let flow = FlowNode::Fanout {
            items: path("$.planner.lanes"),
            bind: path("$.item"),
            body: Box::new(FlowNode::Step {
                ref_: "check".to_string(),
                in_: path("$.item"),
                out: path("$.branch_out"),
            }),
            join: JoinMode::All,
            out: path("$.results"),
        };
        let dispatcher = |_ref: &str, input: Value| -> Result<Value, EvalError> { Ok(input) };
        let final_ctx = mlua_flow_ir::eval(&flow, json!({ "planner": planner_out }), &dispatcher)
            .expect("fanout over the parsed submit must evaluate");

        let lanes: Vec<&Value> = final_ctx["results"]
            .as_array()
            .expect("results is an array")
            .iter()
            .map(|lane_ctx| &lane_ctx["branch_out"])
            .collect();
        assert_eq!(
            lanes,
            vec![&json!("auth"), &json!("billing"), &json!("search")]
        );
    }

    // ──────────────────────────────────────────────────────────────────
    // GH #50 (Subtask 2) — submit-time verdict contract gate, handler-
    // level unit coverage. The full process-boundary HTTP round trip
    // (Acceptance Criterion #7) lives in
    // `crates/mlua-swarm-server/tests/verdict_contract.rs`; these are the
    // fast in-process counterpart exercising `worker_submit` /
    // `worker_artifact` directly, same convention as the sentinel tests
    // above.
    // ──────────────────────────────────────────────────────────────────

    fn body_verdict_contract(values: &[&str]) -> mlua_swarm_schema::VerdictContract {
        mlua_swarm_schema::VerdictContract {
            channel: VerdictChannel::Body,
            values: values.iter().map(|v| v.to_string()).collect(),
        }
    }

    fn part_verdict_contract(values: &[&str]) -> mlua_swarm_schema::VerdictContract {
        mlua_swarm_schema::VerdictContract {
            channel: VerdictChannel::Part,
            values: values.iter().map(|v| v.to_string()).collect(),
        }
    }

    /// A `channel: "body"` contract rejects a `worker_submit` body outside
    /// its declared `values` with `422`, echoing the expected token set.
    #[tokio::test]
    async fn worker_submit_rejects_body_outside_contract_values_with_422() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "gate", 1, None).await;
        state.engine.register_verdict_contracts(HashMap::from([(
            "gate".to_string(),
            body_verdict_contract(&["PASS", "BLOCKED"]),
        )]));

        let err = worker_submit(
            State(state.clone()),
            bearer_headers(&handle),
            Query(SubmitQuery {
                ok: None,
                verdict: None,
            }),
            axum::body::Bytes::from("UNKNOWN"),
        )
        .await
        .expect_err("value outside declared values must reject");
        assert_eq!(err.status, StatusCode::UNPROCESSABLE_ENTITY);
        assert!(
            err.message.contains("PASS") && err.message.contains("BLOCKED"),
            "rejection must echo the declared values, got: {}",
            err.message
        );
    }

    /// The same contract accepts a body that IS a member of `values` —
    /// `204`, unaffected submit.
    #[tokio::test]
    async fn worker_submit_accepts_body_inside_contract_values() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "gate", 1, None).await;
        state.engine.register_verdict_contracts(HashMap::from([(
            "gate".to_string(),
            body_verdict_contract(&["PASS", "BLOCKED"]),
        )]));

        let status = worker_submit(
            State(state.clone()),
            bearer_headers(&handle),
            Query(SubmitQuery {
                ok: None,
                verdict: None,
            }),
            axum::body::Bytes::from("PASS"),
        )
        .await
        .expect("value inside declared values must succeed");
        assert_eq!(status, StatusCode::NO_CONTENT);
    }

    /// Opt-in regression guard: an agent with NO declared verdict contract
    /// is entirely unaffected — `worker_submit` still returns `204` for an
    /// arbitrary body, exactly the pre-GH-#50 behavior.
    #[tokio::test]
    async fn worker_submit_without_a_declared_contract_is_unaffected() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);
        let task_id = StepId::new();
        // No `register_verdict_contracts` call — the agent declared no contract.
        let handle = seed_task_with_handle(&state, &task_id, "undeclared-agent", 1, None).await;

        let status = worker_submit(
            State(state.clone()),
            bearer_headers(&handle),
            Query(SubmitQuery {
                ok: None,
                verdict: None,
            }),
            axum::body::Bytes::from("anything at all, no contract to violate"),
        )
        .await
        .expect("no contract declared must never reject");
        assert_eq!(status, StatusCode::NO_CONTENT);
    }

    /// A `channel: "part"` contract rejects a `worker_artifact?name=verdict`
    /// value outside `values` with `422`.
    #[tokio::test]
    async fn worker_artifact_verdict_part_rejects_value_outside_contract_with_422() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "gate", 1, None).await;
        state.engine.register_verdict_contracts(HashMap::from([(
            "gate".to_string(),
            part_verdict_contract(&["PASS", "BLOCKED"]),
        )]));

        let err = worker_artifact(
            State(state.clone()),
            bearer_headers(&handle),
            Query(ArtifactQuery {
                name: "verdict".to_string(),
            }),
            axum::body::Bytes::from("UNKNOWN"),
        )
        .await
        .expect_err("value outside declared values must reject");
        assert_eq!(err.status, StatusCode::UNPROCESSABLE_ENTITY);
    }

    /// A part named anything OTHER than `"verdict"` skips the gate
    /// entirely, even with a `channel: "part"` contract declared — `204`,
    /// existing pre-GH-#50 behavior unchanged.
    #[tokio::test]
    async fn worker_artifact_non_verdict_part_skips_the_gate() {
        let data_store: Arc<dyn OutputStore> = Arc::new(InMemoryOutputStore::new());
        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
        let state = test_state(data_store, run_store);
        let task_id = StepId::new();
        let handle = seed_task_with_handle(&state, &task_id, "gate", 1, None).await;
        state.engine.register_verdict_contracts(HashMap::from([(
            "gate".to_string(),
            part_verdict_contract(&["PASS", "BLOCKED"]),
        )]));

        let status = worker_artifact(
            State(state.clone()),
            bearer_headers(&handle),
            Query(ArtifactQuery {
                name: "notes".to_string(),
            }),
            axum::body::Bytes::from("anything at all"),
        )
        .await
        .expect("non-verdict part name must never be gated");
        assert_eq!(status, StatusCode::NO_CONTENT);
    }
}