mlua-swarm-server 0.20.0

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
//! HTTP surface for the Task/Run persistence axis (issue #13 ID-hierarchy
//! reconciliation: Blueprint → Task → Run → Step → Attempt).
//!
//! - `GET  /v1/tasks`          — list every persisted `TaskRecord`, newest first.
//! - `GET  /v1/tasks/:id`      — a `TaskRecord` plus every `RunRecord` kicked from it.
//! - `POST /v1/tasks/:id/runs` — re-kick an existing Task: mints a fresh `RunId`,
//!   re-resolves the stored `blueprint_ref` (refreshing `Blueprint.default_init_ctx`
//!   exactly like original launch time — issue #19 ST4), 3-layer-merges it with
//!   `TaskRecord.input_ctx` and an **optional** [`RunKickRequest`] body's
//!   `init_ctx_override` (see [`merge_init_ctx_3layer`]), dispatches through
//!   `TaskApplication::handle_with_run`, and returns the new `{task_id, run_id}`
//!   pair. A body-less request (or one that omits both fields) preserves the
//!   pre-#19 rekick behavior byte-for-byte.
//! - `GET  /v1/runs/:id`       — a single `RunRecord` (`step_entries` trace included).
//! - `GET  /v1/runs/:id/bindings` — requested/effective binding explain from
//!   the immutable launch snapshot (never from the current Blueprint).
//! - `POST /v1/runs/:id/resume` — resume an `Interrupted` Run under the SAME
//!   `run_id` (replay cursor + stored launch-input snapshot).
//! - `POST /v1/runs/:id/rerun-from` — GH #71 Layer A. Rerun a terminal Run
//!   (`Done` / `Failed` / `Interrupted`) from a caller-specified step under
//!   the SAME `run_id`; physically truncates the replay log at the cut
//!   point so re-dispatch does not collide with the pre-rerun rows. See
//!   [`run_rerun_from`] for the full contract + Known Limitations.
//!
//! `POST /v1/tasks` itself (the flow-eval entry point, `tasks_start` /
//! `run_flow_form`) stays in `crate::lib` — it is the pre-existing
//! Operator-inject-aware dispatch path this module's handlers re-kick
//! through, not a new one. This module owns the read/list/re-kick surface
//! plus the [`finalize_run`] persistence helper both paths share.
//!
//! Authorization follows the same convention as the existing `POST /v1/tasks`
//! entry: no `Authorization` header is required (the route is open), and the
//! only Operator-session correlation available is the request-body-level
//! `operator_sid` (see `crate::TaskLaunchRequest` doc) — this module invents no
//! new auth mechanism.

use axum::{
    extract::{Path, Query, State},
    http::StatusCode,
    Json,
};
use futures_util::FutureExt;
use mlua_swarm::application::{
    BlueprintRef, TaskApplicationError, TaskApplicationInput, TaskApplicationOutput,
};
use mlua_swarm::blueprint::{BindRequest, BindingAttestation, BoundAgent};
use mlua_swarm::core::config::CheckPolicy;
use mlua_swarm::service::merge_init_ctx_3layer;
use mlua_swarm::service::TaskLaunchError;
use mlua_swarm::store::replay::ReplayCursor;
use mlua_swarm::store::run::{
    RunContext, RunListFilter, RunRecord, RunStatus, RunStoreError, SnapshotOrigin, StepEntry,
};
use mlua_swarm::store::task::{TaskRecord, TaskRecordStatus, TaskStoreError};
use mlua_swarm::store::trace::{kind as trace_kind, TraceEvent, TraceHandle, TraceQuery};
use mlua_swarm::{
    validate_bound_agent_snapshots, OperatorKind, Role, RunId, TaskId, TaskInputSpec,
};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::panic::AssertUnwindSafe;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use crate::{ApiError, AppState};

/// Current Unix time in whole seconds. `TaskRecord` / `RunRecord` timestamps
/// are `u64` seconds (not milliseconds) — see their field docs in
/// `mlua_swarm::store::task` / `mlua_swarm::store::run`.
pub(crate) fn now_secs() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/// Serializable mirror of [`TaskApplicationInput`] — the launch-input
/// snapshot persisted into `RunRecord.input_json` at Run-creation time so a
/// later `POST /v1/runs/:id/resume` can rebuild the exact input and re-run
/// the flow under the SAME `run_id`.
///
/// [`TaskApplicationInput`] itself is deliberately not `Serialize`/
/// `Deserialize` (its doc comment explains why — keeping the exhaustive
/// `TaskApplicationInput { .. }` struct literal in the MCP adapter
/// compiling), so this is a dedicated snapshot type with the exact same
/// field set. Every field type already derives serde
/// (`BlueprintRef` / `Role` / `Duration` / `OperatorKind` / `TaskInputSpec`
/// / `CheckPolicy`), so the mirror is total — no field is dropped, and an
/// operator-injected launch round-trips as faithfully as a plain one.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct RunLaunchSnapshot {
    blueprint: BlueprintRef,
    operator_id: String,
    role: Role,
    ttl: Duration,
    init_ctx: Value,
    operator_kind: Option<OperatorKind>,
    bridge_id: Option<String>,
    hook_id: Option<String>,
    operator_backend_id: Option<String>,
    /// Run-scoped Operator session pin. `#[serde(default)]` so a Run
    /// snapshotted before the field existed still decodes (it resumes
    /// unpinned, exactly as it launched).
    #[serde(default)]
    operator_pin: Option<String>,
    #[serde(default)]
    operator_kind_overrides: HashMap<String, OperatorKind>,
    task_input: Option<TaskInputSpec>,
    check_policy: Option<CheckPolicy>,
}

impl RunLaunchSnapshot {
    /// Capture a launch input as a snapshot (clones each field — the
    /// original is still dispatched).
    fn from_input(input: &TaskApplicationInput) -> Self {
        Self {
            blueprint: input.blueprint.clone(),
            operator_id: input.operator_id.clone(),
            role: input.role,
            ttl: input.ttl,
            init_ctx: input.init_ctx.clone(),
            operator_kind: input.operator_kind,
            bridge_id: input.bridge_id.clone(),
            hook_id: input.hook_id.clone(),
            operator_backend_id: input.operator_backend_id.clone(),
            operator_pin: input.operator_pin.clone(),
            operator_kind_overrides: input.operator_kind_overrides.clone(),
            task_input: input.task_input.clone(),
            check_policy: input.check_policy,
        }
    }

    /// Rebuild the launch input from a snapshot for resume.
    fn into_input(self) -> TaskApplicationInput {
        TaskApplicationInput {
            blueprint: self.blueprint,
            operator_id: self.operator_id,
            role: self.role,
            ttl: self.ttl,
            init_ctx: self.init_ctx,
            operator_kind: self.operator_kind,
            bridge_id: self.bridge_id,
            hook_id: self.hook_id,
            operator_backend_id: self.operator_backend_id,
            operator_pin: self.operator_pin,
            operator_kind_overrides: self.operator_kind_overrides,
            task_input: self.task_input,
            check_policy: self.check_policy,
        }
    }
}

/// Serialize a launch input into the opaque `RunRecord.input_json` blob.
/// Shared by both Run-creation sites (`run_flow_form` in `crate::lib` and
/// [`task_rekick`]) so every persisted Run carries the snapshot resume
/// needs. A serialization failure is a `400` — it means the caller handed
/// in a value the snapshot cannot round-trip, which must surface before the
/// Run is dispatched, not silently.
pub(crate) fn snapshot_launch_input(input: &TaskApplicationInput) -> Result<String, ApiError> {
    serde_json::to_string(&RunLaunchSnapshot::from_input(input))
        .map_err(|e| ApiError::bad_request(format!("launch input snapshot: {e}")))
}

/// Shared finalize step for a dispatched kick: updates the Run's
/// `result_ref` + status and the owning Task's coarse status based on the
/// `TaskApplication::handle_with_run` outcome, then returns that same
/// outcome unchanged so callers keep shaping their own wire response /
/// error.
///
/// Secondary persistence failures (the store call itself erroring) are
/// logged via `tracing::warn!` and otherwise swallowed — they must not mask
/// the primary dispatch outcome the caller already has in hand.
pub(crate) async fn finalize_run(
    state: &AppState,
    task_id: &TaskId,
    run_id: &RunId,
    outcome: Result<TaskApplicationOutput, TaskApplicationError>,
) -> Result<TaskApplicationOutput, TaskApplicationError> {
    match &outcome {
        Ok(out) => {
            if let Err(e) = state
                .run_store
                .set_result(run_id, out.final_ctx.clone())
                .await
            {
                tracing::warn!(%run_id, error = %e, "finalize_run: set_result failed");
            }
            if let Err(e) = state.run_store.update_status(run_id, RunStatus::Done).await {
                tracing::warn!(%run_id, error = %e, "finalize_run: run update_status(Done) failed");
            }
            if let Err(e) = state
                .task_store
                .update_status(task_id, TaskRecordStatus::Done)
                .await
            {
                tracing::warn!(%task_id, error = %e, "finalize_run: task update_status(Done) failed");
            }
        }
        Err(e) => {
            // GH #76 error surface: persist a structured failure envelope into
            // `RunRecord.result_ref` so the async poll path (`GET
            // /v1/runs/:id`) can surface `failed_step` / `verdict_value` /
            // `partial_ctx` symmetric to the sync path's `ApiError`
            // `details` field. Envelope shape (documented for consumer
            // disambiguation from the Ok arm's raw `final_ctx`):
            //
            // ```json
            // {
            //   "error": {
            //     "message": <string>,
            //     "failed_step": <string|null>,
            //     "verdict_value": <value|null>
            //   },
            //   "partial_ctx": <value|null>
            // }
            // ```
            //
            // Consumers detect failure via the top-level `"error"` key
            // (present iff this arm fired; the Ok arm stores the raw
            // `final_ctx` verbatim, which is either a scalar or an object
            // with the user's own keys — never a top-level `"error"`
            // sibling of `"partial_ctx"`). Non-`FlowEval` errors (e.g.
            // `TaskApplicationError::Store` / `NoStore` — dispatch never
            // reached the flow eval boundary) still get an envelope, but
            // with the structural fields `null` (the underlying error
            // simply carries no `failed_step` semantic).
            let envelope = match e {
                TaskApplicationError::Launch(TaskLaunchError::FlowEval {
                    message,
                    failed_step,
                    verdict_value,
                    partial_ctx,
                }) => json!({
                    "error": {
                        "message": message,
                        "failed_step": failed_step,
                        "verdict_value": verdict_value,
                    },
                    "partial_ctx": partial_ctx,
                }),
                other => json!({
                    "error": {
                        "message": other.to_string(),
                        "failed_step": Value::Null,
                        "verdict_value": Value::Null,
                    },
                    "partial_ctx": Value::Null,
                }),
            };
            if let Err(store_err) = state.run_store.set_result(run_id, envelope).await {
                tracing::warn!(%run_id, error = %store_err, "finalize_run: set_result (failure envelope) failed");
            }
            if let Err(store_err) = state
                .run_store
                .update_status(run_id, RunStatus::Failed)
                .await
            {
                tracing::warn!(%run_id, error = %store_err, "finalize_run: run update_status(Failed) failed");
            }
            if let Err(store_err) = state
                .task_store
                .update_status(task_id, TaskRecordStatus::Failed)
                .await
            {
                tracing::warn!(%task_id, error = %store_err, "finalize_run: task update_status(Failed) failed");
            }
            tracing::warn!(%task_id, %run_id, error = %e, "finalize_run: dispatch failed");
        }
    }
    // Trace rail: mark the Run's terminal status on the stream (the
    // `core.run_started` counterpart appended at the launch sites).
    // Best-effort like every other persistence in this fn.
    let status = if outcome.is_ok() { "done" } else { "failed" };
    TraceHandle::new(run_id.clone(), state.run_trace_store.clone())
        .append(
            trace_kind::RUN_FINISHED,
            None,
            None,
            json!({ "status": status }),
        )
        .await;
    outcome
}

/// Render a caught panic payload as a human-readable string. `panic!` with
/// a literal yields `&'static str`, a formatted `panic!` yields `String`;
/// anything else (a `panic_any` with a custom type) has no textual form, so
/// it is reported by shape rather than dropped silently.
fn panic_payload_to_string(payload: Box<dyn std::any::Any + Send>) -> String {
    if let Some(s) = payload.downcast_ref::<&'static str>() {
        (*s).to_string()
    } else if let Some(s) = payload.downcast_ref::<String>() {
        s.clone()
    } else {
        "non-string panic payload".to_string()
    }
}

/// Terminal-stamp a Run whose driver future panicked: `Interrupted` plus a
/// structured `{"error": "run driver panicked at <site>: <payload>"}`
/// result envelope — the same terminal shape the boot sweep and the
/// shutdown drain stamp, so the Run stays resumable via
/// `POST /v1/runs/:id/resume` (which only accepts `Interrupted`).
///
/// The status flip goes through [`RunStore::try_transition`], so a Run that
/// already reached a terminal status is left alone: a panic raised *after*
/// `finalize_run` persisted `Done` / `Failed` (for example inside the trace
/// tail) must not rewrite that verdict.
///
/// Best-effort like [`finalize_run`]: every secondary store error is logged
/// and swallowed — the panic itself is the primary signal, already logged by
/// [`catch_run_panic`].
pub(crate) async fn mark_run_interrupted_by_panic(
    state: &AppState,
    task_id: &TaskId,
    run_id: &RunId,
    site: &str,
    payload: &str,
) {
    match state
        .run_store
        .try_transition(run_id, RunStatus::Running, RunStatus::Interrupted)
        .await
    {
        Ok(true) => {}
        Ok(false) => {
            tracing::warn!(
                %run_id,
                site,
                "run driver panicked, but the Run is no longer `Running` — leaving its terminal status untouched"
            );
            return;
        }
        Err(e) => {
            tracing::warn!(%run_id, error = %e, "panic guard: run try_transition(Running -> Interrupted) failed");
            return;
        }
    }

    let envelope = json!({ "error": format!("run driver panicked at {site}: {payload}") });
    if let Err(e) = state.run_store.set_result(run_id, envelope).await {
        tracing::warn!(%run_id, error = %e, "panic guard: set_result failed");
    }
    if let Err(e) = state
        .task_store
        .update_status(task_id, TaskRecordStatus::Interrupted)
        .await
    {
        tracing::warn!(%task_id, error = %e, "panic guard: task update_status(Interrupted) failed");
    }
    // This path never reaches `finalize_run`, so the trace stream gets its
    // terminal marker here.
    TraceHandle::new(run_id.clone(), state.run_trace_store.clone())
        .append(
            trace_kind::RUN_FINISHED,
            None,
            None,
            json!({ "status": "interrupted", "reason": "driver panic" }),
        )
        .await;
}

/// Wrap a run driver future so a panic inside it terminates the Run instead
/// of vanishing with the task.
///
/// Without this, a panic in a detached driver unwinds the whole spawned task
/// — including the `tokio::time::timeout` combinator that wraps it, so the
/// TTL ceiling never fires either — and the `RunRecord` is stranded in
/// `Running` with no recovery path. On the synchronous paths the same panic
/// propagates into the hyper connection task and drops the connection
/// mid-request. Here the panic is caught, the Run is marked `Interrupted`
/// via [`mark_run_interrupted_by_panic`], and the caller gets the payload
/// string back to shape its own response.
///
/// Note this relies on unwinding: a future `[profile.release] panic =
/// "abort"` would make the guard a no-op.
pub(crate) async fn catch_run_panic<T, F>(
    state: &AppState,
    task_id: &TaskId,
    run_id: &RunId,
    site: &str,
    fut: F,
) -> Result<T, String>
where
    F: std::future::Future<Output = T>,
{
    match AssertUnwindSafe(fut).catch_unwind().await {
        Ok(value) => Ok(value),
        Err(payload) => {
            let message = panic_payload_to_string(payload);
            tracing::error!(
                %task_id,
                %run_id,
                site,
                payload = %message,
                "run driver panicked — marking the Run Interrupted"
            );
            mark_run_interrupted_by_panic(state, task_id, run_id, site, &message).await;
            Err(message)
        }
    }
}

/// Query params for `GET /v1/tasks`.
#[derive(Debug, Deserialize, Default)]
pub struct TasksListQuery {
    /// Caps the returned list to the first N entries (already newest-first
    /// per `TaskStore::list`). Omitted = no cap.
    #[serde(default)]
    pub limit: Option<usize>,
}

/// `GET /v1/tasks?limit=N`. Lists every persisted `TaskRecord`, newest first.
pub async fn tasks_list(
    State(state): State<AppState>,
    Query(q): Query<TasksListQuery>,
) -> Result<Json<Vec<TaskRecord>>, ApiError> {
    let mut records = state.task_store.list().await.map_err(ApiError::engine)?;
    if let Some(limit) = q.limit {
        records.truncate(limit);
    }
    Ok(Json(records))
}

/// Response body for `GET /v1/tasks/:id`.
#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
pub struct TaskDetailResponse {
    /// The Task's own record.
    pub task: TaskRecord,
    /// Every Run kicked from this Task, oldest first (`RunStore::list_by_task` order).
    pub runs: Vec<RunRecord>,
}

