car-engine 0.32.1

Core runtime engine for Common Agent Runtime
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
//! Core execution engine — propose → validate → execute → commit.

use crate::cache::ResultCache;
use crate::capabilities::CapabilitySet;
use crate::checkpoint::Checkpoint;
use crate::rate_limit::{RateLimit, RateLimiter};
use car_eventlog::{EventKind, EventLog, SpanStatus};
use car_ir::{
    build_dag, Action, ActionProposal, ActionResult, ActionStatus, ActionType, CostSummary,
    FailureBehavior, ProposalResult, ToolSchema,
};
use car_policy::{ApprovalDecision, ApprovalLedger, ApprovalRecord, PermissionTier, PolicyEngine};
use car_state::StateStore;
use car_validator::validate_action;
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{Mutex as TokioMutex, RwLock as TokioRwLock};
use tokio::time::timeout;
use tracing::instrument;
use uuid::Uuid;

/// Retry backoff constants.
const RETRY_BASE_DELAY_MS: u64 = 100;
const RETRY_BACKOFF_FACTOR: u64 = 2;

// ---------------------------------------------------------------------------
// Replan types — failure recovery via model callback
// ---------------------------------------------------------------------------

/// Callback trait for replanning failed proposals.
/// Implement this to let the runtime ask the model for an alternative plan
/// when a proposal aborts.
#[async_trait::async_trait]
pub trait ReplanCallback: Send + Sync {
    async fn replan(&self, ctx: &ReplanContext) -> Result<ActionProposal, String>;
}

/// Context provided to the replan callback so the model can generate an alternative.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ReplanContext {
    /// Original proposal ID.
    pub proposal_id: String,
    /// Which replan attempt this is (1-indexed; attempt 1 = first replan after initial failure).
    pub attempt: u32,
    /// Actions that failed and caused the abort.
    pub failed_actions: Vec<FailedActionSummary>,
    /// Action IDs that succeeded before the abort (now rolled back).
    pub completed_action_ids: Vec<String>,
    /// State snapshot after rollback.
    pub state_snapshot: HashMap<String, Value>,
    /// How many replans remain.
    pub replans_remaining: u32,
    /// Original proposal source (model name, agent, etc.).
    pub original_source: String,
    /// Total actions in the original proposal.
    pub original_action_count: usize,
    /// The original goal/context from the proposal (for generating alternatives).
    pub original_context: HashMap<String, Value>,
}

/// Summary of a failed action, included in ReplanContext.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct FailedActionSummary {
    pub action_id: String,
    pub tool: Option<String>,
    pub error: String,
    pub parameters: HashMap<String, Value>,
}

/// Configuration for the replan loop.
#[derive(Debug, Clone)]
pub struct ReplanConfig {
    /// Maximum number of replan attempts. 0 = disabled (default).
    pub max_replans: u32,
    /// Delay in milliseconds between replan attempts. Prevents burning through
    /// attempts instantly if the model returns garbage fast. 0 = no delay.
    pub delay_ms: u64,
    /// If true, replan proposals are scored via car-planner's verify() before
    /// execution. Proposals with errors are rejected without executing.
    /// Prevents the engine from running a worse plan than the one that failed.
    pub verify_before_execute: bool,
    /// When true, validator/policy/capability rejections (ActionStatus::Rejected)
    /// also trigger rollback + replan, not just runtime Failed actions.
    /// Default false (conservative: preserves prior abort-only-on-Failed behavior).
    pub replan_on_rejected: bool,
}

/// How the runtime treats a proposal that conflicts with the current
/// shared state on a pre-execution transactional check (survey §4.3/§5.2.4
/// — `car_verify::check_transaction` against the versioned `StateStore`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TransactionCheckMode {
    /// Don't run the check (default — preserves prior behavior exactly).
    #[default]
    Off,
    /// Run it and emit any conflicts as `TransactionConflict` telemetry, but
    /// execute anyway.
    Warn,
    /// Run it; if any conflict is found, reject the proposal without
    /// executing (the conflicting actions become `Rejected` results).
    Strict,
}

impl Default for ReplanConfig {
    fn default() -> Self {
        Self {
            max_replans: 0,
            delay_ms: 0,
            verify_before_execute: true,
            replan_on_rejected: false,
        }
    }
}

/// Trait for tool execution. Implement this to provide tools to the runtime.
///
/// In-process: implement directly with function calls.
/// Daemon mode: implement by sending JSON-RPC to the client.
#[async_trait::async_trait]
pub trait ToolExecutor: Send + Sync {
    async fn execute(&self, tool: &str, params: &Value) -> Result<Value, String>;

    /// Variant that also carries the originating proposal `Action.id`
    /// and its `timeout_ms` budget.
    ///
    /// `action_id`: WS-based executors (`car-server-core::WsToolExecutor`)
    /// use it so the daemon-initiated `tools.execute` request to the client
    /// carries the same id the host's process-wide handler is keyed on
    /// — without this round-trip the host can't disambiguate concurrent
    /// callbacks for the same tool (Parslee-ai/car-releases#43 follow-up).
    ///
    /// `timeout_ms`: the action's per-call budget. WS executors MUST bound
    /// their callback wait by this (falling back to a default when `None`)
    /// so the daemon→host wait and the executor's own action deadline stay
    /// coordinated — otherwise a hardcoded inner wait reaps a call the outer
    /// deadline still permits (Parslee-ai/car#259). In-process executors
    /// that don't need either can keep the default forward to [`execute`].
    async fn execute_with_action(
        &self,
        tool: &str,
        params: &Value,
        _action_id: &str,
        _timeout_ms: Option<u64>,
    ) -> Result<Value, String> {
        self.execute(tool, params).await
    }

    /// Streaming entry point for detached invocation modes (C2). Start
    /// the tool and return a channel of [`car_ir::ToolStreamChunk`]s; the
    /// runtime drains it into the per-runtime handle registry while the
    /// DAG proceeds. End the stream with a terminal chunk (`done` /
    /// `error`); dropping the sender without one is reported as failure.
    /// A cooperative executor should stop work when the receiver returned
    /// here is dropped (that's what cancellation looks like from its side).
    ///
    /// Default: unsupported — existing one-shot executors compile and
    /// behave unchanged; a detached action against them is rejected with
    /// this error.
    async fn execute_stream(
        &self,
        tool: &str,
        _params: &Value,
        _action_id: &str,
    ) -> Result<tokio::sync::mpsc::Receiver<car_ir::ToolStreamChunk>, String> {
        Err(format!(
            "tool '{tool}': this executor does not support streaming/long-running invocation"
        ))
    }
}

/// Deterministic key for idempotency deduplication.
/// Deterministic key for idempotency deduplication. Carries the tenant
/// dimension (linus review): without it, tenant A's cached result for
/// an identical idempotent action was served to tenant B — a
/// cross-tenant data leak through the dedup cache. Unscoped executions
/// keep their historical keys (empty tenant segment).
fn idempotency_key(action: &Action, scope: Option<&crate::scope::RuntimeScope>) -> String {
    let sorted: std::collections::BTreeMap<_, _> = action.parameters.iter().collect();
    let params = serde_json::to_string(&sorted).unwrap_or_default();
    let tenant = scope.and_then(|s| s.tenant_id.as_deref()).unwrap_or("");
    format!(
        "{}:{}:{}:{}",
        tenant,
        serde_json::to_string(&action.action_type).unwrap_or_default(),
        action.tool.as_deref().unwrap_or(""),
        params
    )
}

fn rejected_result(action_id: &str, error: String) -> ActionResult {
    ActionResult {
        action_id: action_id.to_string(),
        status: ActionStatus::Rejected,
        output: None,
        error: Some(error),
        state_changes: HashMap::new(),
        duration_ms: None,
        timestamp: chrono::Utc::now(),
    }
}

/// Capture only the state keys relevant to an action (state_dependencies + expected_effects).
/// Returns an empty map if the action declares no relevant keys (e.g., tool calls
/// that don't interact with state).
fn snapshot_relevant_keys(
    state: &car_state::StateStore,
    action: &Action,
) -> HashMap<String, Value> {
    let mut keys: std::collections::HashSet<&str> = std::collections::HashSet::new();
    for dep in &action.state_dependencies {
        keys.insert(dep.as_str());
    }
    for key in action.expected_effects.keys() {
        keys.insert(key.as_str());
    }
    // For state_write actions, capture the key being written
    if action.action_type == ActionType::StateWrite {
        if let Some(key) = action.parameters.get("key").and_then(|v| v.as_str()) {
            keys.insert(key);
        }
    }

    if keys.is_empty() {
        // No declared state interaction — skip snapshot (empty map)
        return HashMap::new();
    }

    keys.iter()
        .filter_map(|&k| state.get(k).map(|v| (k.to_string(), v)))
        .collect()
}

fn skipped_result(action_id: &str, reason: &str) -> ActionResult {
    ActionResult {
        action_id: action_id.to_string(),
        status: ActionStatus::Skipped,
        output: None,
        error: Some(reason.to_string()),
        state_changes: HashMap::new(),
        duration_ms: None,
        timestamp: chrono::Utc::now(),
    }
}

/// Prefix on the `error` field of an `ActionResult` that distinguishes
/// "the user pulled the plug" from "earlier abort cascaded." The
/// `ActionStatus` itself is `Skipped` in both cases (introducing a
/// new variant ripples through every IR consumer + FFI binding); the
/// prefix lets callers like the A2A bridge tell the cases apart
/// without string-matching a magic literal.
pub const CANCELED_PREFIX: &str = "canceled: ";

/// Result for an action that didn't run because the proposal was
/// cancelled mid-flight. Distinct from `Skipped` so callers can tell
/// "didn't run because of an earlier abort" from "didn't run because
/// the user pulled the plug."
fn canceled_result(action_id: &str, reason: &str) -> ActionResult {
    ActionResult {
        action_id: action_id.to_string(),
        status: ActionStatus::Skipped,
        output: None,
        error: Some(format!("{}{}", CANCELED_PREFIX, reason)),
        state_changes: HashMap::new(),
        duration_ms: None,
        timestamp: chrono::Utc::now(),
    }
}

/// Format a tool result for feeding back to a model.
pub fn format_tool_result(result: &ActionResult) -> String {
    match result.status {
        ActionStatus::Succeeded => match &result.output {
            Some(v) => serde_json::to_string(v).unwrap_or_else(|_| v.to_string()),
            None => String::new(),
        },
        ActionStatus::Rejected => format!("[REJECTED] {}", result.error.as_deref().unwrap_or("")),
        ActionStatus::Failed => format!("[FAILED] {}", result.error.as_deref().unwrap_or("")),
        _ => format!(
            "[{:?}] {}",
            result.status,
            result.error.as_deref().unwrap_or("")
        ),
    }
}

/// Budget constraints for proposal execution.
#[derive(Debug, Clone)]
pub struct CostBudget {
    pub max_tool_calls: Option<u32>,
    pub max_duration_ms: Option<f64>,
    pub max_actions: Option<u32>,
}

/// Common Agent Runtime — deterministic execution layer.
///
/// Lock ordering discipline (never hold multiple simultaneously, never hold sync locks across .await):
/// 1. capabilities (RwLock, read-only during execution)
/// 2. tools (RwLock, read-only during execution)
/// 3. policies (RwLock, read-only during execution)
/// 4. session_policies (RwLock to find the per-session engine, then read inner Arc)
/// 5. cost_budget (RwLock, read-only during execution)
/// 6. log (TokioMutex, acquired/released per event)
/// 7. tool_executor (TokioMutex, clone Arc and drop before await)
/// 8. idempotency_cache (TokioMutex, acquired/released per check)
///
/// StateStore uses parking_lot::Mutex (sync) — NEVER hold across .await points.
pub struct Runtime {
    pub state: Arc<StateStore>,
    pub tools: Arc<TokioRwLock<HashMap<String, ToolSchema>>>,
    pub policies: Arc<TokioRwLock<PolicyEngine>>,
    /// Per-session policy registries. Hosts that multiplex multiple
    /// concurrent agent sessions over a single `Runtime` (IDE-style
    /// frontends with per-project rules, multi-tenant servers) call
    /// [`Runtime::open_session`] to mint an id, then
    /// [`Runtime::register_policy_in_session`] to attach session-scoped
    /// rules. Validation under that session walks the global registry
    /// AND the session's — both must pass. Sessions can deny what
    /// global allows; sessions cannot allow what global denies.
    /// Closing a session drops its registry and any closures it holds.
    /// See `docs/proposals/per-session-policy-scoping.md`.
    pub session_policies: Arc<TokioRwLock<HashMap<String, Arc<TokioRwLock<PolicyEngine>>>>>,
    pub log: Arc<TokioMutex<EventLog>>,
    pub rate_limiter: Arc<RateLimiter>,
    pub result_cache: Arc<ResultCache>,
    tool_executor: TokioMutex<Option<Arc<dyn ToolExecutor>>>,
    idempotency_cache: TokioMutex<HashMap<String, ActionResult>>,
    cost_budget: TokioRwLock<Option<CostBudget>>,
    capabilities: TokioRwLock<Option<CapabilitySet>>,
    inference_engine: Option<Arc<car_inference::InferenceEngine>>,
    /// Optional memgine for skill learning (auto-distillation after execution).
    memgine: Option<Arc<TokioMutex<car_memgine::MemgineEngine>>>,
    /// Whether to auto-distill skills after each proposal execution.
    auto_distill: bool,
    /// Optional trajectory store for persisting execution traces.
    trajectory_store: Option<Arc<car_memgine::TrajectoryStore>>,
    /// Optional replan callback for failure recovery.
    replan_callback: TokioMutex<Option<Arc<dyn ReplanCallback>>>,
    /// Replan configuration.
    replan_config: TokioRwLock<ReplanConfig>,
    /// Pre-execution transactional conflict check mode (survey §4.3/§5.2.4).
    /// `Off` by default. When `Warn`/`Strict`, each proposal is checked
    /// against the versioned shared state before execution; `Strict`
    /// rejects on conflict. See [`Runtime::set_transaction_check_mode`].
    transaction_check: TokioRwLock<TransactionCheckMode>,
    /// The live harness operating config the Evolution Agent tunes (survey
    /// §3.5). `None` until one is installed via [`Runtime::set_harness_config`]
    /// — so default behavior is byte-identical to before (no cap on
    /// per-action retries, built-in backoff). Once installed, the runtime
    /// *reads* it: `max_retries` caps per-action retry budgets and
    /// `retry_backoff_ms` sets the inter-attempt delay; the setter also maps
    /// `planning_max_replans` onto the replan config. This is what makes an
    /// applied [`car_memgine::HarnessConfigPatch`] take effect.
    harness_config: TokioRwLock<Option<car_memgine::HarnessConfig>>,
    /// Canonical tool registry (optional — new code should use this).
    pub registry: Arc<crate::registry::ToolRegistry>,
    /// The environment the agent's side-effecting built-in tools act within.
    /// Defaults to [`crate::substrate::LocalSubstrate`] (host fs/process), which
    /// reproduces the historic `agent_basics` host behavior byte-for-byte.
    /// Bind a different environment (e.g. a VM via `McpSubstrate`) with
    /// [`Runtime::with_substrate`] / [`Runtime::set_substrate`]. `calculate`
    /// stays pure and never consults the substrate.
    substrate: TokioRwLock<Arc<dyn crate::substrate::Substrate>>,
    /// Proposal-admission gates — the pre-execution safety seam (EPIC A /
    /// task A1). Each registered [`crate::admission::AdmissionGate`] runs
    /// during admission, before any action executes; a proposal that any
    /// gate blocks (or escalates to approval) is refused. Empty by default,
    /// so a runtime that registers no gates behaves exactly as before.
    /// Individual gates (information-flow, concurrency, blocking-policy)
    /// are layered on via [`Runtime::register_admission_gate`].
    admission_gates: TokioRwLock<Vec<Arc<dyn crate::admission::AdmissionGate>>>,
    /// Durable human-in-the-loop approval ledger (EPIC A / A7). When set,
    /// an admission gate's `NeedsApproval` verdict is resolved against this
    /// ledger by fingerprint: a prior Approved decision admits the
    /// proposal, a Rejected decision blocks it, an unseen one stays pending
    /// (fail-closed). `None` by default — escalations fail closed with an
    /// explanatory reason until a ledger is installed.
    approval_ledger: TokioRwLock<Option<ApprovalLedger>>,
    /// Optional JSONL journal backing the idempotency cache (EPIC A / C3).
    /// `None` by default — the cache is in-memory and lost on restart. When
    /// set via [`Runtime::set_idempotency_cache_path`], idempotent results
    /// are persisted and reloaded so a crash-restart doesn't re-execute a
    /// completed idempotent action (avoiding duplicate side effects).
    idempotency_journal: TokioRwLock<Option<std::path::PathBuf>>,
    /// Detached tool invocations (C2): a `ToolCall` with a
    /// `streaming`/`long_running` invocation mode is registered here and
    /// its handle returned as the action's output while the DAG proceeds.
    /// Chunks are drained via [`Runtime::tool_poll`], cancelled via
    /// [`Runtime::tool_cancel`], and fanned out to
    /// [`Runtime::subscribe_tool_events`] subscribers.
    pub tool_handles: Arc<crate::tool_handles::ToolHandleRegistry>,
}

