stateknot-runtime 0.1.0-alpha.1

Executable registries and durable graph driving for StateKnot
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
// Copyright 2026 StateKnot contributors
// SPDX-License-Identifier: Apache-2.0

//! Durable-before-dispatch model and tool attempt execution.

use std::{
    error::Error as StdError,
    fmt,
    future::poll_fn,
    sync::Arc,
    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};

use serde_json::json;
use stateknot_core::{
    AgentResultProvenance, AttemptId, BoundedJson, BoxFuture, BudgetRemaining, CancellationSignal,
    Digest, DurationMillis, EventId, ExecutionCount, Failure, FailureCategory, FailureCode,
    FailureId, FailureMessage, FailureOrigin, GraphSchemaValidationError, InvocationId,
    JournalAppend, JournalEvent, JournalEventIntent, JournalEventKind, JournalExpectation,
    JournalPayload, ModelContext, ModelContextError, ModelError, ModelErrorPhase,
    ModelErrorProvenance, ModelEvent, ModelEventAccumulator, ModelInvocation,
    ModelInvocationStatus, ModelInvocationTransition, ModelRequest, ModelResponse,
    ModelResponseMode, ModelStopReason, RetryAdvice, RunFence, SchemaReference, Timestamp,
    ToolContext, ToolContextError, ToolDescriptor, ToolError, ToolErrorPhase, ToolErrorProvenance,
    ToolExternalEffect, ToolInputValidationError, ToolInvocation, ToolInvocationError,
    ToolInvocationState, ToolInvocationStatus, ToolInvocationTransition, ToolProgressSink,
    ToolReconciliationContext, ToolReconciliationContextError, ToolReconciliationObservation,
    ToolReconciliationObservationError, ToolReconciliationProbeError, ToolResult, ToolRisk,
    ToolStopReason,
};
use stateknot_store_postgres::{
    ModelInvocationCommitOutcome, PostgresStore, StoreError, ToolInvocationCommitOutcome,
};
use thiserror::Error;

use crate::{
    JsonSchemaRegistry, ModelProviderRegistry, ModelProviderRegistryError,
    StandardInvocationExecutionSchemaError, ToolProviderRegistry, ToolProviderRegistryError,
    standard_invocation_execution_event_schema,
};

const MAX_MUTATION_RETRY_DELAY: Duration = Duration::from_secs(1);

/// Trusted wall/monotonic clock pair captured at one process observation.
#[derive(Clone, Copy, Debug)]
pub struct InvocationClockObservation {
    observed_at: Timestamp,
    observed_instant: Instant,
}

impl InvocationClockObservation {
    /// Constructs one trusted paired observation.
    #[must_use]
    pub const fn new(observed_at: Timestamp, observed_instant: Instant) -> Self {
        Self {
            observed_at,
            observed_instant,
        }
    }

    /// Returns the wall-clock component used for durable budget decisions.
    #[must_use]
    pub const fn observed_at(self) -> Timestamp {
        self.observed_at
    }

    /// Returns the paired monotonic observation used for active deadlines.
    #[must_use]
    pub const fn observed_instant(self) -> Instant {
        self.observed_instant
    }
}

/// Trusted clock source for attempt contexts.
pub trait InvocationClock: Send + Sync + 'static {
    /// Captures paired wall and monotonic observations.
    fn observe(&self) -> Result<InvocationClockObservation, InvocationClockError>;
}

/// Production system/monotonic clock implementation.
#[derive(Clone, Copy, Debug, Default)]
pub struct SystemInvocationClock;

impl InvocationClock for SystemInvocationClock {
    fn observe(&self) -> Result<InvocationClockObservation, InvocationClockError> {
        let observed_instant = Instant::now();
        let elapsed = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_err(|_| InvocationClockError::BeforeUnixEpoch)?;
        let micros = i64::try_from(elapsed.as_micros())
            .map_err(|_| InvocationClockError::TimestampOutOfRange)?;
        let observed_at = Timestamp::from_unix_micros(micros)
            .map_err(|_| InvocationClockError::TimestampOutOfRange)?;
        Ok(InvocationClockObservation::new(
            observed_at,
            observed_instant,
        ))
    }
}

/// Failure to capture a representable runtime clock observation.
#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum InvocationClockError {
    /// Host wall time preceded the Unix epoch.
    #[error("invocation system clock precedes the Unix epoch")]
    BeforeUnixEpoch,
    /// Host wall time exceeded the canonical timestamp range.
    #[error("invocation system clock is outside the supported timestamp range")]
    TimestampOutOfRange,
}

/// Closed external boundary whose next-attempt budget is requested.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum InvocationBoundaryKind {
    /// One model provider attempt.
    Model,
    /// One tool implementation attempt.
    Tool,
}

/// Payload-free trusted request to an admission/accounting implementation.
#[derive(Clone, Debug)]
pub struct InvocationBudgetContext {
    provenance: AgentResultProvenance,
    boundary: InvocationBoundaryKind,
    invocation_id: InvocationId,
    attempt_id: AttemptId,
    intent_digest: Digest,
    observed_at: Timestamp,
}

impl InvocationBudgetContext {
    /// Returns immutable admitted run provenance loaded from storage.
    #[must_use]
    pub const fn provenance(&self) -> &AgentResultProvenance {
        &self.provenance
    }

    /// Returns the external boundary being admitted.
    #[must_use]
    pub const fn boundary(&self) -> InvocationBoundaryKind {
        self.boundary
    }

    /// Returns the stable logical invocation identity.
    #[must_use]
    pub const fn invocation_id(&self) -> InvocationId {
        self.invocation_id
    }

    /// Returns the proposed physical attempt identity.
    #[must_use]
    pub const fn attempt_id(&self) -> AttemptId {
        self.attempt_id
    }

    /// Returns the exact durable invocation-intent checksum.
    #[must_use]
    pub const fn intent_digest(&self) -> Digest {
        self.intent_digest
    }

    /// Returns the trusted clock used to evaluate remaining capacity.
    #[must_use]
    pub const fn observed_at(&self) -> Timestamp {
        self.observed_at
    }
}

/// Trusted admission/accounting source for exact remaining run capacity.
///
/// Implementations load the immutable resolved budget and cumulative durable
/// DIRECT-only usage by `provenance`, recheck the intent/attempt admission policy, and
/// return a finite [`BudgetRemaining`] evaluated at `observed_at`. The executor
/// never accepts a caller-authored remaining-budget value directly. The executor
/// deducts verified child subtree charges exactly once, then binds their account
/// digest to the durable start transaction. Providers must not include children.
pub trait InvocationBudgetProvider: Send + Sync + 'static {
    /// Resolves exact remaining capacity before a durable attempt start.
    fn remaining(
        &self,
        context: InvocationBudgetContext,
    ) -> BoxFuture<'_, Result<BudgetRemaining, InvocationBudgetProviderError>>;
}

type PrivateBudgetSource = dyn StdError + Send + Sync + 'static;

fn deduct_child_budget(
    remaining: BudgetRemaining,
    account: Option<&stateknot_core::ChildRunBudgetAccount>,
) -> Result<BudgetRemaining, StoreError> {
    let Some(account) = account else {
        return Ok(remaining);
    };
    if account
        .children()
        .iter()
        .any(|entry| entry.settlement().is_none())
    {
        return Err(StoreError::UnsettledChildRuns);
    }
    remaining
        .deduct_cumulative(
            &account
                .delegated_usage()
                .map_err(|_| StoreError::IncompleteChildAccounting)?,
        )
        .map_err(|_| StoreError::IncompleteChildAccounting)
}

/// Payload-redacted trusted accounting-provider failure.
#[derive(Clone)]
pub struct InvocationBudgetProviderError {
    private_source: Arc<PrivateBudgetSource>,
}

impl InvocationBudgetProviderError {
    /// Wraps one private admission/accounting diagnostic.
    #[must_use]
    pub fn new<E>(source: E) -> Self
    where
        E: StdError + Send + Sync + 'static,
    {
        Self {
            private_source: Arc::new(source),
        }
    }

    /// Returns the private source to trusted in-process diagnostics only.
    #[must_use]
    pub fn private_source(&self) -> &(dyn StdError + Send + Sync + 'static) {
        self.private_source.as_ref()
    }
}

impl fmt::Debug for InvocationBudgetProviderError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("InvocationBudgetProviderError")
            .field("has_private_source", &true)
            .finish_non_exhaustive()
    }
}

impl fmt::Display for InvocationBudgetProviderError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("invocation budget provider failed")
    }
}

impl StdError for InvocationBudgetProviderError {}

/// Runtime-owned sink for already validated semantic model stream events.
///
/// Implementations must durably deduplicate by `(attempt_id, sequence)` before
/// exposing events externally. A successful future asserts ordered acceptance;
/// the final accumulated response remains authoritative only after its separate
/// invocation-ledger commit.
pub trait ModelEventSink: Send + Sync + 'static {
    /// Accepts one identity-bound, contiguous semantic event.
    fn emit(&self, event: ModelEvent) -> BoxFuture<'_, Result<(), ModelEventSinkError>>;
}

type PrivateEventSinkSource = dyn StdError + Send + Sync + 'static;

/// Payload-redacted model event sink failure.
#[derive(Clone)]
pub struct ModelEventSinkError {
    private_source: Arc<PrivateEventSinkSource>,
}

impl ModelEventSinkError {
    /// Wraps one private durable-sink diagnostic.
    #[must_use]
    pub fn new<E>(source: E) -> Self
    where
        E: StdError + Send + Sync + 'static,
    {
        Self {
            private_source: Arc::new(source),
        }
    }

    /// Returns the private source to trusted in-process diagnostics only.
    #[must_use]
    pub fn private_source(&self) -> &(dyn StdError + Send + Sync + 'static) {
        self.private_source.as_ref()
    }
}

impl fmt::Debug for ModelEventSinkError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ModelEventSinkError")
            .field("has_private_source", &true)
            .finish_non_exhaustive()
    }
}

impl fmt::Display for ModelEventSinkError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("model event sink failed")
    }
}

impl StdError for ModelEventSinkError {}

/// Stable start and terminal event identities for one physical attempt.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct InvocationAttemptEventIds {
    start: EventId,
    terminal: EventId,
}

impl InvocationAttemptEventIds {
    /// Binds two distinct preallocated event identities.
    ///
    /// # Errors
    ///
    /// Rejects identity reuse between start and terminal facts.
    pub fn new(start: EventId, terminal: EventId) -> Result<Self, InvocationAttemptEventIdsError> {
        if start == terminal {
            return Err(InvocationAttemptEventIdsError::Duplicate);
        }
        Ok(Self { start, terminal })
    }

    /// Generates two `UUIDv7` identities for a newly retained handoff.
    #[must_use]
    pub fn generate() -> Self {
        Self {
            start: EventId::generate(),
            terminal: EventId::generate(),
        }
    }

    /// Returns the durable-before-dispatch start event identity.
    #[must_use]
    pub const fn start(self) -> EventId {
        self.start
    }

    /// Returns the stable terminal response/error event identity.
    #[must_use]
    pub const fn terminal(self) -> EventId {
        self.terminal
    }
}

/// Invalid attempt event identity pair.
#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum InvocationAttemptEventIdsError {
    /// Start and terminal facts reused one event identity.
    #[error("invocation start and terminal event identities must be distinct")]
    Duplicate,
}

/// Retained model-attempt handoff safe to retry before physical dispatch.
#[derive(Clone)]
pub struct ModelAttemptHandoff {
    fence: RunFence,
    invocation: ModelInvocation,
    attempt_id: AttemptId,
    events: InvocationAttemptEventIds,
    cancellation: CancellationSignal,
    stream_sink: Option<Arc<dyn ModelEventSink>>,
}

impl ModelAttemptHandoff {
    /// Constructs and scope-checks one model attempt handoff.
    ///
    /// A streaming request requires a durable event sink; a complete request
    /// rejects one so event-delivery configuration cannot be silently ignored.
    ///
    /// # Errors
    ///
    /// Rejects crossed scope, a non-startable invocation state, or an invalid
    /// response-mode/sink pairing.
    pub fn new(
        fence: RunFence,
        invocation: ModelInvocation,
        attempt_id: AttemptId,
        events: InvocationAttemptEventIds,
        cancellation: CancellationSignal,
        stream_sink: Option<Arc<dyn ModelEventSink>>,
    ) -> Result<Self, InvocationAttemptHandoffError> {
        validate_model_handoff(&fence, &invocation, stream_sink.is_some())?;
        Ok(Self {
            fence,
            invocation,
            attempt_id,
            events,
            cancellation,
            stream_sink,
        })
    }

    /// Returns the exact retained worker fence.
    #[must_use]
    pub const fn fence(&self) -> &RunFence {
        &self.fence
    }

    /// Returns the prepared or safely retryable durable invocation revision.
    #[must_use]
    pub const fn invocation(&self) -> &ModelInvocation {
        &self.invocation
    }

    /// Returns the proposed unique physical provider attempt.
    #[must_use]
    pub const fn attempt_id(&self) -> AttemptId {
        self.attempt_id
    }

    /// Returns stable start/terminal journal identities.
    #[must_use]
    pub const fn events(&self) -> InvocationAttemptEventIds {
        self.events
    }
}

impl fmt::Debug for ModelAttemptHandoff {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ModelAttemptHandoff")
            .field("fence", &self.fence)
            .field("invocation_head", &self.invocation.head())
            .field("attempt_id", &self.attempt_id)
            .field("events", &self.events)
            .field("streaming", &self.stream_sink.is_some())
            .finish_non_exhaustive()
    }
}

/// Retained tool-attempt handoff safe to retry before physical dispatch.
#[derive(Clone)]
pub struct ToolAttemptHandoff {
    fence: RunFence,
    invocation: ToolInvocation,
    attempt_id: AttemptId,
    events: InvocationAttemptEventIds,
    cancellation: CancellationSignal,
    progress_sink: Option<Arc<dyn ToolProgressSink>>,
}