/// `GET /v1/tasks/:id`. Returns the `TaskRecord` plus every `RunRecord`
/// kicked from it (`RunStore::list_by_task`, oldest kick first).
pub async fn task_get(
    State(state): State<AppState>,
    Path(id): Path<String>,
) -> Result<Json<TaskDetailResponse>, ApiError> {
    let task_id =
        TaskId::parse(id).map_err(|e| ApiError::bad_request(format!("invalid task id: {e}")))?;
    let task = state
        .task_store
        .get(&task_id)
        .await
        .map_err(map_task_store_err)?;
    let runs = state
        .run_store
        .list_by_task(&task_id)
        .await
        .map_err(ApiError::engine)?;
    Ok(Json(TaskDetailResponse { task, runs }))
}

/// Request body for `POST /v1/tasks/:id/runs` (issue #19 ST4) — every
/// field is optional, and the body itself is optional (see
/// [`task_rekick`]'s `Option<Json<Self>>` parameter); a caller that sends
/// no body, or `{}`, or omits a field gets exactly today's rekick
/// behavior for that layer.
#[derive(Debug, Deserialize, Default, schemars::JsonSchema)]
pub struct RunKickRequest {
    /// Per-Run override for the flow-ir initial ctx. Merged on top of
    /// `TaskRecord.input_ctx` (itself already merged on top of
    /// `Blueprint.default_init_ctx` at original launch time) via
    /// [`merge_init_ctx_3layer`] — Run wins on key collision, same
    /// shallow-merge / non-Object-fully-replaces rule as every other
    /// layer in the cascade. `None` (absent field, or no body at all) is
    /// a no-op: the BP+Task merge alone seeds this kick, identical to
    /// pre-#19 rekick.
    #[serde(default)]
    #[schemars(with = "Option<Value>")]
    pub init_ctx_override: Option<Value>,
    /// Per-Run override for the Task-level canonical fields
    /// (`project_root` / `work_dir` / `task_metadata`). `None` falls back
    /// to `TaskRecord.task_input_spec` (the spec resolved and snapshotted
    /// at original `POST /v1/tasks` time); `Some` replaces it wholesale
    /// for this kick only — the stored `TaskRecord.task_input_spec` is
    /// never mutated by a rekick.
    #[serde(default)]
    pub task_input_override: Option<TaskInputSpec>,
    /// Per-Run ceiling (seconds) for this kick's synchronous dispatch
    /// await (issue #35 ST3 — GH #33 Guard 2 parity). `Some(0)` is
    /// rejected (400). `None` falls back to `AppState.sync_timeout_secs`
    /// (the server-wide default), same cascade as
    /// `TaskLaunchRequest.timeout_secs` (`lib.rs:818-826`).
    #[serde(default)]
    pub timeout_secs: Option<u64>,
    /// GH #37: opt into the detached (asynchronous) rekick — same
    /// semantics as `TaskLaunchRequest.detach`. `false` (default) keeps
    /// the synchronous dispatch; `true` spawns the flow eval as a
    /// detached background task bounded by the run TTL alone and returns
    /// `202 Accepted` with `status: "running"` immediately. Mutually
    /// exclusive with `timeout_secs` (`400` when combined).
    #[serde(default)]
    pub detach: bool,
    /// Per-Run pin to a live Operator session (rekick parity with
    /// `POST /v1/tasks`' `operator_sid` — see
    /// `crate::TaskLaunchRequest::operator_sid` for the full
    /// disconnected-vs-unknown / last-write-wins contract). Resolved
    /// before any Task/Run store write: an unknown sid fails fast with a
    /// `400`, never silently falling back to the BP-level alias lookup.
    /// `Some(sid)` becomes this kick's `operator_backend_id` (this handler
    /// carries no other Operator-override field) and is persisted verbatim
    /// into `RunRecord.operator_sid`; `None` (absent field, or no body at
    /// all) preserves the pre-existing Operator-default rekick path
    /// byte-for-byte.
    #[serde(default)]
    pub operator_sid: Option<String>,
}

/// Response body for `POST /v1/tasks/:id/runs`.
#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
pub struct RunKickResponse {
    /// The re-kicked Task's id (echoes the path param).
    #[schemars(with = "String")]
    pub task_id: TaskId,
    /// The freshly minted Run id for this kick.
    #[schemars(with = "String")]
    pub run_id: RunId,
    /// Kick outcome at response time (GH #37). The synchronous path
    /// reports the dispatched run's terminal-side status (`done`); a
    /// detached kick reports `running` — poll `GET /v1/runs/:id` for the
    /// terminal status and result.
    pub status: RunStatus,
}

/// `POST /v1/tasks/:id/runs`. Re-kicks an existing Task: reads its stored
/// `blueprint_ref`, re-resolves it through [`TaskApplication::resolve`]
/// (issue #19 ST4 — refreshes `Blueprint.default_init_ctx` exactly like
/// original launch time, rather than replaying a launch-time-only
/// snapshot), 3-layer-merges `{bp default, TaskRecord.input_ctx, an
/// optional per-Run override}` via [`merge_init_ctx_3layer`], resolves the
/// Task-level canonical fields (`RunKickRequest.task_input_override`,
/// falling back to `TaskRecord.task_input_spec`), mints a fresh `RunId`,
/// dispatches through `TaskApplication::handle_with_run` (Operator-default
/// unless the caller pins a live session via `RunKickRequest.operator_sid`
/// — the rekick parity for `POST /v1/tasks`' own `operator_sid`; the
/// stored Task carries no persisted Operator preference of its own)
/// plus a freshly-built `RunContext` (issue #13 run_id propagation, so
/// this kick's steps get their own `step_entries` trace), and persists the
/// outcome via [`finalize_run`].
///
/// The body is optional (`Option<Json<RunKickRequest>>`) — no body, or a
/// body with both fields absent, preserves the pre-#19 rekick behavior
/// byte-for-byte (`must_not_simplify #3`).
///
/// Issue #35 ST3 ports the GH #33 sync-hang guards from `run_flow_form` to
/// this handler, both checked before any Task/Run store write: Guard 1
/// (503) fails fast when the resolved Blueprint declares the
/// `operator_delegate` spawner-hint layer and no operator is attached;
/// Guard 2 (504) wraps the dispatch await in `RunKickRequest.timeout_secs`
/// (falling back to the server-wide `sync_timeout_secs`), marking the
/// Run/Task `Failed` rather than leaving them `Running` forever on expiry.
pub async fn task_rekick(
    State(state): State<AppState>,
    Path(id): Path<String>,
    body: Option<Json<RunKickRequest>>,
) -> Result<(StatusCode, Json<RunKickResponse>), ApiError> {
    let task_id =
        TaskId::parse(id).map_err(|e| ApiError::bad_request(format!("invalid task id: {e}")))?;
    let task = state
        .task_store
        .get(&task_id)
        .await
        .map_err(map_task_store_err)?;

    let blueprint_ref: mlua_swarm::application::BlueprintRef =
        serde_json::from_value(task.blueprint_ref.clone()).map_err(|e| {
            ApiError::bad_request(format!(
                "task {task_id}: stored blueprint_ref failed to decode: {e}"
            ))
        })?;

    // issue #19 ST4 (must_not_simplify #5): re-resolve the Blueprint the
    // same way `run_flow_form`'s TTL cascade does, so a store-backed
    // `BlueprintRef::Id` gets its *current* `default_init_ctx` on every
    // rekick rather than whatever was true at original launch time. The
    // Inline path is a pure pass-through, so this is a no-op there.
    let (resolved_bp, _bound_version) = state
        .task_app
        .resolve(&blueprint_ref)
        .await
        .map_err(|e| ApiError::from_task_resolve(&e, &format!("task {task_id}: bp resolve")))?;

    let req = body.map(|Json(r)| r).unwrap_or_default();

    // S2 parity with `run_flow_form` (`lib.rs:1035-1048`): an explicit
    // `operator_sid` pins this rekick to a live Operator session,
    // resolved *before* any Task/Run store write so an unknown sid fails
    // fast with a `400` rather than minting records for a kick that
    // references a session nothing can serve. Unlike `run_flow_form` this
    // handler has no other Operator-override field, so the resolved sid
    // flows straight into `TaskApplicationInput.operator_backend_id`
    // (below) and is persisted verbatim into `RunRecord.operator_sid`. See
    // `crate::TaskLaunchRequest::operator_sid` for the disconnected-vs-
    // unknown distinction.
    let operator_backend_id = match &req.operator_sid {
        Some(sid) => {
            let known_ids = state.engine.list_operator_ids().await;
            if !known_ids.iter().any(|id| id == sid) {
                return Err(ApiError::bad_request(format!(
                    "operator_sid: no such registered operator session '{sid}'"
                )));
            }
            Some(sid.clone())
        }
        None => None,
    };

    // GH #33 Guard 2 ceiling resolution (issue #35 ST3 — mirrors
    // `run_flow_form`'s `lib.rs:813-826` cascade): request field > server
    // config > built-in default. Validated up front, before Guard 1 and
    // before any Task/Run store writes, so a caller-supplied `Some(0)`
    // fails fast with `400` rather than minting records for a rekick that
    // was never going to dispatch.
    // GH #37: `detach: true` makes the sync ceiling meaningless (the
    // detached kick is bounded by the run TTL alone) — combining the two
    // is rejected here, same fail-fast-before-side-effects ordering.
    let detach = req.detach;
    let sync_timeout_secs = match (detach, req.timeout_secs) {
        (true, Some(_)) => {
            return Err(ApiError::bad_request(
                "timeout_secs is the synchronous rekick ceiling and does not apply to a \
                 detached rekick (detach: true), whose lifetime bound is the run TTL — omit \
                 timeout_secs"
                    .into(),
            ));
        }
        (false, Some(0)) => {
            return Err(ApiError::bad_request(
                "timeout_secs: 0 is invalid; omit the field to use the server default".into(),
            ));
        }
        (false, Some(v)) => v,
        (_, None) => state.sync_timeout_secs,
    };

    // GH #33 Guard 1 (issue #35 — adapted signal): the
    // per-request `operator_sid` above already fail-fasts an *unknown*
    // sid, but a rekick with no `operator_sid` still has no per-request
    // "operator backend referenced" signal of its own (unlike
    // `run_flow_form`, whose `op_req.operator_backend_id` is sourced from
    // `TaskLaunchRequest.operator`). The adapted signal is the Blueprint's
    // own `spawner_hints.layers`: when the resolved Blueprint declares the
    // `operator_delegate` layer and zero operators are attached at all,
    // fail fast rather than dispatching into a session nothing can serve.
    // Same ordering invariant `run_flow_form` observes: this check runs
    // before any Task/Run row is touched (no side effects on the 503
    // path).
    if resolved_bp
        .spawner_hints
        .layers
        .iter()
        .any(|l| l == "operator_delegate")
    {
        let attached = state.engine.list_operator_ids().await;
        if attached.is_empty() {
            return Err(ApiError::unavailable(format!(
                "no operator attached to serve this rekick (task {task_id}'s \
                 Blueprint declares the operator_delegate layer): attach an \
                 operator via POST /v1/operators + WS, or use the poll-style \
                 flow (GET /v1/worker/prompt + POST /v1/worker/submit)"
            )));
        }
    }

    let merged_init_ctx = merge_init_ctx_3layer(
        resolved_bp.default_init_ctx.as_ref(),
        &task.input_ctx,
        req.init_ctx_override.as_ref(),
    );

    // must_not_simplify #4: `task_input_override` wins for this kick only;
    // falling back to the Task-level snapshot never mutates
    // `TaskRecord.task_input_spec` itself.
    let task_input_spec: Option<TaskInputSpec> = match req.task_input_override {
        Some(over) => Some(over),
        None => task
            .task_input_spec
            .as_ref()
            .map(|v| serde_json::from_value(v.clone()))
            .transpose()
            .map_err(|e| {
                ApiError::bad_request(format!(
                    "task {task_id}: stored task_input_spec failed to decode: {e}"
                ))
            })?,
    };

    let run_id = RunId::new();
    let now = now_secs();

    let input = TaskApplicationInput {
        blueprint: blueprint_ref,
        operator_id: "http-run".to_string(),
        role: Role::Operator,
        ttl: Duration::from_secs(crate::default_run_ttl()),
        init_ctx: merged_init_ctx,
        operator_kind: None,
        bridge_id: None,
        hook_id: None,
        operator_backend_id,
        // Same value, second axis: the sid also binds this rekick's
        // AgentSpec-axis Operator agents (and their manifest attestation) to
        // that session, so a rekick lands on the session the caller named
        // rather than on whichever session currently holds the role.
        operator_pin: req.operator_sid.clone(),
        operator_kind_overrides: HashMap::new(),
        task_input: task_input_spec,
        // This legacy `POST /v1/tasks/:id/runs`-style path does not carry a
        // per-request check_policy override; `None` preserves the
        // server-wide default (backward compat).
        check_policy: None,
    };
    // Persist a launch-input snapshot so this kick's Run can be resumed
    // under the same run_id if it is later interrupted
    // (`POST /v1/runs/:id/resume`). Built from `input` before it is moved
    // into the dispatch below.
    let input_json = Some(snapshot_launch_input(&input)?);

    state
        .task_store
        .update_status(&task_id, TaskRecordStatus::Running)
        .await
        .map_err(ApiError::engine)?;
    state
        .run_store
        .create(RunRecord {
            id: run_id.clone(),
            task_id: task_id.clone(),
            status: RunStatus::Running,
            step_entries: Vec::new(),
            degradations: Vec::new(),
            operator_sid: req.operator_sid.clone(),
            result_ref: None,
            input_json,
            created_at: now,
            updated_at: now,
        })
        .await
        .map_err(ApiError::engine)?;

    let trace = TraceHandle::new(run_id.clone(), state.run_trace_store.clone());
    trace
        .append(
            trace_kind::RUN_STARTED,
            None,
            None,
            json!({"mode": "rekick"}),
        )
        .await;
    let run_ctx = RunContext::new(run_id.clone(), state.run_store.clone())
        .with_replay_store(state.replay_store.clone())
        .with_trace(trace);

    // GH #37 detached rekick: same driver-detach semantics as
    // `run_flow_form` — the eval runs in its own spawned task bounded by
    // the run TTL alone, `finalize_run` (or the ttl-expiry `Failed`
    // marking) is owned by that task, and this handler returns `202
    // Accepted` immediately.
    if detach {
        let ttl_secs = crate::default_run_ttl();
        let bg_state = state.clone();
        let bg_task_id = task_id.clone();
        let bg_run_id = run_id.clone();
        // Panic guard — see `catch_run_panic`.
        let guard_state = state.clone();
        let guard_task_id = task_id.clone();
        let guard_run_id = run_id.clone();
        tokio::spawn(async move {
            let driver = async move {
                let outcome = match tokio::time::timeout(
                    Duration::from_secs(ttl_secs),
                    bg_state.task_app.handle_with_run(input, Some(run_ctx)),
                )
                .await
                {
                    Ok(outcome) => outcome,
                    Err(_elapsed) => {
                        let reason = serde_json::json!({
                            "error": format!("detached rekick exceeded {ttl_secs}s ttl ceiling"),
                        });
                        if let Err(e) = bg_state.run_store.set_result(&bg_run_id, reason).await {
                            tracing::warn!(%bg_run_id, error = %e, "task_rekick: detached ttl set_result failed");
                        }
                        if let Err(e) = bg_state
                            .run_store
                            .update_status(&bg_run_id, RunStatus::Failed)
                            .await
                        {
                            tracing::warn!(%bg_run_id, error = %e, "task_rekick: detached ttl run update_status failed");
                        }
                        if let Err(e) = bg_state
                            .task_store
                            .update_status(&bg_task_id, TaskRecordStatus::Failed)
                            .await
                        {
                            tracing::warn!(%bg_task_id, error = %e, "task_rekick: detached ttl task update_status failed");
                        }
                        // This arm never reaches `finalize_run`, so the trace
                        // stream gets its terminal marker here.
                        TraceHandle::new(bg_run_id.clone(), bg_state.run_trace_store.clone())
                        .append(
                            trace_kind::RUN_FINISHED,
                            None,
                            None,
                            json!({ "status": "failed", "reason": format!("ttl {ttl_secs}s exceeded") }),
                        )
                        .await;
                        return;
                    }
                };
                // `finalize_run` persists both the Ok and Err outcomes itself;
                // the passthrough return value has no consumer here.
                let _ = finalize_run(&bg_state, &bg_task_id, &bg_run_id, outcome).await;
            };
            let _ = catch_run_panic(
                &guard_state,
                &guard_task_id,
                &guard_run_id,
                "rekick.detach",
                driver,
            )
            .await;
        });
        return Ok((
            StatusCode::ACCEPTED,
            Json(RunKickResponse {
                task_id,
                run_id,
                status: RunStatus::Running,
            }),
        ));
    }

    // GH #33 Guard 2 (issue #35 ST3 — mirrors `run_flow_form`'s
    // `lib.rs:935-990` exactly): the single await point this handler
    // blocks on. On expiry the timed-out future is dropped, cancelling the
    // in-process flow eval — the flow is abandoned, not resumed. Best
    // effort: mark the Run/Task so they do not stay `Running` forever.
    // Wrapped in the panic guard (`catch_run_panic`) — same rationale as the
    // sync launch path in `crate::lib`.
    let timed = catch_run_panic(
        &state,
        &task_id,
        &run_id,
        "rekick.sync",
        tokio::time::timeout(
            Duration::from_secs(sync_timeout_secs),
            state.task_app.handle_with_run(input, Some(run_ctx)),
        ),
    )
    .await
    .map_err(|msg| {
        ApiError::engine(format!(
            "run driver panicked: {msg}; the run was marked Interrupted and can be resumed \
             via POST /v1/runs/{run_id}/resume"
        ))
    })?;
    let outcome = match timed {
        Ok(outcome) => outcome,
        Err(_elapsed) => {
            let reason = serde_json::json!({
                "error": format!("sync rekick exceeded {sync_timeout_secs}s timeout ceiling")
            });
            if let Err(e) = state.run_store.set_result(&run_id, reason).await {
                tracing::warn!(%run_id, error = %e, "task_rekick: timeout set_result failed");
            }
            if let Err(e) = state
                .run_store
                .update_status(&run_id, RunStatus::Failed)
                .await
            {
                tracing::warn!(%run_id, error = %e, "task_rekick: timeout run update_status failed");
            }
            if let Err(e) = state
                .task_store
                .update_status(&task_id, TaskRecordStatus::Failed)
                .await
            {
                tracing::warn!(%task_id, error = %e, "task_rekick: timeout task update_status failed");
            }
            return Err(ApiError::timeout(format!(
                "sync rekick exceeded {sync_timeout_secs}s timeout ceiling: task {task_id}, run {run_id}"
            )));
        }
    };
    finalize_run(&state, &task_id, &run_id, outcome)
        .await
        .map_err(|e| ApiError::bad_request(format!("run: {e}")))?;

    Ok((
        StatusCode::CREATED,
        Json(RunKickResponse {
            task_id,
            run_id,
            status: RunStatus::Done,
        }),
    ))
}