/// A durable idempotency-cache record (C3). `result: None` is a tombstone
/// recorded when a cached entry is invalidated by a rollback.
#[derive(serde::Serialize, serde::Deserialize)]
struct IdempotencyEntry {
    key: String,
    result: Option<ActionResult>,
}

impl Runtime {
    pub fn new() -> Self {
        Self {
            state: Arc::new(StateStore::new()),
            tools: Arc::new(TokioRwLock::new(HashMap::new())),
            policies: Arc::new(TokioRwLock::new(PolicyEngine::new())),
            session_policies: Arc::new(TokioRwLock::new(HashMap::new())),
            log: Arc::new(TokioMutex::new(EventLog::new())),
            rate_limiter: Arc::new(RateLimiter::new()),
            result_cache: Arc::new(ResultCache::new()),
            tool_executor: TokioMutex::new(None),
            idempotency_cache: TokioMutex::new(HashMap::new()),
            cost_budget: TokioRwLock::new(None),
            capabilities: TokioRwLock::new(None),
            inference_engine: None,
            memgine: None,
            auto_distill: false,
            trajectory_store: None,
            replan_callback: TokioMutex::new(None),
            replan_config: TokioRwLock::new(ReplanConfig::default()),
            transaction_check: TokioRwLock::new(TransactionCheckMode::Off),
            harness_config: TokioRwLock::new(None),
            registry: Arc::new(crate::registry::ToolRegistry::new()),
            substrate: TokioRwLock::new(Arc::new(crate::substrate::LocalSubstrate::new())),
            admission_gates: TokioRwLock::new(Vec::new()),
            approval_ledger: TokioRwLock::new(None),
            idempotency_journal: TokioRwLock::new(None),
            tool_handles: Arc::new(crate::tool_handles::ToolHandleRegistry::new()),
        }
    }

    /// Create a runtime with shared state, event log, and policies.
    /// Each runtime gets its own tool set, executor, and idempotency cache.
    pub fn with_shared(
        state: Arc<StateStore>,
        log: Arc<TokioMutex<EventLog>>,
        policies: Arc<TokioRwLock<PolicyEngine>>,
    ) -> Self {
        Self {
            state,
            tools: Arc::new(TokioRwLock::new(HashMap::new())),
            policies,
            // Session-policy registries are per-runtime — sharing them
            // across embedders that share global policies would defeat
            // the isolation point. Hosts that genuinely want shared
            // sessions should drive them through one shared Runtime.
            session_policies: Arc::new(TokioRwLock::new(HashMap::new())),
            log,
            rate_limiter: Arc::new(RateLimiter::new()),
            result_cache: Arc::new(ResultCache::new()),
            tool_executor: TokioMutex::new(None),
            idempotency_cache: TokioMutex::new(HashMap::new()),
            cost_budget: TokioRwLock::new(None),
            capabilities: TokioRwLock::new(None),
            inference_engine: None,
            memgine: None,
            auto_distill: false,
            trajectory_store: None,
            replan_callback: TokioMutex::new(None),
            replan_config: TokioRwLock::new(ReplanConfig::default()),
            transaction_check: TokioRwLock::new(TransactionCheckMode::Off),
            harness_config: TokioRwLock::new(None),
            registry: Arc::new(crate::registry::ToolRegistry::new()),
            substrate: TokioRwLock::new(Arc::new(crate::substrate::LocalSubstrate::new())),
            admission_gates: TokioRwLock::new(Vec::new()),
            approval_ledger: TokioRwLock::new(None),
            idempotency_journal: TokioRwLock::new(None),
            tool_handles: Arc::new(crate::tool_handles::ToolHandleRegistry::new()),
        }
    }

    // ─── Session policy lifecycle ───────────────────────────────────
    //
    // Per-session policy scoping. Policies registered against a
    // session apply to proposals executed under that session id (via
    // [`Self::execute_with_session`] / [`Self::execute_with_session_and_cancel`]).
    // Policies registered globally always apply, on top of any
    // session-scoped layer. See `docs/proposals/per-session-policy-scoping.md`.

    /// Mint a new session id and pre-register an empty policy engine
    /// under it. Hosts call this once per concurrent agent context
    /// (an IDE project window, a multi-tenant client, etc.) and pair
    /// it with [`Self::close_session`] when the context ends.
    ///
    /// Returns the opaque id to pass to subsequent
    /// [`Self::register_policy_in_session`] / [`Self::execute_with_session`]
    /// calls. Ids are UUIDs so collisions across concurrent calls
    /// don't matter.
    pub async fn open_session(&self) -> String {
        let id = Uuid::new_v4().to_string();
        let mut sessions = self.session_policies.write().await;
        sessions.insert(id.clone(), Arc::new(TokioRwLock::new(PolicyEngine::new())));
        id
    }

    /// Drop the session and every policy scoped to it. Returns true
    /// if a session by that id existed; false if it didn't (already
    /// closed, never opened, etc.). Idempotent in effect — closing a
    /// missing session is a no-op the caller is free to ignore.
    pub async fn close_session(&self, session_id: &str) -> bool {
        let mut sessions = self.session_policies.write().await;
        sessions.remove(session_id).is_some()
    }

    /// Register a policy under a specific session id. The policy
    /// applies only when a proposal is executed under that session;
    /// proposals executed without a session (the default) only see
    /// global policies.
    ///
    /// Returns `Err(...)` if the session is unknown — callers either
    /// forgot to call [`Self::open_session`] or are using a
    /// stale/closed id.
    pub async fn register_policy_in_session(
        &self,
        session_id: &str,
        name: &str,
        check: car_policy::PolicyCheck,
        description: &str,
    ) -> Result<(), String> {
        let engine = {
            let sessions = self.session_policies.read().await;
            sessions
                .get(session_id)
                .cloned()
                .ok_or_else(|| format!("unknown session id '{session_id}'"))?
        };
        let mut engine = engine.write().await;
        engine.register(name, check, description);
        Ok(())
    }

    /// Load declarative deny rules from a project's `.car/policies/`
    /// directory and register them on the global policy engine (EPIC A /
    /// task A2).
    ///
    /// `car_dir` is the project's `.car` directory (the engine discovers
    /// it by walking up from cwd); this looks for `car_dir/policies/*.toml`.
    /// A missing directory is not an error (returns 0). A malformed rule
    /// file *is* an error — a dropped security rule must surface loudly.
    /// Returns the number of rules registered.
    ///
    /// These rules are *deny*-only and additive on top of any code-
    /// registered policies. Once A9 makes policy violations blocking at
    /// admission, a matching action refuses the proposal.
    pub async fn load_project_policies(
        &self,
        car_dir: impl AsRef<std::path::Path>,
    ) -> Result<usize, car_policy::PolicyLoadError> {
        let dir = car_dir.as_ref().join("policies");
        let rules = car_policy::load_policy_dir(&dir)?;
        let count =
            rules.deny_tool.len() + rules.deny_keyword.len() + rules.deny_tool_param.len();
        let mut engine = self.policies.write().await;
        rules.apply(&mut engine);
        Ok(count)
    }

    /// Load information-flow tool labels from a project's `.car` directory
    /// and register the information-flow admission gate (EPIC A / A3+A4).
    ///
    /// Reads `car_dir/tool-labels.json` (merged over built-in defaults) and
    /// registers an [`crate::flow::InformationFlowGate`] so every admitted
    /// proposal is checked for data exfiltration (blocked) and forbidden
    /// tool orderings (escalated to approval). A missing labels file is
    /// fine — the built-in defaults still mark the network tools as sinks.
    /// A malformed file is a loud error.
    pub async fn install_information_flow_gate(
        &self,
        car_dir: impl AsRef<std::path::Path>,
    ) -> Result<(), crate::flow::FlowLoadError> {
        let config = crate::flow::load_tool_labels(car_dir)?;
        let gate = Arc::new(crate::flow::InformationFlowGate::new(config));
        self.register_admission_gate(gate).await;
        Ok(())
    }

    /// True if a session with this id is currently open. Mostly for
    /// tests and FFI surface validation — production code should
    /// trust the id it just opened.
    pub async fn session_exists(&self, session_id: &str) -> bool {
        self.session_policies.read().await.contains_key(session_id)
    }

    /// Attach a local inference engine. Registers `infer`, `embed`, `classify`
    /// as built-in tools with real implementations.
    pub fn with_inference(mut self, engine: Arc<car_inference::InferenceEngine>) -> Self {
        self.inference_engine = Some(engine);
        // Register inference tool schemas (non-async init, use try_lock)
        if let Ok(mut tools) = self.tools.try_write() {
            for schema in car_inference::service::all_schemas() {
                tools.insert(schema.name.clone(), schema);
            }
        }
        self
    }

    /// Attach a memgine for automatic skill learning after execution.
    /// When `auto_distill` is true, execution traces are automatically distilled
    /// into skills and domains are evolved when underperforming.
    pub fn with_learning(
        mut self,
        memgine: Arc<TokioMutex<car_memgine::MemgineEngine>>,
        auto_distill: bool,
    ) -> Self {
        self.memgine = Some(memgine);
        self.auto_distill = auto_distill;
        self
    }

    /// Attach a memgine with auto-distillation enabled (recommended default).
    pub fn with_memgine(self, memgine: Arc<TokioMutex<car_memgine::MemgineEngine>>) -> Self {
        self.with_learning(memgine, true)
    }

    /// Attach a trajectory store for persisting execution traces.
    pub fn with_trajectory_store(mut self, store: Arc<car_memgine::TrajectoryStore>) -> Self {
        self.trajectory_store = Some(store);
        self
    }

    pub fn with_executor(self, executor: Arc<dyn ToolExecutor>) -> Self {
        // Use try_lock for non-async init context. Safe because we just created the mutex.
        if let Ok(mut guard) = self.tool_executor.try_lock() {
            *guard = Some(executor);
        }
        self
    }

    /// Set a tool executor for the next execute() call.
    /// Used by NAPI bindings where executor varies per call.
    pub async fn set_executor(&self, executor: Arc<dyn ToolExecutor>) {
        *self.tool_executor.lock().await = Some(executor);
    }

    /// Bind the execution substrate the side-effecting built-in tools
    /// (`read_file`/`write_file`/`edit_file`/`list_dir`/`find_files`/
    /// `grep_files`) act within (builder). Defaults to
    /// [`crate::substrate::LocalSubstrate`]; bind e.g.
    /// [`crate::substrate::McpSubstrate`] to make those tools hit a VM.
    /// `calculate` stays pure and ignores the substrate.
    pub fn with_substrate(self, substrate: Arc<dyn crate::substrate::Substrate>) -> Self {
        // Use try_write for non-async init context. Safe because we just created the lock.
        if let Ok(mut guard) = self.substrate.try_write() {
            *guard = substrate;
        }
        self
    }

    /// Set the execution substrate at runtime.
    pub async fn set_substrate(&self, substrate: Arc<dyn crate::substrate::Substrate>) {
        *self.substrate.write().await = substrate;
    }

    /// Clone the currently bound substrate.
    pub async fn substrate(&self) -> Arc<dyn crate::substrate::Substrate> {
        self.substrate.read().await.clone()
    }

    pub fn with_event_log(mut self, log: EventLog) -> Self {
        self.log = Arc::new(TokioMutex::new(log));
        self
    }

    /// Attach a replan callback for failure recovery (builder).
    pub fn with_replan(self, callback: Arc<dyn ReplanCallback>, config: ReplanConfig) -> Self {
        if let Ok(mut guard) = self.replan_callback.try_lock() {
            *guard = Some(callback);
        }
        if let Ok(mut guard) = self.replan_config.try_write() {
            *guard = config;
        }
        self
    }

    /// Set a replan callback at runtime.
    pub async fn set_replan_callback(&self, callback: Arc<dyn ReplanCallback>) {
        *self.replan_callback.lock().await = Some(callback);
    }

    /// Set replan configuration at runtime.
    pub async fn set_replan_config(&self, config: ReplanConfig) {
        *self.replan_config.write().await = config;
    }

    /// Set the pre-execution transactional conflict-check mode (survey
    /// §4.3/§5.2.4). `Off` (default) preserves prior behavior; `Warn`
    /// records conflicts as telemetry; `Strict` rejects a conflicting
    /// proposal before executing it.
    pub async fn set_transaction_check_mode(&self, mode: TransactionCheckMode) {
        *self.transaction_check.write().await = mode;
    }

    /// Register a proposal-admission gate (EPIC A / task A1).
    ///
    /// Gates run during admission, before any action executes, in the
    /// order they were registered. Each is a verified pre-execution safety
    /// check — information-flow (A4), concurrency (A5), blocking-policy
    /// (A9) — that can block a proposal or escalate it to human approval.
    /// Registering no gates leaves behavior unchanged.
    pub async fn register_admission_gate(
        &self,
        gate: Arc<dyn crate::admission::AdmissionGate>,
    ) {
        self.admission_gates.write().await.push(gate);
    }

    /// Remove all registered admission gates (primarily for tests and
    /// reconfiguration). After this, proposal admission reverts to the
    /// transactional pre-check only.
    pub async fn clear_admission_gates(&self) {
        self.admission_gates.write().await.clear();
    }

    /// The number of currently-registered admission gates.
    pub async fn admission_gate_count(&self) -> usize {
        self.admission_gates.read().await.len()
    }

    /// Register the VIGIL intent gate (arXiv 2601.05755 — the live
    /// verify-before-commit call-site). Installs
    /// [`crate::intent_gate::IntentGate`] as an admission gate: a
    /// forbidden capability or a tool-stream-influenced out-of-intent
    /// action hard-rejects the proposal; untainted drift escalates to
    /// the durable approval flow (A7) by content-bound fingerprint.
    /// Replans are covered automatically (gates re-run on every
    /// replanned proposal).
    pub async fn install_intent_gate(&self, config: crate::intent_gate::IntentGateConfig) {
        self.register_admission_gate(Arc::new(crate::intent_gate::IntentGate::new(config)))
            .await;
    }

    /// Load `.car/intent.json` from `car_dir` and install the intent
    /// gate when present. Absent file → Ok(false) (opt-in, ungated);
    /// malformed file → loud error, never a silently-ungated session.
    pub async fn install_intent_gate_from_project(
        &self,
        car_dir: impl AsRef<std::path::Path>,
    ) -> Result<bool, crate::intent_gate::IntentLoadError> {
        match crate::intent_gate::load_intent_config(car_dir)? {
            Some(cfg) => {
                self.install_intent_gate(cfg).await;
                Ok(true)
            }
            None => Ok(false),
        }
    }