impl ToolAttemptHandoff {
    /// Constructs and scope-checks one tool attempt handoff.
    ///
    /// # Errors
    ///
    /// Rejects crossed scope or a non-startable durable invocation state.
    pub fn new(
        fence: RunFence,
        invocation: ToolInvocation,
        attempt_id: AttemptId,
        events: InvocationAttemptEventIds,
        cancellation: CancellationSignal,
        progress_sink: Option<Arc<dyn ToolProgressSink>>,
    ) -> Result<Self, InvocationAttemptHandoffError> {
        validate_tool_handoff(&fence, &invocation)?;
        Ok(Self {
            fence,
            invocation,
            attempt_id,
            events,
            cancellation,
            progress_sink,
        })
    }

    /// Returns the exact retained worker fence.
    #[must_use]
    pub const fn fence(&self) -> &RunFence {
        &self.fence
    }

    /// Returns the prepared or safely retryable durable invocation revision.
    #[must_use]
    pub const fn invocation(&self) -> &ToolInvocation {
        &self.invocation
    }

    /// Returns the proposed unique physical tool attempt.
    #[must_use]
    pub const fn attempt_id(&self) -> AttemptId {
        self.attempt_id
    }

    /// Returns stable start/terminal journal identities.
    #[must_use]
    pub const fn events(&self) -> InvocationAttemptEventIds {
        self.events
    }
}

impl fmt::Debug for ToolAttemptHandoff {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ToolAttemptHandoff")
            .field("fence", &self.fence)
            .field("invocation_head", &self.invocation.head())
            .field("attempt_id", &self.attempt_id)
            .field("events", &self.events)
            .field("progress", &self.progress_sink.is_some())
            .finish_non_exhaustive()
    }
}

/// Invalid durable attempt handoff.
#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum InvocationAttemptHandoffError {
    /// Fence and invocation crossed tenant/run scope.
    #[error("invocation attempt handoff crosses its retained worker fence")]
    ScopeMismatch,
    /// Invocation is executing or already terminal.
    #[error("invocation attempt handoff does not reference a startable revision")]
    InvocationNotStartable,
    /// Streaming request omitted its required durable semantic-event sink.
    #[error("streaming model attempt requires a durable event sink")]
    MissingStreamSink,
    /// Complete-response request supplied an unused stream sink.
    #[error("complete model attempt must not supply a stream event sink")]
    UnexpectedStreamSink,
}

fn validate_model_handoff(
    fence: &RunFence,
    invocation: &ModelInvocation,
    has_stream_sink: bool,
) -> Result<(), InvocationAttemptHandoffError> {
    if invocation.intent().tenant_id() != fence.tenant_id()
        || invocation.intent().run_id() != fence.run_id()
        || invocation.journal_head().tenant_id() != fence.tenant_id()
        || invocation.journal_head().run_id() != fence.run_id()
    {
        return Err(InvocationAttemptHandoffError::ScopeMismatch);
    }
    if !matches!(
        invocation.status(),
        ModelInvocationStatus::Prepared | ModelInvocationStatus::Failed
    ) {
        return Err(InvocationAttemptHandoffError::InvocationNotStartable);
    }
    match (
        invocation.intent().request().response_mode(),
        has_stream_sink,
    ) {
        (ModelResponseMode::Streaming, false) => {
            Err(InvocationAttemptHandoffError::MissingStreamSink)
        }
        (ModelResponseMode::Complete, true) => {
            Err(InvocationAttemptHandoffError::UnexpectedStreamSink)
        }
        (ModelResponseMode::Complete, false) | (ModelResponseMode::Streaming, true) => Ok(()),
    }
}

fn validate_tool_handoff(
    fence: &RunFence,
    invocation: &ToolInvocation,
) -> Result<(), InvocationAttemptHandoffError> {
    if invocation.intent().tenant_id() != fence.tenant_id()
        || invocation.intent().run_id() != fence.run_id()
        || invocation.journal_head().tenant_id() != fence.tenant_id()
        || invocation.journal_head().run_id() != fence.run_id()
    {
        return Err(InvocationAttemptHandoffError::ScopeMismatch);
    }
    if !matches!(
        invocation.status(),
        ToolInvocationStatus::Prepared | ToolInvocationStatus::Failed
    ) {
        return Err(InvocationAttemptHandoffError::InvocationNotStartable);
    }
    Ok(())
}

/// Bounded identical-mutation retry policy for invocation ledger commits.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DurableInvocationExecutorOptions {
    maximum_mutation_attempts: u8,
    mutation_retry_initial_delay: Duration,
}

impl DurableInvocationExecutorOptions {
    /// Absolute identical transaction-attempt ceiling.
    pub const HARD_MAXIMUM_MUTATION_ATTEMPTS: u8 = 10;

    /// Constructs a bounded lost-acknowledgement retry policy.
    ///
    /// # Errors
    ///
    /// Rejects zero/excessive attempts or a zero/greater-than-one-second delay.
    pub fn new(
        maximum_mutation_attempts: u8,
        mutation_retry_initial_delay: Duration,
    ) -> Result<Self, DurableInvocationExecutorOptionsError> {
        if maximum_mutation_attempts == 0
            || maximum_mutation_attempts > Self::HARD_MAXIMUM_MUTATION_ATTEMPTS
        {
            return Err(DurableInvocationExecutorOptionsError::InvalidMutationAttempts);
        }
        if mutation_retry_initial_delay.is_zero()
            || mutation_retry_initial_delay > MAX_MUTATION_RETRY_DELAY
        {
            return Err(DurableInvocationExecutorOptionsError::InvalidMutationRetryDelay);
        }
        Ok(Self {
            maximum_mutation_attempts,
            mutation_retry_initial_delay,
        })
    }

    /// Returns maximum identical database mutation attempts.
    #[must_use]
    pub const fn maximum_mutation_attempts(self) -> u8 {
        self.maximum_mutation_attempts
    }

    /// Returns the first exponential retry delay.
    #[must_use]
    pub const fn mutation_retry_initial_delay(self) -> Duration {
        self.mutation_retry_initial_delay
    }
}

impl Default for DurableInvocationExecutorOptions {
    fn default() -> Self {
        Self {
            maximum_mutation_attempts: 3,
            mutation_retry_initial_delay: Duration::from_millis(25),
        }
    }
}

/// Invalid durable invocation executor retry policy.
#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum DurableInvocationExecutorOptionsError {
    /// Mutation attempts were zero or above the hard ceiling.
    #[error("invocation executor mutation attempt count is invalid")]
    InvalidMutationAttempts,
    /// Initial mutation delay was zero or above one second.
    #[error("invocation executor mutation retry delay is invalid")]
    InvalidMutationRetryDelay,
}

/// Whether a newly dispatched model attempt committed a response or error.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ModelAttemptTerminalKind {
    /// Complete unary or accumulated streaming response committed.
    Response,
    /// Adapter/provider/supervisor failure evidence committed.
    Error,
}

/// Closed result of one model attempt executor call.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum ModelAttemptOutcome {
    /// This call performed one physical dispatch and committed its terminal fact.
    Dispatched {
        /// Whether response or error evidence won.
        terminal: ModelAttemptTerminalKind,
        /// Exact terminal invocation revision.
        invocation: ModelInvocation,
    },
    /// The start event had already committed, so no provider call was repeated.
    Recovered {
        /// Current exact invocation revision loaded after duplicate suppression.
        invocation: ModelInvocation,
    },
}

/// Whether a newly dispatched tool attempt committed a result or error.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ToolAttemptTerminalKind {
    /// Validated tool result committed.
    Result,
    /// Known or ambiguous failure evidence committed.
    Error,
}

/// Closed result of one tool attempt executor call.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum ToolAttemptOutcome {
    /// This call performed one physical dispatch and committed its terminal fact.
    Dispatched {
        /// Whether result or error evidence won.
        terminal: ToolAttemptTerminalKind,
        /// Exact terminal invocation revision.
        invocation: ToolInvocation,
    },
    /// The start event had already committed, so no tool call was repeated.
    Recovered {
        /// Current exact invocation revision loaded after duplicate suppression.
        invocation: ToolInvocation,
    },
}

/// Closed result of the durable-before-dispatch half of one tool attempt.
#[derive(Debug)]
#[non_exhaustive]
pub enum ToolAttemptStartOutcome {
    /// A fresh executing revision committed and this caller owns dispatch.
    Started(Box<ToolDispatchHandoff>),
    /// The stable start identity already advanced; provider I/O is not allowed.
    Recovered {
        /// Current exact invocation revision after duplicate suppression.
        invocation: Box<ToolInvocation>,
    },
}

impl ToolAttemptStartOutcome {
    /// Returns the current invocation revision in either outcome.
    #[must_use]
    pub fn invocation(&self) -> &ToolInvocation {
        match self {
            Self::Started(handoff) => handoff.invocation(),
            Self::Recovered { invocation } => invocation.as_ref(),
        }
    }
}

/// Fresh durable tool start retained for exactly one provider dispatch.
///
/// This type exists so a trusted coordinator can serialize multiple start
/// facts, overlap only policy-safe provider calls, and then serialize retained
/// terminal evidence in semantic order. Dropping it never calls a provider,
/// but leaves the durable attempt executing for higher-fence recovery.
pub struct ToolDispatchHandoff {
    fence: RunFence,
    invocation: ToolInvocation,
    terminal_event_id: EventId,
    provider: Arc<dyn stateknot_core::ErasedTool>,
    context: ToolContext,
}

impl ToolDispatchHandoff {
    /// Returns the exact live fence that committed the start.
    #[must_use]
    pub const fn fence(&self) -> &RunFence {
        &self.fence
    }

    /// Returns the fresh executing invocation revision.
    #[must_use]
    pub const fn invocation(&self) -> &ToolInvocation {
        &self.invocation
    }
}

impl fmt::Debug for ToolDispatchHandoff {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ToolDispatchHandoff")
            .field("fence", &self.fence)
            .field("invocation_head", &self.invocation.head())
            .field("terminal_event_id", &self.terminal_event_id)
            .finish_non_exhaustive()
    }
}

/// Retained request to probe one exact unknown tool attempt.
///
/// The event identity is stable across node and process retries. A probe that
/// remains pending performs no mutation; authoritative evidence is committed
/// through the existing atomic reconciliation transition.
#[derive(Clone)]
pub struct ToolReconciliationAttemptHandoff {
    fence: RunFence,
    invocation: ToolInvocation,
    event_id: EventId,
    cancellation: CancellationSignal,
}

impl ToolReconciliationAttemptHandoff {
    /// Constructs a scope- and capability-bound reconciliation probe.
    ///
    /// # Errors
    ///
    /// Rejects crossed run scope, non-unknown invocation state, a missing
    /// physical attempt, or a descriptor without status-query support.
    pub fn new(
        fence: RunFence,
        invocation: ToolInvocation,
        event_id: EventId,
        cancellation: CancellationSignal,
    ) -> Result<Self, ToolReconciliationAttemptHandoffError> {
        validate_tool_reconciliation_attempt_handoff(&fence, &invocation)?;
        Ok(Self {
            fence,
            invocation,
            event_id,
            cancellation,
        })
    }

    /// Returns the live worker fence used for reads and commit.
    #[must_use]
    pub const fn fence(&self) -> &RunFence {
        &self.fence
    }

    /// Returns the exact unknown invocation revision.
    #[must_use]
    pub const fn invocation(&self) -> &ToolInvocation {
        &self.invocation
    }

    /// Returns the stable audit-event identity.
    #[must_use]
    pub const fn event_id(&self) -> EventId {
        self.event_id
    }

    /// Rebinds the probe to a newer live fence for the same run.
    ///
    /// # Errors
    ///
    /// Rejects a fence from another tenant or run.
    pub fn rebind_fence(
        mut self,
        fence: RunFence,
    ) -> Result<Self, ToolReconciliationAttemptHandoffError> {
        if self.invocation.intent().tenant_id() != fence.tenant_id()
            || self.invocation.intent().run_id() != fence.run_id()
        {
            return Err(ToolReconciliationAttemptHandoffError::ScopeMismatch);
        }
        self.fence = fence;
        Ok(self)
    }
}

impl fmt::Debug for ToolReconciliationAttemptHandoff {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ToolReconciliationAttemptHandoff")
            .field("fence", &self.fence)
            .field("invocation_head", &self.invocation.head())
            .field("event_id", &self.event_id)
            .field("cancelled", &self.cancellation.is_cancelled())
            .finish_non_exhaustive()
    }
}

/// Invalid request to execute an automated reconciliation probe.
#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum ToolReconciliationAttemptHandoffError {
    /// Fence and invocation crossed tenant/run or journal scope.
    #[error("tool reconciliation attempt crosses its retained worker fence")]
    ScopeMismatch,
    /// The invocation is not currently unknown.
    #[error("tool reconciliation attempt does not reference an unknown invocation")]
    InvocationNotUnknown,
    /// The unknown invocation does not identify its physical attempt.
    #[error("tool reconciliation attempt has no physical attempt identity")]
    MissingAttempt,
    /// The descriptor does not declare status-query support.
    #[error("tool reconciliation attempt is not declared by the descriptor")]
    StatusQueryUnsupported,
}