/// Response body for `POST /v1/runs/:id/resume`.
#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
pub struct RunResumeResponse {
    /// The resumed Run's id — echoes the path param. Resume never mints a
    /// new `RunId`; the interrupted Run is re-run in place so its
    /// replay-entry Ctx snapshots (which bake this id into
    /// `meta.runtime[run_id]`) stay consistent.
    #[schemars(with = "String")]
    pub run_id: RunId,
    /// The Task this Run belongs to.
    #[schemars(with = "String")]
    pub task_id: TaskId,
    /// Count of already-completed steps handed to the replay cursor — the
    /// engine returns each of these verbatim (no re-dispatch) before
    /// resuming fresh work. `0` = the Run was interrupted before any step
    /// completed, so it re-runs from scratch under the same `run_id`.
    pub replayed_steps: usize,
}

/// `POST /v1/runs/:id/resume`. Resumes an `Interrupted` Run under the SAME
/// `run_id` (no new `RunId` is minted): the stored launch-input snapshot
/// (`RunRecord.input_json`) is rebuilt into a `TaskApplicationInput`, a
/// `ReplayCursor` is built from the Run's logged step snapshots
/// (`ReplayStore::list_by_run`), and the flow is re-dispatched with both
/// wired into a fresh `RunContext`. On dispatch the engine's replay path
/// returns each already-completed step's stored value verbatim (cursor hit,
/// no Adapter spawn) and dispatches only the steps that never finished —
/// reconstructing the same final Ctx a restart-free run would have reached.
///
/// Status codes:
/// - `404` — no Run with this id.
/// - `409` — the Run is not `Interrupted` (already `Running` / `Done` /
///   `Failed` / `Pending`), OR a concurrent resume already won the
///   `Interrupted -> Running` compare-and-set (double-resume guard).
/// - `422` — the Run has no recorded launch-input snapshot, so it cannot be
///   resumed (an older row predating resume support, or a path that does
///   not persist one).
/// - `202 Accepted` — resume accepted; the flow re-runs in a detached
///   background task (same `tokio::spawn` + run-TTL ceiling shape as a
///   detached rekick). Poll `GET /v1/runs/:id` for the terminal status.
///
/// The launch-input decode and the `422` check run BEFORE the
/// compare-and-set so a non-resumable Run is never flipped to `Running`
/// and stranded without a driver behind it.
pub async fn run_resume(
    State(state): State<AppState>,
    Path(id): Path<String>,
) -> Result<(StatusCode, Json<RunResumeResponse>), ApiError> {
    let run_id =
        RunId::parse(id).map_err(|e| ApiError::bad_request(format!("invalid run id: {e}")))?;

    // 404 when the Run does not exist.
    let run = state
        .run_store
        .get(&run_id)
        .await
        .map_err(map_run_store_err)?;

    // Status gate: only an `Interrupted` Run can be resumed.
    if run.status != RunStatus::Interrupted {
        return Err(ApiError::conflict(format!(
            "run {run_id} is {:?}, not Interrupted; only an interrupted run can be resumed",
            run.status
        )));
    }

    // Decode the launch-input snapshot BEFORE the compare-and-set: a Run
    // with no recorded input can never be resumed, and returning `422`
    // here — before flipping the status — avoids stranding it in `Running`
    // with no driver behind it.
    let Some(input_json) = run.input_json.clone() else {
        return Err(ApiError::unprocessable(format!(
            "run {run_id} cannot be resumed: no launch input was recorded for it (it \
             predates resume support, or was created by a path that does not persist one)"
        )));
    };
    let snapshot_value: Value = serde_json::from_str(&input_json).map_err(|e| {
        ApiError::unprocessable(format!(
            "run {run_id}: stored launch input failed to decode: {e}"
        ))
    })?;
    validated_bound_agents_from_snapshot(&run_id, &snapshot_value)?;
    let snapshot: RunLaunchSnapshot = serde_json::from_value(snapshot_value).map_err(|e| {
        ApiError::unprocessable(format!(
            "run {run_id}: stored launch input failed to decode: {e}"
        ))
    })?;

    // Atomically flip Interrupted -> Running. A racing double resume loses
    // the compare-and-set and gets a `409` rather than dispatching a second
    // driver over the same Run.
    let won = state
        .run_store
        .try_transition(&run_id, RunStatus::Interrupted, RunStatus::Running)
        .await
        .map_err(ApiError::engine)?;
    if !won {
        return Err(ApiError::conflict(format!(
            "run {run_id} was concurrently resumed (or left the Interrupted state); it is \
             no longer resumable"
        )));
    }

    // Build the replay cursor from the Run's logged step snapshots. An
    // empty log is fine — the cursor has zero hits and every step is
    // dispatched fresh (a from-scratch re-run under the same run_id).
    let entries = state
        .replay_store
        .list_by_run(&run_id)
        .await
        .map_err(|e| ApiError::engine(format!("replay list_by_run: {e}")))?;
    let replayed_steps = entries.len();
    let cursor = ReplayCursor::from_entries(entries);

    // RunContext for the SAME run_id — run_store + replay_store +
    // replay_cursor all wired. No new RunRecord is minted. `with_resume()`
    // marks this as a resume so any binding backfill is stamped
    // `resume_backfill` (and, D2, keeps legacy replay keys).
    let trace = TraceHandle::new(run_id.clone(), state.run_trace_store.clone());
    trace
        .append(
            trace_kind::RUN_STARTED,
            None,
            None,
            json!({"mode": "resume"}),
        )
        .await;
    let run_ctx = RunContext::new(run_id.clone(), state.run_store.clone())
        .with_replay_store(state.replay_store.clone())
        .with_replay_cursor(Arc::new(Mutex::new(cursor)))
        .with_resume()
        .with_trace(trace);

    let input = snapshot.into_input();
    let task_id = run.task_id.clone();

    // A resumed Task is running again; finalize_run resets it to
    // Done/Failed at the end, same as the rekick path.
    state
        .task_store
        .update_status(&task_id, TaskRecordStatus::Running)
        .await
        .map_err(ApiError::engine)?;

    // Detached dispatch — same `tokio::spawn` + run-TTL-ceiling shape as
    // the detached rekick path; `finalize_run` (or the ttl-expiry `Failed`
    // marking) owns the terminal persistence.
    let ttl_secs = crate::default_run_ttl();
    let bg_state = state.clone();
    let bg_task_id = task_id.clone();
    let bg_run_id = run_id.clone();
    // Panic guard — see `catch_run_panic`.
    let guard_state = state.clone();
    let guard_task_id = task_id.clone();
    let guard_run_id = run_id.clone();
    tokio::spawn(async move {
        let driver = async move {
            let outcome = match tokio::time::timeout(
                Duration::from_secs(ttl_secs),
                bg_state.task_app.handle_with_run(input, Some(run_ctx)),
            )
            .await
            {
                Ok(outcome) => outcome,
                Err(_elapsed) => {
                    let reason = serde_json::json!({
                        "error": format!("resumed run exceeded {ttl_secs}s ttl ceiling"),
                    });
                    if let Err(e) = bg_state.run_store.set_result(&bg_run_id, reason).await {
                        tracing::warn!(%bg_run_id, error = %e, "run_resume: ttl set_result failed");
                    }
                    if let Err(e) = bg_state
                        .run_store
                        .update_status(&bg_run_id, RunStatus::Failed)
                        .await
                    {
                        tracing::warn!(%bg_run_id, error = %e, "run_resume: ttl run update_status failed");
                    }
                    if let Err(e) = bg_state
                        .task_store
                        .update_status(&bg_task_id, TaskRecordStatus::Failed)
                        .await
                    {
                        tracing::warn!(%bg_task_id, error = %e, "run_resume: ttl task update_status failed");
                    }
                    return;
                }
            };
            // `finalize_run` persists both the Ok and Err outcomes itself.
            let _ = finalize_run(&bg_state, &bg_task_id, &bg_run_id, outcome).await;
        };
        let _ = catch_run_panic(
            &guard_state,
            &guard_task_id,
            &guard_run_id,
            "resume.detach",
            driver,
        )
        .await;
    });

    Ok((
        StatusCode::ACCEPTED,
        Json(RunResumeResponse {
            run_id,
            task_id,
            replayed_steps,
        }),
    ))
}

/// Request body for `POST /v1/runs/:id/rerun-from` (GH #71 Layer A).
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct RunRerunFromRequest {
    /// The step to re-execute. This is a raw `step_ref` (the agent name the
    /// dispatcher recorded as `ReplayEntry.step_ref`), NOT a projection
    /// canonical name. See [`run_rerun_from`] doc for the Known Limitations
    /// this carries (loop bodies match the first occurrence,
    /// `AgentMeta.projection_name` is not resolved, `BlueprintRef::Inline`
    /// re-decodes the frozen inline BP).
    pub from_step: String,
}

/// Response body for `POST /v1/runs/:id/rerun-from` (GH #71 Layer A).
#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
pub struct RunRerunFromResponse {
    /// The rerun's Run id — echoes the path param. Rerun-from-step never
    /// mints a new `RunId`; it re-runs in place so the replay-entry Ctx
    /// snapshots (which bake this id into `meta.runtime[run_id]`) stay
    /// consistent.
    #[schemars(with = "String")]
    pub run_id: RunId,
    /// The Task this Run belongs to.
    #[schemars(with = "String")]
    pub task_id: TaskId,
    /// Count of pre-cut entries handed to the replay cursor — each is
    /// returned verbatim by the engine before fresh dispatch resumes at
    /// the cut point.
    pub replayed_steps: usize,
    /// Count of entries physically dropped from the replay store — the
    /// target step's row plus every downstream row.
    pub dropped_steps: usize,
}