    /// Register the skill deployment-tier ceiling gate (EPIC A / A8).
    ///
    /// Requires a memgine to be attached (skills live there). When a
    /// proposal names its driving skill in `context["skill"]`, the gate
    /// caps the proposal's actions at that skill's persisted
    /// `deployment_tier`, escalating an over-ceiling action to the durable
    /// approval flow (A7). Returns false if no memgine is attached.
    pub async fn install_skill_ceiling_gate(&self) -> bool {
        match &self.memgine {
            Some(mem) => {
                let gate = Arc::new(crate::skill_ceiling::SkillCeilingGate::new(mem.clone()));
                self.register_admission_gate(gate).await;
                true
            }
            None => false,
        }
    }

    /// Drain buffered chunks + status for a detached tool invocation (C2).
    /// `None` for an unknown or fully-consumed handle. See
    /// [`crate::tool_handles::ToolHandleRegistry::poll`] for the
    /// consume-on-terminal contract.
    pub async fn tool_poll(
        &self,
        handle_id: &str,
    ) -> Option<crate::tool_handles::ToolPollResult> {
        self.tool_handles.poll(handle_id).await
    }

    /// Request cancellation of a detached tool invocation (C2): fires the
    /// handle's cancel token (dropping the executor's chunk receiver) and
    /// seals its status as `cancelled` unless already terminal. Returns
    /// false for an unknown handle.
    pub async fn tool_cancel(&self, handle_id: &str) -> bool {
        self.tool_handles.cancel(handle_id).await
    }

    /// Subscribe to the live [`car_ir::ToolStreamEvent`] fanout for all
    /// detached tool invocations on this runtime (C2). The WS layer
    /// forwards these as `tools.stream.event` notifications.
    pub fn subscribe_tool_events(
        &self,
    ) -> tokio::sync::broadcast::Receiver<car_ir::ToolStreamEvent> {
        self.tool_handles.subscribe()
    }

    /// Enable tamper-evident hash chaining on the event log (EPIC A / A9).
    /// Every event appended from now on is linked to its predecessor by a
    /// content hash, so an after-the-fact edit to a chained event — or an
    /// interior deletion/reordering — is detectable via
    /// [`Runtime::verify_event_log_chain`]. Truncation at either end of the
    /// log (dropping a prefix or suffix wholesale) is NOT detectable — the
    /// chain has no anchored head hash and no trusted tail witness; that is
    /// out of scope until the chain head is anchored. Opt-in: existing logs
    /// stay byte-identical until enabled.
    pub async fn enable_event_log_hash_chaining(&self) {
        self.log.lock().await.enable_hash_chaining();
    }

    /// Verify the event log's tamper-evidence chain (EPIC A / A9). Returns
    /// `Ok(n)` for `n` verified chained events, or `Err(index)` naming the
    /// first event whose hash/linkage doesn't match — the point of an
    /// interior edit, deletion, or reordering. Head/tail truncation is not
    /// detectable (no anchored head hash; the first chained event's
    /// `prev_hash` is taken on trust) — see `EventLog::verify_chain`.
    pub async fn verify_event_log_chain(&self) -> Result<usize, usize> {
        self.log.lock().await.verify_chain()
    }

    /// Install a durable HITL approval ledger backed by a JSONL journal
    /// (EPIC A / A7). Loads any existing decisions so approvals survive a
    /// restart, then resolves future admission-gate `NeedsApproval`
    /// verdicts against it. The canonical daemon path is
    /// `~/.car/approvals.jsonl`.
    pub async fn set_approval_ledger_path(
        &self,
        path: impl Into<std::path::PathBuf>,
    ) -> std::io::Result<()> {
        let ledger = ApprovalLedger::with_journal(path.into())?;
        // Surface journal corruption (or a torn concurrent write) instead of
        // silently trusting a partial ledger (review A7 — the doc on
        // `skipped_on_load` promises callers surface it).
        if ledger.skipped_on_load() > 0 {
            tracing::warn!(
                skipped = ledger.skipped_on_load(),
                "approval ledger journal had unparseable lines skipped on load — \
                 the ledger may be missing decisions"
            );
        }
        *self.approval_ledger.write().await = Some(ledger);
        Ok(())
    }

    /// Use an in-memory approval ledger (no persistence) — primarily for
    /// tests and ephemeral runtimes.
    pub async fn set_approval_ledger_in_memory(&self) {
        *self.approval_ledger.write().await = Some(ApprovalLedger::new());
    }

    /// Record a human approval for an admission fingerprint (EPIC A / A7).
    /// A subsequently re-submitted proposal whose escalation matches this
    /// fingerprint is admitted without asking again.
    pub async fn approve_admission(
        &self,
        fingerprint: &str,
        reviewer: &str,
        reason: &str,
    ) -> Result<(), String> {
        self.record_admission_decision(fingerprint, ApprovalDecision::Approved, reviewer, reason)
            .await
    }

    /// Record a human rejection for an admission fingerprint (EPIC A / A7).
    /// A proposal whose escalation matches a rejected fingerprint is
    /// blocked outright.
    pub async fn reject_admission(
        &self,
        fingerprint: &str,
        reviewer: &str,
        reason: &str,
    ) -> Result<(), String> {
        self.record_admission_decision(fingerprint, ApprovalDecision::Rejected, reviewer, reason)
            .await
    }

    async fn record_admission_decision(
        &self,
        fingerprint: &str,
        decision: ApprovalDecision,
        reviewer: &str,
        reason: &str,
    ) -> Result<(), String> {
        {
            let mut guard = self.approval_ledger.write().await;
            let ledger = guard
                .as_mut()
                .ok_or_else(|| "no approval ledger installed".to_string())?;
            ledger
                .record(ApprovalRecord {
                    fingerprint: fingerprint.to_string(),
                    // Admission escalations aren't tier-classified; record the
                    // most restrictive tier so the decision reads as "elevated".
                    required_tier: PermissionTier::FullAccess,
                    decision,
                    reviewer: reviewer.to_string(),
                    reason: reason.to_string(),
                    evidence: None,
                    decided_at: chrono::Utc::now().to_rfc3339(),
                })
                // A journal write failure means the decision is NOT durable —
                // surface it instead of emitting a false ApprovalRecorded
                // audit event (review A7).
                .map_err(|e| format!("failed to persist approval decision: {e}"))?;
        }
        let approval = match decision {
            ApprovalDecision::Approved => "approved",
            ApprovalDecision::Rejected => "rejected",
        };
        let mut log = self.log.lock().await;
        log.append(
            EventKind::ApprovalRecorded,
            None,
            None,
            [
                ("fingerprint".to_string(), Value::from(fingerprint)),
                ("approval".to_string(), Value::from(approval)),
                ("reviewer".to_string(), Value::from(reviewer)),
                ("reason".to_string(), Value::from(reason)),
            ]
            .into(),
        );
        Ok(())
    }

    /// Back the idempotency cache with a durable JSONL journal (EPIC A / C3).
    ///
    /// Loads any existing entries into the in-memory cache, then persists
    /// future idempotent results (and rollback invalidations, as
    /// tombstones) to the journal. After a crash-restart, re-submitting a
    /// completed idempotent action returns the cached result instead of
    /// re-executing it — preventing duplicate external side effects. The
    /// canonical daemon path is `~/.car/idempotency.jsonl`. Returns the
    /// number of live entries loaded.
    pub async fn set_idempotency_cache_path(
        &self,
        path: impl Into<std::path::PathBuf>,
    ) -> std::io::Result<usize> {
        let path = path.into();
        if let Some(parent) = path.parent() {
            let _ = std::fs::create_dir_all(parent);
        }
        // Replay the journal (last entry per key wins; a tombstone removes).
        let mut loaded: HashMap<String, ActionResult> = HashMap::new();
        if path.exists() {
            let content = std::fs::read_to_string(&path)?;
            for line in content.lines() {
                if line.trim().is_empty() {
                    continue;
                }
                if let Ok(entry) = serde_json::from_str::<IdempotencyEntry>(line) {
                    match entry.result {
                        Some(r) => {
                            loaded.insert(entry.key, r);
                        }
                        None => {
                            loaded.remove(&entry.key);
                        }
                    }
                }
            }
        }
        {
            let mut cache = self.idempotency_cache.lock().await;
            for (k, v) in loaded.iter() {
                cache.entry(k.clone()).or_insert_with(|| v.clone());
            }
        }
        let count = loaded.len();
        *self.idempotency_journal.write().await = Some(path);
        Ok(count)
    }

    /// Append an idempotency record to the journal if one is configured.
    /// `result = None` writes a tombstone (invalidation).
    async fn journal_idempotency(&self, key: &str, result: Option<&ActionResult>) {
        let path = {
            let guard = self.idempotency_journal.read().await;
            guard.clone()
        };
        let Some(path) = path else {
            return;
        };
        let entry = IdempotencyEntry {
            key: key.to_string(),
            result: result.cloned(),
        };
        if let Ok(mut line) = serde_json::to_string(&entry) {
            line.push('\n');
            use std::io::Write;
            // Persistence failure must be VISIBLE (linus review): a
            // silently-dropped journal write means an idempotent action
            // re-executes its side effects after a restart while the
            // operator believes it's covered. Fail-open (the in-memory
            // cache still dedups this process) but loudly.
            let write = std::fs::OpenOptions::new()
                .create(true)
                .append(true)
                .open(&path)
                .and_then(|mut f| f.write_all(line.as_bytes()));
            if let Err(e) = write {
                tracing::warn!(
                    path = %path.display(),
                    error = %e,
                    "idempotency journal write failed — durable dedup is NOT covering this result"
                );
            }
        }
    }

    /// Look up the current decision for an admission fingerprint, if any.
    pub async fn admission_decision(&self, fingerprint: &str) -> Option<ApprovalDecision> {
        let guard = self.approval_ledger.read().await;
        guard
            .as_ref()
            .and_then(|l| l.lookup(fingerprint).map(|r| r.decision))
    }

    /// Verify a model's tool-use claims against the runtime's own execution
    /// receipts (EPIC A / A6 — arXiv 2603.10060). The runtime owns tool
    /// execution and logs it, so it holds unforgeable ground truth: this
    /// projects [`car_eventlog::tool_receipts::ToolReceipt`]s from the event
    /// log and cross-checks the supplied claims, catching a fabricated tool
    /// reference, a misstated result count, or a false "found nothing".
    ///
    /// `proposal_id` scopes the cross-check window to a single proposal's
    /// events (pass the proposal whose response the claims came from) — a
    /// claim is never judged against another run's receipts. The check is
    /// retention-coherent (review A6): when the log has trimmed events and
    /// the window can't be proven complete (unscoped, or the proposal's
    /// `ProposalReceived` marker — which precedes every receipt of that
    /// proposal — was itself evicted), a claim without a receipt comes back
    /// in `ReceiptReport::ungroundable` ("window evicted") instead of being
    /// mis-flagged `fabricated_tool_reference`.
    ///
    /// Returns the [`ReceiptReport`]; when it is not grounded, a
    /// `ToolReceiptHallucination` event is emitted so the caller's
    /// verdict→action loop (reject/flag the response) is auditable.
    /// Deterministic, zero-inference. Claims arrive structured — CAR's
    /// thesis is that intent is structured IR, so a caller extracts claims
    /// from the model's tool_calls / IR rather than regexing prose.
    pub async fn verify_tool_receipts(
        &self,
        claims: &[car_eventlog::tool_receipts::ToolClaim],
        proposal_id: Option<&str>,
    ) -> car_eventlog::tool_receipts::ReceiptReport {
        let (receipts, window_complete) = {
            let log = self.log.lock().await;
            let complete = if log.trimmed_events() == 0 {
                // Nothing was ever evicted — the window is complete whether
                // or not it is scoped.
                true
            } else {
                match proposal_id {
                    // A proposal's window is complete iff its ProposalReceived
                    // marker survived retention: every receipt of the proposal
                    // was appended after it, so if the marker is retained, so
                    // are the receipts.
                    Some(pid) => log.events().iter().any(|e| {
                        e.kind == EventKind::ProposalReceived
                            && e.proposal_id.as_deref() == Some(pid)
                    }),
                    // Unscoped check over a trimmed log: unknowable.
                    None => false,
                }
            };
            (
                car_eventlog::tool_receipts::receipts_from_events_scoped(
                    log.events(),
                    proposal_id,
                ),
                complete,
            )
        };
        let report = car_eventlog::tool_receipts::verify_tool_claims_windowed(
            claims,
            &receipts,
            window_complete,
        );
        if !report.grounded {
            let mut log = self.log.lock().await;
            log.append(
                EventKind::ToolReceiptHallucination,
                None,
                proposal_id,
                [
                    (
                        "count".to_string(),
                        Value::from(report.hallucinations.len()),
                    ),
                    (
                        "hallucinations".to_string(),
                        serde_json::to_value(&report.hallucinations).unwrap_or_default(),
                    ),
                ]
                .into(),
            );
        }
        report
    }

    /// Run every registered admission gate against a proposal and fold
    /// their verdicts into a single [`crate::admission::AdmissionDecision`].
    ///
    /// Each gate's outcome is recorded as an `AdmissionGateDecision` event
    /// so a denial is attributable. Aggregation is conjunctive and
    /// fail-closed: the proposal is admitted only if every gate allowed it.
    /// Returns an admit decision immediately when no gates are registered
    /// (zero overhead on the common path).
    async fn run_admission_gates(
        &self,
        proposal: &ActionProposal,
        session_id: Option<&str>,
        scope: Option<&crate::scope::RuntimeScope>,
    ) -> crate::admission::AdmissionDecision {
        use crate::admission::{AdmissionDecision, GateContext};

        let gates = self.admission_gates.read().await;
        if gates.is_empty() {
            return AdmissionDecision::admit();
        }

        // One consistent snapshot for every gate this pass.
        let (state, versions) = self.state.versioned_snapshot();
        let ctx = GateContext {
            session_id,
            scope,
            state: &state,
            versions: &versions,
        };

        let mut decision = AdmissionDecision::admit();
        for gate in gates.iter() {
            let outcome = gate.check(proposal, &ctx).await;
            // Audit every gate decision (allow included) so the trail shows
            // which gates ran, not just which objected.
            let mut props: HashMap<String, Value> = HashMap::new();
            props.insert("gate".to_string(), Value::from(gate.name()));
            // Pre-execution proposal admission (vs the multi-agent
            // commit barrier, which emits the same event kind with
            // phase:"commit_barrier").
            props.insert("phase".to_string(), Value::from("admission"));
            props.insert("decision".to_string(), Value::from(outcome.label()));
            match &outcome {
                crate::admission::GateOutcome::Allow => {}
                crate::admission::GateOutcome::Reject { blocked, reason } => {
                    props.insert("reason".to_string(), Value::from(reason.clone()));
                    props.insert(
                        "blocked".to_string(),
                        serde_json::to_value(blocked).unwrap_or_default(),
                    );
                }
                crate::admission::GateOutcome::NeedsApproval {
                    actions,
                    fingerprint,
                    reason,
                } => {
                    props.insert("reason".to_string(), Value::from(reason.clone()));
                    props.insert(
                        "blocked".to_string(),
                        serde_json::to_value(actions).unwrap_or_default(),
                    );
                    props.insert("fingerprint".to_string(), Value::from(fingerprint.clone()));
                }
            }
            {
                let mut log = self.log.lock().await;
                log.append(
                    EventKind::AdmissionGateDecision,
                    None,
                    Some(&proposal.id),
                    props,
                );
            }
            decision.absorb(gate.name(), outcome);
        }
        decision
    }

    /// Install a harness operating config — the live end of the Evolution
    /// Agent loop (survey §3.5). After the meta-agent's `HarnessConfig::apply`
    /// produces a governed, regression-gated config, hand it here to take
    /// effect: `max_retries`/`retry_backoff_ms` drive the per-action retry
    /// loop, and `planning_max_replans` is mapped onto the replan budget.
    /// Every `HarnessConfig` knob is consumed here — none is aspirational.
    pub async fn set_harness_config(&self, cfg: car_memgine::HarnessConfig) {
        self.replan_config.write().await.max_replans = cfg.planning_max_replans;
        *self.harness_config.write().await = Some(cfg);
    }