fn validate_tool_reconciliation_attempt_handoff(
    fence: &RunFence,
    invocation: &ToolInvocation,
) -> Result<(), ToolReconciliationAttemptHandoffError> {
    if invocation.intent().tenant_id() != fence.tenant_id()
        || invocation.intent().run_id() != fence.run_id()
        || invocation.journal_head().tenant_id() != fence.tenant_id()
        || invocation.journal_head().run_id() != fence.run_id()
    {
        return Err(ToolReconciliationAttemptHandoffError::ScopeMismatch);
    }
    if invocation.status() != ToolInvocationStatus::Unknown {
        return Err(ToolReconciliationAttemptHandoffError::InvocationNotUnknown);
    }
    if invocation.attempt_id().is_none() {
        return Err(ToolReconciliationAttemptHandoffError::MissingAttempt);
    }
    if !invocation
        .intent()
        .descriptor()
        .semantics()
        .supports_status_query()
    {
        return Err(ToolReconciliationAttemptHandoffError::StatusQueryUnsupported);
    }
    Ok(())
}

/// Result of one bounded provider-backed reconciliation probe.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum ToolReconciliationAttemptOutcome {
    /// Authoritative evidence is now durable, or was already durable.
    Resolved {
        /// Result or known-error evidence classification.
        kind: ToolReconciliationKind,
        /// Current terminal invocation revision.
        invocation: ToolInvocation,
    },
    /// No authoritative evidence exists yet; no ledger mutation occurred.
    Pending {
        /// Earliest safe time for another bounded probe.
        retry_after: DurationMillis,
        /// Current unchanged unknown invocation revision.
        invocation: ToolInvocation,
    },
}

impl ToolReconciliationAttemptOutcome {
    /// Returns the current invocation revision.
    #[must_use]
    pub const fn invocation(&self) -> &ToolInvocation {
        match self {
            Self::Resolved { invocation, .. } | Self::Pending { invocation, .. } => invocation,
        }
    }
}

/// Authoritative evidence classification for one ambiguous tool attempt.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ToolReconciliationKind {
    /// Authoritative evidence supplies the exact successful result.
    Result,
    /// Authoritative evidence supplies a failure and external-effect fact.
    Error,
}

#[derive(Clone)]
enum ToolReconciliationEvidence {
    Result(ToolResult),
    Error(ToolError),
}

/// Retained, validation-bound evidence for reconciling an unknown tool attempt.
///
/// Construction binds the evidence to an exact unknown invocation revision and
/// physical attempt. Debug output deliberately excludes result/error payloads.
/// Committing this handoff performs no tool or provider I/O.
#[derive(Clone)]
pub struct ToolReconciliationHandoff {
    fence: RunFence,
    invocation: ToolInvocation,
    event_id: EventId,
    evidence: ToolReconciliationEvidence,
}

impl ToolReconciliationHandoff {
    /// Binds authoritative successful-result evidence to an unknown attempt.
    ///
    /// # Errors
    ///
    /// Rejects crossed tenant/run scope, a non-unknown invocation, or result
    /// evidence that violates the exact durable invocation contract.
    pub fn result(
        fence: RunFence,
        invocation: ToolInvocation,
        event_id: EventId,
        result: ToolResult,
    ) -> Result<Self, ToolReconciliationHandoffError> {
        validate_tool_reconciliation_scope(&fence, &invocation)?;
        invocation
            .validate_reconciliation_result(&result)
            .map_err(ToolReconciliationHandoffError::invalid_evidence)?;
        Ok(Self {
            fence,
            invocation,
            event_id,
            evidence: ToolReconciliationEvidence::Result(result),
        })
    }

    /// Binds authoritative failure/effect evidence to an unknown attempt.
    ///
    /// `Unknown` effect evidence may intentionally retain the unresolved state;
    /// an authoritative known effect resolves it to `Failed`.
    ///
    /// # Errors
    ///
    /// Rejects crossed tenant/run scope, a non-unknown invocation, or error
    /// evidence that violates the exact durable invocation contract.
    pub fn error(
        fence: RunFence,
        invocation: ToolInvocation,
        event_id: EventId,
        error: ToolError,
    ) -> Result<Self, ToolReconciliationHandoffError> {
        validate_tool_reconciliation_scope(&fence, &invocation)?;
        invocation
            .validate_reconciliation_error(&error)
            .map_err(ToolReconciliationHandoffError::invalid_evidence)?;
        Ok(Self {
            fence,
            invocation,
            event_id,
            evidence: ToolReconciliationEvidence::Error(error),
        })
    }

    /// Returns the authoritative reconciliation classification.
    #[must_use]
    pub const fn kind(&self) -> ToolReconciliationKind {
        match &self.evidence {
            ToolReconciliationEvidence::Result(_) => ToolReconciliationKind::Result,
            ToolReconciliationEvidence::Error(_) => ToolReconciliationKind::Error,
        }
    }

    /// Returns the worker fence attached to this reconciliation mutation.
    #[must_use]
    pub const fn fence(&self) -> &RunFence {
        &self.fence
    }

    /// Returns the exact unknown invocation revision being reconciled.
    #[must_use]
    pub const fn invocation(&self) -> &ToolInvocation {
        &self.invocation
    }

    /// Returns the stable journal event identity retained across commit retries.
    #[must_use]
    pub const fn event_id(&self) -> EventId {
        self.event_id
    }

    /// Rebinds retained evidence to a newer live fence in the same run.
    ///
    /// This changes no evidence bytes and never calls the tool. The durable
    /// store validates current fence ownership at commit time.
    ///
    /// # Errors
    ///
    /// Rejects a fence from another tenant or run.
    pub fn rebind_fence(mut self, fence: RunFence) -> Result<Self, ToolReconciliationHandoffError> {
        validate_tool_reconciliation_scope(&fence, &self.invocation)?;
        self.fence = fence;
        Ok(self)
    }
}

impl fmt::Debug for ToolReconciliationHandoff {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ToolReconciliationHandoff")
            .field("fence", &self.fence)
            .field("invocation_head", &self.invocation.head())
            .field("event_id", &self.event_id)
            .field("kind", &self.kind())
            .finish_non_exhaustive()
    }
}

/// Invalid binding between reconciliation evidence and durable invocation state.
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum ToolReconciliationHandoffError {
    /// Fence and invocation crossed tenant/run or journal scope.
    #[error("tool reconciliation handoff crosses its retained worker fence")]
    ScopeMismatch,
    /// Result/error evidence did not belong to the exact unknown attempt.
    #[error("tool reconciliation evidence violates the durable invocation contract: {source}")]
    InvalidEvidence {
        /// Exact public-safe core invariant violation.
        #[source]
        source: ToolInvocationError,
    },
}

impl ToolReconciliationHandoffError {
    fn invalid_evidence(source: ToolInvocationError) -> Self {
        Self::InvalidEvidence { source }
    }
}

fn validate_tool_reconciliation_scope(
    fence: &RunFence,
    invocation: &ToolInvocation,
) -> Result<(), ToolReconciliationHandoffError> {
    if invocation.intent().tenant_id() != fence.tenant_id()
        || invocation.intent().run_id() != fence.run_id()
        || invocation.journal_head().tenant_id() != fence.tenant_id()
        || invocation.journal_head().run_id() != fence.run_id()
    {
        return Err(ToolReconciliationHandoffError::ScopeMismatch);
    }
    Ok(())
}

/// Result of durably committing authoritative tool reconciliation evidence.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum ToolReconciliationOutcome {
    /// A new reconciliation event and invocation revision committed atomically.
    Committed {
        /// Reconciliation evidence classification.
        kind: ToolReconciliationKind,
        /// Newly committed immutable journal event.
        event: JournalEvent,
        /// Newly committed terminal or deliberately still-unknown revision.
        invocation: ToolInvocation,
    },
    /// The exact reconciliation event and mutation had already committed.
    Idempotent {
        /// Reconciliation evidence classification.
        kind: ToolReconciliationKind,
        /// Previously committed immutable journal event.
        event: JournalEvent,
        /// Previously committed terminal or deliberately still-unknown revision.
        invocation: ToolInvocation,
    },
}

impl ToolReconciliationOutcome {
    /// Returns the reconciliation evidence classification.
    #[must_use]
    pub const fn kind(&self) -> ToolReconciliationKind {
        match self {
            Self::Committed { kind, .. } | Self::Idempotent { kind, .. } => *kind,
        }
    }

    /// Returns the exact reconciliation journal event.
    #[must_use]
    pub const fn event(&self) -> &JournalEvent {
        match self {
            Self::Committed { event, .. } | Self::Idempotent { event, .. } => event,
        }
    }

    /// Returns the resulting durable invocation revision.
    #[must_use]
    pub const fn invocation(&self) -> &ToolInvocation {
        match self {
            Self::Committed { invocation, .. } | Self::Idempotent { invocation, .. } => invocation,
        }
    }

    /// Returns whether this exact reconciliation had already committed.
    #[must_use]
    pub const fn is_idempotent(&self) -> bool {
        matches!(self, Self::Idempotent { .. })
    }
}

#[derive(Clone)]
#[allow(clippy::large_enum_variant)]
enum ModelTerminalEvidence {
    Response(ModelResponse),
    Error(ModelError),
}

/// Retained terminal model evidence after a database commit failure.
///
/// Debug output excludes the response/error payload. Pass this value back to
/// [`DurableInvocationExecutor::commit_model_terminal`] without modification;
/// no provider request is performed by that method.
#[derive(Clone)]
pub struct ModelTerminalCommitHandoff {
    fence: RunFence,
    invocation: ModelInvocation,
    event_id: EventId,
    evidence: ModelTerminalEvidence,
}

impl fmt::Debug for ModelTerminalCommitHandoff {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ModelTerminalCommitHandoff")
            .field("fence", &self.fence)
            .field("invocation_head", &self.invocation.head())
            .field("event_id", &self.event_id)
            .field("terminal", &self.kind())
            .finish_non_exhaustive()
    }
}

impl ModelTerminalCommitHandoff {
    /// Returns response/error classification without exposing payload content.
    #[must_use]
    pub const fn kind(&self) -> ModelAttemptTerminalKind {
        match &self.evidence {
            ModelTerminalEvidence::Response(_) => ModelAttemptTerminalKind::Response,
            ModelTerminalEvidence::Error(_) => ModelAttemptTerminalKind::Error,
        }
    }

    /// Returns the worker fence currently attached to terminal evidence.
    #[must_use]
    pub const fn fence(&self) -> &RunFence {
        &self.fence
    }

    /// Rebinds retained evidence to a newer live fence in the same run.
    ///
    /// This is required when a provider call outlives its original lease. The
    /// store remains authoritative: it validates that the replacement fence is
    /// currently live before accepting the already-produced terminal evidence.
    ///
    /// # Errors
    ///
    /// Rejects a fence from another tenant or run.
    pub fn rebind_fence(mut self, fence: RunFence) -> Result<Self, InvocationAttemptHandoffError> {
        if self.invocation.intent().tenant_id() != fence.tenant_id()
            || self.invocation.intent().run_id() != fence.run_id()
        {
            return Err(InvocationAttemptHandoffError::ScopeMismatch);
        }
        self.fence = fence;
        Ok(self)
    }
}

#[derive(Clone)]
enum ToolTerminalEvidence {
    Result(ToolResult),
    Error(ToolError),
}

/// Retained terminal tool evidence after a database commit failure.
///
/// Debug output excludes tool result/error payloads. Retrying this handoff never
/// calls the tool again.
#[derive(Clone)]
pub struct ToolTerminalCommitHandoff {
    fence: RunFence,
    invocation: ToolInvocation,
    event_id: EventId,
    evidence: ToolTerminalEvidence,
}

impl fmt::Debug for ToolTerminalCommitHandoff {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ToolTerminalCommitHandoff")
            .field("fence", &self.fence)
            .field("invocation_head", &self.invocation.head())
            .field("event_id", &self.event_id)
            .field("terminal", &self.kind())
            .finish_non_exhaustive()
    }
}

impl ToolTerminalCommitHandoff {
    /// Returns result/error classification without exposing payload content.
    #[must_use]
    pub const fn kind(&self) -> ToolAttemptTerminalKind {
        match &self.evidence {
            ToolTerminalEvidence::Result(_) => ToolAttemptTerminalKind::Result,
            ToolTerminalEvidence::Error(_) => ToolAttemptTerminalKind::Error,
        }
    }

    /// Returns the worker fence currently attached to terminal evidence.
    #[must_use]
    pub const fn fence(&self) -> &RunFence {
        &self.fence
    }

    /// Rebinds retained evidence to a newer live fence in the same run.
    ///
    /// This changes no result/error bytes and never calls the tool again. The
    /// durable store validates current fence ownership at commit time.
    ///
    /// # Errors
    ///
    /// Rejects a fence from another tenant or run.
    pub fn rebind_fence(mut self, fence: RunFence) -> Result<Self, InvocationAttemptHandoffError> {
        if self.invocation.intent().tenant_id() != fence.tenant_id()
            || self.invocation.intent().run_id() != fence.run_id()
        {
            return Err(InvocationAttemptHandoffError::ScopeMismatch);
        }
        self.fence = fence;
        Ok(self)
    }
}

/// Payload-safe cause of a retained terminal invocation commit failure.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum InvocationTerminalCommitFailure {
    /// The durable store rejected or could not complete the mutation.
    #[error(transparent)]
    Store(#[from] StoreError),
    /// Runtime-owned standard event data could not be encoded or validated.
    #[error("terminal invocation event payload is invalid")]
    InvalidEventPayload,
    /// Runtime-owned worker journal metadata violated its invariant.
    #[error("terminal invocation journal append is invalid")]
    InvalidJournalAppend,
    /// The run lost its durable journal anchor before terminal evidence could commit.
    #[error("terminal invocation run journal is unavailable")]
    RunJournalUnavailable,
    /// Retained terminal evidence did not reference an executing attempt.
    #[error("terminal invocation does not reference an executing attempt")]
    InvalidInvocationState,
    /// The store returned a future commit outcome unknown to this runtime.
    #[error("terminal invocation store outcome is unsupported by this runtime")]
    UnsupportedStoreOutcome,
}