/// `POST /v1/runs/:id/rerun-from` — GH #71 Layer A. Re-executes a specific
/// step (and every downstream step) of a terminal Run under the SAME
/// `run_id`. Mirrors [`run_resume`], with two deltas: it accepts any
/// terminal status (`Done` / `Failed` / `Interrupted`) rather than only
/// `Interrupted`, and it physically truncates the replay log at the cut
/// point (via [`crate::AppState::replay_store`]'s `delete_from`) so that
/// re-dispatch's `append` does not collide with the pre-rerun row and so
/// `list_by_run` reflects the rerun's real history rather than the
/// pre-rerun ghost.
///
/// # Status codes
///
/// - `400` — invalid `run_id`, malformed body, or launch-snapshot decode failure.
/// - `404` — no Run with this id.
/// - `409` — the Run is `Running` / `Pending` (would race the in-flight
///   driver), OR a concurrent transition won the compare-and-set.
/// - `422` — the Run has no recorded launch-input snapshot, OR `from_step`
///   is not present in this Run's replay log, OR the run's replay log is
///   empty next to a non-empty `RunRecord.step_entries` trace (a prior
///   `rerun-from` reached the truncate stage and consumed the log), OR
///   the current-head Blueprint fails to compile (unresolved
///   `operator_ref` etc.) — the deterministic pre-flight gate that keeps
///   the replay log untouched on a compile-fail.
/// - `202 Accepted` — accepted; the flow re-runs in a detached background
///   task (same `tokio::spawn` + run-TTL ceiling shape as [`run_resume`]).
///   Poll `GET /v1/runs/:id` for the terminal status.
///
/// # Order of operations
///
/// The compare-and-set runs BEFORE the `delete_from` on purpose: a losing
/// cas returns `409` without ever touching the store, so a lost race can
/// never leave the store truncated while the status stayed at its old
/// terminal value. The compile pre-check runs BEFORE the compare-and-set
/// for the same reason: a deterministic compile failure fires a `422`
/// that leaves both `status` and the replay log untouched, so the caller
/// can fix the Blueprint and retry against the same run.
///
/// 1. 404 check.
/// 2. Status gate (fast 409 for `Running` / `Pending`).
/// 3. Decode launch snapshot (fast 400 / 422).
/// 4. Compute cut index via `list_by_run` + `.position(step_ref == from_step)`
///    (fast 422 when the step is not present, with a distinct message when
///    the log is empty but `RunRecord.step_entries` shows the run did
///    trace steps — a consumed log from a prior `rerun-from`).
/// 5. Pre-flight compile check via `TaskApplication::precompile` against
///    the launch snapshot's Blueprint (fast 422 on any `CompileError`).
///    Prevents compile-fail-inside-`tokio::spawn` from consuming the
///    replay log via step 7's `delete_from`.
/// 6. Atomic transition `<current terminal> -> Running` (409 on loss).
/// 7. Physical `delete_from(cut)` on the replay store — safe now because we
///    won the cas and own the Run.
/// 8. Build `ReplayCursor` from the truncated entries.
/// 9. Detached dispatch, same `tokio::spawn` + `default_run_ttl` shape as
///    [`run_resume`].
///
/// # Known limitations (Layer A)
///
/// 1. **`from_step` is a raw `step_ref` (agent name)** — projection alias
///    resolution via `StepNaming` is Layer B territory. For undeclared
///    steps `step_ref == canonical` so this is only visible when
///    `AgentMeta.projection_name` is in use.
/// 2. **`BlueprintRef::Inline` freezes the BP in the launch snapshot** —
///    the rerun re-decodes the same inline BP, so agent-definition edits
///    landed on disk between the original dispatch and the rerun are NOT
///    honored for inline runs. Use `BlueprintRef::Id` for the
///    iterate-and-rerun workflow.
/// 3. **Loop bodies match the first occurrence** — `step_ref` is the agent
///    name, so `.position(|e| e.step_ref == from_step)` finds the FIRST
///    occurrence and truncates from there. Rerunning a specific loop
///    iteration needs Layer B semantics.
/// 4. **Structural BP change is out of scope** — if steps were added /
///    removed / reordered between the original dispatch and the rerun,
///    the flow-ir re-eval will naturally miss the step or dispatch a
///    different downstream. Start a fresh run in that case.
pub async fn run_rerun_from(
    State(state): State<AppState>,
    Path(id): Path<String>,
    Json(req): Json<RunRerunFromRequest>,
) -> Result<(StatusCode, Json<RunRerunFromResponse>), ApiError> {
    let run_id =
        RunId::parse(id).map_err(|e| ApiError::bad_request(format!("invalid run id: {e}")))?;

    if req.from_step.trim().is_empty() {
        return Err(ApiError::bad_request(
            "from_step must be a non-empty step ref".to_string(),
        ));
    }

    // 404 when the Run does not exist.
    let run = state
        .run_store
        .get(&run_id)
        .await
        .map_err(map_run_store_err)?;

    // Status gate — reject in-flight statuses that would race the driver
    // already dispatching against this run_id.
    let current = run.status;
    match current {
        RunStatus::Done | RunStatus::Failed | RunStatus::Interrupted | RunStatus::Cancelled => { /* ok */
        }
        RunStatus::Running | RunStatus::Pending => {
            return Err(ApiError::conflict(format!(
                "run {run_id} is {current:?}; rerun-from requires a terminal run \
                 (Done / Failed / Interrupted / Cancelled)"
            )));
        }
    }

    // Decode the launch-input snapshot BEFORE the compare-and-set: a Run
    // with no recorded input can never be rerun-from, and returning `422`
    // here — before flipping the status — avoids stranding it in `Running`
    // with no driver behind it.
    let Some(input_json) = run.input_json.clone() else {
        return Err(ApiError::unprocessable(format!(
            "run {run_id} cannot be rerun: no launch input was recorded for it (it \
             predates resume/rerun support, or was created by a path that does not \
             persist one)"
        )));
    };
    let snapshot_value: Value = serde_json::from_str(&input_json).map_err(|e| {
        ApiError::unprocessable(format!(
            "run {run_id}: stored launch input failed to decode: {e}"
        ))
    })?;
    validated_bound_agents_from_snapshot(&run_id, &snapshot_value)?;
    let snapshot: RunLaunchSnapshot = serde_json::from_value(snapshot_value).map_err(|e| {
        ApiError::unprocessable(format!(
            "run {run_id}: stored launch input failed to decode: {e}"
        ))
    })?;

    // Load the replay log and locate the cut point via first-match on
    // `step_ref`. See §Known limitations #3 (loop bodies).
    let entries = state
        .replay_store
        .list_by_run(&run_id)
        .await
        .map_err(|e| ApiError::engine(format!("replay list_by_run: {e}")))?;
    let cut = entries
        .iter()
        .position(|e| e.step_ref == req.from_step)
        .ok_or_else(|| {
            // Distinguish two shapes of miss: (a) the log carries entries
            // but none match `from_step` (typo or wrong step name); (b) the
            // log is empty while `RunRecord.step_entries` still traces
            // steps — which means a prior `rerun-from` reached the
            // `delete_from` stage and consumed the log, and no further
            // `rerun-from` against the same run is recoverable. `run.
            // step_entries` and `replay_store` are physically separate
            // tables (the dispatcher writes to both), so an empty log next
            // to a non-empty trace is the reliable tell.
            if entries.is_empty() && !run.step_entries.is_empty() {
                ApiError::unprocessable(format!(
                    "run {run_id}: replay log is empty but {} step entries are traced \
                     on the RunRecord — the log was consumed by a prior rerun-from \
                     that reached the truncate stage. This run can no longer be \
                     rerun-from; start a fresh run via POST /v1/tasks.",
                    run.step_entries.len()
                ))
            } else {
                ApiError::unprocessable(format!(
                    "run {run_id}: from_step {:?} not present in this run's replay log \
                     (nothing to rerun-from)",
                    req.from_step
                ))
            }
        })?;

    // Pre-flight compile check against the current-head Blueprint the
    // rerun will actually launch against. Compile is deterministic — an
    // `UnresolvedOperatorRef` / `UnresolvedMetaRef` / `UnresolvedAuditAgent`
    // / verdict-cond shape violation fails the same way every attempt —
    // so surfacing it here as a 422, BEFORE the compare-and-set and
    // BEFORE `delete_from`, converts an otherwise irrecoverable replay-
    // loss (compile fails INSIDE the detached `tokio::spawn` AFTER the
    // truncation has physically dropped the pre-cut rows) into a fast
    // rejection that leaves the run's status and replay log entirely
    // untouched. Runtime-only failures (spawner error, worker submit
    // failure) are still able to consume the log — inherent to any
    // path that can only be discovered mid-dispatch — but that class
    // needs a different fix (Layer B territory).
    if let Err(e) = state.task_app.precompile(&snapshot.blueprint).await {
        return Err(ApiError::unprocessable(format!(
            "run {run_id} cannot be rerun: current-head Blueprint fails to compile — {e}"
        )));
    }

    // Atomically flip the current terminal status -> Running. A racing
    // rerun (or a boot-time recovery sweep, or a concurrent resume) loses
    // the compare-and-set and gets `409` rather than dispatching a second
    // driver over the same Run.
    let won = state
        .run_store
        .try_transition(&run_id, current, RunStatus::Running)
        .await
        .map_err(ApiError::engine)?;
    if !won {
        return Err(ApiError::conflict(format!(
            "run {run_id} was concurrently transitioned (or left the {current:?} state); \
             it is no longer rerunnable"
        )));
    }

    // We own the run now — physically truncate the replay log at the cut
    // so the rerun dispatch's `append` cannot collide with the pre-rerun
    // row and `list_by_run` reflects the rerun's real history rather than
    // the pre-rerun ghost.
    let dropped_steps = state
        .replay_store
        .delete_from(&run_id, cut)
        .await
        .map_err(|e| ApiError::engine(format!("replay delete_from: {e}")))?;

    // Cursor is built from the pre-cut prefix; every retained entry hits
    // verbatim in the engine's replay path.
    let kept = entries.into_iter().take(cut).collect::<Vec<_>>();
    let replayed_steps = kept.len();
    let cursor = ReplayCursor::from_entries(kept);

    // `with_resume()` — a rerun-from re-derives its snapshot from the current
    // Blueprint exactly like resume, so a binding backfill here is stamped
    // `resume_backfill` (and keeps legacy replay keys, D2).
    let trace = TraceHandle::new(run_id.clone(), state.run_trace_store.clone());
    trace
        .append(
            trace_kind::RUN_STARTED,
            None,
            None,
            json!({"mode": "rerun_from"}),
        )
        .await;
    let run_ctx = RunContext::new(run_id.clone(), state.run_store.clone())
        .with_replay_store(state.replay_store.clone())
        .with_replay_cursor(Arc::new(Mutex::new(cursor)))
        .with_resume()
        .with_trace(trace);

    let input = snapshot.into_input();
    let task_id = run.task_id.clone();

    // A rerun-from is a running Run again; finalize_run resets it to
    // Done/Failed at the end, same as the rekick / resume paths.
    state
        .task_store
        .update_status(&task_id, TaskRecordStatus::Running)
        .await
        .map_err(ApiError::engine)?;

    let ttl_secs = crate::default_run_ttl();
    let bg_state = state.clone();
    let bg_task_id = task_id.clone();
    let bg_run_id = run_id.clone();
    // Panic guard — see `catch_run_panic`.
    let guard_state = state.clone();
    let guard_task_id = task_id.clone();
    let guard_run_id = run_id.clone();
    tokio::spawn(async move {
        let driver = async move {
            let outcome = match tokio::time::timeout(
                Duration::from_secs(ttl_secs),
                bg_state.task_app.handle_with_run(input, Some(run_ctx)),
            )
            .await
            {
                Ok(outcome) => outcome,
                Err(_elapsed) => {
                    let reason = serde_json::json!({
                        "error": format!("rerun-from run exceeded {ttl_secs}s ttl ceiling"),
                    });
                    if let Err(e) = bg_state.run_store.set_result(&bg_run_id, reason).await {
                        tracing::warn!(%bg_run_id, error = %e, "run_rerun_from: ttl set_result failed");
                    }
                    if let Err(e) = bg_state
                        .run_store
                        .update_status(&bg_run_id, RunStatus::Failed)
                        .await
                    {
                        tracing::warn!(%bg_run_id, error = %e, "run_rerun_from: ttl run update_status failed");
                    }
                    if let Err(e) = bg_state
                        .task_store
                        .update_status(&bg_task_id, TaskRecordStatus::Failed)
                        .await
                    {
                        tracing::warn!(%bg_task_id, error = %e, "run_rerun_from: ttl task update_status failed");
                    }
                    return;
                }
            };
            let _ = finalize_run(&bg_state, &bg_task_id, &bg_run_id, outcome).await;
        };
        let _ = catch_run_panic(
            &guard_state,
            &guard_task_id,
            &guard_run_id,
            "rerun_from.detach",
            driver,
        )
        .await;
    });

    Ok((
        StatusCode::ACCEPTED,
        Json(RunRerunFromResponse {
            run_id,
            task_id,
            replayed_steps,
            dropped_steps,
        }),
    ))
}

/// `GET /v1/runs/:id`. Returns a single `RunRecord` (its `step_entries`
/// trace included).
pub async fn run_get(
    State(state): State<AppState>,
    Path(id): Path<String>,
) -> Result<Json<RunRecord>, ApiError> {
    let run_id =
        RunId::parse(id).map_err(|e| ApiError::bad_request(format!("invalid run id: {e}")))?;
    let run = state
        .run_store
        .get(&run_id)
        .await
        .map_err(map_run_store_err)?;
    Ok(Json(run))
}

/// Query params for `GET /v1/runs` (the Run collection read).
#[derive(Debug, Deserialize, Default)]
pub struct RunsListQuery {
    /// Only Runs kicked from this Task.
    #[serde(default)]
    pub task_id: Option<String>,
    /// Only Runs currently in this status (`pending` / `running` / `done`
    /// / `failed` / `interrupted`).
    #[serde(default)]
    pub status: Option<String>,
    /// Page size cap. Omitted = no cap.
    #[serde(default)]
    pub limit: Option<usize>,
    /// Skip the first N matching rows (after newest-first ordering).
    #[serde(default)]
    pub offset: Option<usize>,
}

/// Response body for `GET /v1/runs`.
#[derive(Debug, Serialize)]
pub struct RunsListResponse {
    /// Matching Runs, newest-first.
    pub runs: Vec<RunRecord>,
}

/// `GET /v1/runs?task_id=&status=&limit=&offset=` — filtered Run
/// collection, newest-first. The collection read that was missing from
/// the Run CRUD surface (only `GET /v1/runs/:id` existed before the
/// per-step run stats work).
pub async fn runs_list(
    State(state): State<AppState>,
    Query(q): Query<RunsListQuery>,
) -> Result<Json<RunsListResponse>, ApiError> {
    let task_id = q
        .task_id
        .map(TaskId::parse)
        .transpose()
        .map_err(|e| ApiError::bad_request(format!("invalid task_id: {e}")))?;
    let status = q
        .status
        .as_deref()
        .map(|s| {
            serde_json::from_value::<RunStatus>(Value::String(s.to_string())).map_err(|_| {
                ApiError::bad_request(format!(
                    "invalid status {s:?} (expected pending/running/done/failed/interrupted)"
                ))
            })
        })
        .transpose()?;
    let runs = state
        .run_store
        .list(&RunListFilter {
            task_id,
            status,
            limit: q.limit,
            offset: q.offset,
        })
        .await
        .map_err(map_run_store_err)?;
    Ok(Json(RunsListResponse { runs }))
}

/// Response body for `GET /v1/runs/:id/steps`.
///
/// `JsonSchema` is derived so `mse://api/http-endpoints` can publish the
/// per-step stats surface without restating [`StepEntry`]'s field list.
#[derive(Debug, Serialize, schemars::JsonSchema)]
pub struct RunStepsResponse {
    /// The Run the steps belong to.
    pub run_id: String,
    /// Terminal per-step stats entries, in append (dispatch) order.
    pub steps: Vec<StepEntry>,
}

/// `GET /v1/runs/:id/steps` — the Run's terminal per-step stats
/// (`StepEntry` list) as a standalone sub-resource. Same data
/// `GET /v1/runs/:id` embeds; split out so stats consumers don't drag
/// the full RunRecord (launch snapshot etc.) per poll.
pub async fn run_steps(
    State(state): State<AppState>,
    Path(id): Path<String>,
) -> Result<Json<RunStepsResponse>, ApiError> {
    let run_id =
        RunId::parse(id).map_err(|e| ApiError::bad_request(format!("invalid run id: {e}")))?;
    let run = state
        .run_store
        .get(&run_id)
        .await
        .map_err(map_run_store_err)?;
    Ok(Json(RunStepsResponse {
        run_id: run.id.to_string(),
        steps: run.step_entries,
    }))
}

/// Query params for `GET /v1/runs/:id/trace` — see
/// `mlua_swarm::store::trace::TraceQuery` for semantics (`latest` wins
/// over `after`; `kind` entries are comma-separated prefix matches).
#[derive(Debug, Deserialize, Default)]
pub struct RunTraceQuery {
    /// Forward-paging cursor: only events with `seq > after`.
    #[serde(default)]
    pub after: Option<u64>,
    /// Page size cap.
    #[serde(default)]
    pub limit: Option<usize>,
    /// Tail mode: the LAST n matching events (ascending order).
    #[serde(default)]
    pub latest: Option<usize>,
    /// Comma-separated kind filters, prefix match (e.g. `kind=mw.` or
    /// `kind=core.step_completed,worker.`).
    #[serde(default)]
    pub kind: Option<String>,
    /// Exact `step_ref` filter.
    #[serde(default)]
    pub step: Option<String>,
    /// Exact attempt filter.
    #[serde(default)]
    pub attempt: Option<u32>,
}

/// Response body for `GET /v1/runs/:id/trace`.
#[derive(Debug, Serialize)]
pub struct RunTraceResponse {
    /// The Run the events belong to.
    pub run_id: String,
    /// Matching trace events, ascending by `seq`.
    pub events: Vec<TraceEvent>,
}

/// `GET /v1/runs/:id/trace?after=&limit=&latest=&kind=&step=&attempt=` —
/// the Run's TraceEvent stream (the RunTrace rail). Note the trace rail
/// is deliberately uncoupled from `RunStore` (a trace can outlive or
/// precede its Run row), so an unknown Run id returns an empty list, not
/// 404.
pub async fn run_trace(
    State(state): State<AppState>,
    Path(id): Path<String>,
    Query(q): Query<RunTraceQuery>,
) -> Result<Json<RunTraceResponse>, ApiError> {
    let run_id =
        RunId::parse(id).map_err(|e| ApiError::bad_request(format!("invalid run id: {e}")))?;
    let query = TraceQuery {
        after: q.after,
        limit: q.limit,
        latest: q.latest,
        kinds: q
            .kind
            .as_deref()
            .map(|s| {
                s.split(',')
                    .map(str::trim)
                    .filter(|k| !k.is_empty())
                    .map(str::to_string)
                    .collect()
            })
            .unwrap_or_default(),
        step_ref: q.step,
        attempt: q.attempt,
    };
    let events = state
        .run_trace_store
        .list(&run_id, &query)
        .await
        .map_err(|e| ApiError::engine(format!("trace list: {e}")))?;
    Ok(Json(RunTraceResponse {
        run_id: run_id.to_string(),
        events,
    }))
}

/// `POST /v1/runs/:id/cancel` — record a cancel request on the Run's
/// trace stream (`core.cancel_requested`) and mark the Run's status
/// to `Cancelled` for still-in-flight rows. Idempotent: repeat calls
/// re-append the trace event but keep the status setter idempotent
/// on the store side. In-flight abort itself remains a v3 carry — the
/// current effect is observational + status marker, matching the
/// `swarm_cancel` MCP tool's local semantics but reflected onto the
/// server-side `RunTraceStore` so `GET /v1/runs/:id/trace` reflects
/// it too.
pub async fn run_cancel(
    State(state): State<AppState>,
    Path(id): Path<String>,
) -> Result<axum::http::StatusCode, ApiError> {
    let run_id =
        RunId::parse(id).map_err(|e| ApiError::bad_request(format!("invalid run id: {e}")))?;
    // Load the row to prove it exists; a missing row is a 404 (aligned
    // with `run_delete` — cancel needs an addressable Run).
    let record = state
        .run_store
        .get(&run_id)
        .await
        .map_err(map_run_store_err)?;
    // Best-effort trace append (never gates the response) — the
    // authoritative record is the run_store status update below.
    TraceHandle::new(run_id.clone(), state.run_trace_store.clone())
        .append(trace_kind::CANCEL_REQUESTED, None, None, json!({}))
        .await;
    // Flip the Run's status to Cancelled when it's still non-terminal.
    // Terminal Runs (Done / Failed / Interrupted / already Cancelled)
    // keep their outcome — cancel arriving after finalize is an
    // observation, not a rewrite.
    if matches!(record.status, RunStatus::Pending | RunStatus::Running) {
        if let Err(e) = state
            .run_store
            .update_status(&run_id, RunStatus::Cancelled)
            .await
        {
            tracing::warn!(%run_id, error = %e, "run_cancel: update_status(Cancelled) failed");
        }
    }
    Ok(axum::http::StatusCode::NO_CONTENT)
}

/// `DELETE /v1/runs/:id` — retention prune: deletes the Run row and its
/// trace stream together (`404` when the Run row is absent; the trace
/// stream is pruned best-effort either way). Replay rows are untouched —
/// `ReplayStore` has its own truncation semantics owned by the
/// rerun-from path.
///
/// Trust tier: same auth-free open-router posture as every other route
/// in this module (`POST /v1/tasks` included) — the server is a
/// local-first, loopback-bound single-operator daemon. Flagged in
/// holistic review as the surface's first unauthenticated destructive
/// verb; acceptable under the loopback bind, revisit if the bind ever
/// goes non-local.
pub async fn run_delete(
    State(state): State<AppState>,
    Path(id): Path<String>,
) -> Result<axum::http::StatusCode, ApiError> {
    let run_id =
        RunId::parse(id).map_err(|e| ApiError::bad_request(format!("invalid run id: {e}")))?;
    state
        .run_store
        .delete(&run_id)
        .await
        .map_err(map_run_store_err)?;
    if let Err(e) = state.run_trace_store.delete_run(&run_id).await {
        tracing::warn!(%run_id, error = %e, "run_delete: trace delete_run failed (run row already deleted)");
    }
    Ok(axum::http::StatusCode::NO_CONTENT)
}