    /// The current harness operating config, if one has been installed.
    pub async fn harness_config(&self) -> Option<car_memgine::HarnessConfig> {
        self.harness_config.read().await.clone()
    }

    /// Atomically read-modify-write the harness operating config under ONE
    /// write lock (installing the default first when none is set). The
    /// get→mutate→set alternative is a lost-update race when two requests
    /// mutate concurrently — the daemon's `evolution.run` harness-apply path
    /// uses this instead (kernel review S3). Keeps the same replan-budget
    /// propagation as [`Self::set_harness_config`].
    pub async fn update_harness_config<R>(
        &self,
        f: impl FnOnce(&mut car_memgine::HarnessConfig) -> R,
    ) -> R {
        let mut guard = self.harness_config.write().await;
        let cfg = guard.get_or_insert_with(car_memgine::HarnessConfig::default);
        let out = f(cfg);
        let max_replans = cfg.planning_max_replans;
        drop(guard);
        self.replan_config.write().await.max_replans = max_replans;
        out
    }

    /// Run the pre-execution transactional check against the current
    /// versioned shared state. Returns the conflicting action ids when the
    /// mode is `Strict` and conflicts exist (so the caller can reject those
    /// actions); always emits `TransactionConflict` telemetry for each
    /// conflict found. Empty/`None` means "proceed".
    async fn transaction_precheck(
        &self,
        proposal: &ActionProposal,
    ) -> std::collections::HashSet<String> {
        let mode = *self.transaction_check.read().await;
        if mode == TransactionCheckMode::Off {
            return std::collections::HashSet::new();
        }
        let (state, versions) = self.state.versioned_snapshot();
        let report = car_verify::check_transaction(proposal, &versions, Some(&state));
        if report.consistent {
            return std::collections::HashSet::new();
        }
        let mut blocked = std::collections::HashSet::new();
        let mut log = self.log.lock().await;
        for c in &report.conflicts {
            for aid in &c.actions {
                blocked.insert(aid.clone());
            }
            log.append(
                EventKind::TransactionConflict,
                c.actions.first().map(|s| s.as_str()),
                Some(&proposal.id),
                [
                    // Use the serde representation (snake_case: write_write
                    // / read_write / stale_assumption) the .d.ts/.pyi/doc
                    // contract is written against — NOT Debug, which would
                    // emit "writewrite" (neo review #4).
                    (
                        "kind".to_string(),
                        serde_json::to_value(c.kind).unwrap_or_default(),
                    ),
                    ("key".to_string(), Value::from(c.key.clone())),
                    (
                        "actions".to_string(),
                        serde_json::to_value(&c.actions).unwrap_or_default(),
                    ),
                    (
                        "explanation".to_string(),
                        Value::from(c.explanation.clone()),
                    ),
                    ("resolution".to_string(), Value::from(c.resolution.clone())),
                ]
                .into(),
            );
        }
        drop(log);
        // Only Strict blocks execution; Warn records and proceeds.
        match mode {
            TransactionCheckMode::Strict => blocked,
            _ => std::collections::HashSet::new(),
        }
    }

    /// Register a tool with just a name (backward compatible).
    pub async fn register_tool(&self, name: &str) {
        let schema = ToolSchema {
            name: name.to_string(),
            description: String::new(),
            parameters: serde_json::Value::Object(Default::default()),
            returns: None,
            idempotent: false,
            cache_ttl_secs: None,
            rate_limit: None,
        };
        self.register_tool_schema(schema).await;
    }

    /// Register a tool with full schema.
    pub async fn register_tool_schema(&self, schema: ToolSchema) {
        // Auto-configure cache if schema specifies it
        if let Some(ttl) = schema.cache_ttl_secs {
            self.result_cache.enable_caching(&schema.name, ttl).await;
        }
        // Auto-configure rate limit if schema specifies it
        if let Some(ref rl) = schema.rate_limit {
            self.rate_limiter
                .set_limit(
                    &schema.name,
                    RateLimit {
                        max_calls: rl.max_calls,
                        interval_secs: rl.interval_secs,
                    },
                )
                .await;
        }
        self.tools.write().await.insert(schema.name.clone(), schema);
    }

    /// Register a tool via the canonical registry.
    /// This is the preferred way to register tools — it updates both the
    /// registry and the legacy tools HashMap for backward compatibility.
    pub async fn register_tool_entry(&self, entry: crate::registry::ToolEntry) {
        let schema = entry.schema.clone();
        self.registry.register(entry).await;
        self.register_tool_schema(schema).await;
    }

    /// Remove a tool from both the canonical registry and the legacy
    /// `tools` schema map, so the model no longer sees it and the
    /// validator no longer accepts it. Used when a remote MCP connector
    /// tool is disabled or its connector is removed. Returns true if the
    /// tool was present in either store.
    pub async fn unregister_tool(&self, name: &str) -> bool {
        let removed_entry = self.registry.remove(name).await.is_some();
        let removed_schema = self.tools.write().await.remove(name).is_some();
        removed_entry || removed_schema
    }

    /// Register CAR's built-in agent utility stdlib.
    ///
    /// This is an opt-in convenience layer for common local-file and text tools.
    /// Existing runtimes remain unchanged until this is called.
    pub async fn register_agent_basics(&self) {
        for entry in crate::agent_basics::entries() {
            self.register_tool_entry(entry).await;
        }
    }

    /// Get all registered tool schemas (for model prompt generation).
    pub async fn tool_schemas(&self) -> Vec<ToolSchema> {
        self.tools.read().await.values().cloned().collect()
    }

    /// Set a cost budget that limits proposal execution.
    pub async fn set_cost_budget(&self, budget: CostBudget) {
        *self.cost_budget.write().await = Some(budget);
    }

    /// Set per-agent capability permissions that restrict tools, state keys, and action count.
    pub async fn set_capabilities(&self, caps: CapabilitySet) {
        *self.capabilities.write().await = Some(caps);
    }

    /// Set a per-tool rate limit (token bucket).
    ///
    /// `max_calls` tokens are available per `interval_secs` window.
    /// When the bucket is empty, `dispatch()` applies backpressure by
    /// waiting until a token refills.
    pub async fn set_rate_limit(&self, tool: &str, max_calls: u32, interval_secs: f64) {
        self.rate_limiter
            .set_limit(
                tool,
                RateLimit {
                    max_calls,
                    interval_secs,
                },
            )
            .await;
    }

    /// Enable cross-proposal result caching for a tool with a TTL in seconds.
    pub async fn enable_tool_cache(&self, tool: &str, ttl_secs: u64) {
        self.result_cache.enable_caching(tool, ttl_secs).await;
    }