/// Terminal model commit failure retaining exact retry evidence.
#[derive(Debug, Error)]
#[error("model terminal invocation commit failed: {source}")]
pub struct ModelTerminalCommitError {
    #[source]
    source: InvocationTerminalCommitFailure,
    recovery: Box<ModelTerminalCommitHandoff>,
}

impl ModelTerminalCommitError {
    /// Returns the payload-redacted store failure.
    #[must_use]
    pub const fn source_error(&self) -> &InvocationTerminalCommitFailure {
        &self.source
    }

    /// Recovers the exact response/error commit handoff for a no-dispatch retry.
    #[must_use]
    pub fn into_recovery(self) -> ModelTerminalCommitHandoff {
        *self.recovery
    }
}

/// Terminal tool commit failure retaining exact retry evidence.
#[derive(Debug, Error)]
#[error("tool terminal invocation commit failed: {source}")]
pub struct ToolTerminalCommitError {
    #[source]
    source: InvocationTerminalCommitFailure,
    recovery: Box<ToolTerminalCommitHandoff>,
}

impl ToolTerminalCommitError {
    /// Returns the payload-redacted store failure.
    #[must_use]
    pub const fn source_error(&self) -> &InvocationTerminalCommitFailure {
        &self.source
    }

    /// Recovers the exact result/error commit handoff for a no-dispatch retry.
    #[must_use]
    pub fn into_recovery(self) -> ToolTerminalCommitHandoff {
        *self.recovery
    }
}

/// Payload-safe cause of a durable tool reconciliation commit failure.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ToolReconciliationCommitFailure {
    /// The durable store rejected or could not complete the mutation.
    #[error(transparent)]
    Store(#[from] StoreError),
    /// Successful evidence was rejected by or missing from the frozen registry.
    #[error("tool reconciliation output schema validation failed: {source}")]
    OutputSchema {
        /// Public-safe unavailable/rejected classification.
        #[source]
        source: GraphSchemaValidationError,
    },
    /// Runtime-owned standard event data could not be encoded or validated.
    #[error("tool reconciliation event payload is invalid")]
    InvalidEventPayload,
    /// Runtime-owned worker journal metadata violated its invariant.
    #[error("tool reconciliation journal append is invalid")]
    InvalidJournalAppend,
    /// The run lost its durable journal anchor before evidence could commit.
    #[error("tool reconciliation run journal is unavailable")]
    RunJournalUnavailable,
    /// Retained evidence no longer references an unknown physical attempt.
    #[error("tool reconciliation does not reference an unknown physical attempt")]
    InvalidInvocationState,
    /// The store returned a future commit outcome unknown to this runtime.
    #[error("tool reconciliation store outcome is unsupported by this runtime")]
    UnsupportedStoreOutcome,
}

/// Reconciliation failure retaining the exact evidence for a no-dispatch retry.
#[derive(Debug, Error)]
#[error("tool reconciliation commit failed: {source}")]
pub struct ToolReconciliationCommitError {
    #[source]
    source: ToolReconciliationCommitFailure,
    recovery: Box<ToolReconciliationHandoff>,
}

impl ToolReconciliationCommitError {
    /// Returns the payload-redacted commit failure.
    #[must_use]
    pub const fn source_error(&self) -> &ToolReconciliationCommitFailure {
        &self.source
    }

    /// Recovers the exact evidence handoff for an identical no-dispatch retry.
    #[must_use]
    pub fn into_recovery(self) -> ToolReconciliationHandoff {
        *self.recovery
    }
}