/// Whether a Run-scoped binding has only a declaration or also carries a
/// provider attestation accepted by Core.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RunBindingStatus {
    /// No provider attestation was recorded; `requested` is still the exact
    /// declaration pinned at launch time.
    DeclarationOnly,
    /// Core accepted and pinned the provider's effective capability report.
    Attested,
}

/// Mechanical requested/effective comparison for one immutable binding.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
pub struct RunBindingDifference {
    /// Whether the requested model string and resolved model string differ.
    pub model_changed: bool,
    /// Requested tools absent from the effective grant. Accepted attestations
    /// normally leave this empty because launch validation is fail-closed.
    pub missing_requested_tools: Vec<String>,
    /// Effective tools not present in the minimum requested grant.
    pub additional_effective_tools: Vec<String>,
    /// Whether the requested and effective launch variants differ.
    pub launch_variant_changed: bool,
}

/// Explain view for one agent, derived exclusively from the persisted Run
/// snapshot rather than from the current Blueprint registry.
#[derive(Debug, Clone, PartialEq, Serialize, schemars::JsonSchema)]
pub struct RunBindingExplainEntry {
    /// Logical agent name.
    pub agent: String,
    /// Declaration tier that selected the Runner.
    pub runner_source: mlua_swarm::blueprint::RunnerResolutionSource,
    /// Provider-attestation state.
    pub status: RunBindingStatus,
    /// Exact platform-neutral request reconstructed from the pinned snapshot.
    pub requested: Option<BindRequest>,
    /// Core-validated provider report, when one was accepted at launch.
    pub effective: Option<BindingAttestation>,
    /// Mechanical difference between `requested` and `effective`; absent for
    /// declaration-only bindings.
    pub difference: Option<RunBindingDifference>,
    /// Final immutable replay identity, including the attestation when present.
    pub binding_digest: mlua_swarm::blueprint::BindingDigest,
}

/// Response body for `GET /v1/runs/:id/bindings`.
#[derive(Debug, Clone, PartialEq, Serialize, schemars::JsonSchema)]
pub struct RunBindingsExplainResponse {
    /// Run whose launch snapshot was inspected.
    #[schemars(with = "String")]
    pub run_id: RunId,
    /// Owning Task recorded on that Run.
    #[schemars(with = "String")]
    pub task_id: TaskId,
    /// Provenance of the inspected `bound_agents` snapshot. `launch` means the
    /// bindings were pinned at the Run's initial launch; `resume_backfill`
    /// means they were re-derived from the current Blueprint when a
    /// pre-binding-snapshot Run was resumed/reran — so they carry no
    /// launch-time pin guarantee. A snapshot that carries `bound_agents` but
    /// no origin marker reports `resume_backfill` (the safe side — see
    /// [`SnapshotOrigin::from_snapshot`]).
    pub snapshot_origin: SnapshotOrigin,
    /// Every agent snapshot in Blueprint declaration order.
    pub bindings: Vec<RunBindingExplainEntry>,
}

fn requested_binding(bound: &BoundAgent) -> Option<BindRequest> {
    mlua_swarm::binding_request_for_snapshot(bound)
}

fn binding_difference(
    requested: &BindRequest,
    effective: &BindingAttestation,
) -> RunBindingDifference {
    let missing_requested_tools = requested
        .requested_tools
        .iter()
        .filter(|tool| !effective.effective_tools.contains(tool))
        .cloned()
        .collect();
    let additional_effective_tools = effective
        .effective_tools
        .iter()
        .filter(|tool| !requested.requested_tools.contains(tool))
        .cloned()
        .collect();
    RunBindingDifference {
        model_changed: requested.requested_model != effective.resolved_model,
        missing_requested_tools,
        additional_effective_tools,
        launch_variant_changed: requested.launch_variant != effective.launch_variant,
    }
}

fn validated_bound_agents_from_snapshot(
    run_id: &RunId,
    snapshot: &Value,
) -> Result<Option<Vec<BoundAgent>>, ApiError> {
    let Some(bound_value) = snapshot.get("bound_agents") else {
        return Ok(None);
    };
    let bound_agents: Vec<BoundAgent> =
        serde_json::from_value(bound_value.clone()).map_err(|e| {
            ApiError::unprocessable(format!(
                "run {run_id} contains an invalid binding snapshot: {e}"
            ))
        })?;
    validate_bound_agent_snapshots(&bound_agents).map_err(|error| {
        ApiError::unprocessable(format!(
            "run {run_id} contains an inconsistent binding snapshot: {error}"
        ))
    })?;
    Ok(Some(bound_agents))
}

/// `GET /v1/runs/:id/bindings`. Explains the exact immutable agent bindings
/// used by this Run. The handler never reads or resolves the current Blueprint;
/// old Runs without a binding snapshot return `422` instead of guessed state.
pub async fn run_bindings_explain(
    State(state): State<AppState>,
    Path(id): Path<String>,
) -> Result<Json<RunBindingsExplainResponse>, ApiError> {
    let run_id =
        RunId::parse(id).map_err(|e| ApiError::bad_request(format!("invalid run id: {e}")))?;
    let run = state
        .run_store
        .get(&run_id)
        .await
        .map_err(map_run_store_err)?;
    let input_json = run.input_json.as_deref().ok_or_else(|| {
        ApiError::unprocessable(format!(
            "run {run_id} has no launch snapshot; binding explain is unavailable"
        ))
    })?;
    let snapshot: Value = serde_json::from_str(input_json).map_err(|e| {
        ApiError::unprocessable(format!(
            "run {run_id} launch snapshot is invalid JSON; binding explain is unavailable: {e}"
        ))
    })?;
    let bound_agents = validated_bound_agents_from_snapshot(&run_id, &snapshot)?.ok_or_else(|| {
        ApiError::unprocessable(format!(
            "run {run_id} predates immutable binding snapshots; current Blueprint state was not consulted"
        ))
    })?;

    let bindings = bound_agents
        .into_iter()
        .map(|bound| {
            let requested = requested_binding(&bound);
            let effective = bound.attestation.clone();
            let difference = requested
                .as_ref()
                .zip(effective.as_ref())
                .map(|(request, attestation)| binding_difference(request, attestation));
            RunBindingExplainEntry {
                agent: bound.agent.name,
                runner_source: bound.runner_source,
                status: if effective.is_some() {
                    RunBindingStatus::Attested
                } else {
                    RunBindingStatus::DeclarationOnly
                },
                requested,
                effective,
                difference,
                binding_digest: bound.binding_digest,
            }
        })
        .collect();

    Ok(Json(RunBindingsExplainResponse {
        run_id: run.id,
        task_id: run.task_id,
        snapshot_origin: SnapshotOrigin::from_snapshot(&snapshot),
        bindings,
    }))
}

/// `pub(crate)` so `crate::projection`'s `GET /v1/tasks/:id/ctx` handler can
/// reuse this module's existing-Task-existence-check error mapping (same
/// 404-vs-500 split `task_get` already applies).
pub(crate) fn map_task_store_err(e: TaskStoreError) -> ApiError {
    match e {
        TaskStoreError::NotFound(id) => ApiError::not_found(format!("task not found: {id}")),
        other => ApiError::engine(other),
    }
}

fn map_run_store_err(e: RunStoreError) -> ApiError {
    match e {
        RunStoreError::NotFound(id) => ApiError::not_found(format!("run not found: {id}")),
        other => ApiError::engine(other),
    }
}