    /// Execute a proposal with automatic replanning on failure.
    ///
    /// If a `ReplanCallback` is registered and `max_replans > 0`, the runtime
    /// will catch abort failures, roll back state, ask the model for an
    /// alternative proposal via the callback, and re-execute. This transforms
    /// "execute-and-hope" into "execute-and-recover."
    ///
    /// If no callback is registered or `max_replans == 0`, behaves identically
    /// to a single `execute_inner()` call (zero overhead, fully backward compatible).
    #[instrument(
        name = "proposal.execute",
        skip_all,
        fields(
            proposal_id = %proposal.id,
            action_count = proposal.actions.len(),
        )
    )]
    pub async fn execute(&self, proposal: &ActionProposal) -> ProposalResult {
        // Forward to the cancel-aware variant with a never-cancelled
        // token. Existing callers see no behaviour change.
        let token = tokio_util::sync::CancellationToken::new();
        self.execute_with_cancel(proposal, &token).await
    }

    /// Execute a proposal scoped to a specific session id.
    ///
    /// Validation walks the global policy registry plus the session's
    /// own registry — both must pass for an action to run. Session
    /// policies can deny what global allows; they cannot allow what
    /// global denies (validation is conjunctive).
    ///
    /// Returns the same [`ProposalResult`] shape as [`Self::execute`].
    /// Errors with an action-level rejection if the session id is
    /// unknown — callers should check via [`Self::session_exists`] or
    /// trust an id they minted via [`Self::open_session`].
    pub async fn execute_with_session(
        &self,
        proposal: &ActionProposal,
        session_id: &str,
    ) -> ProposalResult {
        let token = tokio_util::sync::CancellationToken::new();
        self.execute_with_session_and_cancel(proposal, session_id, &token)
            .await
    }

    /// Combined session-scoped + cancellable execute. The session id
    /// is passed verbatim to the per-action policy check; the cancel
    /// token behaves identically to [`Self::execute_with_cancel`].
    pub async fn execute_with_session_and_cancel(
        &self,
        proposal: &ActionProposal,
        session_id: &str,
        cancel: &tokio_util::sync::CancellationToken,
    ) -> ProposalResult {
        self.execute_with_optional_session(proposal, Some(session_id), None, cancel)
            .await
    }

    /// Execute a proposal with cooperative cancellation.
    ///
    /// The runtime checks `token.is_cancelled()` at each DAG level
    /// boundary. When set, every action that hadn't yet started runs
    /// is reported as `Skipped` with `error = "canceled: ..."` so
    /// callers can distinguish "user pulled the plug" from "earlier
    /// abort cascaded." Actions already in flight continue to
    /// completion — tool calls dispatched to user-provided executors
    /// can't be safely interrupted from the engine.
    ///
    /// The CAR A2A bridge uses this so `tasks/cancel` produces a
    /// `ProposalResult` with clean partial state rather than relying
    /// on `JoinHandle::abort` to interrupt mid-await (which leaves
    /// no record of which actions actually ran).
    ///
    /// **FFI exposure:** this method is intentionally not surfaced
    /// through the NAPI / PyO3 / `car-server-core` JSON-RPC bindings.
    /// Those consumers (Node, Python, WebSocket) don't currently
    /// expose long-running async-task surfaces that need
    /// cancellation; the bridge is the lone consumer. When a binding
    /// gains a long-running task surface, the path is clear: add a
    /// per-binding token registry keyed by some caller-provided id,
    /// expose `cancelExecution(id)` / `cancel_execution(id)` /
    /// `proposal.cancel { id }`, and have the runtime call
    /// `execute_with_cancel` with the matching token. Skipping that
    /// today avoids speculative API surface that bloats bindings
    /// without a consumer.
    pub async fn execute_with_cancel(
        &self,
        proposal: &ActionProposal,
        cancel: &tokio_util::sync::CancellationToken,
    ) -> ProposalResult {
        self.execute_with_optional_session(proposal, None, None, cancel)
            .await
    }

    /// Execute a proposal with an attached [`RuntimeScope`]
    /// (Parslee-ai/car#187 phase 3).
    ///
    /// Same contract as [`Self::execute`] plus a per-execution
    /// identity surface — typically built by the car-a2a dispatcher
    /// from the verified `Identity` and cooperative `a2a_caller`
    /// metadata on the inbound `ActionProposal`. The scope is
    /// recorded on the event log so downstream audit / log analysis
    /// can see which caller / tenant issued each action.
    ///
    /// **What this enforces today**: scope is captured + logged.
    /// Memgine queries and state-store ops still hit global
    /// namespaces — those follow-ups are tracked under #187.
    /// Tool / policy code that needs per-tenant behaviour right now
    /// should keep reading `proposal.context["a2a_caller_verified"]`
    /// directly (the phase 1 / 2 surface).
    pub async fn execute_scoped(
        &self,
        proposal: &ActionProposal,
        scope: &crate::scope::RuntimeScope,
    ) -> ProposalResult {
        let token = tokio_util::sync::CancellationToken::new();
        self.execute_scoped_with_cancel(proposal, scope, &token)
            .await
    }

    /// Combined scoped + cancellable execute. Mirrors the shape of
    /// [`Self::execute_with_session_and_cancel`] for symmetry — both
    /// add a side-channel (session id / scope) on top of the
    /// cancellable form.
    pub async fn execute_scoped_with_cancel(
        &self,
        proposal: &ActionProposal,
        scope: &crate::scope::RuntimeScope,
        cancel: &tokio_util::sync::CancellationToken,
    ) -> ProposalResult {
        self.execute_with_optional_session(proposal, None, Some(scope), cancel)
            .await
    }

    /// Internal entry point that backs both
    /// [`Self::execute_with_cancel`] (no session) and
    /// [`Self::execute_with_session_and_cancel`]. Holds the replan
    /// loop and threads `session_id` into the per-action validation
    /// path so session-scoped policies stack on top of global ones.
    async fn execute_with_optional_session(
        &self,
        proposal: &ActionProposal,
        session_id: Option<&str>,
        scope: Option<&crate::scope::RuntimeScope>,
        cancel: &tokio_util::sync::CancellationToken,
    ) -> ProposalResult {
        let config = self.replan_config.read().await.clone();
        let mut current_proposal = proposal.clone();
        let mut attempt: u32 = 0;

        // Phase 3 foundation (Parslee-ai/car#187): record the scope
        // on the event log so audit / log analysis can correlate
        // actions to the caller / tenant that triggered them. Only
        // logged when at least one identity field is set — keeps
        // the existing in-process call sites free of noise.
        if let Some(s) = scope {
            if !s.is_unscoped() {
                let mut props: HashMap<String, Value> = HashMap::new();
                if let Some(cid) = &s.caller_id {
                    props.insert("caller_id".to_string(), Value::from(cid.as_str()));
                }
                if let Some(tid) = &s.tenant_id {
                    props.insert("tenant_id".to_string(), Value::from(tid.as_str()));
                }
                if !s.claims.is_empty() {
                    if let Ok(claims_json) = serde_json::to_value(&s.claims) {
                        props.insert("claims".to_string(), claims_json);
                    }
                }
                let mut log = self.log.lock().await;
                log.append(EventKind::SessionScope, None, Some(&proposal.id), props);
            }
        }

        // Pre-execution transactional conflict check (survey §4.3/§5.2.4).
        // Off by default; Warn records conflicts; Strict rejects the whole
        // proposal before any action runs, since a transactional conflict is
        // a property of the action *set* against current state, not an
        // isolated action. This is an advisory planning-time gate, not a
        // substitute for per-action execution-time validation. Replanned
        // proposals are re-checked inside the loop (at the replan quality
        // gate below). A pre-execution rejection here deliberately produces
        // no execution trajectory — nothing ran; the emitted
        // `TransactionConflict` events are the audit record.
        let blocked = self.transaction_precheck(&current_proposal).await;
        if !blocked.is_empty() {
            let results = current_proposal
                .actions
                .iter()
                .map(|a| {
                    rejected_result(
                        &a.id,
                        "transactional conflict with current shared state (strict mode); \
                         see TransactionConflict events for details and resolution"
                            .to_string(),
                    )
                })
                .collect();
            return ProposalResult {
                proposal_id: proposal.id.clone(),
                results,
                cost: Default::default(),
            };
        }

        // Pre-execution admission gates (EPIC A / task A1 — the safety
        // seam). Runs every registered AdmissionGate against the proposal
        // before any action executes. Aggregation is conjunctive and
        // fail-closed: a proposal any gate blocks (or escalates to
        // approval) does not run. Like the transactional pre-check above, a
        // rejection here produces no execution trajectory — the emitted
        // AdmissionGateDecision events are the audit record. No gates
        // registered → zero overhead, identical behavior.
        let admission = self
            .run_admission_gates(&current_proposal, session_id, scope)
            .await;
        if !admission.admitted {
            let gate = admission.deciding_gate.as_deref().unwrap_or("admission");
            let base_reason = admission
                .reason
                .clone()
                .unwrap_or_else(|| "blocked by admission gate".to_string());
            // Resolve approval escalations against the durable ledger (A7).
            // A hard `Reject` from ANY gate is never overridable — the
            // ledger is not consulted at all in that case (an old approval
            // for one gate's escalation must not steamroll another gate's
            // deny). Otherwise EVERY escalation must resolve to Approved,
            // each by its own fingerprint: one Rejected fingerprint blocks,
            // one unseen fingerprint stays pending (fail-closed).
            let mut approved = false;
            let reason = if admission.hard_rejected {
                format!("{base_reason} (gate: {gate})")
            } else if admission.needs_approval() {
                let mut blocking_reason = None;
                for esc in &admission.escalations {
                    match self.admission_decision(&esc.fingerprint).await {
                        Some(ApprovalDecision::Approved) => continue,
                        Some(ApprovalDecision::Rejected) => {
                            blocking_reason = Some(format!(
                                "rejected by operator (gate: {}; fingerprint: {})",
                                esc.gate, esc.fingerprint
                            ));
                            break;
                        }
                        None => {
                            blocking_reason = Some(format!(
                                "requires human approval (gate: {}; {}); \
                                 approve fingerprint '{}' then re-run",
                                esc.gate, esc.reason, esc.fingerprint
                            ));
                            break;
                        }
                    }
                }
                match blocking_reason {
                    None => {
                        approved = true;
                        // Audit every durable approval taking effect.
                        let mut log = self.log.lock().await;
                        for esc in &admission.escalations {
                            log.append(
                                EventKind::ApprovalRecorded,
                                None,
                                Some(&proposal.id),
                                [
                                    (
                                        "fingerprint".to_string(),
                                        Value::from(esc.fingerprint.as_str()),
                                    ),
                                    ("gate".to_string(), Value::from(esc.gate.as_str())),
                                    ("approval".to_string(), Value::from("approved")),
                                    ("applied".to_string(), Value::from(true)),
                                ]
                                .into(),
                            );
                        }
                        String::new()
                    }
                    Some(r) => r,
                }
            } else {
                format!("{base_reason} (gate: {gate})")
            };
            if approved {
                // Escalation cleared by a durable approval — proceed to
                // execution as if admitted.
            } else {
            let results = current_proposal
                .actions
                .iter()
                .map(|a| {
                    // Name the specific reason on the offending actions; a
                    // generic note on the rest (the whole proposal is held,
                    // since a safety hazard is a property of the set).
                    if admission.blocked.is_empty() || admission.blocked.contains(&a.id) {
                        rejected_result(&a.id, reason.clone())
                    } else {
                        rejected_result(
                            &a.id,
                            format!("proposal blocked by admission gate: {gate}"),
                        )
                    }
                })
                .collect();
            return ProposalResult {
                proposal_id: proposal.id.clone(),
                results,
                cost: Default::default(),
            };
            }
        }

        loop {
            let (result, state_before_map) = self
                .execute_inner_with_cancel(&current_proposal, Some(cancel), session_id, scope)
                .await;

            // Statuses that trigger rollback + replan: always runtime Failed,
            // and (opt-in) validator/policy/capability Rejected.
            let replan_triggers = |s: &ActionStatus| {
                *s == ActionStatus::Failed
                    || (config.replan_on_rejected && *s == ActionStatus::Rejected)
            };

            // Check if we aborted
            let aborted = result.results.iter().any(|r| replan_triggers(&r.status));
            if !aborted || attempt >= config.max_replans {
                if aborted && attempt > 0 {
                    // Exhausted all replan attempts
                    let mut log = self.log.lock().await;
                    log.append(
                        EventKind::ReplanExhausted,
                        None,
                        Some(&proposal.id),
                        [("attempts".to_string(), Value::from(attempt))].into(),
                    );
                }

                // Persist trajectory
                let outcome = if !aborted {
                    if attempt > 0 {
                        car_memgine::TrajectoryOutcome::ReplanSuccess
                    } else {
                        car_memgine::TrajectoryOutcome::Success
                    }
                } else if attempt > 0 {
                    car_memgine::TrajectoryOutcome::ReplanExhausted
                } else {
                    car_memgine::TrajectoryOutcome::Failed
                };
                if let Some(err) = self.persist_trajectory(
                    proposal,
                    &current_proposal,
                    &result,
                    outcome,
                    attempt,
                    &state_before_map,
                ) {
                    let mut log = self.log.lock().await;
                    log.append(
                        EventKind::ActionFailed,
                        None,
                        Some(&proposal.id),
                        [(
                            "trajectory_persist_error".to_string(),
                            Value::from(err.as_str()),
                        )]
                        .into(),
                    );
                }

                return result;
            }

            // Get replan callback (clone Arc, drop lock immediately)
            let callback = {
                let guard = self.replan_callback.lock().await;
                guard.clone()
            };
            let Some(callback) = callback else {
                // No callback registered — persist trajectory and return
                if let Some(err) = self.persist_trajectory(
                    proposal,
                    &current_proposal,
                    &result,
                    car_memgine::TrajectoryOutcome::Failed,
                    attempt,
                    &state_before_map,
                ) {
                    let mut log = self.log.lock().await;
                    log.append(
                        EventKind::ActionFailed,
                        None,
                        Some(&proposal.id),
                        [(
                            "trajectory_persist_error".to_string(),
                            Value::from(err.as_str()),
                        )]
                        .into(),
                    );
                }
                return result;
            };

            // Build replan context
            let failed_actions: Vec<FailedActionSummary> = result
                .results
                .iter()
                .filter(|r| replan_triggers(&r.status))
                .map(|r| {
                    let action = current_proposal
                        .actions
                        .iter()
                        .find(|a| a.id == r.action_id);
                    FailedActionSummary {
                        action_id: r.action_id.clone(),
                        tool: action.and_then(|a| a.tool.clone()),
                        error: r.error.clone().unwrap_or_default(),
                        parameters: action.map(|a| a.parameters.clone()).unwrap_or_default(),
                    }
                })
                .collect();

            let completed_action_ids: Vec<String> = result
                .results
                .iter()
                .filter(|r| r.status == ActionStatus::Succeeded)
                .map(|r| r.action_id.clone())
                .collect();

            let ctx = ReplanContext {
                proposal_id: proposal.id.clone(),
                attempt: attempt + 1,
                failed_actions,
                completed_action_ids,
                state_snapshot: self.state.snapshot(),
                replans_remaining: config.max_replans.saturating_sub(attempt + 1),
                original_source: proposal.source.clone(),
                original_action_count: proposal.actions.len(),
                original_context: proposal.context.clone(),
            };

            // Backoff delay between replan attempts
            if config.delay_ms > 0 {
                tokio::time::sleep(Duration::from_millis(config.delay_ms)).await;
            }

            // Log replan attempt
            {
                let mut log = self.log.lock().await;
                log.append(
                    EventKind::ReplanAttempted,
                    None,
                    Some(&proposal.id),
                    [
                        ("attempt".to_string(), Value::from(attempt + 1)),
                        (
                            "failed_count".to_string(),
                            Value::from(ctx.failed_actions.len()),
                        ),
                    ]
                    .into(),
                );
                // Deep-telemetry breadcrumbs (§3.5.1): record the fork the
                // harness took (replan vs accept vs abandon) and the
                // approach it discarded, so failure-mode diagnosis can see
                // the path *not* taken, not just the path taken.
                let rejected_ids: Vec<String> = ctx
                    .failed_actions
                    .iter()
                    .map(|f| f.action_id.clone())
                    .collect();
                log.append(
                    EventKind::BranchDecision,
                    None,
                    Some(&proposal.id),
                    [
                        ("branch".to_string(), Value::from("replan")),
                        (
                            "reason".to_string(),
                            Value::from("actions failed; requesting a revised plan"),
                        ),
                        ("attempt".to_string(), Value::from(attempt + 1)),
                    ]
                    .into(),
                );
                log.append(
                    EventKind::AlternativeRejected,
                    None,
                    Some(&proposal.id),
                    [
                        (
                            "alternative".to_string(),
                            serde_json::to_value(&rejected_ids).unwrap_or_default(),
                        ),
                        (
                            "reason".to_string(),
                            Value::from("plan superseded by replan after action failure"),
                        ),
                    ]
                    .into(),
                );
            }

            // Call the model for a new plan
            match callback.replan(&ctx).await {
                Ok(new_proposal) => {
                    // Quality gate: verify replan proposal before executing
                    if config.verify_before_execute {
                        let current_state = self.state.snapshot();
                        // Verify against the full registered schemas
                        // (not just names) so a replan with a bad
                        // parameter type / missing required field is
                        // rejected here, per register_tool_schema's
                        // contract (car-releases#56). The read guard is
                        // held across the synchronous verify call.
                        let tools_guard = self.tools.read().await;
                        let vr = car_verify::verify_with_schemas(
                            &new_proposal,
                            Some(&current_state),
                            Some(&tools_guard),
                            100,
                        );
                        drop(tools_guard);
                        if !vr.valid {
                            let error_msgs: Vec<String> = vr
                                .issues
                                .iter()
                                .filter(|i| i.severity == "error")
                                .map(|i| i.message.clone())
                                .collect();
                            let mut log = self.log.lock().await;
                            log.append(
                                EventKind::ReplanRejected,
                                None,
                                Some(&proposal.id),
                                [
                                    ("errors".to_string(), Value::from(error_msgs.join("; "))),
                                    ("attempt".to_string(), Value::from(attempt + 1)),
                                ]
                                .into(),
                            );
                            // Don't execute a broken replan — count as failed attempt
                            attempt += 1;
                            continue;
                        }
                    }

                    // Transactional re-check of the replan against the now-
                    // mutated shared state (neo review #1): a replan runs
                    // after earlier actions changed state, so it's exactly
                    // where a fresh stale-assumption/write conflict appears.
                    // A Strict conflict rejects this replan attempt via the
                    // same bounded ReplanRejected path (capped by
                    // max_replans), never an infinite loop.
                    let replan_blocked = self.transaction_precheck(&new_proposal).await;
                    if !replan_blocked.is_empty() {
                        let mut log = self.log.lock().await;
                        log.append(
                            EventKind::ReplanRejected,
                            None,
                            Some(&proposal.id),
                            [
                                (
                                    "errors".to_string(),
                                    Value::from("transactional conflict with current state"),
                                ),
                                ("attempt".to_string(), Value::from(attempt + 1)),
                            ]
                            .into(),
                        );
                        drop(log);
                        attempt += 1;
                        continue;
                    }

                    // Admission gates re-run on EVERY replanned proposal
                    // (linus review C-2): the replan callback is exactly
                    // where injected/adversarial content reshapes a plan,
                    // so a proposal that was clean at first admission must
                    // not smuggle a hazardous replan past the gates. Same
                    // fail-closed contract as first admission — a hard
                    // reject or any unapproved escalation rejects this
                    // replan attempt (bounded by max_replans).
                    let replan_admission = self
                        .run_admission_gates(&new_proposal, session_id, scope)
                        .await;
                    if !replan_admission.admitted {
                        let mut cleared = !replan_admission.hard_rejected
                            && replan_admission.needs_approval();
                        if cleared {
                            for esc in &replan_admission.escalations {
                                if self.admission_decision(&esc.fingerprint).await
                                    != Some(ApprovalDecision::Approved)
                                {
                                    cleared = false;
                                    break;
                                }
                            }
                        }
                        if !cleared {
                            let gate = replan_admission
                                .deciding_gate
                                .as_deref()
                                .unwrap_or("admission");
                            let why = replan_admission
                                .reason
                                .clone()
                                .unwrap_or_else(|| "blocked by admission gate".to_string());
                            let mut log = self.log.lock().await;
                            log.append(
                                EventKind::ReplanRejected,
                                None,
                                Some(&proposal.id),
                                [
                                    (
                                        "errors".to_string(),
                                        Value::from(format!(
                                            "admission gate blocked replan (gate: {gate}; {why})"
                                        )),
                                    ),
                                    ("attempt".to_string(), Value::from(attempt + 1)),
                                ]
                                .into(),
                            );
                            drop(log);
                            attempt += 1;
                            continue;
                        }
                    }

                    // Log accepted proposal
                    {
                        let mut log = self.log.lock().await;
                        log.append(
                            EventKind::ReplanProposalReceived,
                            None,
                            Some(&proposal.id),
                            [
                                ("attempt".to_string(), Value::from(attempt + 1)),
                                (
                                    "new_action_count".to_string(),
                                    Value::from(new_proposal.actions.len()),
                                ),
                            ]
                            .into(),
                        );
                    }
                    current_proposal = new_proposal;
                    attempt += 1;
                }
                Err(e) => {
                    // Replan callback itself failed — log and return original failure
                    let mut log = self.log.lock().await;
                    log.append(
                        EventKind::ReplanExhausted,
                        None,
                        Some(&proposal.id),
                        [
                            ("reason".to_string(), Value::from("callback_error")),
                            ("error".to_string(), Value::from(e.as_str())),
                            ("attempt".to_string(), Value::from(attempt + 1)),
                        ]
                        .into(),
                    );
                    if let Some(err) = self.persist_trajectory(
                        proposal,
                        &current_proposal,
                        &result,
                        car_memgine::TrajectoryOutcome::Failed,
                        attempt,
                        &state_before_map,
                    ) {
                        log.append(
                            EventKind::ActionFailed,
                            None,
                            Some(&proposal.id),
                            [(
                                "trajectory_persist_error".to_string(),
                                Value::from(err.as_str()),
                            )]
                            .into(),
                        );
                    }
                    return result;
                }
            }
        }
    }

    /// Persist a trajectory to the store if configured.
    fn persist_trajectory(
        &self,
        proposal: &ActionProposal,
        current_proposal: &ActionProposal,
        result: &ProposalResult,
        outcome: car_memgine::TrajectoryOutcome,
        attempt: u32,
        state_before_map: &HashMap<String, HashMap<String, Value>>,
    ) -> Option<String> {
        let store = self.trajectory_store.as_ref()?;

        let trace_events: Vec<car_memgine::TraceEvent> = result
            .results
            .iter()
            .map(|r| {
                let kind = match r.status {
                    ActionStatus::Succeeded => "action_succeeded",
                    ActionStatus::Failed => "action_failed",
                    ActionStatus::Rejected => "action_rejected",
                    ActionStatus::Skipped => "action_skipped",
                    _ => "unknown",
                };
                let tool = current_proposal
                    .actions
                    .iter()
                    .find(|a| a.id == r.action_id)
                    .and_then(|a| a.tool.clone());
                let reward = match r.status {
                    ActionStatus::Succeeded => Some(1.0),
                    ActionStatus::Failed => Some(0.0),
                    ActionStatus::Rejected => Some(0.0),
                    ActionStatus::Skipped => None,
                    _ => None,
                };
                car_memgine::TraceEvent {
                    kind: kind.to_string(),
                    action_id: Some(r.action_id.clone()),
                    tool,
                    data: r
                        .error
                        .as_ref()
                        .map(|e| serde_json::json!({"error": e}))
                        .unwrap_or(serde_json::json!({})),
                    duration_ms: r.duration_ms,
                    state_before: state_before_map.get(&r.action_id).cloned(),
                    state_after: if !r.state_changes.is_empty() {
                        Some(r.state_changes.clone())
                    } else {
                        None
                    },
                    reward,
                }
            })
            .collect();

        let trajectory = car_memgine::Trajectory {
            proposal_id: proposal.id.clone(),
            source: proposal.source.clone(),
            action_count: current_proposal.actions.len(),
            events: trace_events,
            outcome,
            timestamp: chrono::Utc::now(),
            duration_ms: result.cost.total_duration_ms,
            replan_attempts: attempt,
        };

        match store.append(&trajectory) {
            Ok(()) => None,
            Err(e) => Some(e.to_string()),
        }
    }

    /// Score N candidate proposals, execute the best valid one, fall back to
    /// next-best on failure. Combines car-planner scoring with engine execution.
    ///
    /// Returns the result from whichever proposal was executed (best or fallback).
    /// If all candidates fail verification, returns an error result for the first.
    pub async fn plan_and_execute(
        &self,
        candidates: &[ActionProposal],
        planner_config: Option<car_planner::PlannerConfig>,
        feedback: Option<&car_planner::ToolFeedback>,
    ) -> ProposalResult {
        if candidates.is_empty() {
            return ProposalResult {
                proposal_id: "empty".to_string(),
                results: vec![],
                cost: car_ir::CostSummary::default(),
            };
        }

        // Score all candidates
        let planner = car_planner::Planner::new(planner_config.unwrap_or_default());
        let tools_guard = self.tools.read().await;
        let tool_names: std::collections::HashSet<String> = tools_guard.keys().cloned().collect();
        drop(tools_guard);

        let pre_plan_snapshot = self.state.snapshot();
        let pre_plan_transitions = self.state.transition_count();
        let ranked = planner.rank_with_feedback(
            candidates,
            Some(&pre_plan_snapshot),
            Some(&tool_names),
            feedback,
        );

        // Try each valid candidate in score order
        let mut first_failure: Option<ProposalResult> = None;
        for scored in &ranked {
            if !scored.valid {
                continue;
            }

            // Restore clean state before each candidate (don't rely on execute's
            // internal rollback — it only fires on Abort, not Skip/Retry failures)
            self.state
                .restore(pre_plan_snapshot.clone(), pre_plan_transitions);

            let proposal = &candidates[scored.index];
            let result = self.execute(proposal).await;

            if result.all_succeeded() {
                return result;
            }

            tracing::info!(
                proposal_id = %proposal.id,
                score = scored.score,
                "plan_and_execute: proposal failed, trying next candidate"
            );

            if first_failure.is_none() {
                first_failure = Some(result);
            }
        }

        // Return the first failure result (don't re-execute — avoids duplicate side effects)
        first_failure.unwrap_or_else(|| ProposalResult {
            proposal_id: candidates[0].id.clone(),
            results: vec![],
            cost: car_ir::CostSummary::default(),
        })
    }

    /// Execute a single proposal through the runtime loop (no replanning).
    /// Returns (result, state_before_map) where state_before_map has per-action snapshots.
    ///
    /// `session_id`, when `Some`, scopes per-action policy validation
    /// to the named session in addition to global policies. Both
    /// layers must pass for an action to run; the session layer cannot
    /// loosen what global denies.
    async fn execute_inner_with_cancel(
        &self,
        proposal: &ActionProposal,
        cancel: Option<&tokio_util::sync::CancellationToken>,
        session_id: Option<&str>,
        scope: Option<&crate::scope::RuntimeScope>,
    ) -> (ProposalResult, HashMap<String, HashMap<String, Value>>) {
        // Whether validator/policy/capability rejections should count toward
        // the abort-and-replan path (default false). Read once up front so the
        // per-action loop doesn't take the replan_config lock repeatedly (and
        // never inside join_all). Independent lock from log/tools/policies/
        // capabilities, so no lock-ordering conflict.
        let replan_on_rejected = self.replan_config.read().await.replan_on_rejected;

        // Generate trace_id for this proposal execution
        let trace_id = Uuid::new_v4().to_string();

        // Begin root span for proposal execution
        let root_span_id = {
            let mut log = self.log.lock().await;
            log.begin_span(
                "proposal.execute",
                &trace_id,
                None,
                [("proposal_id".to_string(), Value::from(proposal.id.as_str()))].into(),
            )
        };

        // Log proposal received
        {
            let mut log = self.log.lock().await;
            log.append(
                EventKind::ProposalReceived,
                None,
                Some(&proposal.id),
                [
                    ("source".to_string(), Value::from(proposal.source.as_str())),
                    (
                        "action_count".to_string(),
                        Value::from(proposal.actions.len()),
                    ),
                ]
                .into(),
            );
        }

        // Capability check: max_actions budget for entire proposal
        {
            let caps = self.capabilities.read().await;
            if let Some(ref cap) = *caps {
                if !cap.actions_within_budget(proposal.actions.len() as u32) {
                    let mut action_results = Vec::new();
                    for action in &proposal.actions {
                        action_results.push(rejected_result(
                            &action.id,
                            format!(
                                "capability denied: proposal has {} actions, max allowed is {:?}",
                                proposal.actions.len(),
                                cap.max_actions
                            ),
                        ));
                    }
                    return (
                        ProposalResult {
                            proposal_id: proposal.id.clone(),
                            results: action_results,
                            cost: CostSummary::default(),
                        },
                        HashMap::new(),
                    );
                }
            }
        }

        // Snapshot for rollback. When the proposal carries a tenant scope,
        // snapshot only that tenant's namespace so a rollback can't clobber
        // concurrent tenants' state (EPIC E / E2). No tenant → unchanged
        // full snapshot.
        let rollback_tenant: Option<&str> = scope.and_then(|s| s.tenant_id.as_deref());
        let snapshot = match rollback_tenant {
            Some(_) => self.state.snapshot_scoped(rollback_tenant),
            None => self.state.snapshot(),
        };
        let transition_count = self.state.transition_count();

        let mut results: Vec<ActionResult> = Vec::new();
        // Per-action state snapshots captured before execution (for TraceEvent.state_before).
        let mut state_before_map: HashMap<String, HashMap<String, Value>> = HashMap::new();
        let mut aborted = false;
        let mut budget_exceeded = false;
        let mut total_retries: u32 = 0;

        // Running cost counters for budget enforcement
        let mut running_tool_calls: u32 = 0;
        let mut running_actions: u32 = 0;
        let mut running_duration_ms: f64 = 0.0;

        // Snapshot the budget once
        let budget = self.cost_budget.read().await.clone();

        // Build DAG
        let levels = build_dag(&proposal.actions);

        let mut canceled = false;
        for level in &levels {
            // Cooperative cancellation check at the level boundary.
            // Actions already in flight aren't interrupted (we can't
            // safely cancel a tool call dispatched to a user-provided
            // executor), but every action that hadn't started runs
            // is recorded as canceled with a clear reason.
            if !canceled {
                if let Some(token) = cancel {
                    if token.is_cancelled() {
                        canceled = true;
                    }
                }
            }
            if canceled {
                for &idx in level {
                    results.push(canceled_result(
                        &proposal.actions[idx].id,
                        "cancellation requested by caller",
                    ));
                }
                continue;
            }
            if aborted || budget_exceeded {
                let skip_reason = if budget_exceeded {
                    "cost budget exceeded"
                } else {
                    "skipped due to earlier abort"
                };
                for &idx in level {
                    results.push(skipped_result(&proposal.actions[idx].id, skip_reason));
                }
                continue;
            }

            // Check if any action in this level has ABORT behavior
            let has_abort = level
                .iter()
                .any(|&i| proposal.actions[i].failure_behavior == FailureBehavior::Abort);

            if level.len() == 1 || has_abort {
                // Sequential execution
                for &idx in level {
                    if aborted || budget_exceeded {
                        let skip_reason = if budget_exceeded {
                            "cost budget exceeded"
                        } else {
                            "skipped due to abort"
                        };
                        results.push(skipped_result(&proposal.actions[idx].id, skip_reason));
                        continue;
                    }

                    // Budget check before execution
                    if let Some(ref b) = budget {
                        if let Some(max) = b.max_actions {
                            if running_actions >= max {
                                budget_exceeded = true;
                                results.push(skipped_result(
                                    &proposal.actions[idx].id,
                                    "cost budget exceeded",
                                ));
                                continue;
                            }
                        }
                        if let Some(max) = b.max_tool_calls {
                            if proposal.actions[idx].action_type == ActionType::ToolCall
                                && running_tool_calls >= max
                            {
                                budget_exceeded = true;
                                results.push(skipped_result(
                                    &proposal.actions[idx].id,
                                    "cost budget exceeded",
                                ));
                                continue;
                            }
                        }
                        if let Some(max) = b.max_duration_ms {
                            if running_duration_ms >= max {
                                budget_exceeded = true;
                                results.push(skipped_result(
                                    &proposal.actions[idx].id,
                                    "cost budget exceeded",
                                ));
                                continue;
                            }
                        }
                    }

                    state_before_map.insert(
                        proposal.actions[idx].id.clone(),
                        snapshot_relevant_keys(&self.state, &proposal.actions[idx]),
                    );
                    let (ar, action_retries) = self
                        .process_action(
                            &proposal.actions[idx],
                            &proposal.id,
                            &trace_id,
                            &root_span_id,
                            session_id,
                            scope,
                        )
                        .await;
                    total_retries += action_retries;

                    // Update running counters
                    if ar.status == ActionStatus::Succeeded
                        && proposal.actions[idx].action_type == ActionType::ToolCall
                    {
                        running_tool_calls += 1;
                    }
                    if ar.status != ActionStatus::Skipped {
                        running_actions += 1;
                    }
                    if let Some(d) = ar.duration_ms {
                        running_duration_ms += d;
                    }

                    if (ar.status == ActionStatus::Failed
                        || (replan_on_rejected && ar.status == ActionStatus::Rejected))
                        && proposal.actions[idx].failure_behavior == FailureBehavior::Abort
                    {
                        aborted = true;
                    }
                    results.push(ar);
                }
            } else {
                // Concurrent execution via futures::join_all
                // Snapshot only relevant keys per action (all see same pre-level state)
                for &idx in level {
                    state_before_map.insert(
                        proposal.actions[idx].id.clone(),
                        snapshot_relevant_keys(&self.state, &proposal.actions[idx]),
                    );
                }
                let futs: Vec<_> = level
                    .iter()
                    .map(|&idx| {
                        self.process_action(
                            &proposal.actions[idx],
                            &proposal.id,
                            &trace_id,
                            &root_span_id,
                            session_id,
                            scope,
                        )
                    })
                    .collect();
                let level_results = futures::future::join_all(futs).await;

                for (i, (ar, action_retries)) in level_results.into_iter().enumerate() {
                    let idx = level[i];
                    total_retries += action_retries;
                    if ar.status == ActionStatus::Succeeded
                        && proposal.actions[idx].action_type == ActionType::ToolCall
                    {
                        running_tool_calls += 1;
                    }
                    if ar.status != ActionStatus::Skipped {
                        running_actions += 1;
                    }
                    if let Some(d) = ar.duration_ms {
                        running_duration_ms += d;
                    }
                    results.push(ar);
                }
            }
        }

        // Handle rollback
        if aborted {
            // Tenant-scoped rollback when the proposal is tenant-scoped
            // (EPIC E / E2), else the full restore.
            match rollback_tenant {
                Some(_) => {
                    self.state
                        .restore_scoped(rollback_tenant, snapshot.clone(), transition_count)
                }
                None => self.state.restore(snapshot.clone(), transition_count),
            }

            let mut log = self.log.lock().await;
            log.append(
                EventKind::StateSnapshot,
                None,
                Some(&proposal.id),
                [(
                    "state".to_string(),
                    serde_json::to_value(&snapshot).unwrap_or_default(),
                )]
                .into(),
            );
            log.append(
                EventKind::StateRollback,
                None,
                Some(&proposal.id),
                [(
                    "rolled_back_to".to_string(),
                    Value::from("pre-proposal snapshot"),
                )]
                .into(),
            );

            // Clear idempotency cache for rolled-back actions
            let mut invalidated: Vec<String> = Vec::new();
            {
                let mut cache = self.idempotency_cache.lock().await;
                for r in &results {
                    if r.status == ActionStatus::Succeeded {
                        for action in &proposal.actions {
                            if action.id == r.action_id && action.idempotent {
                                let key = idempotency_key(action, scope);
                                cache.remove(&key);
                                invalidated.push(key);
                            }
                        }
                    }
                }
            }
            // Record tombstones so the durable journal (C3) doesn't resurrect
            // a rolled-back result on reload.
            for key in &invalidated {
                self.journal_idempotency(key, None).await;
            }
        }

        // Sort results to match original action order
        let action_order: HashMap<String, usize> = proposal
            .actions
            .iter()
            .enumerate()
            .map(|(i, a)| (a.id.clone(), i))
            .collect();
        results.sort_by_key(|r| {
            action_order
                .get(&r.action_id)
                .copied()
                .unwrap_or(usize::MAX)
        });

        // Compute cost summary from results
        let mut cost = CostSummary::default();
        for r in &results {
            let action = action_order
                .get(&r.action_id)
                .and_then(|&i| proposal.actions.get(i));
            match r.status {
                ActionStatus::Succeeded => {
                    cost.actions_executed += 1;
                    if let Some(a) = action {
                        if a.action_type == ActionType::ToolCall {
                            cost.tool_calls += 1;
                        }
                    }
                }
                ActionStatus::Failed | ActionStatus::Rejected => {
                    cost.actions_executed += 1;
                }
                ActionStatus::Skipped => {
                    cost.actions_skipped += 1;
                }
                _ => {}
            }
            if let Some(d) = r.duration_ms {
                cost.total_duration_ms += d;
            }
        }

        // Set retries from inline counter
        cost.retries = total_retries;

        // End root span — Ok if no abort, Error if aborted
        {
            let span_status = if aborted {
                SpanStatus::Error
            } else {
                SpanStatus::Ok
            };
            let mut log = self.log.lock().await;
            log.end_span(&root_span_id, span_status);
        }

        let proposal_result = ProposalResult {
            proposal_id: proposal.id.clone(),
            results,
            cost,
        };

        // Post-execution: auto-distill skills from this execution trace
        if self.auto_distill {
            if let Some(ref memgine) = self.memgine {
                // Convert results to TraceEvents for distillation
                let trace_events: Vec<car_memgine::TraceEvent> = proposal_result
                    .results
                    .iter()
                    .map(|r| {
                        let kind = match r.status {
                            ActionStatus::Succeeded => "action_succeeded",
                            ActionStatus::Failed => "action_failed",
                            ActionStatus::Rejected => "action_rejected",
                            ActionStatus::Skipped => "action_skipped",
                            _ => "unknown",
                        };
                        // Find the matching action to get the tool name
                        let tool = proposal
                            .actions
                            .iter()
                            .find(|a| a.id == r.action_id)
                            .and_then(|a| a.tool.clone());
                        let mut data = serde_json::Map::new();
                        if let Some(ref e) = r.error {
                            data.insert("error".into(), Value::from(e.as_str()));
                        }
                        if let Some(ref o) = r.output {
                            data.insert("output".into(), o.clone());
                        }
                        car_memgine::TraceEvent {
                            kind: kind.to_string(),
                            action_id: Some(r.action_id.clone()),
                            tool,
                            data: Value::Object(data),
                            duration_ms: r.duration_ms,
                            reward: match r.status {
                                ActionStatus::Succeeded => Some(1.0),
                                ActionStatus::Failed | ActionStatus::Rejected => Some(0.0),
                                _ => None,
                            },
                            ..Default::default()
                        }
                    })
                    .collect();

                let mut engine = memgine.lock().await;
                let skills = engine.distill_skills(&trace_events).await;
                if !skills.is_empty() {
                    let count = skills.len();
                    // Validation-gated ingest (SkillOpt-inspired). Distilled
                    // skills are NOT trusted straight into the active pool; each
                    // enters as a PROVISIONAL candidate on trial and must prove
                    // itself (or beat its incumbent) before the promotion gate in
                    // consolidate() makes it Active. Tenant is threaded through so
                    // candidates are stamped for the calling tenant's namespace.
                    let tenant = scope.and_then(|s| s.tenant_id.as_deref());
                    let provisional = engine.ingest_provisional_candidates(&skills, tenant);

                    // Log the distillation event
                    let mut log = self.log.lock().await;
                    log.append(
                        EventKind::SkillDistilled,
                        None,
                        Some(&proposal_result.proposal_id),
                        [
                            ("skills_count".to_string(), Value::from(count)),
                            ("provisional_ingested".to_string(), Value::from(provisional)),
                            (
                                "skill_names".to_string(),
                                Value::from(
                                    skills.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(),
                                ),
                            ),
                        ]
                        .into(),
                    );

                    // Check if any domains need evolution
                    let threshold = engine.evolution_threshold();
                    let domains = engine.domains_needing_evolution(threshold);
                    for domain in &domains {
                        // Collect failed events for this domain
                        let failed: Vec<car_memgine::TraceEvent> = trace_events
                            .iter()
                            .filter(|e| {
                                matches!(e.kind.as_str(), "action_failed" | "action_rejected")
                            })
                            .cloned()
                            .collect();
                        if !failed.is_empty() {
                            let evolved = engine.evolve_skills(&failed, domain).await;
                            if !evolved.is_empty() {
                                log.append(
                                    EventKind::EvolutionTriggered,
                                    None,
                                    Some(&proposal_result.proposal_id),
                                    [
                                        ("domain".to_string(), Value::from(domain.as_str())),
                                        ("new_skills".to_string(), Value::from(evolved.len())),
                                    ]
                                    .into(),
                                );
                            }
                        }
                    }
                }
            }
        }

        (proposal_result, state_before_map)
    }

    /// Process a single action: capability → validate → policy → idempotency → execute.
    /// (Idempotency dedup runs AFTER the deny checks — review C3: a durable
    /// cached result must never outlive a tool's revocation.)
    /// Returns (ActionResult, retries_count).
    async fn process_action(
        &self,
        action: &Action,
        proposal_id: &str,
        trace_id: &str,
        parent_span_id: &str,
        session_id: Option<&str>,
        scope: Option<&crate::scope::RuntimeScope>,
    ) -> (ActionResult, u32) {
        // Derive action type name for span naming
        let action_type_name = serde_json::to_string(&action.action_type)
            .unwrap_or_default()
            .trim_matches('"')
            .to_string();
        let span_name = format!("action.{}", action_type_name);

        // Begin child span for this action
        let action_span_id = {
            let mut attrs: HashMap<String, Value> = HashMap::new();
            attrs.insert("action_id".to_string(), Value::from(action.id.as_str()));
            if let Some(ref tool) = action.tool {
                attrs.insert("tool".to_string(), Value::from(tool.as_str()));
            }
            let mut log = self.log.lock().await;
            log.begin_span(&span_name, trace_id, Some(parent_span_id), attrs)
        };

        // Execute the action pipeline and capture result
        let (result, retries) = self
            .process_action_inner(action, proposal_id, session_id, scope)
            .await;

        // End action span based on result status
        let span_status = match result.status {
            ActionStatus::Succeeded => SpanStatus::Ok,
            ActionStatus::Failed | ActionStatus::Rejected => SpanStatus::Error,
            _ => SpanStatus::Unset,
        };
        {
            let mut log = self.log.lock().await;
            log.end_span(&action_span_id, span_status);
        }

        (result, retries)
    }

    /// Inner action processing: idempotency -> validate -> policy -> execute.
    /// Returns (ActionResult, retries_count).
    #[instrument(
        name = "action.process",
        skip_all,
        fields(
            action_id = %action.id,
            action_type = ?action.action_type,
            tool = action.tool.as_deref().unwrap_or("none"),
        )
    )]
    async fn process_action_inner(
        &self,
        action: &Action,
        proposal_id: &str,
        session_id: Option<&str>,
        scope: Option<&crate::scope::RuntimeScope>,
    ) -> (ActionResult, u32) {
        // Capability check
        {
            let caps = self.capabilities.read().await;
            if let Some(ref cap) = *caps {
                // Check tool capability for ToolCall actions
                if action.action_type == ActionType::ToolCall {
                    if let Some(ref tool_name) = action.tool {
                        if !cap.tool_allowed(tool_name) {
                            let mut log = self.log.lock().await;
                            log.append(
                                EventKind::ActionRejected,
                                Some(&action.id),
                                Some(proposal_id),
                                HashMap::new(),
                            );
                            return (
                                rejected_result(
                                    &action.id,
                                    format!("capability denied: tool '{}' not allowed", tool_name),
                                ),
                                0,
                            );
                        }
                    }
                }

                // Check state key capability for StateWrite/StateRead actions
                if action.action_type == ActionType::StateWrite
                    || action.action_type == ActionType::StateRead
                {
                    if let Some(key) = action.parameters.get("key").and_then(|v| v.as_str()) {
                        if !cap.state_key_allowed(key) {
                            let mut log = self.log.lock().await;
                            log.append(
                                EventKind::ActionRejected,
                                Some(&action.id),
                                Some(proposal_id),
                                HashMap::new(),
                            );
                            return (
                                rejected_result(
                                    &action.id,
                                    format!("capability denied: state key '{}' not allowed", key),
                                ),
                                0,
                            );
                        }
                    }
                }
            }
        }

        // Validate
        let tools = self.tools.read().await;
        let validation = validate_action(action, &self.state, &tools);
        drop(tools);

        if !validation.valid() {
            let error = validation
                .errors
                .iter()
                .map(|e| e.reason.as_str())
                .collect::<Vec<_>>()
                .join("; ");
            let mut log = self.log.lock().await;
            log.append(
                EventKind::ActionRejected,
                Some(&action.id),
                Some(proposal_id),
                HashMap::new(),
            );
            return (rejected_result(&action.id, error), 0);
        }

        // Policy check — global registry plus, when the proposal is
        // executed under a session, that session's registry. Both
        // layers must pass for the action to proceed; session
        // policies are additive deny rules — they can deny what
        // global allows but cannot allow what global denies.
        {
            let mut violations = {
                let policies = self.policies.read().await;
                policies.check(action, &self.state)
            };
            if let Some(sid) = session_id {
                // Snapshot the per-session engine handle out from under
                // the outer registry lock so the inner check holds
                // only the engine's own RwLock — preserves the
                // documented lock-ordering discipline.
                let session_engine = {
                    let sessions = self.session_policies.read().await;
                    sessions.get(sid).cloned()
                };
                if let Some(engine) = session_engine {
                    let engine = engine.read().await;
                    violations.extend(engine.check(action, &self.state));
                } else {
                    // Unknown session id — refuse the action rather
                    // than silently fall back to global-only. A
                    // proposal submitted under a closed session
                    // shouldn't run with looser rules than the caller
                    // intended.
                    let mut log = self.log.lock().await;
                    log.append(
                        EventKind::PolicyViolation,
                        Some(&action.id),
                        Some(proposal_id),
                        HashMap::new(),
                    );
                    return (
                        rejected_result(
                            &action.id,
                            format!(
                                "unknown session id '{sid}' — open one via Runtime::open_session before executing under a session"
                            ),
                        ),
                        0,
                    );
                }
            }
            if !violations.is_empty() {
                let error = violations
                    .iter()
                    .map(|v| format!("policy '{}': {}", v.policy_name, v.reason))
                    .collect::<Vec<_>>()
                    .join("; ");
                let mut log = self.log.lock().await;
                log.append(
                    EventKind::PolicyViolation,
                    Some(&action.id),
                    Some(proposal_id),
                    HashMap::new(),
                );
                return (rejected_result(&action.id, error), 0);
            }
        }

        // Idempotency check — deliberately AFTER capability + policy
        // (linus review C3): with the durable journal, a cached result
        // consulted first would let a tool that is denied TODAY serve
        // yesterday's cached result after every restart, forever. Deny
        // rules must win over dedup.
        if action.idempotent && !action.invocation_mode.is_detached() {
            let key = idempotency_key(action, scope);
            let cache = self.idempotency_cache.lock().await;
            if let Some(cached) = cache.get(&key) {
                let mut log = self.log.lock().await;
                log.append(
                    EventKind::ActionDeduplicated,
                    Some(&action.id),
                    Some(proposal_id),
                    [(
                        "cached_action_id".to_string(),
                        Value::from(cached.action_id.as_str()),
                    )]
                    .into(),
                );
                return (
                    ActionResult {
                        action_id: action.id.clone(),
                        status: cached.status.clone(),
                        output: cached.output.clone(),
                        error: cached.error.clone(),
                        state_changes: cached.state_changes.clone(),
                        duration_ms: Some(0.0),
                        timestamp: chrono::Utc::now(),
                    },
                    0,
                );
            }
        }

        // Validated
        {
            let mut log = self.log.lock().await;
            log.append(
                EventKind::ActionValidated,
                Some(&action.id),
                Some(proposal_id),
                HashMap::new(),
            );
        }

        // Execute with retry
        let (result, retries) = self.execute_with_retry(action, proposal_id, scope).await;

        // Cache idempotent results. Detached invocations are exempt
        // (linus review D4): their Succeeded output is a live tool
        // HANDLE, exactly as uncacheable here as in the result cache —
        // deduping would return a stale handle instead of starting the
        // tool, and journaling would replay a handle id that doesn't
        // exist in a fresh registry after restart.
        if action.idempotent
            && !action.invocation_mode.is_detached()
            && result.status == ActionStatus::Succeeded
        {
            let key = idempotency_key(action, scope);
            {
                let mut cache = self.idempotency_cache.lock().await;
                cache.insert(key.clone(), result.clone());
            }
            // Persist to the durable journal (C3) so the result survives a
            // restart and the action isn't re-executed.
            self.journal_idempotency(&key, Some(&result)).await;
        }

        tracing::info!(
            status = ?result.status,
            duration_ms = result.duration_ms,
            "action completed"
        );

        (result, retries)
    }

    /// Execute with retry logic and timeout.
    /// Returns (ActionResult, retries_count).
    async fn execute_with_retry(
        &self,
        action: &Action,
        proposal_id: &str,
        scope: Option<&crate::scope::RuntimeScope>,
    ) -> (ActionResult, u32) {
        // The harness config (Evolution Agent, §3.5), when installed, caps
        // the per-action retry budget and sets the inter-attempt backoff —
        // this is where an applied retry-config mutation actually takes
        // effect. `None` (the default) preserves prior behavior exactly.
        let hc = self.harness_config.read().await.clone();
        let retry_cap = hc.as_ref().map(|c| c.max_retries).unwrap_or(u32::MAX);
        let backoff_override = hc.as_ref().map(|c| c.retry_backoff_ms).filter(|&v| v > 0);
        let max_attempts = if action.failure_behavior == FailureBehavior::Retry {
            action.max_retries.min(retry_cap) + 1
        } else {
            1
        };

        let mut last_error: Option<String> = None;
        let mut retries: u32 = 0;

        for attempt in 0..max_attempts {
            if attempt > 0 {
                retries += 1;
                // Base delay from the harness config when installed (an
                // applied retry-config mutation), else the built-in default.
                let base = backoff_override.unwrap_or(RETRY_BASE_DELAY_MS);
                let delay = base * RETRY_BACKOFF_FACTOR.pow(attempt as u32 - 1);
                tokio::time::sleep(Duration::from_millis(delay)).await;
                let mut log = self.log.lock().await;
                log.append(
                    EventKind::ActionRetrying,
                    Some(&action.id),
                    Some(proposal_id),
                    [("attempt".to_string(), Value::from(attempt + 1))].into(),
                );
            }

            {
                let mut log = self.log.lock().await;
                log.append(
                    EventKind::ActionExecuting,
                    Some(&action.id),
                    Some(proposal_id),
                    HashMap::new(),
                );
            }

            let start = std::time::Instant::now();
            let transitions_before = self.state.transition_count();

            // Execute with optional timeout
            let exec_result = if let Some(timeout_ms) = action.timeout_ms {
                match timeout(
                    Duration::from_millis(timeout_ms),
                    self.dispatch(action, scope),
                )
                .await
                {
                    Ok(r) => r,
                    Err(_) => Err(format!("action timed out after {}ms", timeout_ms)),
                }
            } else {
                self.dispatch(action, scope).await
            };

            let duration_ms = start.elapsed().as_secs_f64() * 1000.0;

            match exec_result {
                Ok(output) => {
                    // Commit post-effects. Tenant-scoped when the
                    // proposal carries a scope (Parslee-ai/car#187
                    // phase 3) — distinct tenants write to disjoint
                    // namespaces so concurrent multi-tenant proposals
                    // don't trample each other's keys.
                    let tenant_for_effects = scope.and_then(|s| s.tenant_id.as_deref());
                    let scoped_state = self.state.scoped(tenant_for_effects);
                    let mut state_changes: HashMap<String, Value> = HashMap::new();
                    for (key, value) in &action.expected_effects {
                        scoped_state.set(key, value.clone(), &action.id);
                        state_changes.insert(key.clone(), value.clone());
                    }

                    // Capture state changes from dispatch
                    for t in self.state.transitions_since(transitions_before) {
                        if !state_changes.contains_key(&t.key) {
                            if let Some(v) = t.new_value {
                                state_changes.insert(t.key.clone(), v);
                            }
                        }
                    }

                    let mut log = self.log.lock().await;
                    // Record the tool name + result count so the tool-receipt
                    // verifier (A6) can project ground-truth receipts from the
                    // log and catch tool-use hallucinations.
                    let mut succ_data: HashMap<String, Value> = HashMap::new();
                    if let Some(tool) = &action.tool {
                        succ_data.insert("tool".to_string(), Value::from(tool.as_str()));
                        succ_data.insert("ok".to_string(), Value::from(true));
                        if let Value::Array(arr) = &output {
                            succ_data
                                .insert("result_count".to_string(), Value::from(arr.len() as u64));
                        }
                    }
                    // Record duration through the standardized metric path
                    // (§3.5.1) so it feeds `EventLog::metrics_totals` via the
                    // same contract as inference token metrics — one path,
                    // not a coincidentally-matching `"duration_ms"` string.
                    log.append_metered(
                        EventKind::ActionSucceeded,
                        Some(&action.id),
                        Some(proposal_id),
                        succ_data,
                        car_eventlog::Metrics::latency(duration_ms),
                    );

                    if !state_changes.is_empty() {
                        log.append(
                            EventKind::StateChanged,
                            Some(&action.id),
                            Some(proposal_id),
                            [(
                                "changes".to_string(),
                                serde_json::to_value(&state_changes).unwrap_or_default(),
                            )]
                            .into(),
                        );
                    }

                    return (
                        ActionResult {
                            action_id: action.id.clone(),
                            status: ActionStatus::Succeeded,
                            output: Some(output),
                            error: None,
                            state_changes,
                            duration_ms: Some(duration_ms),
                            timestamp: chrono::Utc::now(),
                        },
                        retries,
                    );
                }
                Err(e) => {
                    last_error = Some(e.clone());
                    let mut log = self.log.lock().await;
                    let mut fail_data: HashMap<String, Value> = [
                        ("error".to_string(), Value::from(e.as_str())),
                        ("attempt".to_string(), Value::from(attempt + 1)),
                    ]
                    .into();
                    // Tool name + ok=false so the receipt verifier (A6) records
                    // that the tool *executed* (a failed call still ran).
                    if let Some(tool) = &action.tool {
                        fail_data.insert("tool".to_string(), Value::from(tool.as_str()));
                        fail_data.insert("ok".to_string(), Value::from(false));
                    }
                    log.append(
                        EventKind::ActionFailed,
                        Some(&action.id),
                        Some(proposal_id),
                        fail_data,
                    );
                }
            }
        }

        // All attempts exhausted
        if action.failure_behavior == FailureBehavior::Skip {
            return (
                skipped_result(
                    &action.id,
                    last_error.as_deref().unwrap_or("all attempts exhausted"),
                ),
                retries,
            );
        }

        (
            ActionResult {
                action_id: action.id.clone(),
                status: ActionStatus::Failed,
                output: None,
                error: last_error,
                state_changes: HashMap::new(),
                duration_ms: None,
                timestamp: chrono::Utc::now(),
            },
            retries,
        )
    }

    /// Dispatch an action to the appropriate handler.
    ///
    /// `scope` is the per-execution caller / tenant surface
    /// (Parslee-ai/car#187 phase 3). When the scope carries a
    /// tenant id, state R/W operations (`StateWrite`, `StateRead`,
    /// `Assertion`) route through `StateStore::scoped(tenant_id)`
    /// so distinct tenants can't see each other's keys. Unscoped
    /// proposals get the legacy flat-namespace behaviour
    /// automatically.
    async fn dispatch(
        &self,
        action: &Action,
        scope: Option<&crate::scope::RuntimeScope>,
    ) -> Result<Value, String> {
        match action.action_type {
            ActionType::ToolCall => {
                let tool_name = action.tool.as_deref().ok_or("tool_call has no tool")?;
                let params = Value::Object(
                    action
                        .parameters
                        .iter()
                        .map(|(k, v)| (k.clone(), v.clone()))
                        .collect(),
                );

                // Detached invocation modes (C2): start the tool via the
                // configured executor's streaming entry point, register a
                // handle, and return immediately — the DAG must not block
                // on a streaming/long-running tool. Deliberately BEFORE
                // the result cache (a handle is a live invocation, never a
                // cacheable value) but still behind the rate limiter.
                // Built-ins don't stream; a detached call requires a
                // configured executor that implements execute_stream.
                if action.invocation_mode.is_detached() {
                    self.rate_limiter.acquire(tool_name).await;
                    let configured = {
                        let guard = self.tool_executor.lock().await;
                        guard.as_ref().cloned()
                    };
                    let executor = configured.ok_or_else(|| {
                        format!(
                            "tool '{tool_name}': detached invocation requires a tool executor"
                        )
                    })?;
                    let rx = executor
                        .execute_stream(tool_name, &params, &action.id)
                        .await?;
                    let (handle, cancel) =
                        self.tool_handles.register(tool_name, &action.id).await;
                    crate::tool_handles::spawn_drain(
                        self.tool_handles.clone(),
                        handle.id.clone(),
                        rx,
                        cancel,
                    );
                    return Ok(serde_json::json!({
                        "tool_handle": handle.id,
                        "status": "running",
                    }));
                }

                // Check cross-proposal result cache.
                if let Some(cached) = self.result_cache.get(tool_name, &params).await {
                    return Ok(cached);
                }

                // Apply rate limit backpressure before executing.
                self.rate_limiter.acquire(tool_name).await;

                // Try built-in inference tools first when the inference engine is available.
                if matches!(
                    tool_name,
                    "infer" | "infer.grounded" | "embed" | "classify" | "transcribe" | "synthesize"
                ) {
                    if let Some(ref engine) = self.inference_engine {
                        // For "infer.grounded" or "infer" with memgine available,
                        // build context from memory and attach it to the request.
                        let params = {
                            let should_ground =
                                tool_name == "infer.grounded" || tool_name == "infer";
                            if should_ground {
                                if let Some(ref memgine) = self.memgine {
                                    if let Some(prompt) =
                                        params.get("prompt").and_then(|v| v.as_str())
                                    {
                                        let ctx = {
                                            let mut m = memgine.lock().await;
                                            m.build_context(prompt)
                                        };
                                        if !ctx.is_empty() {
                                            let mut p = params.clone();
                                            if let Some(obj) = p.as_object_mut() {
                                                obj.insert("context".to_string(), Value::from(ctx));
                                            }
                                            p
                                        } else {
                                            params
                                        }
                                    } else {
                                        params
                                    }
                                } else {
                                    params
                                }
                            } else {
                                params
                            }
                        };

                        // Route "infer.grounded" to "infer" for the service layer
                        let effective_tool = if tool_name == "infer.grounded" {
                            "infer"
                        } else {
                            tool_name
                        };
                        let result =
                            car_inference::service::execute_tool(engine, effective_tool, &params)
                                .await
                                .map_err(|e| e.to_string());

                        if let Ok(ref value) = result {
                            self.result_cache
                                .put(tool_name, &params, value.clone())
                                .await;
                        }

                        return result;
                    }
                }

                // Built-in memory consolidation tool.
                if tool_name == "memory.consolidate" {
                    if let Some(ref memgine) = self.memgine {
                        let report = {
                            let mut m = memgine.lock().await;
                            m.consolidate().await
                        };
                        // Log the consolidation event
                        {
                            let mut log = self.log.lock().await;
                            log.append(
                                EventKind::Consolidated,
                                None,
                                None,
                                [
                                    (
                                        "expired_pruned".to_string(),
                                        Value::from(report.expired_pruned),
                                    ),
                                    (
                                        "superseded_gc".to_string(),
                                        Value::from(report.superseded_gc),
                                    ),
                                    (
                                        "stale_embeddings_removed".to_string(),
                                        Value::from(report.stale_embeddings_removed),
                                    ),
                                    (
                                        "nodes_embedded".to_string(),
                                        Value::from(report.nodes_embedded),
                                    ),
                                    (
                                        "domains_evolved".to_string(),
                                        Value::from(report.domains_evolved.clone()),
                                    ),
                                    ("total_nodes".to_string(), Value::from(report.total_nodes)),
                                    ("total_edges".to_string(), Value::from(report.total_edges)),
                                ]
                                .into(),
                            );
                            // Per-candidate gate telemetry (SkillOpt-inspired):
                            // one event per promotion/rejection so the skill
                            // bank's evolution is auditable.
                            for key in &report.candidates_promoted {
                                log.append(
                                    EventKind::CandidatePromoted,
                                    None,
                                    None,
                                    [("candidate".to_string(), Value::from(key.as_str()))].into(),
                                );
                            }
                            for key in &report.candidates_rejected {
                                log.append(
                                    EventKind::CandidateRejected,
                                    None,
                                    None,
                                    [("candidate".to_string(), Value::from(key.as_str()))].into(),
                                );
                            }
                        }
                        return Ok(serde_json::to_value(&report).unwrap_or(Value::Null));
                    } else {
                        return Err(
                            "memory.consolidate requires memgine (attach with with_learning)"
                                .into(),
                        );
                    }
                }

                // Prefer a configured tool_executor for any tool it claims to handle.
                // Fall through to agent_basics only when the configured executor is absent
                // or explicitly returns "unknown tool" — this prevents agent_basics' built-in
                // read_file/write_file (which resolve paths via std::env::current_dir) from
                // silently overriding an executor that carries its own working_dir.
                let configured = {
                    let guard = self.tool_executor.lock().await;
                    guard.as_ref().cloned()
                };

                if let Some(ref executor) = configured {
                    let result = executor
                        .execute_with_action(tool_name, &params, &action.id, action.timeout_ms)
                        .await;
                    let fall_through = matches!(&result, Err(e) if e.starts_with("unknown tool"));
                    if !fall_through {
                        if let Ok(ref value) = result {
                            self.result_cache
                                .put(tool_name, &params, value.clone())
                                .await;
                        }
                        return result;
                    }
                }

                // Built-in commodity tools resolve against the bound substrate
                // (default: LocalSubstrate → historic host behavior). `calculate`
                // stays pure inside agent_basics and ignores the substrate.
                let substrate = self.substrate.read().await.clone();
                if let Some(result) =
                    crate::agent_basics::execute(&substrate, tool_name, &params).await
                {
                    if let Ok(ref value) = result {
                        self.result_cache
                            .put(tool_name, &params, value.clone())
                            .await;
                    }
                    return result;
                }

                Err(format!("no handler for tool '{}'", tool_name))
            }
            ActionType::StateWrite => {
                let key = action
                    .parameters
                    .get("key")
                    .and_then(|v| v.as_str())
                    .ok_or("state_write requires 'key' parameter")?;
                let value = action
                    .parameters
                    .get("value")
                    .cloned()
                    .unwrap_or(Value::Null);
                let tenant = scope.and_then(|s| s.tenant_id.as_deref());
                self.state.scoped(tenant).set(key, value, &action.id);
                Ok(Value::from(format!("written: {}", key)))
            }
            ActionType::StateRead => {
                let key = action
                    .parameters
                    .get("key")
                    .and_then(|v| v.as_str())
                    .ok_or("state_read requires 'key' parameter")?;
                let tenant = scope.and_then(|s| s.tenant_id.as_deref());
                Ok(self.state.scoped(tenant).get(key).unwrap_or(Value::Null))
            }
            ActionType::Assertion => {
                let key = action
                    .parameters
                    .get("key")
                    .and_then(|v| v.as_str())
                    .ok_or("assertion requires 'key' parameter")?;
                let expected = action
                    .parameters
                    .get("expected")
                    .cloned()
                    .unwrap_or(Value::Null);
                let tenant = scope.and_then(|s| s.tenant_id.as_deref());
                let actual = self.state.scoped(tenant).get(key).unwrap_or(Value::Null);
                if actual != expected {
                    Err(format!(
                        "assertion failed: state['{}'] = {:?}, expected {:?}",
                        key, actual, expected
                    ))
                } else {
                    Ok(serde_json::json!({"asserted": key, "value": actual}))
                }
            }
        }
    }

    // --- Checkpoint and resume ---

    /// Save a checkpoint of the current runtime state.
    pub async fn save_checkpoint(&self) -> Checkpoint {
        let state = self.state.snapshot();
        let tools: Vec<String> = self.tools.read().await.keys().cloned().collect();
        let log = self.log.lock().await;
        let events: Vec<Value> = log
            .events()
            .iter()
            .map(|e| serde_json::to_value(e).unwrap_or_default())
            .collect();

        Checkpoint {
            checkpoint_id: Uuid::new_v4().to_string(),
            created_at: chrono::Utc::now(),
            state,
            events,
            tools,
            metadata: HashMap::new(),
        }
    }

    /// Save checkpoint to a JSON file.
    pub async fn save_checkpoint_to_file(&self, path: &str) -> Result<(), String> {
        let checkpoint = self.save_checkpoint().await;
        let json = serde_json::to_string_pretty(&checkpoint)
            .map_err(|e| format!("serialize error: {}", e))?;
        tokio::fs::write(path, json)
            .await
            .map_err(|e| format!("write error: {}", e))?;
        Ok(())
    }

    /// Load a checkpoint from a JSON file and restore state.
    pub async fn load_checkpoint_from_file(&self, path: &str) -> Result<Checkpoint, String> {
        let json = tokio::fs::read_to_string(path)
            .await
            .map_err(|e| format!("read error: {}", e))?;
        let checkpoint: Checkpoint =
            serde_json::from_str(&json).map_err(|e| format!("deserialize error: {}", e))?;
        self.restore_checkpoint(&checkpoint).await;
        Ok(checkpoint)
    }

    /// Restore runtime state from a checkpoint.
    pub async fn restore_checkpoint(&self, checkpoint: &Checkpoint) {
        // Replace state completely — don't merge, don't create synthetic transitions
        self.state.replace_all(checkpoint.state.clone());
        // Clear idempotency cache — stale results from pre-checkpoint execution
        // must not bypass validation/policy on the restored state
        self.idempotency_cache.lock().await.clear();
        // Restore tools (as name-only schemas; full schemas are not persisted in checkpoint)
        let mut tools = self.tools.write().await;
        tools.clear();
        for tool_name in &checkpoint.tools {
            let schema = ToolSchema {
                name: tool_name.clone(),
                description: String::new(),
                parameters: serde_json::Value::Object(Default::default()),
                returns: None,
                idempotent: false,
                cache_ttl_secs: None,
                rate_limit: None,
            };
            tools.insert(tool_name.clone(), schema);
        }
    }

    /// Register a subprocess tool and set up the subprocess executor.
    /// If no executor exists, creates a new SubprocessToolExecutor.
    /// If one already exists, creates a new SubprocessToolExecutor with the
    /// existing executor as fallback.
    pub async fn register_subprocess_tool(
        &self,
        name: &str,
        tool: crate::subprocess::SubprocessTool,
    ) {
        use crate::subprocess::SubprocessToolExecutor;

        let schema = ToolSchema {
            name: name.to_string(),
            description: format!("Subprocess tool: {}", tool.command),
            parameters: serde_json::Value::Object(Default::default()),
            returns: None,
            idempotent: false,
            cache_ttl_secs: None,
            rate_limit: None,
        };
        self.register_tool_schema(schema).await;

        let mut guard = self.tool_executor.lock().await;
        let mut executor = match guard.take() {
            Some(existing) => {
                let mut sub = SubprocessToolExecutor::new();
                sub = sub.with_fallback(existing);
                sub
            }
            None => SubprocessToolExecutor::new(),
        };
        executor.register(name, tool);
        *guard = Some(std::sync::Arc::new(executor));
    }
}