/// Failure before, during, or after one automated reconciliation probe.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ToolReconciliationAttemptExecutionError {
    /// The retained probe request violated scope or state invariants.
    #[error(transparent)]
    Handoff(#[from] ToolReconciliationAttemptHandoffError),
    /// No exact executable tool binding was installed.
    #[error(transparent)]
    Registry(#[from] ToolProviderRegistryError),
    /// The exact binding leaves status reconciliation to an external operator.
    #[error("installed tool binding does not implement automated reconciliation")]
    ProviderReconciliationUnsupported,
    /// Durable state could not be loaded.
    #[error(transparent)]
    Store(#[from] StoreError),
    /// Stored run provenance crossed the retained worker fence.
    #[error("stored run provenance does not match the tool reconciliation fence")]
    RunProvenanceMismatch,
    /// Runtime clock observation failed.
    #[error(transparent)]
    Clock(#[from] InvocationClockError),
    /// The descriptor-bounded fallback deadline was not representable.
    #[error("tool reconciliation deadline is outside the supported timestamp range")]
    DeadlineOutOfRange,
    /// A finite reconciliation context could not be constructed.
    #[error(transparent)]
    Context(#[from] ToolReconciliationContextError),
    /// Cancellation or the run/probe deadline won.
    #[error("tool reconciliation stopped: {reason:?}")]
    Stopped {
        /// Deterministic stop reason.
        reason: ToolStopReason,
    },
    /// The provider's probe itself failed without resolving the original call.
    #[error(transparent)]
    Probe(#[from] ToolReconciliationProbeError),
    /// Provider polling advice violated hard resource bounds.
    #[error(transparent)]
    Observation(#[from] ToolReconciliationObservationError),
    /// A probe returned another ambiguous outcome instead of `Pending`.
    #[error("tool reconciliation returned unresolved error evidence")]
    UnresolvedErrorEvidence,
    /// A newer provider observation variant is unsupported by this runtime.
    #[error("tool reconciliation observation is unsupported by this runtime")]
    UnsupportedObservation,
    /// Result or known-error evidence violated the exact unknown invocation.
    #[error(transparent)]
    Evidence(#[from] ToolReconciliationHandoffError),
    /// The invocation changed to another durable intent.
    #[error("recovered tool reconciliation invocation does not match the retained intent")]
    RecoveredInvocationMismatch,
    /// The invocation no longer references the original physical attempt.
    #[error("tool reconciliation invocation advanced under another attempt or state")]
    InvocationAdvanced,
    /// Authoritative evidence was produced but its atomic commit failed.
    #[error(transparent)]
    Commit(#[from] ToolReconciliationCommitError),
}

impl ToolReconciliationAttemptExecutionError {
    /// Returns explicit node-level recovery advice for this probe failure.
    ///
    /// Retryability is inherited only from an explicit provider failure or a
    /// retryable durable-store classification. Contract and integrity failures
    /// remain terminal.
    #[must_use]
    pub fn retry_advice(&self) -> RetryAdvice {
        let store_retry = || RetryAdvice::SafeAfter {
            delay: DurationMillis::new(100).expect("positive static retry delay"),
        };
        match self {
            Self::Probe(source) => source.failure().retry_advice(),
            Self::Store(source) if source.is_retryable() => store_retry(),
            Self::Commit(source)
                if matches!(
                    source.source_error(),
                    ToolReconciliationCommitFailure::Store(store) if store.is_retryable()
                ) =>
            {
                store_retry()
            }
            Self::Handoff(_)
            | Self::Registry(_)
            | Self::ProviderReconciliationUnsupported
            | Self::Store(_)
            | Self::RunProvenanceMismatch
            | Self::Clock(_)
            | Self::DeadlineOutOfRange
            | Self::Context(_)
            | Self::Stopped { .. }
            | Self::Observation(_)
            | Self::UnresolvedErrorEvidence
            | Self::UnsupportedObservation
            | Self::Evidence(_)
            | Self::RecoveredInvocationMismatch
            | Self::InvocationAdvanced
            | Self::Commit(_) => RetryAdvice::Never,
        }
    }
}

/// First-party durable model/tool attempt executor.
#[derive(Clone)]
pub struct DurableInvocationExecutor {
    store: PostgresStore,
    schemas: JsonSchemaRegistry,
    event_schema: SchemaReference,
    models: ModelProviderRegistry,
    tools: ToolProviderRegistry,
    budget: Arc<dyn InvocationBudgetProvider>,
    clock: Arc<dyn InvocationClock>,
    options: DurableInvocationExecutorOptions,
}

impl DurableInvocationExecutor {
    /// Returns whether the exact installed binding implements reconciliation.
    ///
    /// # Errors
    ///
    /// Fails if no exact provider binding exists for the descriptor snapshot.
    pub fn supports_tool_reconciliation(
        &self,
        descriptor: &ToolDescriptor,
    ) -> Result<bool, ToolProviderRegistryError> {
        self.tools
            .resolve(descriptor)
            .map(|provider| provider.supports_reconciliation())
    }

    /// Builds an executor using the production system/monotonic clock.
    ///
    /// # Errors
    ///
    /// Fails unless the exact embedded invocation journal schema is installed
    /// in the frozen offline registry.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        store: PostgresStore,
        schemas: JsonSchemaRegistry,
        models: ModelProviderRegistry,
        tools: ToolProviderRegistry,
        budget: Arc<dyn InvocationBudgetProvider>,
        options: DurableInvocationExecutorOptions,
    ) -> Result<Self, DurableInvocationExecutorBuildError> {
        Self::with_clock(
            store,
            schemas,
            models,
            tools,
            budget,
            Arc::new(SystemInvocationClock),
            options,
        )
    }

    /// Builds an executor with an injected trusted paired clock.
    ///
    /// # Errors
    ///
    /// Fails unless the exact embedded invocation journal schema is installed.
    #[allow(clippy::too_many_arguments)]
    pub fn with_clock(
        store: PostgresStore,
        schemas: JsonSchemaRegistry,
        models: ModelProviderRegistry,
        tools: ToolProviderRegistry,
        budget: Arc<dyn InvocationBudgetProvider>,
        clock: Arc<dyn InvocationClock>,
        options: DurableInvocationExecutorOptions,
    ) -> Result<Self, DurableInvocationExecutorBuildError> {
        let (event_schema, _) = standard_invocation_execution_event_schema()?;
        if !schemas.contains(&event_schema) {
            return Err(DurableInvocationExecutorBuildError::MissingEventSchema);
        }
        Ok(Self {
            store,
            schemas,
            event_schema,
            models,
            tools,
            budget,
            clock,
            options,
        })
    }

    async fn prepare_model_context(
        &self,
        handoff: &ModelAttemptHandoff,
    ) -> Result<(ModelContext, Option<Digest>), ModelAttemptExecutionError> {
        let run = self
            .store
            .load_run(handoff.fence.tenant_id(), handoff.fence.run_id())
            .await?;
        let provenance = run.lifecycle().provenance().clone();
        validate_run_provenance(&provenance, &handoff.fence)?;
        let account = self
            .store
            .load_child_budget_account(handoff.fence.tenant_id(), handoff.fence.run_id())
            .await?;
        let child_budget = account
            .as_ref()
            .map(stateknot_core::ChildRunBudgetAccount::digest);
        let observation = self.clock.observe()?;
        let remaining = self
            .budget
            .remaining(InvocationBudgetContext {
                provenance: provenance.clone(),
                boundary: InvocationBoundaryKind::Model,
                invocation_id: handoff.invocation.intent().invocation_id(),
                attempt_id: handoff.attempt_id,
                intent_digest: handoff.invocation.intent().intent_digest(),
                observed_at: observation.observed_at,
            })
            .await?;
        validate_model_budget(&remaining, handoff.invocation.intent().request())?;
        let remaining = deduct_child_budget(remaining, account.as_ref()).map_err(|error| {
            ModelAttemptExecutionError::BudgetProvider(InvocationBudgetProviderError::new(error))
        })?;
        validate_model_budget(&remaining, handoff.invocation.intent().request())?;
        let context = ModelContext::new(
            provenance.tenant_id().clone(),
            provenance.run_id(),
            provenance.thread_id(),
            handoff.attempt_id,
            remaining,
            observation.observed_at,
            observation.observed_instant,
            handoff.cancellation.clone(),
        )?;
        if let Some(reason) = context.stop_reason_at(Instant::now()) {
            return Err(ModelAttemptExecutionError::StoppedBeforeStart { reason });
        }
        Ok((context, child_budget))
    }

    async fn prepare_tool_context(
        &self,
        handoff: &ToolAttemptHandoff,
    ) -> Result<(ToolContext, Option<Digest>), ToolAttemptExecutionError> {
        let run = self
            .store
            .load_run(handoff.fence.tenant_id(), handoff.fence.run_id())
            .await?;
        let provenance = run.lifecycle().provenance().clone();
        validate_tool_run_provenance(&provenance, &handoff.fence)?;
        let account = self
            .store
            .load_child_budget_account(handoff.fence.tenant_id(), handoff.fence.run_id())
            .await?;
        let child_budget = account
            .as_ref()
            .map(stateknot_core::ChildRunBudgetAccount::digest);
        let observation = self.clock.observe()?;
        let remaining = self
            .budget
            .remaining(InvocationBudgetContext {
                provenance: provenance.clone(),
                boundary: InvocationBoundaryKind::Tool,
                invocation_id: handoff.invocation.intent().invocation_id(),
                attempt_id: handoff.attempt_id,
                intent_digest: handoff.invocation.intent().intent_digest(),
                observed_at: observation.observed_at,
            })
            .await?;
        let remaining = deduct_child_budget(remaining, account.as_ref()).map_err(|error| {
            ToolAttemptExecutionError::BudgetProvider(InvocationBudgetProviderError::new(error))
        })?;
        validate_tool_budget(
            &remaining,
            handoff.invocation.intent().descriptor().semantics().risk(),
        )?;
        let context = Self::build_tool_context(handoff, &provenance, remaining, observation)?;
        handoff
            .invocation
            .intent()
            .input()
            .validate_for(&context, handoff.invocation.intent().descriptor())?;
        if let Some(reason) = context.stop_reason_at(Instant::now()) {
            return Err(ToolAttemptExecutionError::StoppedBeforeStart { reason });
        }
        Ok((context, child_budget))
    }

    fn build_tool_context(
        handoff: &ToolAttemptHandoff,
        provenance: &AgentResultProvenance,
        remaining: BudgetRemaining,
        observation: InvocationClockObservation,
    ) -> Result<ToolContext, ToolContextError> {
        let intent = handoff.invocation.intent();
        let context = if let Some(progress_sink) = &handoff.progress_sink {
            ToolContext::new_with_progress(
                provenance.tenant_id().clone(),
                provenance.run_id(),
                provenance.thread_id(),
                intent.invocation_id(),
                handoff.attempt_id,
                intent.descriptor(),
                remaining,
                intent.effective_limits().timeout(),
                observation.observed_at,
                observation.observed_instant,
                handoff.cancellation.clone(),
                Arc::clone(progress_sink),
            )?
        } else {
            ToolContext::new(
                provenance.tenant_id().clone(),
                provenance.run_id(),
                provenance.thread_id(),
                intent.invocation_id(),
                handoff.attempt_id,
                intent.descriptor(),
                remaining,
                intent.effective_limits().timeout(),
                observation.observed_at,
                observation.observed_instant,
                handoff.cancellation.clone(),
            )?
        };
        Ok(context
            .with_durable_origin_event(handoff.events.start())
            .narrow_artifact_limits(intent.effective_limits()))
    }

    async fn prepare_tool_reconciliation_context(
        &self,
        handoff: &ToolReconciliationAttemptHandoff,
        invocation: &ToolInvocation,
    ) -> Result<ToolReconciliationContext, ToolReconciliationAttemptExecutionError> {
        let run = self
            .store
            .load_run(handoff.fence.tenant_id(), handoff.fence.run_id())
            .await?;
        let provenance = run.lifecycle().provenance();
        if provenance.tenant_id() != handoff.fence.tenant_id()
            || provenance.run_id() != handoff.fence.run_id()
        {
            return Err(ToolReconciliationAttemptExecutionError::RunProvenanceMismatch);
        }
        let observation = self.clock.observe()?;
        let intent = invocation.intent();
        let timeout_micros = intent
            .effective_limits()
            .timeout()
            .as_i64()
            .checked_mul(1_000)
            .ok_or(ToolReconciliationAttemptExecutionError::DeadlineOutOfRange)?;
        let fallback_deadline_micros = observation
            .observed_at()
            .unix_micros()
            .checked_add(timeout_micros)
            .ok_or(ToolReconciliationAttemptExecutionError::DeadlineOutOfRange)?;
        let fallback_deadline = Timestamp::from_unix_micros(fallback_deadline_micros)
            .map_err(|_| ToolReconciliationAttemptExecutionError::DeadlineOutOfRange)?;
        let run_deadline = match self
            .store
            .load_agent_admission(handoff.fence.tenant_id(), handoff.fence.run_id())
            .await
        {
            Ok(stored) => stored.admission().intent().budget().deadline(),
            Err(StoreError::AgentAdmissionNotFound) => fallback_deadline,
            Err(source) => return Err(source.into()),
        };
        let recovery_handle = match invocation.state() {
            ToolInvocationState::Unknown { error } => error.recovery_handle().cloned(),
            _ => None,
        };
        let origin_event_id = invocation
            .previous()
            .filter(|head| head.status() == stateknot_core::ToolInvocationStatus::Executing)
            .map(|head| head.journal_head().event_id())
            .ok_or(ToolReconciliationAttemptExecutionError::InvocationAdvanced)?;
        let context = ToolReconciliationContext::new(
            provenance.tenant_id().clone(),
            provenance.run_id(),
            provenance.thread_id(),
            intent.invocation_id(),
            invocation
                .attempt_id()
                .ok_or(ToolReconciliationAttemptExecutionError::InvocationAdvanced)?,
            intent.descriptor(),
            intent.effective_limits().timeout(),
            observation.observed_at(),
            observation.observed_instant(),
            run_deadline,
            handoff.cancellation.clone(),
        )?
        .with_durable_recovery(origin_event_id, recovery_handle)
        .narrow_artifact_limits(intent.effective_limits());
        if let Some(reason) = context.stop_reason_at(Instant::now()) {
            return Err(ToolReconciliationAttemptExecutionError::Stopped { reason });
        }
        Ok(context)
    }

    async fn recover_model_if_started(
        &self,
        handoff: &ModelAttemptHandoff,
    ) -> Result<Option<ModelAttemptOutcome>, ModelAttemptExecutionError> {
        let current = self
            .store
            .load_model_invocation(
                handoff.fence.tenant_id(),
                handoff.fence.run_id(),
                handoff.invocation.intent().invocation_id(),
            )
            .await?;
        if current.intent() != handoff.invocation.intent() {
            return Err(ModelAttemptExecutionError::RecoveredInvocationMismatch);
        }
        if current.head() == handoff.invocation.head() {
            return Ok(None);
        }
        if current.attempt_id() != Some(handoff.attempt_id) {
            return Err(ModelAttemptExecutionError::InvocationAdvanced);
        }
        Ok(Some(ModelAttemptOutcome::Recovered {
            invocation: current,
        }))
    }

    async fn recover_tool_if_started(
        &self,
        handoff: &ToolAttemptHandoff,
    ) -> Result<Option<ToolAttemptOutcome>, ToolAttemptExecutionError> {
        let current = self
            .store
            .load_tool_invocation(
                handoff.fence.tenant_id(),
                handoff.fence.run_id(),
                handoff.invocation.intent().invocation_id(),
            )
            .await?;
        if current.intent() != handoff.invocation.intent() {
            return Err(ToolAttemptExecutionError::RecoveredInvocationMismatch);
        }
        if current.head() == handoff.invocation.head() {
            return Ok(None);
        }
        if current.attempt_id() != Some(handoff.attempt_id) {
            return Err(ToolAttemptExecutionError::InvocationAdvanced);
        }
        Ok(Some(ToolAttemptOutcome::Recovered {
            invocation: current,
        }))
    }

    /// Executes at most one physical model provider exchange.
    ///
    /// `StartAttempt` commits before provider I/O. If that event is found
    /// idempotently, this method loads current state and never calls the model.
    /// A terminal database failure returns the exact response/error recovery
    /// handoff so callers can retry persistence without repeating provider I/O.
    pub fn execute_model(
        &self,
        handoff: ModelAttemptHandoff,
    ) -> BoxFuture<'_, Result<ModelAttemptOutcome, ModelAttemptExecutionError>> {
        Box::pin(self.execute_model_inner(handoff))
    }

    async fn execute_model_inner(
        &self,
        handoff: ModelAttemptHandoff,
    ) -> Result<ModelAttemptOutcome, ModelAttemptExecutionError> {
        validate_model_handoff(
            &handoff.fence,
            &handoff.invocation,
            handoff.stream_sink.is_some(),
        )?;
        if let Some(recovered) = self.recover_model_if_started(&handoff).await? {
            return Ok(recovered);
        }
        let provider = self
            .models
            .resolve(handoff.invocation.intent().descriptor())?;
        let (context, child_budget) = self.prepare_model_context(&handoff).await?;

        let start_transition = ModelInvocationTransition::StartAttempt {
            attempt_id: handoff.attempt_id,
        };
        let start_payload = self.event_payload(
            "model-attempt-started",
            "model_attempt_started",
            "model",
            handoff.invocation.intent().invocation_id(),
            handoff.attempt_id,
            handoff.invocation.intent().intent_digest(),
        )?;
        let start_append = worker_append(
            &handoff.fence,
            handoff.invocation.journal_head().clone(),
            handoff.events.start,
            start_payload,
        )
        .map_err(|_| ModelAttemptExecutionError::JournalAppend)?;
        let start = self
            .advance_model_with_retry(
                start_append,
                &handoff.invocation,
                start_transition,
                child_budget,
            )
            .await?;
        let executing = match start {
            ModelInvocationCommitOutcome::Committed { invocation, .. } => invocation,
            ModelInvocationCommitOutcome::Idempotent { .. } => {
                let current = self
                    .store
                    .load_model_invocation(
                        handoff.fence.tenant_id(),
                        handoff.fence.run_id(),
                        handoff.invocation.intent().invocation_id(),
                    )
                    .await?;
                if current.intent() != handoff.invocation.intent() {
                    return Err(ModelAttemptExecutionError::RecoveredInvocationMismatch);
                }
                if current.attempt_id() != Some(handoff.attempt_id) {
                    return Err(ModelAttemptExecutionError::InvocationAdvanced);
                }
                return Ok(ModelAttemptOutcome::Recovered {
                    invocation: current,
                });
            }
            _ => return Err(ModelAttemptExecutionError::UnsupportedStoreOutcome),
        };

        let evidence = match context.stop_reason_at(Instant::now()) {
            Some(reason) => ModelTerminalEvidence::Error(model_stop_error(
                &context,
                executing.intent().descriptor(),
                reason,
            )),
            None => {
                self.dispatch_model(
                    provider,
                    context,
                    executing.intent().request().clone(),
                    handoff.stream_sink,
                )
                .await
            }
        };
        let terminal = ModelTerminalCommitHandoff {
            fence: handoff.fence,
            invocation: executing,
            event_id: handoff.events.terminal,
            evidence,
        };
        self.commit_model_terminal(terminal)
            .await
            .map_err(ModelAttemptExecutionError::Terminal)
    }

    /// Commits retained terminal model evidence without provider I/O.
    pub fn commit_model_terminal(
        &self,
        handoff: ModelTerminalCommitHandoff,
    ) -> BoxFuture<'_, Result<ModelAttemptOutcome, ModelTerminalCommitError>> {
        Box::pin(self.commit_model_terminal_inner(handoff))
    }

    async fn commit_model_terminal_inner(
        &self,
        handoff: ModelTerminalCommitHandoff,
    ) -> Result<ModelAttemptOutcome, ModelTerminalCommitError> {
        let terminal_kind = handoff.kind();
        let (operation, event_kind, transition) = match &handoff.evidence {
            ModelTerminalEvidence::Response(response) => (
                "model_response_committed",
                "model-response-committed",
                ModelInvocationTransition::RecordResponse {
                    response: response.clone(),
                },
            ),
            ModelTerminalEvidence::Error(error) => (
                "model_error_committed",
                "model-error-committed",
                ModelInvocationTransition::RecordError {
                    error: error.clone(),
                },
            ),
        };
        let Some(attempt_id) = handoff.invocation.attempt_id() else {
            return Err(ModelTerminalCommitError {
                source: InvocationTerminalCommitFailure::InvalidInvocationState,
                recovery: Box::new(handoff),
            });
        };
        let Ok(payload) = self.event_payload(
            event_kind,
            operation,
            "model",
            handoff.invocation.intent().invocation_id(),
            attempt_id,
            handoff.invocation.intent().intent_digest(),
        ) else {
            return Err(ModelTerminalCommitError {
                source: InvocationTerminalCommitFailure::InvalidEventPayload,
                recovery: Box::new(handoff),
            });
        };
        let run = match self
            .store
            .load_run(
                handoff.invocation.intent().tenant_id(),
                handoff.invocation.intent().run_id(),
            )
            .await
        {
            Ok(run) => run,
            Err(source) => {
                return Err(ModelTerminalCommitError {
                    source: InvocationTerminalCommitFailure::Store(source),
                    recovery: Box::new(handoff),
                });
            }
        };
        let Some(journal_head) = run.journal_head().cloned() else {
            return Err(ModelTerminalCommitError {
                source: InvocationTerminalCommitFailure::RunJournalUnavailable,
                recovery: Box::new(handoff),
            });
        };
        let Ok(append) = worker_append(&handoff.fence, journal_head, handoff.event_id, payload)
        else {
            return Err(ModelTerminalCommitError {
                source: InvocationTerminalCommitFailure::InvalidJournalAppend,
                recovery: Box::new(handoff),
            });
        };
        match self
            .advance_model_with_retry(append, &handoff.invocation, transition, None)
            .await
        {
            Ok(outcome) => Ok(ModelAttemptOutcome::Dispatched {
                terminal: terminal_kind,
                invocation: outcome.invocation().clone(),
            }),
            Err(source) => Err(ModelTerminalCommitError {
                source: InvocationTerminalCommitFailure::Store(source),
                recovery: Box::new(handoff),
            }),
        }
    }

    /// Executes at most one physical tool implementation call.
    ///
    /// Start duplicate suppression and retained terminal recovery have the same
    /// no-repeat semantics as [`Self::execute_model`].
    pub fn execute_tool(
        &self,
        handoff: ToolAttemptHandoff,
    ) -> BoxFuture<'_, Result<ToolAttemptOutcome, ToolAttemptExecutionError>> {
        Box::pin(self.execute_tool_inner(handoff))
    }

    async fn execute_tool_inner(
        &self,
        handoff: ToolAttemptHandoff,
    ) -> Result<ToolAttemptOutcome, ToolAttemptExecutionError> {
        let started = self.start_tool_attempt_inner(handoff).await?;
        let ToolAttemptStartOutcome::Started(dispatch) = started else {
            let ToolAttemptStartOutcome::Recovered { invocation } = started else {
                unreachable!("closed tool attempt start outcome")
            };
            return Ok(ToolAttemptOutcome::Recovered {
                invocation: *invocation,
            });
        };
        let terminal = self.dispatch_started_tool_inner(*dispatch).await;
        self.commit_tool_terminal(terminal)
            .await
            .map_err(ToolAttemptExecutionError::Terminal)
    }

    /// Commits a tool attempt start without performing provider I/O.
    ///
    /// Only [`ToolAttemptStartOutcome::Started`] grants dispatch authority.
    /// This split is intended for bounded ordered coordinators; ordinary
    /// callers should prefer [`Self::execute_tool`].
    pub fn start_tool_attempt(
        &self,
        handoff: ToolAttemptHandoff,
    ) -> BoxFuture<'_, Result<ToolAttemptStartOutcome, ToolAttemptExecutionError>> {
        Box::pin(self.start_tool_attempt_inner(handoff))
    }

    async fn start_tool_attempt_inner(
        &self,
        handoff: ToolAttemptHandoff,
    ) -> Result<ToolAttemptStartOutcome, ToolAttemptExecutionError> {
        validate_tool_handoff(&handoff.fence, &handoff.invocation)?;
        if let Some(recovered) = self.recover_tool_if_started(&handoff).await? {
            let ToolAttemptOutcome::Recovered { invocation } = recovered else {
                return Err(ToolAttemptExecutionError::UnsupportedStoreOutcome);
            };
            return Ok(ToolAttemptStartOutcome::Recovered {
                invocation: Box::new(invocation),
            });
        }
        let provider = self
            .tools
            .resolve(handoff.invocation.intent().descriptor())?;
        let (context, child_budget) = self.prepare_tool_context(&handoff).await?;

        let start_payload = self.event_payload(
            "tool-attempt-started",
            "tool_attempt_started",
            "tool",
            handoff.invocation.intent().invocation_id(),
            handoff.attempt_id,
            handoff.invocation.intent().intent_digest(),
        )?;
        let start_append = worker_append(
            &handoff.fence,
            handoff.invocation.journal_head().clone(),
            handoff.events.start,
            start_payload,
        )
        .map_err(|_| ToolAttemptExecutionError::JournalAppend)?;
        let start = self
            .advance_tool_with_retry(
                start_append,
                &handoff.invocation,
                ToolInvocationTransition::StartAttempt {
                    attempt_id: handoff.attempt_id,
                },
                child_budget,
            )
            .await?;
        let executing = match start {
            ToolInvocationCommitOutcome::Committed { invocation, .. } => invocation,
            ToolInvocationCommitOutcome::Idempotent { .. } => {
                let current = self
                    .store
                    .load_tool_invocation(
                        handoff.fence.tenant_id(),
                        handoff.fence.run_id(),
                        handoff.invocation.intent().invocation_id(),
                    )
                    .await?;
                if current.intent() != handoff.invocation.intent() {
                    return Err(ToolAttemptExecutionError::RecoveredInvocationMismatch);
                }
                if current.attempt_id() != Some(handoff.attempt_id) {
                    return Err(ToolAttemptExecutionError::InvocationAdvanced);
                }
                return Ok(ToolAttemptStartOutcome::Recovered {
                    invocation: Box::new(current),
                });
            }
            _ => return Err(ToolAttemptExecutionError::UnsupportedStoreOutcome),
        };

        Ok(ToolAttemptStartOutcome::Started(Box::new(
            ToolDispatchHandoff {
                fence: handoff.fence,
                invocation: executing,
                terminal_event_id: handoff.events.terminal,
                provider,
                context,
            },
        )))
    }

    /// Performs exactly one provider call for a fresh durable start and retains
    /// its terminal evidence without committing it.
    ///
    /// The returned handoff must be committed with
    /// [`Self::commit_tool_terminal`]. Separating provider completion from the
    /// commit lets a coordinator restore proposal-order journal semantics even
    /// when read-only calls finish out of order.
    pub fn dispatch_started_tool(
        &self,
        handoff: ToolDispatchHandoff,
    ) -> BoxFuture<'_, ToolTerminalCommitHandoff> {
        Box::pin(self.dispatch_started_tool_inner(handoff))
    }

    async fn dispatch_started_tool_inner(
        &self,
        handoff: ToolDispatchHandoff,
    ) -> ToolTerminalCommitHandoff {
        let evidence = if let Some(reason) = handoff.context.stop_reason_at(Instant::now()) {
            ToolTerminalEvidence::Error(tool_stop_error(
                &handoff.context,
                handoff.invocation.intent().descriptor(),
                reason,
            ))
        } else {
            let input = handoff.invocation.intent().input().clone();
            self.dispatch_tool(handoff.provider, handoff.context, input)
                .await
        };
        ToolTerminalCommitHandoff {
            fence: handoff.fence,
            invocation: handoff.invocation,
            event_id: handoff.terminal_event_id,
            evidence,
        }
    }

    /// Commits retained terminal tool evidence without calling the tool.
    pub fn commit_tool_terminal(
        &self,
        handoff: ToolTerminalCommitHandoff,
    ) -> BoxFuture<'_, Result<ToolAttemptOutcome, ToolTerminalCommitError>> {
        Box::pin(self.commit_tool_terminal_inner(handoff))
    }

    async fn commit_tool_terminal_inner(
        &self,
        handoff: ToolTerminalCommitHandoff,
    ) -> Result<ToolAttemptOutcome, ToolTerminalCommitError> {
        let terminal_kind = handoff.kind();
        let (operation, event_kind, transition) = match &handoff.evidence {
            ToolTerminalEvidence::Result(result) => (
                "tool_result_committed",
                "tool-result-committed",
                ToolInvocationTransition::RecordResult {
                    result: result.clone(),
                },
            ),
            ToolTerminalEvidence::Error(error) => (
                "tool_error_committed",
                "tool-error-committed",
                ToolInvocationTransition::RecordError {
                    error: error.clone(),
                },
            ),
        };
        let Some(attempt_id) = handoff.invocation.attempt_id() else {
            return Err(ToolTerminalCommitError {
                source: InvocationTerminalCommitFailure::InvalidInvocationState,
                recovery: Box::new(handoff),
            });
        };
        let Ok(payload) = self.event_payload(
            event_kind,
            operation,
            "tool",
            handoff.invocation.intent().invocation_id(),
            attempt_id,
            handoff.invocation.intent().intent_digest(),
        ) else {
            return Err(ToolTerminalCommitError {
                source: InvocationTerminalCommitFailure::InvalidEventPayload,
                recovery: Box::new(handoff),
            });
        };
        let run = match self
            .store
            .load_run(
                handoff.invocation.intent().tenant_id(),
                handoff.invocation.intent().run_id(),
            )
            .await
        {
            Ok(run) => run,
            Err(source) => {
                return Err(ToolTerminalCommitError {
                    source: InvocationTerminalCommitFailure::Store(source),
                    recovery: Box::new(handoff),
                });
            }
        };
        let Some(journal_head) = run.journal_head().cloned() else {
            return Err(ToolTerminalCommitError {
                source: InvocationTerminalCommitFailure::RunJournalUnavailable,
                recovery: Box::new(handoff),
            });
        };
        let Ok(append) = worker_append(&handoff.fence, journal_head, handoff.event_id, payload)
        else {
            return Err(ToolTerminalCommitError {
                source: InvocationTerminalCommitFailure::InvalidJournalAppend,
                recovery: Box::new(handoff),
            });
        };
        match self
            .advance_tool_with_retry(append, &handoff.invocation, transition, None)
            .await
        {
            Ok(outcome) => Ok(ToolAttemptOutcome::Dispatched {
                terminal: terminal_kind,
                invocation: outcome.invocation().clone(),
            }),
            Err(source) => Err(ToolTerminalCommitError {
                source: InvocationTerminalCommitFailure::Store(source),
                recovery: Box::new(handoff),
            }),
        }
    }

    /// Performs at most one bounded provider reconciliation probe and commits
    /// any authoritative evidence atomically.
    ///
    /// The current invocation is reloaded before provider I/O. If the stable
    /// reconciliation event already won, this returns the terminal revision
    /// without another query or replay. `Pending` performs no durable mutation;
    /// callers should persist a delayed node retry using the supplied interval.
    pub fn reconcile_tool(
        &self,
        handoff: ToolReconciliationAttemptHandoff,
    ) -> BoxFuture<
        '_,
        Result<ToolReconciliationAttemptOutcome, ToolReconciliationAttemptExecutionError>,
    > {
        Box::pin(self.reconcile_tool_inner(handoff))
    }

    async fn reconcile_tool_inner(
        &self,
        handoff: ToolReconciliationAttemptHandoff,
    ) -> Result<ToolReconciliationAttemptOutcome, ToolReconciliationAttemptExecutionError> {
        validate_tool_reconciliation_attempt_handoff(&handoff.fence, &handoff.invocation)?;
        let current = self
            .store
            .load_tool_invocation(
                handoff.fence.tenant_id(),
                handoff.fence.run_id(),
                handoff.invocation.intent().invocation_id(),
            )
            .await?;
        if current.intent() != handoff.invocation.intent() {
            return Err(ToolReconciliationAttemptExecutionError::RecoveredInvocationMismatch);
        }
        if current.attempt_id() != handoff.invocation.attempt_id() {
            return Err(ToolReconciliationAttemptExecutionError::InvocationAdvanced);
        }
        match current.state() {
            ToolInvocationState::Committed { .. } => {
                return Ok(ToolReconciliationAttemptOutcome::Resolved {
                    kind: ToolReconciliationKind::Result,
                    invocation: current,
                });
            }
            ToolInvocationState::Failed { .. } => {
                return Ok(ToolReconciliationAttemptOutcome::Resolved {
                    kind: ToolReconciliationKind::Error,
                    invocation: current,
                });
            }
            ToolInvocationState::Unknown { .. } => {}
            ToolInvocationState::Prepared | ToolInvocationState::Executing { .. } => {
                return Err(ToolReconciliationAttemptExecutionError::InvocationAdvanced);
            }
        }

        let provider = self.tools.resolve(current.intent().descriptor())?;
        if !provider.supports_reconciliation() {
            return Err(ToolReconciliationAttemptExecutionError::ProviderReconciliationUnsupported);
        }
        let context = self
            .prepare_tool_reconciliation_context(&handoff, &current)
            .await?;
        let input = current.intent().input().clone();
        let deadline = tokio::time::Instant::from_std(context.deadline_instant());
        let observation = tokio::select! {
            biased;
            () = context.cancellation().cancelled() => {
                return Err(ToolReconciliationAttemptExecutionError::Stopped {
                    reason: ToolStopReason::Cancelled,
                });
            }
            () = tokio::time::sleep_until(deadline) => {
                return Err(ToolReconciliationAttemptExecutionError::Stopped {
                    reason: ToolStopReason::DeadlineExceeded,
                });
            }
            observation = provider.reconcile(context.clone(), input) => observation?,
        };
        observation.validate()?;

        let evidence = match observation {
            ToolReconciliationObservation::Pending { retry_after } => {
                return Ok(ToolReconciliationAttemptOutcome::Pending {
                    retry_after,
                    invocation: current,
                });
            }
            ToolReconciliationObservation::Result(result) => {
                ToolReconciliationHandoff::result(handoff.fence, current, handoff.event_id, result)?
            }
            ToolReconciliationObservation::Error(error) => {
                if error.external_effect() == ToolExternalEffect::Unknown {
                    return Err(ToolReconciliationAttemptExecutionError::UnresolvedErrorEvidence);
                }
                ToolReconciliationHandoff::error(handoff.fence, current, handoff.event_id, error)?
            }
            _ => {
                return Err(ToolReconciliationAttemptExecutionError::UnsupportedObservation);
            }
        };
        let outcome = self.commit_tool_reconciliation(evidence).await?;
        Ok(ToolReconciliationAttemptOutcome::Resolved {
            kind: outcome.kind(),
            invocation: outcome.invocation().clone(),
        })
    }

    /// Atomically commits authoritative evidence for an unknown tool attempt.
    ///
    /// This is a trusted worker/operations boundary. It validates successful
    /// output against the frozen local schema registry, appends a distinct audit
    /// event, and advances the invocation in one fenced `PostgreSQL` transaction.
    /// It never resolves or calls a tool provider.
    pub fn commit_tool_reconciliation(
        &self,
        handoff: ToolReconciliationHandoff,
    ) -> BoxFuture<'_, Result<ToolReconciliationOutcome, ToolReconciliationCommitError>> {
        Box::pin(self.commit_tool_reconciliation_inner(handoff))
    }

    async fn commit_tool_reconciliation_inner(
        &self,
        handoff: ToolReconciliationHandoff,
    ) -> Result<ToolReconciliationOutcome, ToolReconciliationCommitError> {
        let kind = handoff.kind();
        let (operation, event_kind, transition) = match self.reconciliation_transition(&handoff) {
            Ok(prepared) => prepared,
            Err(source) => {
                return Err(ToolReconciliationCommitError {
                    source,
                    recovery: Box::new(handoff),
                });
            }
        };
        let Some(attempt_id) = handoff.invocation.attempt_id() else {
            return Err(ToolReconciliationCommitError {
                source: ToolReconciliationCommitFailure::InvalidInvocationState,
                recovery: Box::new(handoff),
            });
        };
        let Ok(payload) = self.event_payload(
            event_kind,
            operation,
            "tool",
            handoff.invocation.intent().invocation_id(),
            attempt_id,
            handoff.invocation.intent().intent_digest(),
        ) else {
            return Err(ToolReconciliationCommitError {
                source: ToolReconciliationCommitFailure::InvalidEventPayload,
                recovery: Box::new(handoff),
            });
        };
        let run = match self
            .store
            .load_run(
                handoff.invocation.intent().tenant_id(),
                handoff.invocation.intent().run_id(),
            )
            .await
        {
            Ok(run) => run,
            Err(source) => {
                return Err(ToolReconciliationCommitError {
                    source: ToolReconciliationCommitFailure::Store(source),
                    recovery: Box::new(handoff),
                });
            }
        };
        let Some(journal_head) = run.journal_head().cloned() else {
            return Err(ToolReconciliationCommitError {
                source: ToolReconciliationCommitFailure::RunJournalUnavailable,
                recovery: Box::new(handoff),
            });
        };
        let Ok(append) = worker_append(&handoff.fence, journal_head, handoff.event_id, payload)
        else {
            return Err(ToolReconciliationCommitError {
                source: ToolReconciliationCommitFailure::InvalidJournalAppend,
                recovery: Box::new(handoff),
            });
        };
        match self
            .advance_tool_with_retry(append, &handoff.invocation, transition, None)
            .await
        {
            Ok(ToolInvocationCommitOutcome::Committed { event, invocation }) => {
                Ok(ToolReconciliationOutcome::Committed {
                    kind,
                    event,
                    invocation,
                })
            }
            Ok(ToolInvocationCommitOutcome::Idempotent { event, invocation }) => {
                Ok(ToolReconciliationOutcome::Idempotent {
                    kind,
                    event,
                    invocation,
                })
            }
            Ok(_) => Err(ToolReconciliationCommitError {
                source: ToolReconciliationCommitFailure::UnsupportedStoreOutcome,
                recovery: Box::new(handoff),
            }),
            Err(source) => Err(ToolReconciliationCommitError {
                source: ToolReconciliationCommitFailure::Store(source),
                recovery: Box::new(handoff),
            }),
        }
    }

    fn reconciliation_transition(
        &self,
        handoff: &ToolReconciliationHandoff,
    ) -> Result<
        (&'static str, &'static str, ToolInvocationTransition),
        ToolReconciliationCommitFailure,
    > {
        match &handoff.evidence {
            ToolReconciliationEvidence::Result(result) => {
                self.schemas
                    .validate_bounded(result.output_schema(), result.output())
                    .map_err(|source| ToolReconciliationCommitFailure::OutputSchema { source })?;
                Ok((
                    "tool_result_committed",
                    "tool-reconciliation-result-committed",
                    ToolInvocationTransition::ReconcileResult {
                        result: result.clone(),
                    },
                ))
            }
            ToolReconciliationEvidence::Error(error) => Ok((
                "tool_error_committed",
                "tool-reconciliation-error-committed",
                ToolInvocationTransition::ReconcileError {
                    error: error.clone(),
                },
            )),
        }
    }

    async fn dispatch_model(
        &self,
        provider: Arc<dyn stateknot_core::Model>,
        context: ModelContext,
        request: ModelRequest,
        stream_sink: Option<Arc<dyn ModelEventSink>>,
    ) -> ModelTerminalEvidence {
        match request.response_mode() {
            ModelResponseMode::Complete => {
                Self::dispatch_complete_model(provider, context, request).await
            }
            ModelResponseMode::Streaming => {
                Self::dispatch_streaming_model(provider, context, request, stream_sink).await
            }
        }
    }

    async fn dispatch_complete_model(
        provider: Arc<dyn stateknot_core::Model>,
        context: ModelContext,
        request: ModelRequest,
    ) -> ModelTerminalEvidence {
        let result = tokio::select! {
            biased;
            () = context.cancellation().cancelled() => {
                return ModelTerminalEvidence::Error(model_stop_error(
                    &context,
                    provider.descriptor(),
                    ModelStopReason::Cancelled,
                ));
            }
            () = tokio::time::sleep_until(tokio::time::Instant::from_std(context.deadline_instant())) => {
                return ModelTerminalEvidence::Error(model_stop_error(
                    &context,
                    provider.descriptor(),
                    ModelStopReason::DeadlineExceeded,
                ));
            }
            result = provider.invoke(context.clone(), request.clone()) => result,
        };
        match result {
            Ok(response)
                if response.provenance().attempt_id() == context.attempt_id()
                    && response
                        .validate_for(provider.descriptor(), &request)
                        .is_ok() =>
            {
                ModelTerminalEvidence::Response(response)
            }
            Ok(_) => ModelTerminalEvidence::Error(model_contract_error(
                &context,
                provider.descriptor(),
                ModelErrorPhase::Response,
                "runtime.model.invalid_response",
                "Model provider returned a response outside its registered contract.",
            )),
            Err(error)
                if error
                    .validate_for(&context, provider.descriptor(), &request)
                    .is_ok() =>
            {
                ModelTerminalEvidence::Error(error)
            }
            Err(_) => ModelTerminalEvidence::Error(model_contract_error(
                &context,
                provider.descriptor(),
                ModelErrorPhase::Response,
                "runtime.model.invalid_error",
                "Model provider returned failure evidence outside its registered contract.",
            )),
        }
    }

    async fn dispatch_streaming_model(
        provider: Arc<dyn stateknot_core::Model>,
        context: ModelContext,
        request: ModelRequest,
        stream_sink: Option<Arc<dyn ModelEventSink>>,
    ) -> ModelTerminalEvidence {
        let Some(sink) = stream_sink else {
            return ModelTerminalEvidence::Error(model_contract_error(
                &context,
                provider.descriptor(),
                ModelErrorPhase::Preparation,
                "runtime.model.missing_stream_sink",
                "Streaming model execution has no durable event sink.",
            ));
        };
        let Ok(mut accumulator) =
            ModelEventAccumulator::new(context.attempt_id(), provider.descriptor(), &request)
        else {
            return ModelTerminalEvidence::Error(model_contract_error(
                &context,
                provider.descriptor(),
                ModelErrorPhase::Preparation,
                "runtime.model.invalid_stream_setup",
                "Streaming model execution could not satisfy its registered contract.",
            ));
        };
        let mut stream = provider.stream(context.clone(), request.clone());
        loop {
            let next = tokio::select! {
                biased;
                () = context.cancellation().cancelled() => {
                    return ModelTerminalEvidence::Error(model_stop_error(
                        &context,
                        provider.descriptor(),
                        ModelStopReason::Cancelled,
                    ));
                }
                () = tokio::time::sleep_until(tokio::time::Instant::from_std(context.deadline_instant())) => {
                    return ModelTerminalEvidence::Error(model_stop_error(
                        &context,
                        provider.descriptor(),
                        ModelStopReason::DeadlineExceeded,
                    ));
                }
                next = poll_fn(|task| stream.as_mut().poll_next(task)) => next,
            };
            match next {
                Some(Ok(event)) => {
                    if let Err(evidence) = Self::accept_model_stream_event(
                        provider.as_ref(),
                        &context,
                        &mut accumulator,
                        sink.as_ref(),
                        event,
                    )
                    .await
                    {
                        return evidence;
                    }
                }
                Some(Err(error))
                    if error
                        .validate_for(&context, provider.descriptor(), &request)
                        .is_ok() =>
                {
                    return ModelTerminalEvidence::Error(error);
                }
                Some(Err(_)) => {
                    return ModelTerminalEvidence::Error(model_contract_error(
                        &context,
                        provider.descriptor(),
                        ModelErrorPhase::Stream,
                        "runtime.model.invalid_stream_error",
                        "Model provider returned invalid stream failure evidence.",
                    ));
                }
                None => return finish_model_stream(&context, provider.descriptor(), accumulator),
            }
        }
    }

    async fn accept_model_stream_event(
        provider: &dyn stateknot_core::Model,
        context: &ModelContext,
        accumulator: &mut ModelEventAccumulator<'_>,
        sink: &dyn ModelEventSink,
        event: ModelEvent,
    ) -> Result<(), ModelTerminalEvidence> {
        if accumulator.push(event.clone()).is_err() {
            return Err(ModelTerminalEvidence::Error(model_contract_error(
                context,
                provider.descriptor(),
                ModelErrorPhase::Stream,
                "runtime.model.invalid_stream_event",
                "Model provider emitted an invalid semantic stream event.",
            )));
        }
        let emitted = tokio::select! {
            biased;
            () = context.cancellation().cancelled() => {
                return Err(ModelTerminalEvidence::Error(model_stop_error(
                    context,
                    provider.descriptor(),
                    ModelStopReason::Cancelled,
                )));
            }
            () = tokio::time::sleep_until(tokio::time::Instant::from_std(context.deadline_instant())) => {
                return Err(ModelTerminalEvidence::Error(model_stop_error(
                    context,
                    provider.descriptor(),
                    ModelStopReason::DeadlineExceeded,
                )));
            }
            emitted = sink.emit(event) => emitted,
        };
        emitted.map_err(|_| {
            ModelTerminalEvidence::Error(model_contract_error(
                context,
                provider.descriptor(),
                ModelErrorPhase::Stream,
                "runtime.model.stream_sink_failed",
                "The durable model stream sink did not accept an event.",
            ))
        })
    }

    async fn dispatch_tool(
        &self,
        provider: Arc<dyn stateknot_core::ErasedTool>,
        context: ToolContext,
        input: stateknot_core::ToolInput,
    ) -> ToolTerminalEvidence {
        let result = tokio::select! {
            biased;
            () = context.cancellation().cancelled() => {
                return ToolTerminalEvidence::Error(tool_stop_error(
                    &context,
                    provider.descriptor(),
                    ToolStopReason::Cancelled,
                ));
            }
            () = tokio::time::sleep_until(tokio::time::Instant::from_std(context.deadline_instant())) => {
                return ToolTerminalEvidence::Error(tool_stop_error(
                    &context,
                    provider.descriptor(),
                    ToolStopReason::DeadlineExceeded,
                ));
            }
            result = provider.call(context.clone(), input) => result,
        };
        match result {
            Ok(result) if result.validate_for(&context, provider.descriptor()).is_ok() => {
                ToolTerminalEvidence::Result(result)
            }
            Ok(_) => ToolTerminalEvidence::Error(tool_contract_error(
                &context,
                provider.descriptor(),
                ToolErrorPhase::Result,
                true,
                "runtime.tool.invalid_result",
                "Tool returned a result outside its registered contract.",
            )),
            Err(error) if error.validate_for(&context, provider.descriptor()).is_ok() => {
                ToolTerminalEvidence::Error(error)
            }
            Err(_) => ToolTerminalEvidence::Error(tool_contract_error(
                &context,
                provider.descriptor(),
                ToolErrorPhase::Execution,
                false,
                "runtime.tool.invalid_error",
                "Tool returned failure evidence outside its registered contract.",
            )),
        }
    }

    async fn advance_model_with_retry(
        &self,
        append: JournalAppend,
        expected: &ModelInvocation,
        transition: ModelInvocationTransition,
        child_budget: Option<Digest>,
    ) -> Result<ModelInvocationCommitOutcome, StoreError> {
        let mut attempt = 1_u8;
        loop {
            match self
                .store
                .advance_model_invocation_with_child_budget(
                    append.clone(),
                    &expected.head(),
                    transition.clone(),
                    child_budget,
                )
                .await
            {
                Ok(outcome) => return Ok(outcome),
                Err(error)
                    if attempt < self.options.maximum_mutation_attempts()
                        && error.is_retryable() =>
                {
                    tokio::time::sleep(exponential_backoff(
                        self.options.mutation_retry_initial_delay(),
                        attempt,
                    ))
                    .await;
                    attempt = attempt.saturating_add(1);
                }
                Err(error) => return Err(error),
            }
        }
    }

    async fn advance_tool_with_retry(
        &self,
        append: JournalAppend,
        expected: &ToolInvocation,
        transition: ToolInvocationTransition,
        child_budget: Option<Digest>,
    ) -> Result<ToolInvocationCommitOutcome, StoreError> {
        let mut attempt = 1_u8;
        loop {
            match self
                .store
                .advance_tool_invocation_with_child_budget(
                    append.clone(),
                    &expected.head(),
                    transition.clone(),
                    child_budget,
                )
                .await
            {
                Ok(outcome) => return Ok(outcome),
                Err(error)
                    if attempt < self.options.maximum_mutation_attempts()
                        && error.is_retryable() =>
                {
                    tokio::time::sleep(exponential_backoff(
                        self.options.mutation_retry_initial_delay(),
                        attempt,
                    ))
                    .await;
                    attempt = attempt.saturating_add(1);
                }
                Err(error) => return Err(error),
            }
        }
    }

    fn event_payload(
        &self,
        kind: &'static str,
        operation: &'static str,
        binding_kind: &'static str,
        invocation_id: InvocationId,
        attempt_id: AttemptId,
        intent_digest: Digest,
    ) -> Result<JournalPayload, InvocationEventPayloadError> {
        let data = BoundedJson::try_from_value(json!({
            "operation": operation,
            "binding_kind": binding_kind,
            "invocation_id": invocation_id.to_string(),
            "attempt_id": attempt_id.to_string(),
            "intent_digest": digest_hex(intent_digest)
        }))
        .map_err(|_| InvocationEventPayloadError::Invalid)?;
        self.schemas
            .validate_bounded(&self.event_schema, &data)
            .map_err(|_| InvocationEventPayloadError::Invalid)?;
        JournalPayload::new(
            self.event_schema.clone(),
            JournalEventKind::new(kind).map_err(|_| InvocationEventPayloadError::Invalid)?,
            data,
        )
        .map_err(|_| InvocationEventPayloadError::Invalid)
    }
}