// ──────────────────────────────────────────────────────────────────────────
// UT
// ──────────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use mlua_swarm::application::BlueprintRef;
    use mlua_swarm::blueprint::{
        current_schema_version, AgentDef, AgentKind, Blueprint, BlueprintMetadata, CompilerHints,
        CompilerStrategy, Runner,
    };
    use mlua_swarm::core::config::EngineCfg;
    use mlua_swarm::core::engine::Engine;
    use mlua_swarm::store::output::InMemoryOutputStore;
    use mlua_swarm::store::run::InMemoryRunStore;
    use mlua_swarm::store::task::InMemoryTaskStore;
    use std::collections::HashMap;
    use std::sync::Arc;
    use tokio::sync::Mutex;

    /// A single-step flow.ir Blueprint that always succeeds: `Step { ref:
    /// "identity", in: lit("hello"), out: $.out }` against the baseline
    /// `RustFn` identity worker (same shape as `seed_blueprint` in
    /// `mlua-swarm-cli`'s `serve.rs`, self-contained here rather than
    /// importing a binary crate).
    fn identity_blueprint() -> Blueprint {
        Blueprint {
            schema_version: current_schema_version(),
            id: "tasks-test-bp".into(),
            flow: serde_json::from_value(serde_json::json!({
                "kind": "step",
                "ref": mlua_swarm::worker::baseline::AG_IDENTITY,
                "in": {"op": "lit", "value": "hello"},
                "out": {"op": "path", "at": "$.out"},
            }))
            .expect("flow parse"),
            agents: vec![AgentDef {
                name: mlua_swarm::worker::baseline::AG_IDENTITY.into(),
                kind: AgentKind::RustFn,
                spec: serde_json::json!({"fn_id": mlua_swarm::worker::baseline::AG_IDENTITY}),
                profile: None,
                meta: None,
                runner: None,
                runner_ref: None,
                verdict: 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(),
        }
    }

    /// Minimal `AppState` for handler-level tests — mirrors the construction
    /// `build_router_full` does internally, but skips the `Router` wrapper so
    /// tests can call handler functions directly (this crate's established
    /// unit-test convention; see e.g. `operator_ws::login`'s tests).
    fn test_state() -> AppState {
        let engine = Engine::new_with_layers(EngineCfg::default(), crate::default_layer_registry());
        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: Arc::new(InMemoryOutputStore::new()),
            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: Arc::new(InMemoryRunStore::new()),
            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,
        }
    }

    fn post_tasks_req(goal: &str) -> crate::TaskLaunchRequest {
        crate::TaskLaunchRequest {
            blueprint: BlueprintRef::Inline {
                value: Box::new(identity_blueprint()),
            },
            init_ctx: serde_json::json!({"in": "hello"}),
            project_root: None,
            work_dir: None,
            task_metadata: None,
            ttl_secs: None,
            operator: None,
            operator_sid: None,
            timeout_secs: None,
            goal: Some(goal.to_string()),
            detach: false,
            check_policy: None,
        }
    }

    #[test]
    fn task_id_serializes_as_bare_string() {
        // Sanity check for the newtype-struct transparency relied on
        // throughout this module's response shapes (`TaskId` / `RunId`
        // serialize as plain JSON strings, not `{"0": "..."}`).
        let v = serde_json::to_value(TaskId::parse("T-abc").unwrap()).expect("serialize");
        assert_eq!(v, serde_json::json!("T-abc"));
    }

    #[tokio::test]
    async fn post_then_get_drill_down() {
        let state = test_state();

        let posted = crate::tasks_start(State(state.clone()), Json(post_tasks_req("smoke goal")))
            .await
            .expect("tasks_start")
            .0;
        let task_id = posted.task_id.clone();
        let run_id = posted.run_id.clone();

        // GET /v1/tasks lists it.
        let list = tasks_list(State(state.clone()), Query(TasksListQuery { limit: None }))
            .await
            .expect("tasks_list")
            .0;
        assert!(
            list.iter().any(|t| t.id == task_id),
            "task {task_id} missing from list of {} tasks",
            list.len()
        );

        // GET /v1/tasks/:id drills down to the Task + its Run.
        let detail = task_get(State(state.clone()), Path(task_id.to_string()))
            .await
            .expect("task_get")
            .0;
        assert_eq!(detail.task.id, task_id);
        assert_eq!(detail.task.goal, "smoke goal");
        assert_eq!(detail.task.status, TaskRecordStatus::Done);
        assert_eq!(detail.runs.len(), 1);
        assert_eq!(detail.runs[0].id, run_id);
        assert_eq!(detail.runs[0].status, RunStatus::Done);

        // GET /v1/runs/:id returns the same Run directly.
        let run = run_get(State(state.clone()), Path(run_id.to_string()))
            .await
            .expect("run_get")
            .0;
        assert_eq!(run.id, run_id);
        assert_eq!(run.task_id, task_id);
        assert_eq!(run.result_ref, Some(posted.final_ctx));

        // issue #13 run_id propagation: `POST /v1/tasks` (`run_flow_form`)
        // wires a `RunContext` into `TaskApplication::handle_with_run`, so
        // the single dispatched step must be traced into `step_entries`.
        assert_eq!(
            run.step_entries.len(),
            1,
            "expected one step_entry for the 1-step identity Blueprint, got {:?}",
            run.step_entries
        );
        assert_eq!(
            run.step_entries[0].step_ref,
            Some(mlua_swarm::worker::baseline::AG_IDENTITY.to_string())
        );
        assert_eq!(run.step_entries[0].status, Some("passed".to_string()));
    }

    // ──────────────────────────────────────────────────────────────────
    // GH #33 — sync-hang guards (readiness precheck / timeout ceiling)
    // ──────────────────────────────────────────────────────────────────

    /// Same 1-step identity flow as [`identity_blueprint`], but opts into
    /// the Blueprint-global Operator delegate axis
    /// (`spawner_hints.layers = ["operator_delegate"]`) so a registered
    /// `Operator` backend can be exercised end-to-end through the real
    /// `tasks_start` dispatch path (`OperatorDelegateMiddleware` bypasses
    /// `inner.spawn` and calls `operator.execute` instead — see
    /// `mlua_swarm::middleware::OperatorDelegateMiddleware` doc).
    fn identity_blueprint_with_operator_delegate() -> Blueprint {
        Blueprint {
            spawner_hints: mlua_swarm::SpawnerHints {
                layers: vec!["operator_delegate".to_string()],
            },
            ..identity_blueprint()
        }
    }

    /// `Operator` stub whose `execute` never resolves — the GH #33 Guard 2
    /// fixture ("a registered-but-never-acking operator").
    struct StallingOperator;

    #[async_trait::async_trait]
    impl mlua_swarm::Operator for StallingOperator {
        async fn execute(
            &self,
            _ctx: &mlua_swarm::Ctx,
            _system: Option<String>,
            _prompt: Value,
            _worker: Option<mlua_swarm::WorkerBinding>,
            _worker_token: mlua_swarm::CapToken,
        ) -> Result<mlua_swarm::WorkerResult, mlua_swarm::WorkerError> {
            std::future::pending::<()>().await;
            unreachable!("StallingOperator.execute must never resolve")
        }
    }

    /// A launch request that references an operator backend by id (via
    /// `operator.operator_backend_id`, the coarse Guard 1 signal) against
    /// [`identity_blueprint_with_operator_delegate`].
    fn operator_launch_req(
        backend_id: &str,
        timeout_secs: Option<u64>,
    ) -> crate::TaskLaunchRequest {
        crate::TaskLaunchRequest {
            blueprint: BlueprintRef::Inline {
                value: Box::new(identity_blueprint_with_operator_delegate()),
            },
            init_ctx: serde_json::json!({"in": "hello"}),
            project_root: None,
            work_dir: None,
            task_metadata: None,
            ttl_secs: None,
            operator: Some(crate::OperatorReq {
                operator_backend_id: Some(backend_id.to_string()),
                ..Default::default()
            }),
            operator_sid: None,
            timeout_secs,
            goal: Some("operator delegate test goal".to_string()),
            detach: false,
            check_policy: None,
        }
    }

    /// Guard 1: an operator-requiring launch with zero attached operators
    /// must fail immediately with a structured `503`, not hang waiting on
    /// a session nothing can serve.
    #[tokio::test]
    async fn sync_launch_zero_operators_fails_fast() {
        let state = test_state();
        // No `state.engine.register_operator(...)` call — zero operators
        // attached, matching `list_operator_ids()` being empty.
        let req = operator_launch_req("nonexistent-op", None);

        let started = std::time::Instant::now();
        let result = crate::tasks_start(State(state), Json(req)).await;
        let elapsed = started.elapsed();

        let err = match result {
            Err(e) => e,
            Ok(_) => panic!("zero attached operators must fail the operator-delegate launch"),
        };
        assert_eq!(err.status, StatusCode::SERVICE_UNAVAILABLE);
        assert!(
            err.message.contains("no operator attached"),
            "error message must mention the missing operator: {}",
            err.message
        );
        assert!(
            elapsed < Duration::from_secs(1),
            "guard 1 must fail fast (no dispatch, no timeout wait): took {elapsed:?}"
        );
    }

    /// Guard 2: a launch that resolves to a registered-but-stalled
    /// operator session must return a structured `504` within the
    /// requested `timeout_secs` ceiling, not hang the request forever.
    #[tokio::test]
    async fn sync_launch_stalled_times_out() {
        let state = test_state();
        state
            .engine
            .register_operator("stall-op", Arc::new(StallingOperator))
            .await;
        let req = operator_launch_req("stall-op", Some(1));

        let started = std::time::Instant::now();
        // Outer safety-net timeout: if guard 2 itself regressed into an
        // infinite hang, fail this test loudly instead of stalling `cargo
        // test` indefinitely.
        let result = tokio::time::timeout(
            Duration::from_secs(5),
            crate::tasks_start(State(state), Json(req)),
        )
        .await
        .expect("tasks_start must resolve well within 5s when guard 2's ceiling is 1s");
        let elapsed = started.elapsed();

        let err = match result {
            Err(e) => e,
            Ok(_) => panic!("a stalled operator session must time out, not succeed"),
        };
        assert_eq!(err.status, StatusCode::GATEWAY_TIMEOUT);
        assert!(
            err.message.contains('1'),
            "error message must mention the configured 1s ceiling: {}",
            err.message
        );
        assert!(
            elapsed < Duration::from_secs(3),
            "guard 2 must fire close to the requested 1s ceiling: took {elapsed:?}"
        );
    }

    /// Invariant 2: a launch that never references an operator backend
    /// must never be rejected by guard 1 — the simplest existing passing
    /// fixture (`post_tasks_req`) still succeeds unaffected.
    #[tokio::test]
    async fn sync_launch_without_operator_path_unaffected() {
        let state = test_state();
        let result = crate::tasks_start(
            State(state),
            Json(post_tasks_req("non-operator launch goal")),
        )
        .await;
        if let Err(e) = &result {
            panic!(
                "non-operator launch must succeed unaffected by guard 1: {}",
                e.message
            );
        }
    }

    /// Guard 2 ceiling resolution: `timeout_secs: Some(0)` is invalid
    /// (design doc: "0 = reject with 400 or treat as invalid — pick one
    /// and test it") — rejected fast, before any Task/Run side effects.
    #[tokio::test]
    async fn sync_launch_zero_timeout_secs_rejected() {
        let state = test_state();
        let mut req = post_tasks_req("zero timeout goal");
        req.timeout_secs = Some(0);

        let result = crate::tasks_start(State(state), Json(req)).await;
        let err = match result {
            Err(e) => e,
            Ok(_) => panic!("timeout_secs: Some(0) must be rejected, not treated as a no-op"),
        };
        assert_eq!(err.status, StatusCode::BAD_REQUEST);
        assert!(
            err.message.contains("timeout_secs"),
            "error message must reference timeout_secs: {}",
            err.message
        );
    }

    // ──────────────────────────────────────────────────────────────────
    // GH #37 — detached launch / rekick (driver decoupled from request)
    // ──────────────────────────────────────────────────────────────────

    /// Polls the run store until the given Run reaches a terminal status,
    /// panicking after ~5s — the detached paths complete in the
    /// background, so tests must wait on the store rather than the
    /// response.
    async fn wait_for_terminal_run(state: &AppState, run_id: &RunId) -> RunRecord {
        for _ in 0..50 {
            let rec = state.run_store.get(run_id).await.expect("run get");
            if !matches!(rec.status, RunStatus::Pending | RunStatus::Running) {
                return rec;
            }
            tokio::time::sleep(Duration::from_millis(100)).await;
        }
        panic!("run {run_id} did not reach a terminal status within ~5s");
    }

    /// GH #37: `detach: true` returns `202 Accepted` immediately with
    /// `status: "running"` and a null `final_ctx`; the eval completes in
    /// the background and the Run/Task reach `Done` with the result and
    /// step trace persisted — the same terminal state the sync path
    /// produces.
    #[tokio::test]
    async fn detached_launch_returns_202_and_completes_in_background() {
        let state = test_state();
        let mut req = post_tasks_req("detached goal");
        req.detach = true;

        let reply = crate::tasks_start(State(state.clone()), Json(req))
            .await
            .expect("tasks_start (detached)");
        assert_eq!(reply.1, StatusCode::ACCEPTED);
        let posted = reply.0;
        assert_eq!(posted.status, RunStatus::Running);
        assert_eq!(
            posted.final_ctx,
            serde_json::Value::Null,
            "a detached launch has no final_ctx at response time"
        );

        let rec = wait_for_terminal_run(&state, &posted.run_id).await;
        assert_eq!(rec.status, RunStatus::Done);
        assert!(
            rec.result_ref.is_some(),
            "finalize_run must persist the background eval's final_ctx"
        );
        assert_eq!(
            rec.step_entries.len(),
            1,
            "the background eval must trace its step_entries like the sync path: {:?}",
            rec.step_entries
        );
        let task = state
            .task_store
            .get(&posted.task_id)
            .await
            .expect("task get");
        assert_eq!(task.status, TaskRecordStatus::Done);
    }

    /// GH #37: `detach: true` + `timeout_secs` is contradictory (the sync
    /// ceiling has no meaning for a detached run) — rejected with `400`
    /// before any Task/Run side effects.
    #[tokio::test]
    async fn detached_launch_with_timeout_secs_rejected() {
        let state = test_state();
        let mut req = post_tasks_req("detached + ceiling goal");
        req.detach = true;
        req.timeout_secs = Some(60);

        let err = match crate::tasks_start(State(state.clone()), Json(req)).await {
            Err(e) => e,
            Ok(_) => panic!("detach + timeout_secs must be rejected"),
        };
        assert_eq!(err.status, StatusCode::BAD_REQUEST);
        assert!(
            err.message.contains("detach"),
            "error message must explain the detach/timeout_secs conflict: {}",
            err.message
        );
        let tasks = state.task_store.list().await.expect("task list");
        assert!(
            tasks.is_empty(),
            "the 400 must fire before any TaskRecord is minted"
        );
    }

    /// GH #37: a detached rekick returns `202 Accepted` with `status:
    /// "running"` immediately and completes in the background, adding a
    /// second `Done` Run to the same Task.
    #[tokio::test]
    async fn rekick_detached_returns_202_and_completes_in_background() {
        let state = test_state();
        let posted = crate::tasks_start(
            State(state.clone()),
            Json(post_tasks_req("detached rekick goal")),
        )
        .await
        .expect("tasks_start")
        .0;

        let (status, rekicked) = task_rekick(
            State(state.clone()),
            Path(posted.task_id.to_string()),
            Some(Json(RunKickRequest {
                init_ctx_override: None,
                task_input_override: None,
                timeout_secs: None,
                detach: true,
                operator_sid: None,
            })),
        )
        .await
        .expect("task_rekick (detached)");
        assert_eq!(status, StatusCode::ACCEPTED);
        assert_eq!(rekicked.0.status, RunStatus::Running);
        assert_ne!(rekicked.0.run_id, posted.run_id);

        let rec = wait_for_terminal_run(&state, &rekicked.0.run_id).await;
        assert_eq!(rec.status, RunStatus::Done);
        assert!(
            rec.result_ref.is_some(),
            "finalize_run must persist the background rekick's final_ctx"
        );
    }

    /// GH #37: `detach: true` + `timeout_secs` on the rekick path is the
    /// same contradiction as on the launch path — `400`, no new Run
    /// minted.
    #[tokio::test]
    async fn rekick_detached_with_timeout_secs_rejected() {
        let state = test_state();
        let posted = crate::tasks_start(
            State(state.clone()),
            Json(post_tasks_req("detached rekick ceiling goal")),
        )
        .await
        .expect("tasks_start")
        .0;

        let err = match task_rekick(
            State(state.clone()),
            Path(posted.task_id.to_string()),
            Some(Json(RunKickRequest {
                init_ctx_override: None,
                task_input_override: None,
                timeout_secs: Some(60),
                detach: true,
                operator_sid: None,
            })),
        )
        .await
        {
            Err(e) => e,
            Ok(_) => panic!("detach + timeout_secs must be rejected on rekick"),
        };
        assert_eq!(err.status, StatusCode::BAD_REQUEST);
        assert!(
            err.message.contains("detach"),
            "error message must explain the detach/timeout_secs conflict: {}",
            err.message
        );
        let runs = state
            .run_store
            .list_by_task(&posted.task_id)
            .await
            .expect("runs list");
        assert_eq!(
            runs.len(),
            1,
            "the 400 must fire before a second Run is minted"
        );
    }

    // ──────────────────────────────────────────────────────────────────
    // Run driver panic guard (`catch_run_panic`)
    // ──────────────────────────────────────────────────────────────────

    /// Seeds a `Running` Task + Run pair directly in the stores — the panic
    /// guard operates on an already-dispatched Run, so these tests do not
    /// need a real dispatch to reach it.
    async fn seed_running_run(state: &AppState) -> (TaskId, RunId) {
        let now = now_secs();
        let task_id = TaskId::new();
        let run_id = RunId::new();
        state
            .task_store
            .create(TaskRecord {
                id: task_id.clone(),
                goal: "panic guard goal".into(),
                blueprint_ref: json!({}),
                input_ctx: json!({}),
                task_input_spec: None,
                status: TaskRecordStatus::Running,
                created_at: now,
                updated_at: now,
            })
            .await
            .expect("task create");
        state
            .run_store
            .create(RunRecord {
                id: run_id.clone(),
                task_id: task_id.clone(),
                status: RunStatus::Running,
                step_entries: Vec::new(),
                degradations: Vec::new(),
                operator_sid: None,
                result_ref: None,
                input_json: None,
                created_at: now,
                updated_at: now,
            })
            .await
            .expect("run create");
        (task_id, run_id)
    }

    async fn run_finished_events(state: &AppState, run_id: &RunId) -> Vec<TraceEvent> {
        state
            .run_trace_store
            .list(run_id, &TraceQuery::default())
            .await
            .expect("trace list")
            .into_iter()
            .filter(|e| e.kind == trace_kind::RUN_FINISHED)
            .collect()
    }

    /// A panicking driver terminates its Run instead of stranding it: the
    /// Run goes `Interrupted` (resumable) with a structured reason naming
    /// the site and carrying the panic payload, the Task follows, and the
    /// trace stream gets exactly one terminal marker.
    #[tokio::test]
    async fn panicking_driver_marks_run_interrupted() {
        let state = test_state();
        let (task_id, run_id) = seed_running_run(&state).await;

        let outcome: Result<(), String> =
            catch_run_panic(&state, &task_id, &run_id, "test.detach", async {
                panic!("boom");
            })
            .await;
        let message = outcome.expect_err("a panicking driver must report the panic to its caller");
        assert!(
            message.contains("boom"),
            "the panic payload must survive as the caller-visible message: {message}"
        );

        let rec = state.run_store.get(&run_id).await.expect("run get");
        assert_eq!(
            rec.status,
            RunStatus::Interrupted,
            "a panicked Run must be resumable, not left Running or marked Failed"
        );
        let reason = rec
            .result_ref
            .as_ref()
            .and_then(|v| v.get("error"))
            .and_then(Value::as_str)
            .expect("a structured {\"error\": ...} envelope");
        assert!(
            reason.contains("boom") && reason.contains("test.detach"),
            "the reason must name both the panic payload and the site: {reason}"
        );

        let task = state.task_store.get(&task_id).await.expect("task get");
        assert_eq!(task.status, TaskRecordStatus::Interrupted);

        let finished = run_finished_events(&state, &run_id).await;
        assert_eq!(finished.len(), 1, "expected one terminal trace marker");
        assert_eq!(
            finished[0].payload.get("status").and_then(Value::as_str),
            Some("interrupted")
        );
        assert_eq!(
            finished[0].payload.get("reason").and_then(Value::as_str),
            Some("driver panic")
        );
    }

    /// The guard is compare-and-set: a panic raised after the Run already
    /// finalized (say inside the trace tail that follows `finalize_run`)
    /// must not rewrite the terminal verdict or its result.
    #[tokio::test]
    async fn panic_guard_does_not_clobber_a_finalized_run() {
        let state = test_state();
        let (task_id, run_id) = seed_running_run(&state).await;
        state
            .run_store
            .set_result(&run_id, json!({"kept": true}))
            .await
            .expect("set_result");
        state
            .run_store
            .update_status(&run_id, RunStatus::Done)
            .await
            .expect("update_status");

        let outcome: Result<(), String> =
            catch_run_panic(&state, &task_id, &run_id, "test.detach", async {
                panic!("late boom");
            })
            .await;
        assert!(
            outcome.is_err(),
            "the panic is still reported to the caller"
        );

        let rec = state.run_store.get(&run_id).await.expect("run get");
        assert_eq!(rec.status, RunStatus::Done, "the CAS must have refused");
        assert_eq!(rec.result_ref, Some(json!({"kept": true})));
        let finished = run_finished_events(&state, &run_id).await;
        assert!(
            finished.is_empty(),
            "a refused CAS must not append a second terminal marker: {finished:?}"
        );
    }

    /// The synchronous launch/rekick shape: the driver is wrapped
    /// `timeout(..)`-and-all, so a panic surfaces as an `Err` the handler
    /// maps to a `500` (`ApiError::engine`) — instead of unwinding into the
    /// connection task and dropping the response — while the Run is left
    /// `Interrupted` and therefore resumable.
    #[tokio::test]
    async fn sync_panic_returns_err_and_interrupts_run() {
        let state = test_state();
        let (task_id, run_id) = seed_running_run(&state).await;

        let timed = catch_run_panic(
            &state,
            &task_id,
            &run_id,
            "launch.sync",
            tokio::time::timeout(Duration::from_secs(30), async {
                panic!("sync boom");
            }),
        )
        .await;
        let message = timed.expect_err("the sync path must observe the panic as an Err");
        assert!(message.contains("sync boom"), "payload lost: {message}");

        let err = ApiError::engine(format!("run driver panicked: {message}"));
        assert_eq!(err.status, StatusCode::INTERNAL_SERVER_ERROR);

        let rec = state.run_store.get(&run_id).await.expect("run get");
        assert_eq!(rec.status, RunStatus::Interrupted);
    }

    #[tokio::test]
    async fn rekick_adds_a_second_run_to_the_same_task() {
        let state = test_state();
        let posted = crate::tasks_start(State(state.clone()), Json(post_tasks_req("rekick goal")))
            .await
            .expect("tasks_start")
            .0;
        let task_id = posted.task_id.clone();
        let first_run_id = posted.run_id.clone();

        let (status, rekicked) = task_rekick(State(state.clone()), Path(task_id.to_string()), None)
            .await
            .expect("task_rekick");
        assert_eq!(status, StatusCode::CREATED);
        let second_run_id = rekicked.0.run_id.clone();
        assert_ne!(first_run_id, second_run_id);

        let detail = task_get(State(state.clone()), Path(task_id.to_string()))
            .await
            .expect("task_get")
            .0;
        assert_eq!(
            detail.runs.len(),
            2,
            "expected 2 runs, got {:?}",
            detail.runs
        );
        let ids: Vec<&RunId> = detail.runs.iter().map(|r| &r.id).collect();
        assert!(ids.contains(&&first_run_id));
        assert!(ids.contains(&&second_run_id));

        // issue #13 run_id propagation: each kick's own `EngineDispatcher`
        // (built fresh per `TaskApplication::handle_with_run` call) must
        // trace its own dispatched step into its own `RunRecord` —
        // independent `step_entries`, not shared/accumulated across kicks.
        let first_run = detail
            .runs
            .iter()
            .find(|r| r.id == first_run_id)
            .expect("first run present in detail.runs");
        let second_run = detail
            .runs
            .iter()
            .find(|r| r.id == second_run_id)
            .expect("second run present in detail.runs");
        assert_eq!(
            first_run.step_entries.len(),
            1,
            "first run step_entries: {:?}",
            first_run.step_entries
        );
        assert_eq!(
            second_run.step_entries.len(),
            1,
            "second run step_entries: {:?}",
            second_run.step_entries
        );
        assert_eq!(
            first_run.step_entries[0].step_ref,
            Some(mlua_swarm::worker::baseline::AG_IDENTITY.to_string())
        );
        assert_eq!(
            second_run.step_entries[0].step_ref,
            Some(mlua_swarm::worker::baseline::AG_IDENTITY.to_string())
        );
        assert_eq!(first_run.step_entries[0].status, Some("passed".to_string()));
        assert_eq!(
            second_run.step_entries[0].status,
            Some("passed".to_string())
        );
        assert_ne!(
            first_run.step_entries[0].step_id, second_run.step_entries[0].step_id,
            "each kick dispatches its own StepId — runs must not share step_entries"
        );
    }

    #[tokio::test]
    async fn rekick_unknown_task_returns_404() {
        let state = test_state();
        // `.expect_err()` needs the Ok variant to be `Debug`; `Json<T>`'s
        // `Debug` impl is not guaranteed for every `T` across axum versions,
        // so a plain match sidesteps that bound entirely.
        match task_rekick(State(state), Path("T-does-not-exist".to_string()), None).await {
            Ok(_) => panic!("expected 404 for an unknown task"),
            Err(e) => assert_eq!(e.status, StatusCode::NOT_FOUND),
        }
    }

    // ──────────────────────────────────────────────────────────────────
    // issue #19 ST4: `RunKickRequest` (optional body / 3-layer merge)
    // ──────────────────────────────────────────────────────────────────

    /// A single-step flow.ir Blueprint that echoes `$.greeting` into
    /// `$.out` — unlike [`identity_blueprint`] (a fixed `lit("hello")`
    /// input), this one reads its `Step.in` from `ctx`, so it observes
    /// whichever `init_ctx` layer actually won the merge.
    fn greeting_blueprint() -> Blueprint {
        Blueprint {
            schema_version: current_schema_version(),
            id: "tasks-test-greeting-bp".into(),
            flow: serde_json::from_value(serde_json::json!({
                "kind": "step",
                "ref": mlua_swarm::worker::baseline::AG_IDENTITY,
                "in": {"op": "path", "at": "$.greeting"},
                "out": {"op": "path", "at": "$.out"},
            }))
            .expect("flow parse"),
            agents: vec![AgentDef {
                name: mlua_swarm::worker::baseline::AG_IDENTITY.into(),
                kind: AgentKind::RustFn,
                spec: serde_json::json!({"fn_id": mlua_swarm::worker::baseline::AG_IDENTITY}),
                profile: None,
                meta: None,
                runner: None,
                runner_ref: None,
                verdict: 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(),
        }
    }

    fn post_greeting_task_req(
        greeting: &str,
        project_root: Option<&str>,
    ) -> crate::TaskLaunchRequest {
        crate::TaskLaunchRequest {
            blueprint: BlueprintRef::Inline {
                value: Box::new(greeting_blueprint()),
            },
            init_ctx: serde_json::json!({ "greeting": greeting }),
            project_root: project_root.map(str::to_string),
            work_dir: None,
            task_metadata: None,
            ttl_secs: None,
            operator: None,
            operator_sid: None,
            timeout_secs: None,
            goal: Some("st4 rekick goal".to_string()),
            detach: false,
            check_policy: None,
        }
    }

    #[tokio::test]
    async fn rekick_no_body_preserves_stored_task_input_ctx_byte_for_byte() {
        // must_not_simplify #3: a body-less rekick must behave exactly
        // like pre-#19 — the Task's own `input_ctx` alone seeds the kick.
        let state = test_state();
        let posted = crate::tasks_start(
            State(state.clone()),
            Json(post_greeting_task_req("from-task", None)),
        )
        .await
        .expect("tasks_start")
        .0;
        assert_eq!(posted.final_ctx["out"]["echoed"], "from-task");

        let (status, rekicked) =
            task_rekick(State(state.clone()), Path(posted.task_id.to_string()), None)
                .await
                .expect("task_rekick");
        assert_eq!(status, StatusCode::CREATED);

        let run = run_get(State(state.clone()), Path(rekicked.0.run_id.to_string()))
            .await
            .expect("run_get")
            .0;
        assert_eq!(
            run.result_ref.expect("result_ref present")["out"]["echoed"],
            "from-task"
        );
    }

    #[tokio::test]
    async fn rekick_with_init_ctx_override_wins_over_stored_task_input_ctx() {
        let state = test_state();
        let posted = crate::tasks_start(
            State(state.clone()),
            Json(post_greeting_task_req("from-task", None)),
        )
        .await
        .expect("tasks_start")
        .0;
        assert_eq!(posted.final_ctx["out"]["echoed"], "from-task");

        let (status, rekicked) = task_rekick(
            State(state.clone()),
            Path(posted.task_id.to_string()),
            Some(Json(RunKickRequest {
                init_ctx_override: Some(serde_json::json!({ "greeting": "from-run" })),
                task_input_override: None,
                timeout_secs: None,
                detach: false,
                operator_sid: None,
            })),
        )
        .await
        .expect("task_rekick");
        assert_eq!(status, StatusCode::CREATED);

        let run = run_get(State(state.clone()), Path(rekicked.0.run_id.to_string()))
            .await
            .expect("run_get")
            .0;
        assert_eq!(
            run.result_ref.expect("result_ref present")["out"]["echoed"],
            "from-run",
            "Run's init_ctx_override must win over the stored Task input_ctx"
        );
    }

    #[tokio::test]
    async fn rekick_with_stored_task_input_spec_dispatches_and_leaves_it_unmutated() {
        // Done Criteria: "Task record が task-level canonical fields を
        // 保持している時の rekick test". A Task created with
        // `project_root` set gets a `task_input_spec` snapshot; a
        // body-less rekick must both dispatch successfully (the stored
        // spec decodes and resolves without erroring) and leave
        // `TaskRecord.task_input_spec` untouched (must_not_simplify #4 —
        // a rekick never mutates the stored Task-level snapshot).
        let state = test_state();
        let posted = crate::tasks_start(
            State(state.clone()),
            Json(post_greeting_task_req("from-task", Some("/repo"))),
        )
        .await
        .expect("tasks_start")
        .0;

        let before = state
            .task_store
            .get(&posted.task_id)
            .await
            .expect("task fetch");
        let before_spec: Option<TaskInputSpec> = before
            .task_input_spec
            .as_ref()
            .map(|v| serde_json::from_value(v.clone()).expect("decode task_input_spec"));
        assert_eq!(
            before_spec,
            Some(TaskInputSpec {
                project_root: Some("/repo".to_string()),
                work_dir: None,
                task_metadata: None,
            })
        );

        let (status, _rekicked) =
            task_rekick(State(state.clone()), Path(posted.task_id.to_string()), None)
                .await
                .expect("task_rekick");
        assert_eq!(status, StatusCode::CREATED);

        let after = state
            .task_store
            .get(&posted.task_id)
            .await
            .expect("task fetch");
        assert_eq!(
            after.task_input_spec, before.task_input_spec,
            "rekick must not mutate the stored Task-level task_input_spec snapshot"
        );
    }

    #[tokio::test]
    async fn rekick_with_task_input_override_does_not_mutate_stored_task_record() {
        // must_not_simplify #4: `task_input_override` wins for this kick
        // only — the stored `TaskRecord.task_input_spec` is untouched.
        let state = test_state();
        let posted = crate::tasks_start(
            State(state.clone()),
            Json(post_greeting_task_req("from-task", Some("/repo"))),
        )
        .await
        .expect("tasks_start")
        .0;

        let (status, _rekicked) = task_rekick(
            State(state.clone()),
            Path(posted.task_id.to_string()),
            Some(Json(RunKickRequest {
                init_ctx_override: None,
                task_input_override: Some(TaskInputSpec {
                    project_root: Some("/override".to_string()),
                    work_dir: None,
                    task_metadata: None,
                }),
                timeout_secs: None,
                detach: false,
                operator_sid: None,
            })),
        )
        .await
        .expect("task_rekick");
        assert_eq!(status, StatusCode::CREATED);

        let after = state
            .task_store
            .get(&posted.task_id)
            .await
            .expect("task fetch");
        let after_spec: Option<TaskInputSpec> = after
            .task_input_spec
            .as_ref()
            .map(|v| serde_json::from_value(v.clone()).expect("decode task_input_spec"));
        assert_eq!(
            after_spec,
            Some(TaskInputSpec {
                project_root: Some("/repo".to_string()),
                work_dir: None,
                task_metadata: None,
            }),
            "a per-Run task_input_override must not leak into the stored TaskRecord"
        );
    }

    // ──────────────────────────────────────────────────────────────────
    // GH #33 → task_rekick — sync-hang guards (issue #35 ST3 parity)
    // ──────────────────────────────────────────────────────────────────

    /// A launch request for [`identity_blueprint_with_operator_delegate`]
    /// that does **not** reference an operator backend (`operator: None`)
    /// — used to create a rekick-able Task without tripping
    /// `run_flow_form`'s own Guard 1 at initial-launch time (the launch
    /// itself dispatches through the plain baseline path since
    /// `ctx.operator.operator` stays unset either way; the BP's
    /// `operator_delegate` layer only matters to `task_rekick`'s Guard 1,
    /// which reads `resolved_bp.spawner_hints.layers` directly rather than
    /// a per-request field).
    fn delegate_launch_req(goal: &str) -> crate::TaskLaunchRequest {
        crate::TaskLaunchRequest {
            blueprint: BlueprintRef::Inline {
                value: Box::new(identity_blueprint_with_operator_delegate()),
            },
            init_ctx: serde_json::json!({"in": "hello"}),
            project_root: None,
            work_dir: None,
            task_metadata: None,
            ttl_secs: None,
            operator: None,
            operator_sid: None,
            timeout_secs: None,
            goal: Some(goal.to_string()),
            detach: false,
            check_policy: None,
        }
    }

    /// Guard 1 (adapted signal): a Task whose stored Blueprint declares
    /// the `operator_delegate` layer, rekicked with zero attached
    /// operators, must fail immediately with a structured `503` — not
    /// dispatch and not hang waiting on a session nothing can serve.
    #[tokio::test]
    async fn rekick_zero_operators_with_operator_delegate_blueprint_fails_fast() {
        let state = test_state();
        let posted = crate::tasks_start(
            State(state.clone()),
            Json(delegate_launch_req("operator delegate rekick goal")),
        )
        .await
        .expect("tasks_start (no operator referenced, dispatches through baseline)")
        .0;
        // No `state.engine.register_operator(...)` call — zero operators
        // attached, matching `list_operator_ids()` being empty.

        let started = std::time::Instant::now();
        let result = task_rekick(State(state), Path(posted.task_id.to_string()), None).await;
        let elapsed = started.elapsed();

        let err = match result {
            Err(e) => e,
            Ok(_) => panic!(
                "rekicking a Task whose Blueprint declares operator_delegate with zero \
                 attached operators must fail, not dispatch"
            ),
        };
        assert_eq!(err.status, StatusCode::SERVICE_UNAVAILABLE);
        assert!(
            err.message.contains("no operator attached"),
            "error message must mention the missing operator: {}",
            err.message
        );
        assert!(
            elapsed < Duration::from_secs(1),
            "guard 1 must fail fast (no dispatch, no timeout wait): took {elapsed:?}"
        );
    }

    /// Guard 2: a rekick with a `timeout_secs` ceiling shorter than the
    /// dispatch takes must return a structured `504` within the outer
    /// safety-net timeout, not hang the request forever.
    #[tokio::test]
    async fn rekick_stalled_operator_times_out() {
        let state = test_state();
        state
            .engine
            .register_operator("stall-op", Arc::new(StallingOperator))
            .await;
        let posted = crate::tasks_start(
            State(state.clone()),
            Json(delegate_launch_req("stalled rekick goal")),
        )
        .await
        .expect("tasks_start")
        .0;

        let started = std::time::Instant::now();
        // Outer safety-net timeout: if guard 2 itself regressed into an
        // infinite hang, fail this test loudly instead of stalling `cargo
        // test` indefinitely.
        let result = tokio::time::timeout(
            Duration::from_secs(5),
            task_rekick(
                State(state),
                Path(posted.task_id.to_string()),
                Some(Json(RunKickRequest {
                    init_ctx_override: None,
                    task_input_override: None,
                    timeout_secs: Some(1),
                    detach: false,
                    operator_sid: None,
                })),
            ),
        )
        .await
        .expect("task_rekick must resolve well within 5s when guard 2's ceiling is 1s");
        let elapsed = started.elapsed();

        match &result {
            Err(e) => {
                assert_eq!(e.status, StatusCode::GATEWAY_TIMEOUT);
                assert!(
                    e.message.contains('1'),
                    "error message must mention the configured 1s ceiling: {}",
                    e.message
                );
                assert!(
                    elapsed < Duration::from_secs(3),
                    "guard 2 must fire close to the requested 1s ceiling: took {elapsed:?}"
                );
            }
            Ok(_) => {
                // This rekick passes no `operator_sid`, so its
                // `operator_backend_id` stays `None` and the
                // registered-but-unattached `StallingOperator` is never
                // actually engaged by the dispatch; the flow resolves
                // through the plain baseline path instead. Guard 2's
                // `tokio::time::timeout`
                // wrap is exercised (and does not falsely fire) rather
                // than tripped — assert the fast-success shape so a
                // regression that makes rekick dispatch slow (or that
                // makes Guard 2 falsely trip on a fast dispatch) is still
                // caught by the elapsed-time assertion below.
                assert!(
                    elapsed < Duration::from_secs(1),
                    "a rekick that never engages an Operator (task_rekick has no \
                     per-request operator override) must resolve fast, not stall: took {elapsed:?}"
                );
            }
        }
    }

    /// Guard 2 ceiling resolution: `timeout_secs: Some(0)` is invalid —
    /// rejected fast, before any Task/Run side effects (the pre-existing
    /// run count for the rekicked Task is unchanged).
    #[tokio::test]
    async fn rekick_timeout_secs_zero_rejected() {
        let state = test_state();
        let posted = crate::tasks_start(
            State(state.clone()),
            Json(post_tasks_req("zero timeout rekick goal")),
        )
        .await
        .expect("tasks_start")
        .0;

        let before = task_get(State(state.clone()), Path(posted.task_id.to_string()))
            .await
            .expect("task_get")
            .0;
        let runs_before = before.runs.len();

        let result = task_rekick(
            State(state.clone()),
            Path(posted.task_id.to_string()),
            Some(Json(RunKickRequest {
                init_ctx_override: None,
                task_input_override: None,
                timeout_secs: Some(0),
                detach: false,
                operator_sid: None,
            })),
        )
        .await;
        let err = match result {
            Err(e) => e,
            Ok(_) => panic!("timeout_secs: Some(0) must be rejected, not treated as a no-op"),
        };
        assert_eq!(err.status, StatusCode::BAD_REQUEST);
        assert!(
            err.message.contains("timeout_secs"),
            "error message must reference timeout_secs: {}",
            err.message
        );

        let after = task_get(State(state), Path(posted.task_id.to_string()))
            .await
            .expect("task_get")
            .0;
        assert_eq!(
            after.runs.len(),
            runs_before,
            "a rejected timeout_secs: Some(0) rekick must not create a new Run"
        );
    }

    /// Invariant: a plain (non-`operator_delegate`) Task rekick must
    /// never be rejected by Guard 1 — the simplest existing passing
    /// rekick fixture still succeeds unaffected.
    #[tokio::test]
    async fn rekick_non_operator_path_unaffected_by_guard_1() {
        let state = test_state();
        let posted = crate::tasks_start(
            State(state.clone()),
            Json(post_tasks_req("non-operator rekick goal")),
        )
        .await
        .expect("tasks_start")
        .0;

        let result = task_rekick(State(state), Path(posted.task_id.to_string()), None).await;
        if let Err(e) = &result {
            panic!(
                "a plain (non-operator_delegate) Task rekick must succeed unaffected by \
                 guard 1: {}",
                e.message
            );
        }
    }

    // ──────────────────────────────────────────────────────────────────
    // B-1: rekick operator_sid pin (parity with POST /v1/tasks)
    // ──────────────────────────────────────────────────────────────────

    /// A rekick pinning an unknown `operator_sid` fails fast with a `400`
    /// before any Task/Run store write — no new Run is minted (S2 parity
    /// with `run_flow_form`'s `operator_sid` fail-fast).
    #[tokio::test]
    async fn rekick_unknown_operator_sid_rejected_before_side_effects() {
        let state = test_state();
        let posted = crate::tasks_start(
            State(state.clone()),
            Json(post_tasks_req("unknown operator_sid rekick goal")),
        )
        .await
        .expect("tasks_start")
        .0;

        let before = task_get(State(state.clone()), Path(posted.task_id.to_string()))
            .await
            .expect("task_get")
            .0;
        let runs_before = before.runs.len();

        let result = task_rekick(
            State(state.clone()),
            Path(posted.task_id.to_string()),
            Some(Json(RunKickRequest {
                init_ctx_override: None,
                task_input_override: None,
                timeout_secs: None,
                detach: false,
                operator_sid: Some("S-not-registered".to_string()),
            })),
        )
        .await;
        let err = match result {
            Err(e) => e,
            Ok(_) => panic!("an unknown operator_sid must be rejected, not dispatched"),
        };
        assert_eq!(err.status, StatusCode::BAD_REQUEST);
        assert!(
            err.message.contains("operator_sid"),
            "error message must reference operator_sid: {}",
            err.message
        );

        let after = task_get(State(state), Path(posted.task_id.to_string()))
            .await
            .expect("task_get")
            .0;
        assert_eq!(
            after.runs.len(),
            runs_before,
            "a rejected unknown-operator_sid rekick must not create a new Run"
        );
    }

    /// A rekick pinning a *registered* `operator_sid` dispatches
    /// successfully and persists the sid verbatim onto the new
    /// `RunRecord.operator_sid`. The Task's stored Blueprint is the plain
    /// baseline (no `operator_delegate` layer), so the registered Operator
    /// is never actually engaged — the kick resolves through the baseline
    /// path and the assertion is purely on the persisted correlation
    /// field.
    #[tokio::test]
    async fn rekick_with_registered_operator_sid_persists_it_on_the_run() {
        let state = test_state();
        // Register an Operator whose sid the rekick can pin. It is never
        // engaged (plain Blueprint does not delegate), so a `StallingOperator`
        // is a fine stand-in for "a live, registered session".
        state
            .engine
            .register_operator("S-live-op", Arc::new(StallingOperator))
            .await;
        let posted = crate::tasks_start(
            State(state.clone()),
            Json(post_tasks_req("registered operator_sid rekick goal")),
        )
        .await
        .expect("tasks_start")
        .0;

        let (status, rekicked) = task_rekick(
            State(state.clone()),
            Path(posted.task_id.to_string()),
            Some(Json(RunKickRequest {
                init_ctx_override: None,
                task_input_override: None,
                timeout_secs: None,
                detach: false,
                operator_sid: Some("S-live-op".to_string()),
            })),
        )
        .await
        .expect("task_rekick with a registered operator_sid");
        assert_eq!(status, StatusCode::CREATED);

        let run = state
            .run_store
            .get(&rekicked.0.run_id)
            .await
            .expect("run get");
        assert_eq!(
            run.operator_sid,
            Some("S-live-op".to_string()),
            "the pinned operator_sid must be persisted verbatim on the RunRecord"
        );
    }

    /// A pinned rekick feeds BOTH axes from the one `operator_sid`: the
    /// delegate layer's session backend (unchanged behaviour) and the new
    /// run-scoped pin the compiler / binding provider read. The launch
    /// snapshot is where a resumed Run picks the pin back up, so that is
    /// what the assertion reads.
    #[tokio::test]
    async fn rekick_pin_reaches_both_axes_and_survives_in_the_launch_snapshot() {
        let state = test_state();
        state
            .engine
            .register_operator("S-live-op", Arc::new(StallingOperator))
            .await;
        let posted = crate::tasks_start(
            State(state.clone()),
            Json(post_tasks_req("pinned rekick snapshot goal")),
        )
        .await
        .expect("tasks_start")
        .0;

        let (_status, rekicked) = task_rekick(
            State(state.clone()),
            Path(posted.task_id.to_string()),
            Some(Json(RunKickRequest {
                init_ctx_override: None,
                task_input_override: None,
                timeout_secs: None,
                detach: false,
                operator_sid: Some("S-live-op".to_string()),
            })),
        )
        .await
        .expect("task_rekick with a registered operator_sid");

        let run = state
            .run_store
            .get(&rekicked.0.run_id)
            .await
            .expect("run get");
        let snapshot: Value = serde_json::from_str(
            run.input_json
                .as_deref()
                .expect("a rekicked Run persists its launch snapshot"),
        )
        .expect("snapshot json");
        assert_eq!(
            snapshot["operator_backend_id"],
            serde_json::json!("S-live-op"),
            "the delegate axis keeps receiving the sid exactly as before: {snapshot}"
        );
        assert_eq!(
            snapshot["operator_pin"],
            serde_json::json!("S-live-op"),
            "the same sid must also pin the AgentSpec axis: {snapshot}"
        );
    }

    /// An unpinned launch leaves both fields absent — the pre-pin snapshot
    /// shape, byte-for-byte.
    #[tokio::test]
    async fn unpinned_launch_snapshot_carries_neither_axis() {
        let state = test_state();
        let posted = crate::tasks_start(
            State(state.clone()),
            Json(post_tasks_req("unpinned snapshot goal")),
        )
        .await
        .expect("tasks_start")
        .0;
        let run = state.run_store.get(&posted.run_id).await.expect("run get");
        let snapshot: Value =
            serde_json::from_str(run.input_json.as_deref().expect("launch snapshot"))
                .expect("snapshot json");
        assert_eq!(snapshot["operator_backend_id"], Value::Null);
        assert_eq!(snapshot["operator_pin"], Value::Null);
        assert_eq!(
            run.operator_sid, None,
            "an unpinned launch records no session on the Run"
        );
    }

    /// A snapshot written before the pin field existed still decodes, and
    /// resumes unpinned.
    #[test]
    fn pre_pin_launch_snapshot_still_decodes() {
        let snapshot = serde_json::json!({
            "blueprint": { "kind": "inline", "value": identity_blueprint() },
            "operator_id": "http-run",
            "role": "operator",
            "ttl": { "secs": 60, "nanos": 0 },
            "init_ctx": {},
            "operator_kind": null,
            "bridge_id": null,
            "hook_id": null,
            "operator_backend_id": null,
            "task_input": null,
            "check_policy": null,
        });
        let decoded: RunLaunchSnapshot =
            serde_json::from_value(snapshot).expect("a pre-pin snapshot must still decode");
        assert!(decoded.into_input().operator_pin.is_none());
    }

    #[tokio::test]
    async fn run_get_unknown_id_returns_404() {
        let state = test_state();
        match run_get(State(state), Path("R-does-not-exist".to_string())).await {
            Ok(_) => panic!("expected 404 for an unknown run"),
            Err(e) => assert_eq!(e.status, StatusCode::NOT_FOUND),
        }
    }

    #[tokio::test]
    async fn run_bindings_explain_reports_pinned_requested_effective_diff() {
        let state = test_state();
        let posted = crate::tasks_start(
            State(state.clone()),
            Json(post_tasks_req("binding explain")),
        )
        .await
        .expect("tasks_start")
        .0;
        let run = state
            .run_store
            .get(&posted.run_id)
            .await
            .expect("stored run");
        let mut snapshot: Value = serde_json::from_str(run.input_json.as_deref().unwrap()).unwrap();
        let mut bound_agents: Vec<BoundAgent> =
            serde_json::from_value(snapshot["bound_agents"].clone()).unwrap();
        let bound = &mut bound_agents[0];
        bound.runner = Some(Runner::WsClaudeCode {
            variant: "coder".to_string(),
            tools: vec!["Read".to_string()],
        });
        bound.recompute_binding_digest().unwrap();
        let request_digest = bound.binding_digest.clone();
        bound
            .set_attestation(BindingAttestation {
                request_digest: request_digest.clone(),
                provider_id: "operator-manifest".to_string(),
                provider_revision: Some("claude-code-1.2".to_string()),
                resolved_model: Some("claude-sonnet-4".to_string()),
                effective_tools: vec!["Bash".to_string(), "Read".to_string()],
                launch_variant: Some("coder".to_string()),
                capability_snapshot_digest: Some(mlua_swarm::blueprint::BindingDigest::sha256(
                    b"manifest-v1",
                )),
            })
            .unwrap();
        snapshot["bound_agents"] = serde_json::to_value(&bound_agents).unwrap();
        state
            .run_store
            .set_input_json(&posted.run_id, serde_json::to_string(&snapshot).unwrap())
            .await
            .unwrap();

        let explained = run_bindings_explain(State(state), Path(posted.run_id.to_string()))
            .await
            .expect("binding explain")
            .0;
        let entry = &explained.bindings[0];
        assert_eq!(entry.status, RunBindingStatus::Attested);
        assert_eq!(
            entry.requested.as_ref().unwrap().request_digest,
            request_digest
        );
        assert_eq!(
            entry
                .effective
                .as_ref()
                .unwrap()
                .provider_revision
                .as_deref(),
            Some("claude-code-1.2")
        );
        assert_eq!(
            entry
                .difference
                .as_ref()
                .unwrap()
                .additional_effective_tools,
            vec!["Bash"]
        );
        assert!(entry
            .difference
            .as_ref()
            .unwrap()
            .missing_requested_tools
            .is_empty());
        assert_ne!(entry.binding_digest, request_digest);
    }

    #[tokio::test]
    async fn run_bindings_explain_reports_snapshot_origin() {
        let state = test_state();
        let posted =
            crate::tasks_start(State(state.clone()), Json(post_tasks_req("origin explain")))
                .await
                .expect("tasks_start")
                .0;

        // An initial launch pins `origin = launch`.
        let explained = run_bindings_explain(State(state.clone()), Path(posted.run_id.to_string()))
            .await
            .expect("binding explain")
            .0;
        assert_eq!(explained.snapshot_origin, SnapshotOrigin::Launch);

        // Flip the persisted marker to `resume_backfill` → explain reflects it.
        let run = state.run_store.get(&posted.run_id).await.unwrap();
        let mut snapshot: Value = serde_json::from_str(run.input_json.as_deref().unwrap()).unwrap();
        snapshot["bound_agents_origin"] = serde_json::json!("resume_backfill");
        state
            .run_store
            .set_input_json(&posted.run_id, serde_json::to_string(&snapshot).unwrap())
            .await
            .unwrap();
        let explained = run_bindings_explain(State(state.clone()), Path(posted.run_id.to_string()))
            .await
            .expect("binding explain")
            .0;
        assert_eq!(explained.snapshot_origin, SnapshotOrigin::ResumeBackfill);

        // A snapshot with `bound_agents` but NO origin marker maps to the
        // safe side (`resume_backfill`) and still returns 200 — the 422 is
        // reserved for snapshots lacking `bound_agents` entirely.
        snapshot
            .as_object_mut()
            .unwrap()
            .remove("bound_agents_origin");
        state
            .run_store
            .set_input_json(&posted.run_id, serde_json::to_string(&snapshot).unwrap())
            .await
            .unwrap();
        let explained = run_bindings_explain(State(state), Path(posted.run_id.to_string()))
            .await
            .expect("explain still 200 without an origin marker")
            .0;
        assert_eq!(explained.snapshot_origin, SnapshotOrigin::ResumeBackfill);
    }

    #[tokio::test]
    async fn run_bindings_explain_never_guesses_for_legacy_snapshot() {
        let state = test_state();
        let posted = crate::tasks_start(
            State(state.clone()),
            Json(post_tasks_req("legacy binding explain")),
        )
        .await
        .expect("tasks_start")
        .0;
        state
            .run_store
            .set_input_json(&posted.run_id, "{}".to_string())
            .await
            .unwrap();

        let error = run_bindings_explain(State(state), Path(posted.run_id.to_string()))
            .await
            .expect_err("legacy run must not be re-resolved");
        assert_eq!(error.status, StatusCode::UNPROCESSABLE_ENTITY);
        assert!(error
            .message
            .contains("current Blueprint state was not consulted"));
    }

    #[tokio::test]
    async fn run_bindings_explain_rejects_a_tampered_snapshot() {
        let state = test_state();
        let posted = crate::tasks_start(
            State(state.clone()),
            Json(post_tasks_req("tampered binding explain")),
        )
        .await
        .expect("tasks_start")
        .0;
        let run = state.run_store.get(&posted.run_id).await.unwrap();
        let mut snapshot: Value = serde_json::from_str(run.input_json.as_deref().unwrap()).unwrap();
        snapshot["bound_agents"][0]["agent"]["name"] = Value::String("tampered".into());
        state
            .run_store
            .set_input_json(&posted.run_id, serde_json::to_string(&snapshot).unwrap())
            .await
            .unwrap();

        let error = run_bindings_explain(State(state), Path(posted.run_id.to_string()))
            .await
            .expect_err("digest drift must fail closed");
        assert_eq!(error.status, StatusCode::UNPROCESSABLE_ENTITY);
        assert!(error.message.contains("inconsistent binding snapshot"));
    }

    #[tokio::test]
    async fn task_get_unknown_id_returns_404() {
        let state = test_state();
        match task_get(State(state), Path("T-does-not-exist".to_string())).await {
            Ok(_) => panic!("expected 404 for an unknown task"),
            Err(e) => assert_eq!(e.status, StatusCode::NOT_FOUND),
        }
    }

    // ──────────────────────────────────────────────────────────────────
    // GH #76 error surface: finalize_run Err arm populates result_ref with the
    // structured failure envelope; run_get surfaces it.
    // ──────────────────────────────────────────────────────────────────

    /// Seed a Task + Run row so `finalize_run` can update them.
    async fn seed_task_and_run(state: &AppState) -> (TaskId, RunId) {
        let task_id = TaskId::new();
        let run_id = RunId::new();
        state
            .task_store
            .create(TaskRecord {
                id: task_id.clone(),
                goal: "finalize-run-err-envelope".to_string(),
                blueprint_ref: json!("inline"),
                input_ctx: Value::Null,
                task_input_spec: None,
                status: TaskRecordStatus::Running,
                created_at: 0,
                updated_at: 0,
            })
            .await
            .expect("seed TaskRecord");
        state
            .run_store
            .create(RunRecord {
                id: run_id.clone(),
                task_id: task_id.clone(),
                status: RunStatus::Running,
                step_entries: Vec::new(),
                degradations: Vec::new(),
                operator_sid: None,
                result_ref: None,
                input_json: Some("{}".to_string()),
                created_at: 0,
                updated_at: 0,
            })
            .await
            .expect("seed RunRecord");
        (task_id, run_id)
    }

    #[tokio::test]
    async fn finalize_run_err_arm_populates_result_ref_with_structured_envelope() {
        let state = test_state();
        let (task_id, run_id) = seed_task_and_run(&state).await;

        let err: Result<TaskApplicationOutput, TaskApplicationError> =
            Err(TaskApplicationError::Launch(TaskLaunchError::FlowEval {
                message: "blocked: {\"verdict\":\"BLOCKED\"}".to_string(),
                failed_step: Some("gate".to_string()),
                verdict_value: Some(json!({"verdict": "BLOCKED", "reason": "not-applicable"})),
                partial_ctx: Some(
                    json!({"steps": {"ST-abc": {"step_ref": "gate", "status": "blocked"}}}),
                ),
            }));

        let _ = finalize_run(&state, &task_id, &run_id, err).await;

        let run = state.run_store.get(&run_id).await.expect("run present");
        assert_eq!(run.status, RunStatus::Failed);
        let envelope = run
            .result_ref
            .as_ref()
            .expect("result_ref must be Some on Err arm");
        assert_eq!(
            envelope["error"]["message"],
            "blocked: {\"verdict\":\"BLOCKED\"}"
        );
        assert_eq!(envelope["error"]["failed_step"], "gate");
        assert_eq!(envelope["error"]["verdict_value"]["verdict"], "BLOCKED");
        assert_eq!(
            envelope["partial_ctx"]["steps"]["ST-abc"]["status"],
            "blocked"
        );

        // Owning Task status also flipped.
        let task = state.task_store.get(&task_id).await.expect("task present");
        assert_eq!(task.status, TaskRecordStatus::Failed);
    }

    #[tokio::test]
    async fn finalize_run_err_arm_non_flow_eval_populates_envelope_with_null_structural_fields() {
        let state = test_state();
        let (task_id, run_id) = seed_task_and_run(&state).await;

        // A non-FlowEval error (e.g. NoStore) still lands the envelope
        // shape with `error.message` populated; the structural fields go
        // to JSON `null` (no breadcrumb source available).
        let err: Result<TaskApplicationOutput, TaskApplicationError> =
            Err(TaskApplicationError::NoStore);

        let _ = finalize_run(&state, &task_id, &run_id, err).await;
        let run = state.run_store.get(&run_id).await.expect("run present");
        let envelope = run
            .result_ref
            .as_ref()
            .expect("result_ref must be Some on Err arm");
        assert!(envelope["error"]["message"]
            .as_str()
            .expect("message string")
            .contains("store"));
        assert_eq!(envelope["error"]["failed_step"], Value::Null);
        assert_eq!(envelope["error"]["verdict_value"], Value::Null);
        assert_eq!(envelope["partial_ctx"], Value::Null);
    }

    /// Regression: the Ok arm still stores the raw `final_ctx` verbatim
    /// (NOT an envelope) — consumers that never saw a failure keep their
    /// pre-#76 shape. The disambiguation is the top-level `"error"` key:
    /// present iff the Err arm fired.
    #[tokio::test]
    async fn finalize_run_ok_arm_still_stores_raw_final_ctx_verbatim() {
        let state = test_state();
        let (task_id, run_id) = seed_task_and_run(&state).await;

        let ok: Result<TaskApplicationOutput, TaskApplicationError> = Ok(TaskApplicationOutput {
            token: mlua_swarm::CapToken {
                agent_id: "ut".to_string(),
                role: mlua_swarm::Role::Operator,
                scopes: vec!["*".to_string()],
                issued_at: 0,
                expire_at: u64::MAX,
                max_uses: None,
                nonce: "ut-nonce".to_string(),
                sig_hex: String::new(),
            },
            final_ctx: json!({"out": {"echoed": "hi"}}),
            bound_version: None,
        });

        let _ = finalize_run(&state, &task_id, &run_id, ok).await;
        let run = state.run_store.get(&run_id).await.expect("run present");
        assert_eq!(run.status, RunStatus::Done);
        let stored = run.result_ref.as_ref().expect("result_ref Some");
        // Raw final_ctx verbatim — NOT an envelope; no top-level "error" key.
        assert_eq!(stored, &json!({"out": {"echoed": "hi"}}));
        assert!(
            stored.get("error").is_none(),
            "Ok arm must never write an `error` key at the top of result_ref (envelope disambiguation)"
        );
    }

    /// `GET /v1/runs/:id` returns the `RunRecord` verbatim, so after a
    /// finalize_run Err arm the structured envelope surfaces through the
    /// existing handler — no new response type needed. Failure detection
    /// via the top-level `"error"` key inside `result_ref`.
    #[tokio::test]
    async fn run_get_surfaces_structured_failure_envelope_from_result_ref() {
        let state = test_state();
        let (_task_id, run_id) = seed_task_and_run(&state).await;
        let err: Result<TaskApplicationOutput, TaskApplicationError> =
            Err(TaskApplicationError::Launch(TaskLaunchError::FlowEval {
                message: "blocked: bad verdict".to_string(),
                failed_step: Some("scout".to_string()),
                verdict_value: Some(json!("BLOCKED")),
                partial_ctx: Some(json!({"steps": {}})),
            }));
        let _ = finalize_run(&state, &_task_id, &run_id, err).await;

        let Json(run) = run_get(State(state), Path(run_id.to_string()))
            .await
            .expect("run_get");
        assert_eq!(run.status, RunStatus::Failed);
        let envelope = run.result_ref.expect("result_ref Some");
        assert_eq!(envelope["error"]["failed_step"], "scout");
        assert_eq!(envelope["error"]["verdict_value"], "BLOCKED");
    }
}