impl Default for Runtime {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod timeout_integration_tests {
    //! Integration coverage for the #259/#262 timeout coordination the unit
    //! tests in `car-server-core` / `car-ffi-common` only exercise as pure
    //! selection helpers (#266 item 4): that the executor's per-action deadline
    //! reaps a slow dispatch first, and that `action.timeout_ms` flows
    //! end-to-end onto `execute_with_action`.
    use super::*;
    use car_ir::ActionProposal;
    use std::sync::atomic::{AtomicU64, Ordering};

    /// A tool executor that (a) records the `timeout_ms` it was handed and
    /// (b) sleeps `delay_ms` before returning, so a test can prove the
    /// executor's own `timeout(action.timeout_ms, dispatch)` reaps a call that
    /// outlives its budget.
    struct RecordingExecutor {
        seen_timeout_ms: Arc<AtomicU64>,
        delay_ms: u64,
    }

    #[async_trait::async_trait]
    impl ToolExecutor for RecordingExecutor {
        async fn execute(&self, _tool: &str, _params: &Value) -> Result<Value, String> {
            Ok(Value::Null)
        }
        async fn execute_with_action(
            &self,
            _tool: &str,
            _params: &Value,
            _action_id: &str,
            timeout_ms: Option<u64>,
        ) -> Result<Value, String> {
            // `u64::MAX` sentinel = "None was passed".
            self.seen_timeout_ms
                .store(timeout_ms.unwrap_or(u64::MAX), Ordering::SeqCst);
            tokio::time::sleep(Duration::from_millis(self.delay_ms)).await;
            Ok(serde_json::json!({ "ok": true }))
        }
    }