/// Startup failure for the durable invocation executor.
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum DurableInvocationExecutorBuildError {
    /// Embedded release schema was malformed.
    #[error(transparent)]
    EventSchema(#[from] StandardInvocationExecutionSchemaError),
    /// Frozen offline schema registry omitted the exact standard event schema.
    #[error("invocation execution event schema is absent from the frozen registry")]
    MissingEventSchema,
}

/// Failure before or around one model attempt dispatch.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ModelAttemptExecutionError {
    /// Handoff invariants changed before execution.
    #[error(transparent)]
    Handoff(#[from] InvocationAttemptHandoffError),
    /// No exact provider binding was installed.
    #[error(transparent)]
    Registry(#[from] ModelProviderRegistryError),
    /// Store read/start mutation failed before provider I/O.
    #[error(transparent)]
    Store(#[from] StoreError),
    /// Trusted run provenance crossed the retained fence.
    #[error("stored run provenance does not match the model attempt fence")]
    RunProvenanceMismatch,
    /// Runtime clock observation failed.
    #[error(transparent)]
    Clock(#[from] InvocationClockError),
    /// Trusted admission/accounting provider failed.
    #[error(transparent)]
    BudgetProvider(#[from] InvocationBudgetProviderError),
    /// Remaining capacity cannot admit the exact request snapshot.
    #[error("remaining run budget cannot admit the model attempt")]
    BudgetInsufficient,
    /// Finite model context could not be constructed.
    #[error(transparent)]
    Context(#[from] ModelContextError),
    /// Cancellation or deadline won before the durable start.
    #[error("model attempt stopped before durable start: {reason:?}")]
    StoppedBeforeStart {
        /// Deterministic stop reason.
        reason: ModelStopReason,
    },
    /// Standard public-safe journal payload could not be constructed.
    #[error("model invocation journal payload is invalid")]
    EventPayload(#[from] InvocationEventPayloadError),
    /// Worker journal append could not be constructed.
    #[error("model invocation worker journal append is invalid")]
    JournalAppend,
    /// Idempotent start recovery loaded another durable intent.
    #[error("recovered model invocation does not match the retained intent")]
    RecoveredInvocationMismatch,
    /// Another physical attempt advanced the invocation from this handoff.
    #[error("model invocation advanced under another physical attempt")]
    InvocationAdvanced,
    /// The store returned a future commit outcome unknown to this runtime.
    #[error("model invocation store outcome is unsupported by this runtime")]
    UnsupportedStoreOutcome,
    /// Provider I/O completed but terminal persistence needs a no-dispatch retry.
    #[error(transparent)]
    Terminal(#[from] ModelTerminalCommitError),
}

/// Failure before or around one tool attempt dispatch.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ToolAttemptExecutionError {
    /// Handoff invariants changed before execution.
    #[error(transparent)]
    Handoff(#[from] InvocationAttemptHandoffError),
    /// No exact executable tool binding was installed.
    #[error(transparent)]
    Registry(#[from] ToolProviderRegistryError),
    /// Store read/start mutation failed before tool I/O.
    #[error(transparent)]
    Store(#[from] StoreError),
    /// Trusted run provenance crossed the retained fence.
    #[error("stored run provenance does not match the tool attempt fence")]
    RunProvenanceMismatch,
    /// Runtime clock observation failed.
    #[error(transparent)]
    Clock(#[from] InvocationClockError),
    /// Trusted admission/accounting provider failed.
    #[error(transparent)]
    BudgetProvider(#[from] InvocationBudgetProviderError),
    /// Remaining capacity cannot admit the exact tool risk class.
    #[error("remaining run budget cannot admit the tool attempt")]
    BudgetInsufficient,
    /// Finite tool context could not be constructed.
    #[error(transparent)]
    Context(#[from] ToolContextError),
    /// Durable input no longer fits the trusted context/descriptor snapshot.
    #[error(transparent)]
    Input(#[from] ToolInputValidationError),
    /// Cancellation or deadline won before the durable start.
    #[error("tool attempt stopped before durable start: {reason:?}")]
    StoppedBeforeStart {
        /// Deterministic stop reason.
        reason: ToolStopReason,
    },
    /// Standard public-safe journal payload could not be constructed.
    #[error("tool invocation journal payload is invalid")]
    EventPayload(#[from] InvocationEventPayloadError),
    /// Worker journal append could not be constructed.
    #[error("tool invocation worker journal append is invalid")]
    JournalAppend,
    /// Idempotent start recovery loaded another durable intent.
    #[error("recovered tool invocation does not match the retained intent")]
    RecoveredInvocationMismatch,
    /// Another physical attempt advanced the invocation from this handoff.
    #[error("tool invocation advanced under another physical attempt")]
    InvocationAdvanced,
    /// The store returned a future commit outcome unknown to this runtime.
    #[error("tool invocation store outcome is unsupported by this runtime")]
    UnsupportedStoreOutcome,
    /// Tool I/O completed but terminal persistence needs a no-dispatch retry.
    #[error(transparent)]
    Terminal(#[from] ToolTerminalCommitError),
}

/// Invalid standard invocation journal event data.
#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum InvocationEventPayloadError {
    /// Bounds, pinned schema, event kind, or payload construction failed.
    #[error("standard invocation event payload is invalid")]
    Invalid,
}

#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
#[error("invocation worker journal append is invalid")]
struct InvocationJournalAppendError;

fn validate_run_provenance(
    provenance: &AgentResultProvenance,
    fence: &RunFence,
) -> Result<(), ModelAttemptExecutionError> {
    if provenance.tenant_id() != fence.tenant_id() || provenance.run_id() != fence.run_id() {
        return Err(ModelAttemptExecutionError::RunProvenanceMismatch);
    }
    Ok(())
}

fn validate_tool_run_provenance(
    provenance: &AgentResultProvenance,
    fence: &RunFence,
) -> Result<(), ToolAttemptExecutionError> {
    if provenance.tenant_id() != fence.tenant_id() || provenance.run_id() != fence.run_id() {
        return Err(ToolAttemptExecutionError::RunProvenanceMismatch);
    }
    Ok(())
}

fn validate_model_budget(
    remaining: &BudgetRemaining,
    request: &ModelRequest,
) -> Result<(), ModelAttemptExecutionError> {
    if remaining.model_attempts() == ExecutionCount::ZERO
        || remaining.model_turns() == ExecutionCount::ZERO
        || remaining.input_tokens() < request.limits().max_input_tokens()
        || remaining.output_tokens() < request.limits().max_output_tokens()
        || remaining.input_bytes() < request.content_bytes()
    {
        return Err(ModelAttemptExecutionError::BudgetInsufficient);
    }
    Ok(())
}

fn validate_tool_budget(
    remaining: &BudgetRemaining,
    risk: ToolRisk,
) -> Result<(), ToolAttemptExecutionError> {
    if remaining.tool_calls() == ExecutionCount::ZERO
        || (risk != ToolRisk::ReadOnly && remaining.write_calls() == ExecutionCount::ZERO)
    {
        return Err(ToolAttemptExecutionError::BudgetInsufficient);
    }
    Ok(())
}

fn worker_append(
    fence: &RunFence,
    head: stateknot_core::JournalHead,
    event_id: EventId,
    payload: JournalPayload,
) -> Result<JournalAppend, InvocationJournalAppendError> {
    let intent = JournalEventIntent::worker(
        fence.tenant_id().clone(),
        fence.run_id(),
        event_id,
        fence.clone(),
        payload,
    )
    .map_err(|_| InvocationJournalAppendError)?;
    JournalAppend::new(JournalExpectation::exact(head), intent)
        .map_err(|_| InvocationJournalAppendError)
}

fn finish_model_stream(
    context: &ModelContext,
    descriptor: &stateknot_core::ModelDescriptor,
    accumulator: ModelEventAccumulator<'_>,
) -> ModelTerminalEvidence {
    match accumulator.finish() {
        Ok(response) => ModelTerminalEvidence::Response(response),
        Err(_) => ModelTerminalEvidence::Error(model_contract_error(
            context,
            descriptor,
            ModelErrorPhase::Stream,
            "runtime.model.incomplete_stream",
            "Model provider stream ended without a valid terminal event.",
        )),
    }
}

fn model_stop_error(
    context: &ModelContext,
    descriptor: &stateknot_core::ModelDescriptor,
    reason: ModelStopReason,
) -> ModelError {
    let (category, code, message) = match reason {
        ModelStopReason::Cancelled => (
            FailureCategory::Cancelled,
            "runtime.model.cancelled",
            "Model attempt stopped after cancellation was requested.",
        ),
        ModelStopReason::DeadlineExceeded => (
            FailureCategory::DeadlineExceeded,
            "runtime.model.deadline_exceeded",
            "Model attempt exceeded its effective deadline.",
        ),
        _ => (
            FailureCategory::Internal,
            "runtime.model.unsupported_stop_reason",
            "Model attempt stopped for a reason unsupported by this runtime.",
        ),
    };
    ModelError::new(
        runtime_failure(category, code, message, RetryAdvice::Never),
        ModelErrorPhase::Dispatch,
        ModelErrorProvenance::new(
            context.attempt_id(),
            descriptor.metadata().identity().clone(),
            None,
            None,
            None,
        ),
        None,
    )
}

fn model_contract_error(
    context: &ModelContext,
    descriptor: &stateknot_core::ModelDescriptor,
    phase: ModelErrorPhase,
    code: &'static str,
    message: &'static str,
) -> ModelError {
    ModelError::new(
        runtime_failure(FailureCategory::Internal, code, message, RetryAdvice::Never),
        phase,
        ModelErrorProvenance::new(
            context.attempt_id(),
            descriptor.metadata().identity().clone(),
            None,
            None,
            None,
        ),
        None,
    )
}

fn tool_stop_error(
    context: &ToolContext,
    descriptor: &stateknot_core::ToolDescriptor,
    reason: ToolStopReason,
) -> ToolError {
    let risk = descriptor.semantics().risk();
    let (failure, effect) = if risk == ToolRisk::ReadOnly {
        let (category, code, message) = match reason {
            ToolStopReason::Cancelled => (
                FailureCategory::Cancelled,
                "runtime.tool.cancelled",
                "Tool attempt stopped after cancellation was requested.",
            ),
            ToolStopReason::DeadlineExceeded => (
                FailureCategory::DeadlineExceeded,
                "runtime.tool.deadline_exceeded",
                "Tool attempt exceeded its effective deadline.",
            ),
            _ => (
                FailureCategory::Internal,
                "runtime.tool.unsupported_stop_reason",
                "Tool attempt stopped for a reason unsupported by this runtime.",
            ),
        };
        (
            runtime_failure(category, code, message, RetryAdvice::Never),
            ToolExternalEffect::NotApplicable,
        )
    } else {
        let (code, message) = match reason {
            ToolStopReason::Cancelled => (
                "runtime.tool.cancelled_outcome_unknown",
                "A cancelled tool write may have changed external state and requires reconciliation.",
            ),
            ToolStopReason::DeadlineExceeded => (
                "runtime.tool.deadline_outcome_unknown",
                "A timed-out tool write may have changed external state and requires reconciliation.",
            ),
            _ => (
                "runtime.tool.unsupported_stop_reason_outcome_unknown",
                "A stopped tool write may have changed external state and requires reconciliation.",
            ),
        };
        (
            runtime_failure(
                FailureCategory::AmbiguousExternalOutcome,
                code,
                message,
                RetryAdvice::ReconcileFirst,
            ),
            ToolExternalEffect::Unknown,
        )
    };
    ToolError::new(
        failure,
        ToolErrorPhase::Execution,
        effect,
        ToolErrorProvenance::for_invocation(context, descriptor),
    )
    .expect("runtime stop evidence is constructed from valid risk/effect pairs")
}

fn tool_contract_error(
    context: &ToolContext,
    descriptor: &stateknot_core::ToolDescriptor,
    phase: ToolErrorPhase,
    nominal_success: bool,
    code: &'static str,
    message: &'static str,
) -> ToolError {
    let risk = descriptor.semantics().risk();
    let (category, advice, effect) = match risk {
        ToolRisk::ReadOnly => (
            FailureCategory::Internal,
            RetryAdvice::Never,
            ToolExternalEffect::NotApplicable,
        ),
        ToolRisk::IdempotentWrite | ToolRisk::NonIdempotentWrite if nominal_success => (
            FailureCategory::Internal,
            RetryAdvice::Never,
            ToolExternalEffect::Applied,
        ),
        ToolRisk::IdempotentWrite | ToolRisk::NonIdempotentWrite => (
            FailureCategory::AmbiguousExternalOutcome,
            RetryAdvice::ReconcileFirst,
            ToolExternalEffect::Unknown,
        ),
    };
    ToolError::new(
        runtime_failure(category, code, message, advice),
        phase,
        effect,
        ToolErrorProvenance::for_invocation(context, descriptor),
    )
    .expect("runtime adapter-contract evidence is constructed from valid risk/effect pairs")
}

fn runtime_failure(
    category: FailureCategory,
    code: &'static str,
    message: &'static str,
    advice: RetryAdvice,
) -> Failure {
    Failure::new(
        FailureId::generate(),
        category,
        FailureCode::new(code).expect("runtime failure code is static and valid"),
        FailureOrigin::new("stateknot.runtime")
            .expect("runtime failure origin is static and valid"),
        FailureMessage::new(message).expect("runtime failure message is static and valid"),
        advice,
    )
    .expect("runtime failure category and advice are statically compatible")
}

fn exponential_backoff(initial: Duration, attempt: u8) -> Duration {
    let multiplier = 1_u32
        .checked_shl(u32::from(attempt.saturating_sub(1)))
        .unwrap_or(u32::MAX);
    initial
        .checked_mul(multiplier)
        .unwrap_or(MAX_MUTATION_RETRY_DELAY)
        .min(MAX_MUTATION_RETRY_DELAY)
}

fn digest_hex(digest: Digest) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut value = String::with_capacity(Digest::SHA256_LEN * 2);
    for byte in digest.as_bytes() {
        value.push(char::from(HEX[usize::from(byte >> 4)]));
        value.push(char::from(HEX[usize::from(byte & 0x0f)]));
    }
    value
}

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

    #[test]
    fn event_ids_and_retry_options_reject_unsafe_shapes() {
        let event = EventId::generate();
        assert_eq!(
            InvocationAttemptEventIds::new(event, event),
            Err(InvocationAttemptEventIdsError::Duplicate)
        );
        assert_eq!(
            DurableInvocationExecutorOptions::new(0, Duration::from_millis(1)),
            Err(DurableInvocationExecutorOptionsError::InvalidMutationAttempts)
        );
        assert_eq!(
            DurableInvocationExecutorOptions::new(1, Duration::ZERO),
            Err(DurableInvocationExecutorOptionsError::InvalidMutationRetryDelay)
        );
    }

    #[test]
    fn system_clock_produces_a_canonical_paired_observation() {
        let before = Instant::now();
        let observation = SystemInvocationClock.observe().unwrap();
        assert!(observation.observed_at().unix_micros() > 0);
        assert!(observation.observed_instant() >= before);
    }
}