    fn one_tool_proposal(timeout_ms: Option<u64>) -> ActionProposal {
        let mut action = serde_json::json!({
            "id": "a0",
            "type": "tool_call",
            "tool": "slow",
            "parameters": {},
            "dependencies": [],
        });
        if let Some(ms) = timeout_ms {
            action["timeout_ms"] = serde_json::json!(ms);
        }
        serde_json::from_value(serde_json::json!({
            "source": "test",
            "actions": [action],
        }))
        .expect("proposal deserializes")
    }

    #[tokio::test]
    async fn action_timeout_ms_reaches_executor_and_reaps_slow_dispatch() {
        let seen = Arc::new(AtomicU64::new(0));
        let rt = Runtime::new();
        rt.register_tool("slow").await;
        rt.set_executor(Arc::new(RecordingExecutor {
            seen_timeout_ms: seen.clone(),
            delay_ms: 2_000, // outlives the 100ms budget below
        }))
        .await;

        // 100ms budget against a 2s dispatch: the executor's own
        // `timeout(action.timeout_ms, dispatch)` must reap it (#262 — the
        // executor is the authority), and the budget must have reached
        // `execute_with_action` (the #262 harness→action propagation, proven
        // end-to-end here rather than only via the pure helper).
        let result = rt.execute(&one_tool_proposal(Some(100))).await;
        assert_eq!(
            seen.load(Ordering::SeqCst),
            100,
            "budget must reach the executor"
        );
        let action_result = &result.results[0];
        assert!(
            action_result
                .error
                .as_deref()
                .unwrap_or("")
                .contains("timed out"),
            "slow dispatch must be reaped by the action deadline: {:?}",
            action_result.error
        );
    }

    #[tokio::test]
    async fn no_budget_applies_no_executor_deadline() {
        // The `None` path: the executor applies NO deadline, so a dispatch that
        // outlives any per-attempt budget still completes (the WS callback wait
        // is the sole bound on that path, exercised in car-server-core). Here a
        // 300ms dispatch with no budget must succeed, not be reaped.
        let seen = Arc::new(AtomicU64::new(0));
        let rt = Runtime::new();
        rt.register_tool("slow").await;
        rt.set_executor(Arc::new(RecordingExecutor {
            seen_timeout_ms: seen.clone(),
            delay_ms: 300,
        }))
        .await;

        let result = rt.execute(&one_tool_proposal(None)).await;
        assert_eq!(
            seen.load(Ordering::SeqCst),
            u64::MAX,
            "None budget must be forwarded as None"
        );
        assert_eq!(result.results[0].status, ActionStatus::Succeeded);
    }
}