1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
//! [`StepCtx`] — the only door out of a skill.
//!
//! Everything non-deterministic or externally visible passes through here, and
//! that is what makes replay sound. A skill holds no clock, no socket, and no
//! RNG of its own; it holds a context that journals.
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
use rand::SeedableRng;
use rand_chacha::ChaCha8Rng;
use serde_json::Value;
use crate::case::{CaseStore, EventStore, TaskStore, TimerStore};
use crate::core::{
AwaitSpec, Calendar, CaseId, CaseStatus, CaseVersion, CorrelationKey, Deadline, DeadlineSpec,
DeadlineState, Decision, Effect, EffectDescriptor, EffectKey, Epoch, Ledger, OnExpiry, Phase,
PolicyError, RunId, StepError, StepId, Subscription, Tainted, Task, TaskId, TaskSpec,
TaskState, Timestamp, canon,
};
/// The event kind a decision arrives as.
///
/// Human tasks reuse the durable-wait machinery wholesale: completing a task
/// delivers an event of this kind correlated to the task id, and the waiting run
/// resumes exactly as it would for any other message.
pub(crate) const TASK_DECIDED: &str = "agentplane.task.decided";
use crate::journal::{Append, EffectReplay, JournalStore, RecordKind, StepCursor};
use super::effects::{Clock, ResolveDeadline};
use super::metrics;
use super::telemetry;
use tracing::Instrument;
/// What the wiring declares about an effect's data ceilings, carried to the
/// manifest gate beside the descriptor.
///
/// A separate value because the descriptor cannot carry it: the descriptor is
/// the effect key, and a reviewed allowance is not part of what a call asks
/// for — a catalogue edit re-keying history is the failure that rule prevents.
#[derive(Debug, Clone, Copy)]
#[cfg_attr(not(feature = "manifest"), allow(dead_code))]
pub(crate) struct DeclaredCeilings {
pub max_input: crate::core::Sensitivity,
pub output: crate::core::Sensitivity,
}
impl DeclaredCeilings {
pub(crate) fn of<E: Effect + ?Sized>(effect: &E) -> Self {
Self {
max_input: effect.max_sensitivity(),
output: effect.output_sensitivity(),
}
}
}
/// The case-facing services a step may reach, when the runtime has them.
#[derive(Clone)]
pub(crate) struct CaseContext {
pub cases: Arc<dyn CaseStore>,
/// Only human tasks need this.
pub tasks: Option<Arc<dyn TaskStore>>,
/// Only durable waits need this. Correlation, state, and obligations work
/// without it, so a runtime that never waits is not made to configure one.
pub events: Option<Arc<dyn EventStore>>,
pub calendar: Arc<dyn Calendar>,
pub case_id: CaseId,
/// The case's business keys as recorded at binding.
///
/// Carried on the context rather than fetched on demand because a fetch is
/// a store read, and a store read inside the deterministic zone is exactly
/// the non-determinism the effect protocol exists to forbid — a key added
/// to the case next month would change what a replayed run resolves. The
/// journal's `CaseBound` record is the source on both the live and the
/// resumed path.
pub correlation: Vec<crate::core::CorrelationKey>,
}
impl CaseContext {
pub(crate) fn id(&self) -> CaseId {
self.case_id
}
}
impl std::fmt::Debug for CaseContext {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CaseContext")
.field("case_id", &self.case_id)
.finish_non_exhaustive()
}
}
/// What the journal says about a durable wait a replay just met.
///
/// Internal to the wait machinery: `Recorded` carries the delivered value, and
/// `Repair` says the wait was announced but its registration may not have
/// survived — the caller re-registers idempotently under the same key.
enum ReplayedWait {
Recorded(Tainted<Value>),
Repair,
}
/// How a step is being executed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
/// Normal execution: effects are performed and journaled.
Live,
/// Re-execution from history. Effects are read back, never performed.
///
/// When the cursor runs out, execution continues live — which is exactly
/// how a crashed run resumes mid-flight instead of starting over.
///
/// **Resume is for crashes, not for code changes.** It requires the journal
/// to be a *prefix* of what the current code does. A journal written by a
/// different program is divergence, and the run is quarantined rather than
/// continued — which is the desired outcome, not a limitation. Continuing
/// would graft new behaviour onto a history that never produced it, and the
/// resulting audit trail would be a plausible lie.
///
/// To run changed code against recorded inputs, use [`Mode::Strict`] as a
/// regression check and start a fresh run for real work.
Resume,
/// Verification. Reaching the end of history is itself a failure, because it
/// means this build does more than the recorded one did.
Strict,
}
impl Mode {
#[must_use]
pub fn is_replaying(self) -> bool {
matches!(self, Self::Resume | Self::Strict)
}
}
/// What a step needs to know about itself.
///
/// Gathered into a struct because the alternative was eight positional
/// arguments, several of them the same shape — an ordering mistake waiting to
/// compile cleanly.
#[derive(Debug)]
pub(crate) struct Frame {
pub run: RunId,
pub epoch: Epoch,
pub step: StepId,
/// Whether this frame is doing the work or undoing it.
pub phase: Phase,
pub mode: Mode,
pub case: Option<CaseContext>,
/// Durable wake-ups. Deliberately *not* inside `CaseContext`: a timer has
/// nothing to correlate and no business horizon to bound it, so requiring a
/// case would deny durable sleep to exactly the plain runs that most want
/// it — including a retry backing off past the point where holding a worker
/// is reasonable.
pub timers: Option<Arc<dyn TimerStore>>,
pub blobs: Option<Arc<dyn crate::blob::BlobStore>>,
pub memories: Option<Arc<dyn crate::memory::MemoryStore>>,
/// The plane's embedder and index, paired because a query vector is only
/// meaningful against the index it was built for.
pub semantic: Option<Arc<super::SemanticMemory>>,
pub authorities: Option<Arc<dyn crate::authority::AuthorityStore>>,
/// The plane's checked catalogue and transport, for [`StepCtx::call_tool`].
#[cfg(feature = "manifest")]
pub tools: Option<(
Arc<crate::tools::ToolCatalog>,
Arc<dyn crate::tools::ToolClient>,
)>,
pub meter: crate::runtime::metrics::Meter,
#[cfg(feature = "keyring")]
pub keyring: Option<Arc<dyn crate::keyring::KeyRing>>,
pub tenant: crate::core::TenantId,
pub ledger: Arc<Mutex<Ledger>>,
/// The authorization engine, if this plane has one.
///
/// `None` means no policy layer — which is the same behaviour as a
/// permissive engine, and deliberately the only way to spell it. See
/// `core::policy` on why there is no `AllowAll`.
pub policy: Option<Arc<dyn crate::core::PolicyEngine>>,
/// The chain this run acts under, for the policy context.
pub identity: Option<crate::core::Delegation>,
/// Who is acting, for the policy principal.
pub agent: String,
/// The plane this step runs on, so it can commission other agents on it.
pub plane: std::sync::Weak<super::Runtime>,
/// The declaration this agent runs under, if it has one.
///
/// Held by the *runtime* and handed down, never held by a skill. An agent
/// has skills, not the other way round — a skill separately configured with
/// a copy of the agent's own declaration would be able to disagree with the
/// agent about what the agent is.
#[cfg(feature = "manifest")]
pub manifest: Option<Arc<crate::manifest::Manifest>>,
/// The plane's workload identity, for signing what it tells a callee.
///
/// Separate from the store's signer even though a deployment should give
/// both the same one: the store signs *records*, this signs *outward
/// claims*, and a plane can legitimately have one without the other.
pub signer: Option<Arc<dyn crate::core::Signer>>,
/// Group records this step and phase already wrote, with how many opens
/// and settlements each name has. Always empty on a live run. Group
/// records are not effects, so the cursor cannot dedup them; without this
/// a resumed step re-opening or re-settling its group at the frontier
/// would report one group as two. Counts rather than a set, because a
/// step may legitimately open and settle the same name twice — a set
/// would swallow the second pair of a pass that recorded only the first.
pub recorded_groups: std::collections::BTreeMap<String, RecordedGroup>,
}
/// How often a group name already appears on one step-and-phase's record.
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct RecordedGroup {
pub(crate) opened: usize,
pub(crate) settled: usize,
}
/// Per-step execution context.
#[derive(Debug)]
pub struct StepCtx<'a> {
store: &'a Arc<dyn JournalStore>,
run: RunId,
epoch: Epoch,
step: StepId,
phase: Phase,
ordinal: u32,
mode: Mode,
cursor: StepCursor,
rng: ChaCha8Rng,
case: Option<CaseContext>,
timers: Option<Arc<dyn TimerStore>>,
blobs: Option<Arc<dyn crate::blob::BlobStore>>,
memories: Option<Arc<dyn crate::memory::MemoryStore>>,
semantic: Option<Arc<super::SemanticMemory>>,
authorities: Option<Arc<dyn crate::authority::AuthorityStore>>,
#[cfg(feature = "manifest")]
tools: Option<(
Arc<crate::tools::ToolCatalog>,
Arc<dyn crate::tools::ToolClient>,
)>,
meter: crate::runtime::metrics::Meter,
#[cfg(feature = "keyring")]
keyring: Option<Arc<dyn crate::keyring::KeyRing>>,
tenant: crate::core::TenantId,
/// The run's budget. Shared because it spans steps; a step never gets its
/// own allowance to blow.
ledger: Arc<Mutex<Ledger>>,
policy: Option<Arc<dyn crate::core::PolicyEngine>>,
identity: Option<crate::core::Delegation>,
agent: String,
plane: std::sync::Weak<super::Runtime>,
#[cfg(feature = "manifest")]
manifest: Option<Arc<crate::manifest::Manifest>>,
signer: Option<Arc<dyn crate::core::Signer>>,
/// Whether this context is currently taking a group back.
///
/// A reversal runs in the step's **forward** phase — same step, same cursor
/// — so the phase cannot say what it is. Without this flag a reversal is
/// gated like a forward call, and a run that reached its ceiling mid-group
/// could not undo the hold it had already placed. That is the exact outcome
/// the compensation exemption exists to prevent, reached by a different
/// road.
reversing: bool,
/// The effect group this step is inside, if any.
///
/// Here rather than in the `EffectGroup` handle because a skill that fails
/// with `?` drops the handle without settling, and `Drop` cannot run an
/// async reversal. The executor settles what the handle abandoned.
open_group: Option<super::group::OpenGroup>,
/// Whether the effect being dispatched right now *is* a group member.
///
/// A group's `Aborted` settlement claims the world was taken back whole.
/// An ordinary mutating effect performed while a group is open falsifies
/// that claim: it is journaled, gated and metered like any other, but it
/// registers no reversal and survives the unwind. So an open group refuses
/// them — and the runtime has to tell a member's own dispatch apart from
/// an ambient one, because members reach the world through the same two
/// methods everything else does.
member_dispatch: bool,
/// Whether this step has appended anything to the journal.
///
/// The executor's "did this step do new work" bit: a resumed step that
/// merely re-read its own history appends nothing here, and its ending is
/// already on the record — writing a second `StepFinished` for it reports
/// one piece of work as two and grows the chain on every resume.
wrote: bool,
/// Group records this step and phase already wrote — see
/// [`Frame::recorded_groups`].
pub(crate) recorded_groups: std::collections::BTreeMap<String, RecordedGroup>,
}
impl<'a> StepCtx<'a> {
pub(crate) fn new(store: &'a Arc<dyn JournalStore>, cursor: StepCursor, frame: Frame) -> Self {
let Frame {
run,
epoch,
step,
phase,
mode,
case,
timers,
blobs,
memories,
semantic,
authorities,
#[cfg(feature = "manifest")]
tools,
meter,
#[cfg(feature = "keyring")]
keyring,
tenant,
ledger,
policy,
identity,
agent,
plane,
#[cfg(feature = "manifest")]
manifest,
signer,
recorded_groups,
} = frame;
Self {
store,
run,
epoch,
step,
phase,
ordinal: 0,
mode,
cursor,
rng: seeded_rng(run, step),
case,
timers,
blobs,
memories,
semantic,
authorities,
#[cfg(feature = "manifest")]
tools,
meter,
#[cfg(feature = "keyring")]
keyring,
tenant,
ledger,
policy,
identity,
agent,
plane,
#[cfg(feature = "manifest")]
manifest,
signer,
recorded_groups,
reversing: false,
open_group: None,
member_dispatch: false,
wrote: false,
}
}
/// Whether this step appended anything — the executor's "did new work" bit.
pub(crate) const fn wrote_records(&self) -> bool {
self.wrote
}
/// Run something with the gate exempted, because it is taking work back.
pub(crate) fn set_reversing(&mut self, reversing: bool) {
self.reversing = reversing;
}
/// Derive the next effect key at this step and consume its ordinal, in one
/// call so the two can never be done out of step.
///
/// Advancing the ordinal is the bookkeeping a hand-rolled effect path can
/// forget, and a forgotten advance collides the next effect's key — a replay
/// divergence with nothing on the record to explain it. This bundles the two,
/// so every single-attempt effect (a group member, a timer, a release) gets
/// a fresh key by construction rather than by the author remembering.
///
/// The *retried* forward path (`effect_unlabelled`) cannot use this: it
/// re-derives per attempt with the attempt number in the key, so its ordinal
/// is taken once, before the retry loop, and the derivation lives there.
pub(crate) fn next_effect_key(&mut self, descriptor: &EffectDescriptor) -> EffectKey {
let ordinal = self.ordinal;
self.ordinal += 1;
EffectKey::derive(
self.step,
self.phase,
ordinal,
1,
&descriptor.kind,
&canon::value_bytes(&descriptor.args),
)
}
pub(crate) fn replaying(&self) -> bool {
self.mode.is_replaying()
}
pub(crate) const fn is_strict(&self) -> bool {
matches!(self.mode, Mode::Strict)
}
pub(crate) fn cursor_next(
&mut self,
key: EffectKey,
) -> Result<Option<crate::journal::EffectReplay>, StepError> {
self.cursor.next(key)
}
pub(crate) const fn epoch(&self) -> Epoch {
self.epoch
}
pub(crate) const fn phase_of(&self) -> Phase {
self.phase
}
pub(crate) fn bound_case(&self) -> Option<crate::core::CaseId> {
self.case.as_ref().map(CaseContext::id)
}
pub(crate) fn journal(&self) -> &Arc<dyn JournalStore> {
self.store
}
pub(crate) fn open_group(&self) -> Option<&super::group::OpenGroup> {
self.open_group.as_ref()
}
pub(crate) fn open_group_mut(&mut self) -> Option<&mut super::group::OpenGroup> {
self.open_group.as_mut()
}
pub(crate) fn set_open_group(&mut self, group: super::group::OpenGroup) {
self.open_group = Some(group);
}
pub(crate) fn take_open_group(&mut self) -> Option<super::group::OpenGroup> {
self.open_group.take()
}
/// Dispatch an effect **as a group member**, exempt from the ambient
/// refusal above.
///
/// Scoped rather than sticky: the flag is cleared on the way out whatever
/// the effect did, so a member that fails cannot leave the group open to
/// ambient mutations for the rest of the step.
pub(crate) async fn effect_as_member<E: Effect>(
&mut self,
effect: E,
) -> Result<Tainted<E::Output>, StepError> {
self.member_dispatch = true;
let out = self.effect(effect).await;
self.member_dispatch = false;
out
}
/// Commission another agent on this plane, and journal that you did.
///
/// The hand-off, done properly. A skill cannot hold an `Arc<Runtime>` —
/// the runtime needs the skill before the skill can have the runtime — so
/// commissioning belongs to the runtime and is reached through here.
///
/// Three properties, none of them optional:
///
/// * **Journaled**, so a strict replay reads the answer back instead of
/// commissioning the work a second time. A skill that called another
/// runtime inline would be doing non-deterministic work outside the
/// journal, and replay would re-run the whole room.
/// * **The label travels.** A specialist's answer is untrusted — it came
/// from a model — and the next agent is commissioned with that label
/// intact, so the receiving run's taint gates judge what they were
/// actually given.
/// * **The cost comes back**, and is billed to the commissioning run, so an
/// orchestrator's ceiling bounds the work it ordered rather than its own
/// idling.
///
/// The answer is untrusted whatever the org chart says: another agent's
/// output is somebody else's data.
///
/// # Errors
///
/// [`StepError`] if the sub-run fails. Reported as *in doubt* rather than
/// *did not happen*: the commissioned agent may have performed effects
/// before failing, and its own journal is where that is answered.
pub async fn commission(
&mut self,
capability: &str,
input: Tainted<Value>,
) -> Result<Tainted<Value>, StepError> {
let plane = self.plane.clone();
let depth = self
.identity
.as_ref()
.map_or(0, crate::core::Delegation::depth);
let commissioned = self
.effect(Commission {
capability: capability.to_owned(),
input: input.peek().clone(),
label: input.label().clone(),
plane,
depth,
})
.await?;
// Raised, never lowered — the same rule the effect layer applies to a
// declared sensitivity, applied here because only now is the figure
// known. A specialist that handled `Confidential` data must not have
// its answer arrive as `Internal` merely because it crossed a
// delegation boundary.
let sensitivity = commissioned.peek().sensitivity;
let label = commissioned
.label()
.clone()
.with_sensitivity(commissioned.label().sensitivity.max(sensitivity));
Ok(Tainted::with_label(
commissioned.into_unlabelled().answer,
label,
))
}
/// The declaration this agent runs under.
///
/// `None` when the runtime was wired by builder calls instead. A skill asks
/// its context which agent it is part of — it does not hold a manifest of
/// its own, because **an agent has skills**, and a skill carrying a separate
/// copy of the agent's declaration could disagree with the agent about what
/// the agent is.
///
/// What a skill typically wants from it: the system prompt
/// ([`Identity::system_prompt`](crate::manifest::Identity::system_prompt)),
/// the model role to call, and
/// [`output_schema`](crate::manifest::Manifest::output_schema).
#[cfg(feature = "manifest")]
#[must_use]
pub fn manifest(&self) -> Option<&crate::manifest::Manifest> {
self.manifest.as_deref()
}
/// Complete a prompt on the **manifest's own** model, through the
/// **plane's own** driver.
///
/// The model-call counterpart to [`call_tool`](Self::call_tool), and it
/// closes the same gap. A declarative agent resolves its model from the
/// declaration and its driver from the plane's registry; a hand-written
/// skill had to carry an `Arc<dyn ModelProvider>` field and name a model
/// in code — so the skill held wiring its manifest never described, and
/// the file's `models.privileged` governed the declarative tier while the
/// coded tier read it or did not. This is the path where it cannot be
/// ignored: the privileged role supplies the model and its reviewed
/// ceilings, the plane supplies the driver registered under the role's
/// provider name, and the manifest's egress ceiling rides the call.
///
/// ```ignore
/// let completion = cx.complete(&prompt).await?;
/// ```
///
/// An explicit `(provider, model)` remains one construction away —
/// `cx.sink_with(&prompt, |value| ModelCall::new(provider, model, value))`
/// — which is the honest spelling for a call the manifest does not govern.
///
/// # Errors
///
/// [`StepError`] when this skill runs under no manifest, when the manifest
/// declares no privileged model, when no driver is registered under the
/// role's provider name, or whatever the dispatch itself refuses.
#[cfg(feature = "manifest")]
pub async fn complete(
&mut self,
prompt: &Tainted<Value>,
) -> Result<Tainted<crate::model::Completion>, StepError> {
self.complete_with(prompt, |call| call).await
}
/// [`complete`](Self::complete), with the call adjusted before dispatch.
///
/// The closure receives the fully-resolved call — model, role ceilings and
/// egress ceiling already applied — and may add what only the skill knows:
///
/// ```ignore
/// let completion = cx
/// .complete_with(&prompt, |call| call.expecting(schema.clone()))
/// .await?;
/// ```
///
/// It runs *after* the manifest's declarations are applied, so a skill can
/// tighten or reshape the call; what it cannot do is dodge the `declared`
/// gate, which still refuses a model the manifest never named.
///
/// # Errors
///
/// As [`complete`](Self::complete).
#[cfg(feature = "manifest")]
pub async fn complete_with<F>(
&mut self,
prompt: &Tainted<Value>,
tune: F,
) -> Result<Tainted<crate::model::Completion>, StepError>
where
F: FnOnce(crate::model::ModelCall) -> crate::model::ModelCall,
{
let refuse = |detail: String| StepError::Effect(crate::core::EffectError::Other(detail));
let manifest = self.manifest.clone().ok_or_else(|| {
refuse(
"this skill runs under no manifest, so `cx.complete` has no declared \
model to call — register it with `Agent::new(&manifest).skill(..)`, or \
construct a `ModelCall` and dispatch it with `cx.sink_with`"
.into(),
)
})?;
let role = manifest.privileged_role().ok_or_else(|| {
refuse(format!(
"manifest '{}' declares no privileged model — `spec.models.privileged` \
is what `cx.complete` calls",
manifest.metadata.name
))
})?;
let provider = self
.plane
.upgrade()
.and_then(|plane| plane.model_provider(&role.model.provider))
.ok_or_else(|| {
refuse(format!(
"no driver is registered for provider '{}' — \
`RuntimeBuilder::provider(\"{}\", ..)` is what maps the manifest's \
name to one",
role.model.provider, role.model.provider
))
})?;
let egress = manifest.spec.security.max_sensitivity_egress;
self.sink_with(prompt, |value| {
let mut call = role.applied_to(crate::model::ModelCall::new(
provider,
role.model.clone(),
value,
));
if let Some(ceiling) = egress {
call = call.with_max_sensitivity(ceiling);
}
tune(call)
})
.await
}
/// Call a tool through the **plane's own** catalogue.
///
/// # Why this exists, and why the obvious alternative is a hole
///
/// A declarative agent gets its [`ToolCatalog`] from the runtime. A
/// hand-written skill had to construct and carry one:
///
/// ```ignore
/// ToolCall::prepare(&self.catalog, Arc::clone(&self.client), id, args)?
/// ```
///
/// and nothing bound `self.catalog` to the manifest governing that skill.
/// [`ToolCatalog::from_manifest`] is the right primitive and it is one call
/// away — but the *obvious* thing, hand-building a catalogue with the tools
/// you know you call, compiles, runs, and grants the skill reach its
/// declaration never described. Worse, it can be **laxer**: a
/// [`ToolSafety::read_only`] entry for a tool the manifest calls mutating
/// exempts it from the whole-value taint gate and carries
/// [`Recovery::Retry`](crate::core::Recovery::Retry), so a timed-out
/// money-moving call is sent a second time.
///
/// [`RuntimeBuilder::try_build`](crate::runtime::RuntimeBuilder::try_build)
/// refuses exactly that divergence — for the *plane's* catalogue. A
/// catalogue built inside a skill never passed under that check. So this is
/// the same dispatch a declarative agent performs, over the same checked
/// catalogue, and the drift is unrepresentable rather than merely
/// discouraged.
///
/// # Everything else is unchanged
///
/// The manifest gate still refuses a tool this agent's declaration does not
/// grant, the protected-field rules still have to match, the egress ceiling
/// still applies, and the result still comes back
/// [`Tainted`] and untrusted. This narrows what a skill can reach; it grants
/// nothing.
///
/// ```ignore
/// let overdue = cx
/// .call_tool(ToolId::new("obsd", "list_overdue_processes"), args)
/// .await?;
/// ```
///
/// [`ToolCatalog`]: crate::tools::ToolCatalog
/// [`ToolCatalog::from_manifest`]: crate::tools::ToolCatalog::from_manifest
/// [`ToolSafety::read_only`]: crate::tools::ToolSafety::read_only
///
/// # Errors
///
/// [`StepError`] when this plane has no tool catalogue, when the tool is not
/// in it, when this agent's manifest does not grant it, or when the
/// arguments' label is refused at the sink.
#[cfg(feature = "manifest")]
pub async fn call_tool(
&mut self,
tool: crate::tools::ToolId,
arguments: Tainted<Value>,
) -> Result<Tainted<Value>, StepError> {
let (catalog, client) = self.tools.clone().ok_or_else(|| {
StepError::Effect(crate::core::EffectError::Other(
"this plane has no tool catalogue — `RuntimeBuilder::toolbox(..)` derives \
one from the agents' declarations, and `.tools(catalog, client)` states \
it explicitly"
.into(),
))
})?;
self.sink_with(&arguments, |value| {
crate::tools::ToolCall::prepare(&catalog, client, tool, value)
.map_err(|e| StepError::Effect(crate::core::EffectError::Rejected(e.to_string())))
})
.await
}
/// What this run tells a callee about itself, sealed for one call.
///
/// Unsigned when the plane has no workload identity, which is honest: a
/// self-signed block would look attested and prove nothing, the same
/// reasoning that leaves unsigned journal records unsigned.
fn provenance(
&self,
key: EffectKey,
ordinal: u32,
descriptor: &EffectDescriptor,
) -> crate::core::Provenance {
// The same key with the attempt pinned to zero: one identity for the
// logical dispatch, however many times it is attempted. A callee
// deduplicates on this, because "have I already done this work?" must
// answer *yes* for a retry — while the effect key must differ per
// attempt so replay reads back the retry rather than the failure before
// it. Two questions, two identifiers.
let dispatch = EffectKey::derive(
self.step,
self.phase,
ordinal,
0,
&descriptor.kind,
&canon::value_bytes(&descriptor.args),
);
let block = crate::core::Provenance::new(self.run, key, self.agent.clone())
.dispatching(dispatch)
.in_case(self.case.as_ref().map(|c| c.case_id));
match &self.signer {
Some(signer) => block.seal(signer.as_ref(), &descriptor.kind, &descriptor.args),
None => block,
}
}
/// Hand the step's history back once it has finished with it.
pub(crate) fn into_cursor(self) -> StepCursor {
self.cursor
}
#[must_use]
pub fn run_id(&self) -> RunId {
self.run
}
#[must_use]
pub fn step_id(&self) -> StepId {
self.step
}
/// What this run has consumed so far, and against what limits.
#[must_use]
pub fn budget(&self) -> crate::core::Consumed {
self.ledger.lock().expect("budget mutex").consumed()
}
/// Count one dispatched effect and add what it consumed.
///
/// Called for failures as well as successes, with a zero spend, because a
/// call that failed still *happened*: it took a slot against `max_effects`,
/// and a budget that only counted successes could never bound a call that
/// fails every time. Replay bills the same way from the same records, so the
/// two paths reach the same verdict at the same point.
///
/// A separate function so the guard's scope is a single statement and cannot
/// accidentally span an await.
fn bill(&self, spend: crate::core::Spend) {
self.ledger
.lock()
.expect("budget mutex")
.record_effect(spend);
}
/// [`bill`](Self::bill), for an effect this pass actually dispatched.
///
/// The distinction feeds the tenant's period ledger: replayed spend is
/// billed to the run's own budget so a resume exhausts where the original
/// did, but only live spend accrues at settlement — otherwise every
/// suspend/resume cycle re-accrues the prefix and every strict pass bills
/// history into today's period.
fn bill_live(&self, spend: crate::core::Spend) {
self.ledger
.lock()
.expect("budget mutex")
.record_live_effect(spend);
}
/// A deterministic random source.
///
/// Seeded from `(run_id, step)` rather than journaled per draw: the sequence
/// is reproducible by construction, so replay reproduces it for free and the
/// journal carries no entropy records at all. Cheaper *and* stronger than
/// recording each value — there is no way for the recorded and recomputed
/// streams to disagree.
pub fn rng(&mut self) -> &mut impl rand::Rng {
&mut self.rng
}
/// The current instant, as a journaled effect.
///
/// On replay this returns the instant the original run saw, not the instant
/// now — which is why a replayed run makes the same time-dependent decisions
/// as the run it is reproducing.
pub async fn now(&mut self) -> Result<Timestamp, StepError> {
Ok(self.effect(Clock).await?.into_unlabelled())
}
/// Record structured reasoning in the journal, adjacent to the effects it
/// explains.
///
/// Adjacency is the point: a note next to the action it claims to justify
/// makes reasoning-versus-action mismatch detectable after the fact and
/// testable under replay. A summary written at the end of a run cannot do
/// that, because by then the ordering evidence is gone.
pub async fn note(&mut self, text: impl Into<String>) -> Result<(), StepError> {
self.append(RecordKind::Note { text: text.into() }).await
}
/// Perform (or replay) an effect, repeating it if it fails and repeating is
/// safe.
///
/// The whole determinism boundary is this function.
///
/// # Why one loop covers both replay and live execution
///
/// A retry sequence is history like any other. Each attempt has its own
/// effect key (the attempt number is hashed in), so the journal holds
/// attempts 1..N as ordinary consecutive effects, and replay walks them the
/// same way it walks anything else. There is no separate "replay the
/// retries" path to drift out of sync with the live one.
///
/// # History outranks policy
///
/// While history has attempts left, they are consumed regardless of what
/// the current [`RetryPolicy`](crate::core::RetryPolicy) says. A run that made four attempts under
/// yesterday's policy still made four attempts, and a replay under a
/// two-attempt policy that stopped early would leave unconsumed records and
/// report divergence for a run that did nothing wrong. The policy governs
/// only what happens *after* history runs out.
/// # The result is labelled
///
/// An effect is how the deterministic zone reaches the outside world, so
/// what comes back *is* the outside world's data. It arrives as
/// [`Tainted`], labelled from the effect's own [`Effect::trust`]
/// declaration — which defaults to untrusted.
///
/// That is what makes the architecture hold rather than merely be
/// described. A tool result flowing into a downstream step's input is
/// labelled automatically, so the replan refusal and the taint gate see it
/// without the skill author having to remember; and a skill that wants to
/// treat a tool response as trusted has to say so, in a call that leaves a
/// record.
pub async fn effect<E: Effect>(&mut self, effect: E) -> Result<Tainted<E::Output>, StepError> {
if effect.sink_arguments().is_some() {
return Err(PolicyError::SinkGateRequired {
sink: effect.descriptor().kind,
}
.into());
}
self.effect_after_sink_gate(effect, None).await
}
/// Dispatch an effect once any required information-flow checks have run.
async fn effect_after_sink_gate<E: Effect>(
&mut self,
effect: E,
outbound: Option<&crate::core::Label>,
) -> Result<Tainted<E::Output>, StepError> {
// Captured before dispatch consumes the effect. This is the name a
// `ProtectedField::from_sources` rule matches, so it is per *effect* —
// `tool://crm/lookup`, `model:openai/gpt-4o` — not per family: a rule
// that can only say `effect:tool.call` admits whichever granted tool an
// injected prompt reached first, which is no rule at all.
let source = effect.source();
let kind = effect.descriptor().kind;
// A mutation beside an open group, rather than inside it. Refused:
// the group's `Aborted` outcome says *taken back whole*, and this
// write would still be standing when it was written. Reads are
// untouched — a read changes nothing there is to take back — and a
// member's own dispatch sets `member_dispatch` on the way through.
if let Some(open) = self.open_group.as_ref()
&& !self.member_dispatch
&& effect.mutates()
{
return Err(StepError::GroupFootprint {
group: open.name.clone(),
detail: format!(
"'{kind}' mutates and is not a member of the open group — it \
would survive an abort that claims the world was taken back \
whole. Register it with the group, or perform it before the \
group opens or after it settles"
),
});
}
// The declaration comes back with the value, because for a replayed
// effect it is **history** rather than a fresh reading of the
// catalogue. See `DeclaredOutput` for what re-reading would cost.
let (output, declared) = self.effect_unlabelled(effect, outbound).await?;
let labelled = match declared.trust {
crate::core::Trust::Trusted => Tainted::trusted(output),
crate::core::Trust::Untrusted => Tainted::from_source(output, source),
};
// Raised, never lowered: an untrusted result is already `Internal`, and
// an effect that could declare its output *less* sensitive than its
// provenance implies would be a laundering primitive.
let sensitivity = labelled.label().sensitivity.max(declared.sensitivity);
let label = labelled.label().clone().with_sensitivity(sensitivity);
Ok(Tainted::with_label(labelled.into_unlabelled(), label))
}
/// The effect protocol itself, before the result is labelled.
///
/// Split out so the label is applied at exactly one place: a second exit
/// from this function that forgot to wrap would be an unlabelled tool
/// result, which is the hole the labelling exists to close.
///
/// Returns the [`DeclaredOutput`](crate::core::DeclaredOutput) that applies
/// to the value beside it, which is **not** always the one the effect would
/// answer now: a value read back from history carries the declaration that
/// was recorded with it, so a catalogue edited since cannot relabel it.
async fn effect_unlabelled<E: Effect>(
&mut self,
mut effect: E,
outbound: Option<&crate::core::Label>,
) -> Result<(E::Output, crate::core::DeclaredOutput), StepError> {
// Checked once, on the path *both* `effect` and `sink` take, and before
// the retry loop because a depth violation is not attempt-dependent.
//
// It lived in `sink` alone, which meant the ceiling governed the A2A
// peer call and not `cx.commission` — the rule held across a network
// boundary and not across a function call, which is the wrong way
// round. The loop a `specialist` role exists to prevent is the in-plane
// one: A commissions B commissions C commissions A, inside one process,
// with no peer boundary to cross and no allowlist to notice.
//
// A refusal is journaled like the sink gates': it fires before any key
// exists, so the record takes the dispatch's position, and replay
// consumes the verdict instead of re-deciding it.
let descriptor = effect.descriptor();
self.refuse_excess_delegation(&effect, &descriptor).await?;
let policy = effect.retry();
let recovery = effect.recovery();
let ordinal = self.ordinal;
self.ordinal += 1;
let mut attempt: u32 = 1;
// What the last failure's peer said about when to come back. The wait
// belongs to the *next* attempt, so it crosses the iteration boundary;
// a replayed pass never waits, because the wait already happened and
// its outcome is the record being read back.
let mut advice: Option<std::time::Duration> = None;
loop {
let key = EffectKey::derive(
self.step,
self.phase,
ordinal,
attempt,
&descriptor.kind,
&canon::value_bytes(&descriptor.args),
);
// Hand the effect what it needs to identify itself to a callee.
// After the key is derived and before anything is announced: the key
// is part of the block, and the block is signed for *this* call.
effect.attach(&self.provenance(key, ordinal, &descriptor));
// ── Replay: is this attempt already in history? ────────────────
if self.mode.is_replaying() {
match self.cursor.next(key)? {
Some(EffectReplay::Done {
output,
spend,
declared,
..
}) => {
self.replayed_done(&descriptor.kind, attempt, spend);
return Ok((serde_json::from_value(output)?, declared));
}
Some(
refusal @ (EffectReplay::Refused { .. } | EffectReplay::Denied { .. }),
) => {
// Re-admitted refusals fall through to a live dispatch
// of the same key; everything else re-raises inside.
self.replayed_refusal(key, refusal).await?;
continue;
}
Some(EffectReplay::Failed {
error,
disposition,
spend,
permanent,
}) => {
attempt = self.replay_recorded_failure(
&descriptor,
ordinal,
attempt,
key,
&recovery,
&policy,
&error,
disposition,
spend,
permanent,
// Recomputed from the code, like the recovery and
// the policy: replay assumes the same program, and
// the record's own `mutates` lives on the start
// record the cursor has already collapsed.
effect.mutates(),
)?;
continue;
}
Some(EffectReplay::Orphan {
recovery: recorded, ..
}) => {
if let Some(output) = self
.orphan_verdict(&effect, key, attempt, &recorded, &recovery, &policy)
.await?
{
// Recovered by a probe this pass ran, so the
// declaration this pass reads is the one its own
// `EffectReconciled` record just carried.
return Ok((output, crate::core::DeclaredOutput::of(&effect)));
}
attempt += 1;
continue;
}
// History exhausted: this attempt runs live, unless a
// strict pass is verifying — where reaching the end is
// itself the finding.
None if self.mode == Mode::Strict => {
return Err(StepError::ReplayOverrun { actual: key });
}
None => {}
}
}
// ── Live ───────────────────────────────────────────────────────
//
// Admission is checked per attempt, not once per effect. A retry is
// a real call that costs real money, and a budget that only counted
// the first one would be a ceiling a retry storm walks straight
// through.
//
// Checked *before* dispatch: the point of a budget is to stop the
// spending, not to notice it. Only live execution is gated —
// replay must reproduce whatever the original run did, or history
// would change shape with the limit in force when you replayed it.
//
// Compensation is exempt. Refusing to undo because the ceiling was
// reached is how a run ends with a charged card and no order — the
// ceiling exists to bound work, not to strand it half-done. The
// spend is still billed and journaled, so the overshoot is visible
// rather than silent.
let ceilings = Some(DeclaredCeilings::of(&effect));
self.gate(key, &descriptor, effect.mutates(), outbound, ceilings)
.await?;
let backoff = policy.wait_before(self.run, key, attempt, advice.take());
if !backoff.is_zero() {
tokio::time::sleep(backoff).await;
}
let waited = u64::try_from(backoff.as_millis()).unwrap_or(u64::MAX);
let failure = match self
.traced_attempt(&effect, key, attempt, waited, outbound)
.await?
{
// Dispatched live, so the effect's own answer is both what the
// value carries and what the `EffectDone` record just stored.
Ok(output) => return Ok((output, crate::core::DeclaredOutput::of(&effect))),
Err(e) => e,
};
if let Some(output) = self
.failed_attempt_verdict(&effect, key, attempt, &recovery, &policy, &failure)
.await?
{
return Ok((output, crate::core::DeclaredOutput::of(&effect)));
}
advice = failure.retry_after();
attempt += 1;
}
}
/// Decide what a failed attempt means: a reconciled answer, a stop, or a
/// retry.
///
/// One implementation for the live path and the resolved-orphan path,
/// because they are one rule: an in-doubt failure on a reconcilable
/// effect is a question asked before deciding, and everything else goes
/// to the stop machinery. `Ok(Some(output))` is an answer reconciliation
/// recovered; `Ok(None)` tells the attempt loop to retry.
async fn failed_attempt_verdict<E: Effect>(
&mut self,
effect: &E,
key: EffectKey,
attempt: u32,
recovery: &crate::core::Recovery,
policy: &crate::core::RetryPolicy,
failure: &crate::core::EffectError,
) -> Result<Option<E::Output>, StepError> {
let mut disposition = failure.disposition();
if disposition == crate::core::Disposition::InDoubt
&& matches!(recovery, crate::core::Recovery::Reconcile)
{
match self.reconcile_and_record(effect, key).await? {
crate::core::Reconciliation::Landed(output) => return Ok(Some(output)),
resolved => disposition = resolved.disposition(),
}
}
if let Some(stop) = Self::stop_reason(
disposition,
recovery,
key,
attempt,
policy,
&failure.to_string(),
matches!(failure, crate::core::EffectError::Refused(_)),
effect.mutates(),
) {
return Err(stop);
}
Ok(None)
}
/// Resolve an orphan and classify what came of it.
///
/// A resolved orphan that *fails* is a live failure and takes the live
/// failure's path — disposition, reconciliation, stop machinery — rather
/// than a verdict of its own. The re-performance already wrote its
/// terminal record inside `resolve_orphan`; what is decided here is only
/// what the failure means, and deciding it anywhere else is how a
/// mutating in-doubt outcome once unwound as a plain failure.
///
/// `Ok(Some(output))` is a landed answer; `Ok(None)` tells the attempt
/// loop to retry under the recomputed policy.
#[allow(clippy::too_many_arguments)]
async fn orphan_verdict<E: Effect>(
&mut self,
effect: &E,
key: EffectKey,
attempt: u32,
recorded: &crate::core::Recovery,
recovery: &crate::core::Recovery,
policy: &crate::core::RetryPolicy,
) -> Result<Option<E::Output>, StepError> {
match self.resolve_orphan(effect, key, attempt, recorded).await? {
Ok(output) => Ok(Some(output)),
Err(failure) => {
self.failed_attempt_verdict(effect, key, attempt, recovery, policy, &failure)
.await
}
}
}
/// An `EffectStarted` with no terminal record: a crash landed between
/// "sent the request" and "recorded the answer".
///
/// Whether the call landed is undecidable from the journal, so the declared
/// recovery mode decides. This is the same question an
/// [`InDoubt`](crate::core::Disposition::InDoubt) failure asks — a crash and
/// a timeout leave the runtime knowing exactly as much — and it is answered
/// the same way, by declaration rather than by guessing.
///
/// The nested result is the point of the signature: the inner `Err` is a
/// re-performance that **failed**, handed back to the ordinary attempt
/// loop so the same disposition, reconciliation and stop machinery decides
/// what it means. An earlier version collapsed it to a step failure here,
/// which skipped the classifier — a resumed orphan whose re-performance
/// timed out `InDoubt` on a mutating effect read as a plain failure, and
/// the failure unwind then compensated completed steps around a call that
/// may have landed. The outer `Err` carries only the verdicts this
/// function can reach alone: strict refuses to probe, an operator-recovery
/// effect stays undecidable, and an inconclusive probe stays undecidable.
async fn resolve_orphan<E: Effect>(
&mut self,
effect: &E,
key: EffectKey,
attempt: u32,
recovery: &crate::core::Recovery,
) -> Result<Result<E::Output, crate::core::EffectError>, StepError> {
use crate::core::{Reconciliation, Recovery};
// Strict replay is a pure read, and resolving an orphan is not reading —
// every branch below either performs an effect or probes a provider, and
// both write to the journal being verified.
//
// An earlier version fell straight through to the `Retry` arm here, so
// verifying a crashed run re-performed its interrupted effect for real
// and appended to the history it was meant to be checking.
if self.mode == Mode::Strict {
return Err(StepError::Undecidable {
key,
recovery: recovery.clone(),
detail: "the journal ends mid-effect; strict replay verifies history and will \
not perform or probe to complete it"
.into(),
});
}
match recovery {
// Re-performed under the *same* key, and without a second
// `EffectStarted`: the announcement already in the journal covers
// this call, and writing another would report two attempts where
// one interrupted attempt was resumed. A failure is handed back to
// the attempt loop, not decided here.
Recovery::Retry | Recovery::Idempotent { .. } => {
self.perform_once(effect, key, attempt, 0, false, None)
.await
}
// Ask, rather than assume. This is the only branch that turns an
// undecidable outcome into a decided one without betting on it.
Recovery::Reconcile => match self.reconcile_and_record(effect, key).await? {
Reconciliation::Landed(output) => Ok(Ok(output)),
Reconciliation::DidNotHappen => {
self.perform_once(effect, key, attempt, 0, false, None)
.await
}
Reconciliation::Inconclusive => Err(StepError::Undecidable {
key,
recovery: recovery.clone(),
detail: "started before a crash, and the reconciliation probe could not \
establish whether it landed"
.into(),
}),
},
Recovery::RequiresOperator => Err(StepError::Undecidable {
key,
recovery: recovery.clone(),
detail: "started before a crash and never completed".into(),
}),
}
}
/// Decide what a replayed refusal means in this pass.
///
/// `Err` re-raises the recorded verdict; `Ok(())` means a budget refusal
/// was superseded by a re-admission this pass just journaled, and the
/// caller dispatches the same key live. One implementation for the
/// ordinary dispatch loop and the atomic-member path, because it is one
/// rule — and the step-level twin lives in `admit_ready`, so the two
/// tiers must move together: an effect tier that replayed its refusal
/// verbatim would leave a run exhausted by `max_effects` paused forever
/// under a ceiling that now admits it, while its step-limited sibling
/// resumes.
///
/// The asymmetry between the two refusal kinds is deliberate. A budget is
/// raised, so a resume re-asks the ledger now in force — still refused
/// consumes the standing record and re-concludes without stacking a
/// second, admitted journals `BudgetReadmitted` beside the refusal it
/// supersedes. A policy denial is argued with, not raised: resume already
/// requires the exact bundle recorded at admission, so the verdict is
/// consumed rather than re-decided — a gate must not re-decide a dispatch
/// history already settled.
pub(crate) async fn replayed_refusal(
&mut self,
key: EffectKey,
refusal: EffectReplay,
) -> Result<(), StepError> {
let EffectReplay::Refused { limit, used } = refusal else {
return Err(recorded_refusal(refusal));
};
// Re-askable only at the history frontier, and the condition is
// deliberately `writes_enabled`: a re-admission is a write, and
// bookkeeping writes begin where history ends. A refusal *inside* the
// replayed prefix was already answered by the run itself — the group
// abort that follows one is history — so re-admitting it mid-prefix
// would dispatch where the record holds the abort's reversals,
// manufacturing divergence out of a raise. Strict is covered by the
// same condition: verification writes nothing and consults no ledger.
if !self.writes_enabled() {
return Err(recorded_refusal(EffectReplay::Refused { limit, used }));
}
// Scoped so the guard is gone before the await below.
let verdict = self.ledger.lock().expect("budget mutex").admit_effect();
if verdict.is_err() {
// The ledger now in force still refuses: the run concludes
// exhausted again, and the standing refusal already says so — no
// second record.
return Err(StepError::Budget(crate::core::BudgetExceeded::Recorded {
limit,
used,
}));
}
self.append_effect(key, RecordKind::BudgetReadmitted { limit })
.await?;
Ok(())
}
/// Ask the provider whether a call landed, and journal the answer.
///
/// The verdict goes in the journal — including an inconclusive one, because
/// "we did not know, we asked, and we still do not know" is exactly what an
/// operator picking up the escalation needs to see. Omitting it would make
/// the escalation look like nobody tried.
///
/// Journaling also makes the probe replayable: it is a network call like any
/// other, and replay reads its verdict back rather than asking again.
async fn reconcile_and_record<E: Effect>(
&mut self,
effect: &E,
key: EffectKey,
) -> Result<crate::core::Reconciliation<E::Output>, StepError> {
use crate::core::Reconciliation;
// A probe that fails tells us nothing new, so the doubt stands. It is
// recorded rather than retried: a probe worth repeating is a probe the
// driver should be repeating internally, and stacking a retry loop on
// top of one is a multiplication nobody asked for.
let (outcome, detail) = match effect.reconcile().await {
Ok(r) => (r, None),
Err(e) => (Reconciliation::Inconclusive, Some(e.to_string())),
};
let (output, spend) = match &outcome {
Reconciliation::Landed(value) => {
let spend = effect.spend(value);
self.bill_live(spend);
(Some(serde_json::to_value(value)?), spend)
}
_ => (None, crate::core::Spend::default()),
};
tracing::info!(
target: telemetry::RECONCILED,
run = %self.run,
step = %self.step,
verdict = ?outcome.disposition(),
);
self.meter
.count(metrics::RECONCILIATIONS, outcome.disposition().as_str());
self.append_effect(
key,
RecordKind::EffectReconciled {
disposition: outcome.disposition(),
// Present exactly when the probe recovered a value, so the two
// are derived from one match rather than from two.
declared: output
.is_some()
.then(|| crate::core::DeclaredOutput::of(effect)),
output,
spend,
detail,
},
)
.await?;
Ok(outcome)
}
/// What history says about a wait, if anything.
///
/// `Ok(None)` means the journal has nothing here and the wait must be
/// registered live. `Ok(Some(ReplayedWait::Repair))` means the wait was announced and
/// its registration may not have survived — the caller re-registers
/// idempotently under the same key, without a second announcement. Every
/// other arm is a decision the recorded run already made, reproduced
/// rather than re-derived.
async fn replayed_wait(
&mut self,
key: EffectKey,
spec: &AwaitSpec,
cx: &CaseContext,
) -> Result<Option<ReplayedWait>, StepError> {
match self.cursor.next(key)? {
Some(EffectReplay::Done {
output,
source,
spend,
// An inbound payload's label is rebuilt from `source` and the
// wait's own kind, which `label_inbound` holds together.
declared: _,
}) => {
self.bill(spend);
Ok(Some(ReplayedWait::Recorded(Self::label_inbound(
output,
&spec.kind,
source.as_deref(),
))))
}
Some(EffectReplay::Refused { limit, used }) => {
Err(StepError::Budget(crate::core::BudgetExceeded::Recorded {
limit,
used,
}))
}
Some(EffectReplay::Denied {
reason,
action,
resource,
}) => Err(StepError::Denied {
action,
resource,
reason,
}),
Some(EffectReplay::Failed { error, .. }) => {
Err(StepError::Effect(crate::core::EffectError::Rejected(error)))
}
// Announced, and *possibly* registered: a crash — or a transient
// store error — between the announcement and the subscription
// leaves exactly this record, and suspending without repairing
// would strand the run forever: later events buffer until they
// dead-letter while the run sleeps with nothing in the system
// naming it. A resume re-walks the registration path, which is
// idempotent end to end (the subscription keeps its first row,
// the task row derives its id from this same key), skipping only
// the announcement that already exists. A strict pass dispatches
// nothing and suspends as the record reads.
Some(EffectReplay::Orphan { .. }) => {
if self.mode == Mode::Resume {
Ok(Some(ReplayedWait::Repair))
} else {
Err(StepError::Suspended(self.suspend_reason(spec, cx).await?))
}
}
None if self.mode == Mode::Strict => Err(StepError::ReplayOverrun { actual: key }),
None => Ok(None),
}
}
/// Account for an effect served from the journal rather than performed.
///
/// Marked replayed so metrics like "effect latency by driver" do not average
/// real calls with journal reads, and billed at the figure that was
/// *recorded* — so a replayed run reaches the same budget verdict at the
/// same point as the original.
fn replayed_done(&mut self, kind: &str, attempt: u32, spend: crate::core::Spend) {
tracing::debug!(
target: telemetry::EFFECT_SPAN,
kind = %kind,
attempt,
replayed = true,
outcome = "done",
);
self.meter.count(metrics::EFFECTS_REPLAYED, kind);
self.bill(spend);
}
/// The reviewed grant for an effect, if the manifest names one.
///
/// The bridge between a declaration and a dispatch. Without it
/// `ToolGrant::mutates` and `ToolGrant::max_sensitivity` are fields a
/// reviewer approves and nothing consults — the "manufactures confidence"
/// failure the binding rule exists to prevent.
#[cfg(feature = "manifest")]
fn tool_grant_for(&self, descriptor: &EffectDescriptor) -> Option<&crate::manifest::ToolGrant> {
if descriptor.kind != "tool.call" {
return None;
}
let server = descriptor.args["server"].as_str()?;
let tool = descriptor.args["tool"].as_str()?;
self.manifest
.as_ref()?
.tool_grant(&crate::tools::ToolId::new(server, tool).reference())
}
/// Everything that can refuse an attempt before it is dispatched.
///
/// `ceilings` is what the wiring declares about the effect's data limits,
/// carried beside the descriptor because the descriptor cannot hold it:
/// the descriptor is the effect key, and a reviewed allowance is not part
/// of what a call asks for — keying history on a catalogue edit is the
/// failure that rule exists to prevent. `None` marks a dispatch path that
/// has no ceilings to state (an atomic group member); the manifest arms
/// that need them refuse on `None` rather than assume.
///
/// Authorization before accounting: both refuse before dispatch, but an
/// unauthorized call should not first consume the run's allowance —
/// otherwise a denied agent can still exhaust a budget by asking.
///
/// Compensation is exempt from both, for the same reason: refusing to undo
/// is how a run ends with a charged card and no order.
pub(crate) async fn gate(
&mut self,
key: EffectKey,
descriptor: &EffectDescriptor,
mutates: bool,
outbound: Option<&crate::core::Label>,
ceilings: Option<DeclaredCeilings>,
) -> Result<(), StepError> {
// A compensating phase, or a group being taken back inside a forward
// one. Both are undo, and both are exempt for the same reason: refusing
// to undo is how a run ends with a charged card and no order.
if !self.phase.is_forward() || self.reversing {
return Ok(());
}
// First, because it is the cheapest and the most fundamental: an effect
// the agent's own declaration never mentioned should not reach the
// deployment's policy engine, let alone the world.
#[cfg(feature = "manifest")]
self.declared(key, descriptor, ceilings).await?;
#[cfg(not(feature = "manifest"))]
let _ = ceilings;
// The reviewed grant may only tighten. A tool the operator declared
// mutating gets the cautious treatment even if the catalogue advertises
// otherwise, because a server's own description of itself is an
// advertisement and the grant is the operator's decision about it.
#[cfg(feature = "manifest")]
let mutates = mutates || self.tool_grant_for(descriptor).is_some_and(|g| g.mutates);
self.authorize(key, descriptor, mutates, outbound).await?;
self.admit(key, &descriptor.kind).await
}
/// Check an effect against the agent's **own manifest**, journalling any
/// refusal.
///
/// This is what makes a manifest a control rather than a comment. Without
/// it, `spec.models` and `spec.tools` describe what the code is *supposed*
/// to do: a reviewer approves `model: haiku`, the code calls opus, and
/// nothing anywhere disagrees. The declaration and the behaviour are then
/// two independent copies of one decision, which is the failure mode a
/// single reviewable file exists to remove.
///
/// Only the fields a descriptor can be checked against are enforced here —
/// the model and the tool reference. An effect kind this does not recognise
/// passes, because inventing a constraint for it would be worse than saying
/// nothing.
///
/// Runs on live dispatch only, like every other gate: a replayed effect
/// reads its result from the journal, so editing a manifest cannot re-judge
/// a run that already happened.
#[cfg(feature = "manifest")]
#[allow(clippy::too_many_lines)]
async fn declared(
&mut self,
key: EffectKey,
descriptor: &EffectDescriptor,
ceilings: Option<DeclaredCeilings>,
) -> Result<(), StepError> {
let Some(manifest) = self.manifest.as_ref() else {
return Ok(());
};
let refusal = match descriptor.kind.as_str() {
"model.complete" => {
let provider = descriptor.args["provider"].as_str().unwrap_or_default();
let model = descriptor.args["model"].as_str().unwrap_or_default();
(!manifest.permits_model(provider, model)).then(|| {
format!(
"manifest '{}' does not declare the model '{provider}/{model}' — a model this agent's declaration never named is a behaviour change nobody reviewed",
manifest.metadata.name
)
})
}
"tool.call" => {
let server = descriptor.args["server"].as_str().unwrap_or_default();
let tool = descriptor.args["tool"].as_str().unwrap_or_default();
let reference = crate::tools::ToolId::new(server, tool).reference();
match manifest.tool_grant(&reference) {
None => Some(format!(
"manifest '{}' does not grant '{reference}' — a tool the agent's declaration never listed is authority nobody granted",
manifest.metadata.name
)),
// Compared canonically. The descriptor sorts on the way
// out, so the grant must be sorted too or a manifest whose
// fields were listed in another order is refused for a
// difference that means nothing.
Some(grant)
if serde_json::to_value(crate::tools::sorted_fields(
&grant.protected_fields,
))
.ok()
!= descriptor.args.get("protected_fields").cloned() =>
{
Some(format!(
"manifest '{}' and the live catalogue disagree about protected fields for '{reference}' — authority-bearing argument policy must be digest-covered and exact",
manifest.metadata.name
))
}
Some(_) => None,
}
}
// The grant's ceilings are compared against what the *effect*
// declares, never against the descriptor: the descriptor is the
// effect key, and a reviewed allowance is not part of what a call
// asks for. The wiring's ceilings arrive beside the descriptor,
// and a dispatch that did not supply them is refused rather than
// waved through — an MCP context effect with unstated ceilings is
// exactly the case this check exists for.
"mcp.prompt/get" => {
let server = descriptor.args["server"].as_str().unwrap_or_default();
let name = descriptor.args["name"].as_str().unwrap_or_default();
match (manifest.prompt_grant(server, name), ceilings) {
(None, _) => Some(format!(
"manifest '{}' does not grant MCP prompt '{server}/{name}'",
manifest.metadata.name
)),
(Some(_), None) => Some(format!(
"MCP prompt '{server}/{name}' was dispatched without declared ceilings, so the manifest grant cannot be checked",
)),
(Some(grant), Some(wired))
if wired.max_input != grant.max_input_sensitivity
|| wired.output != grant.output_sensitivity =>
{
Some(format!(
"manifest '{}' grants MCP prompt '{server}/{name}' at input {:?} / output {:?}, but the wiring declares input {:?} / output {:?} — the reviewed artifact and the code disagree about a data ceiling",
manifest.metadata.name,
grant.max_input_sensitivity,
grant.output_sensitivity,
wired.max_input,
wired.output,
))
}
(Some(_), Some(_)) => None,
}
}
"mcp.resource/read" => {
let server = descriptor.args["server"].as_str().unwrap_or_default();
let uri = descriptor.args["uri"].as_str().unwrap_or_default();
match (manifest.resource_grant(server, uri), ceilings) {
(None, _) => Some(format!(
"manifest '{}' does not grant MCP resource '{server}/{uri}'",
manifest.metadata.name
)),
(Some(_), None) => Some(format!(
"MCP resource '{server}/{uri}' was dispatched without declared ceilings, so the manifest grant cannot be checked",
)),
(Some(grant), Some(wired)) if wired.output != grant.output_sensitivity => {
Some(format!(
"manifest '{}' grants MCP resource '{server}/{uri}' at output {:?}, but the wiring declares output {:?} — the reviewed artifact and the code disagree about a data ceiling",
manifest.metadata.name, grant.output_sensitivity, wired.output,
))
}
(Some(_), Some(_)) => None,
}
}
"mcp.task/update" => {
let server = descriptor.args["server"].as_str().unwrap_or_default();
match (manifest.task_input_grant(server), ceilings) {
(None, _) => Some(format!(
"manifest '{}' does not grant task input responses to MCP server '{server}' — an elicitation is a server asking this plane for data, and the manifest never said it may have an answer",
manifest.metadata.name
)),
(Some(_), None) => Some(format!(
"task input for MCP server '{server}' was dispatched without declared ceilings, so the manifest grant cannot be checked",
)),
(Some(grant), Some(wired))
if wired.max_input != grant.max_input_sensitivity =>
{
Some(format!(
"manifest '{}' grants task input to MCP server '{server}' at input {:?}, but the wiring declares input {:?} — the reviewed artifact and the code disagree about a data ceiling",
manifest.metadata.name, grant.max_input_sensitivity, wired.max_input,
))
}
(Some(_), Some(_)) => None,
}
}
_ => None,
};
let Some(reason) = refusal else {
return Ok(());
};
tracing::error!(
target: telemetry::POLICY_DENIED,
run = %self.run,
step = %self.step,
action = crate::core::ACTION_DECLARED,
resource = %descriptor.kind,
%reason,
);
self.meter
.count(metrics::POLICY_DENIALS, crate::core::ACTION_DECLARED);
// Journaled under the refused effect's key, for the same reason a budget
// refusal is: a replay that found no history here would report that the
// *build* performs more effects than the record, sending an operator to
// look for a code change that does not exist.
self.append_effect(
key,
RecordKind::PolicyDenied {
reason: reason.clone(),
action: crate::core::ACTION_DECLARED.to_owned(),
resource: descriptor.kind.clone(),
},
)
.await?;
Err(StepError::Denied {
action: crate::core::ACTION_DECLARED.to_owned(),
resource: descriptor.kind.clone(),
reason,
})
}
/// Check an effect against the policy in force, journalling any denial.
///
/// Runs **only on live dispatch**. A replayed effect never reaches here,
/// because its result comes back from the journal rather than from the
/// world — which is what keeps a policy edit from re-judging a run that
/// already happened. See `core::policy`.
///
/// A permit is not recorded. The effect's own `EffectStarted` is already
/// evidence it was allowed, and journaling "yes" beside every call doubles
/// the log to say nothing.
async fn authorize(
&mut self,
key: EffectKey,
descriptor: &EffectDescriptor,
mutates: bool,
outbound: Option<&crate::core::Label>,
) -> Result<(), StepError> {
let Some(engine) = self.policy.as_ref() else {
return Ok(());
};
let mut context = serde_json::json!({
"run": self.run.to_string(),
"step": self.step.0,
// Every authorization request carries the tenant, not only
// admission. A gate that knows which tenant is acting at the door
// and forgets by the time an effect reaches the world is a gate
// that cannot express "this tenant may not call that tool".
"tenant": self.tenant.as_str(),
"mutates": mutates,
"args": descriptor.args,
});
// **Where the value came from**, not only what it is.
//
// Provenance and authorization are two graphs, and an attack lives in
// the gap between them: an agent is permitted to call a tool in general,
// and that permission never accounts for the provenance of the
// particular value it is called with. This crate closes the gap with
// checks written *here* — the taint gate and per-field source rules —
// but without the label in the request a **deployment** cannot express
// the alignment at all. It could say "amounts over 5000 need approval";
// it could not say "not with data that passed through that peer".
//
// Present only for `sink`, which is the only call that has a labelled
// value to bind — so a rule reading it must guard on `context has
// label`. Unguarded is not "fails closed for this request": Cedar
// evaluates every rule against every request, so reading an absent
// attribute **errors**, and an unevaluable rule refuses the call
// whatever it would have decided. One such rule denies every effect of
// every run, which is why `preflight_policy` asks these questions at
// build rather than leaving them to the first dispatch.
if let Some(label) = outbound {
context["label"] = serde_json::to_value(label).unwrap_or(Value::Null);
}
merge_identity(&mut context, self.identity.as_ref());
let request = crate::core::PolicyRequest {
principal: &self.agent,
action: crate::core::ACTION_PERFORM,
resource: &descriptor.kind,
context: &context,
};
// Before the policy is consulted, not after. A refusal is journaled as
// it happens, so a ceiling applied afterwards bounds nothing an
// observer can see — the record is already written and the bit is
// already out. Refusing here means the attempt produces neither.
if let Err(exceeded) = self
.ledger
.lock()
.expect("budget mutex")
.admit_policy_check()
{
return Err(StepError::Budget(exceeded));
}
// Both refusals, one path. `let … else` over `Deny` alone would send
// every other variant to the permit branch, so a decision this gate
// does not know about becomes an allow — a gate that fails open the
// moment the vocabulary grows. `Malformed` is refused like a denial
// and journaled like one; what differs is the operator's telemetry,
// because the fix is the policy set rather than the request.
let decision = engine.authorize(&request);
let malformed = decision.is_malformed();
let Some(reason) = decision.reason().map(ToOwned::to_owned) else {
return Ok(());
};
tracing::error!(
target: telemetry::POLICY_DENIED,
run = %self.run,
step = %self.step,
action = crate::core::ACTION_PERFORM,
resource = %descriptor.kind,
policy_error = malformed,
%reason,
);
self.meter
.count(metrics::POLICY_DENIALS, crate::core::ACTION_PERFORM);
self.append_effect(
key,
RecordKind::PolicyDenied {
reason: reason.clone(),
action: crate::core::ACTION_PERFORM.to_owned(),
resource: descriptor.kind.clone(),
},
)
.await?;
// Counted after the record, and the ordering matters: the refusal has
// already happened and belongs in the journal whatever the ceiling says.
// What the ceiling stops is the *next* attempt, which is the one that
// would learn something the last one did not.
if let Err(exceeded) = self.ledger.lock().expect("budget mutex").record_denial() {
return Err(StepError::Budget(exceeded));
}
Err(StepError::Denied {
action: crate::core::ACTION_PERFORM.to_owned(),
resource: descriptor.kind.clone(),
reason,
})
}
/// Check an effect against the run's ceilings, journalling any refusal.
///
/// The refusal goes in the journal under the key of the effect it refused.
/// Without it a replayed run reaches this point, finds no history, and
/// reports that the *build* performs more effects than the record — sending
/// an operator to look for a code change that does not exist.
async fn admit(&mut self, key: EffectKey, kind: &str) -> Result<(), StepError> {
// Scoped so the guard is gone before any await below.
let verdict = self.ledger.lock().expect("budget mutex").admit_effect();
let Err(exceeded) = verdict else {
return Ok(());
};
tracing::warn!(
target: telemetry::BUDGET_REFUSED,
run = %self.run,
step = %self.step,
%kind,
limit = %exceeded,
);
self.meter
.count(metrics::BUDGET_REFUSALS, exceeded.as_str());
self.append_effect(
key,
RecordKind::BudgetRefused {
limit: exceeded.to_string(),
used: format!("{:?}", self.budget()),
},
)
.await?;
Err(StepError::Budget(exceeded))
}
/// Perform one attempt inside its own span.
///
/// One span per *attempt*, not per effect, so a retried call shows as
/// several — which is what makes "how often does this driver need a second
/// try" answerable at all.
async fn traced_attempt<E: Effect>(
&mut self,
effect: &E,
key: EffectKey,
attempt: u32,
waited_ms: u64,
outbound: Option<&crate::core::Label>,
) -> Result<Result<E::Output, crate::core::EffectError>, StepError> {
let span = tracing::info_span!(
telemetry::EFFECT_SPAN,
{ telemetry::EFFECT_KIND } = tracing::field::display(&effect.descriptor().kind),
{ telemetry::EFFECT_ATTEMPT } = attempt,
{ telemetry::EFFECT_MUTATES } = effect.mutates(),
{ telemetry::EFFECT_REPLAYED } = false,
{ telemetry::OUTCOME } = tracing::field::Empty,
// Present only on the effects that *are* GenAI operations. Recorded
// rather than declared with a value so a clock read does not carry
// an empty `gen_ai.operation.name`, which would make the attribute
// useless for the tooling that keys on it.
{ telemetry::GEN_AI_OPERATION } = tracing::field::Empty,
);
if let Some(op) = effect.gen_ai_operation() {
span.record(telemetry::GEN_AI_OPERATION, op);
}
// `Instrument`, never `enter()`. An `Entered` guard held across an
// `.await` stays entered on the *thread*, so when the future yields,
// whatever runs next is attributed to this span. With concurrent step
// dispatch that silently reparents a sibling's work.
// Counted per *attempt*, matching the span: a driver that needs two
// tries has performed two effects against the world, and a count that
// collapsed them would hide exactly the retry rate an operator is
// looking for.
self.meter
.count(metrics::EFFECTS, &effect.descriptor().kind);
let outcome = self
.perform_once(effect, key, attempt, waited_ms, true, outbound)
.instrument(span.clone())
.await?;
span.record(
telemetry::OUTCOME,
if outcome.is_ok() { "done" } else { "failed" },
);
Ok(outcome)
}
/// What to do about a failure the journal already holds.
///
/// Returns the next attempt number to try. Errors if the recorded run
/// stopped here — which is the faithful outcome, not a fault.
#[allow(clippy::too_many_arguments)]
fn recorded_failure(
&mut self,
descriptor: &EffectDescriptor,
ordinal: u32,
attempt: u32,
key: EffectKey,
recovery: &crate::core::Recovery,
policy: &crate::core::RetryPolicy,
error: &str,
disposition: crate::core::Disposition,
permanent: bool,
mutates: bool,
) -> Result<u32, StepError> {
// Billed on replay exactly as it was live, or a run that exhausted its
// budget on failures would replay as healthy under the same limit.
self.bill(crate::core::Spend::default());
// Did the recorded run go on to retry? Ask history rather than infer:
// if the next journaled effect is this one's attempt + 1, it retried.
let next = EffectKey::derive(
self.step,
self.phase,
ordinal,
attempt + 1,
&descriptor.kind,
&canon::value_bytes(&descriptor.args),
);
if self.cursor.peek_is(next) {
// Follow history, whatever the current policy says.
return Ok(attempt + 1);
}
// History ends here. Recompute what the recorded run would have done
// next — a pure function of the disposition, the recovery mode, and the
// policy. If it would have stopped, this failure was final.
if let Some(stop) = Self::stop_reason(
disposition,
recovery,
key,
attempt,
policy,
error,
permanent,
mutates,
) {
return Err(stop);
}
// It would have retried, so it died between recording this failure and
// starting the next attempt. A strict pass reports that rather than
// performing anything; a resume carries on live.
if self.mode == Mode::Strict {
return Err(StepError::ReplayOverrun { actual: next });
}
Ok(attempt + 1)
}
/// Whether to stop after a failed attempt, and with what.
///
/// Three gates in order, and a policy can only ever narrow what the first
/// two allow:
///
/// 1. [`Landed`](crate::core::Disposition::Landed) — the call took effect.
/// Repeating it would be a second real performance, so it never happens.
/// 2. [`InDoubt`](crate::core::Disposition::InDoubt) — the same
/// undecidability a crash produces, resolved the same way: by the
/// declared [`Recovery`], never by guessing.
/// 3. The policy's attempt count, which governs only failures the first two
/// have already cleared.
///
/// Returns `None` when another attempt is permitted.
#[allow(clippy::too_many_arguments)]
fn stop_reason(
disposition: crate::core::Disposition,
recovery: &crate::core::Recovery,
key: EffectKey,
attempt: u32,
policy: &crate::core::RetryPolicy,
message: &str,
permanent: bool,
mutates: bool,
) -> Option<StepError> {
use crate::core::{Disposition, Recovery};
match disposition {
Disposition::Landed => {
return Some(StepError::Effect(crate::core::EffectError::Final {
detail: format!(
"effect {key} took effect and its response could not be used \
({message}); repeating it would perform it a second time"
),
disposition,
}));
}
Disposition::InDoubt => match recovery {
// Safe to repeat by declaration: either genuinely idempotent,
// or carrying an idempotency key the provider honours — while
// attempts remain. Once they run out the doubt is *final*,
// and for a mutating effect a final unknown is an operator's
// question, not a `Failed` (I5): a failure unwinds, and the
// unwind would compensate every step around a call that may
// have landed — the refund for money nobody took, issued by
// the retry policy having merely given up.
Recovery::Retry | Recovery::Idempotent { .. } => {
if mutates && !policy.permits(attempt) {
return Some(StepError::Undecidable {
key,
recovery: recovery.clone(),
detail: format!(
"{message} — attempts exhausted with the outcome still \
unknown, and the effect mutates; whether the last call \
landed is a question for an operator, not for an unwind"
),
});
}
}
Recovery::Reconcile => {
// Reached only once the probe has already run and come back
// inconclusive — the caller resolves what it can before
// asking this. The doubt survived being asked about.
return Some(StepError::Undecidable {
key,
recovery: recovery.clone(),
detail: format!(
"{message} — the reconciliation probe could not establish whether \
it landed"
),
});
}
Recovery::RequiresOperator => {
return Some(StepError::Undecidable {
key,
recovery: recovery.clone(),
detail: format!("{message} — it may well have been applied"),
});
}
},
Disposition::DidNotHappen => {
// An answer, not a fault. The peer understood the request and
// said no, so a second attempt asks the same rule the same
// question — every further attempt would be spent teaching the
// operator that retries are noise. The bit comes from the
// failure itself live and from the record on replay, so both
// stop at the same attempt.
if permanent {
return Some(StepError::Effect(crate::core::EffectError::Final {
detail: format!(
"effect {key} was refused on attempt {attempt}, and the refusal is an answer rather than a fault ({message}); no retry would change it"
),
disposition,
}));
}
}
}
// The disposition travels with the failure. Flattening it to `Other`
// here — which reads as `InDoubt` — would tell every caller that a call
// the driver explicitly *refused* might have happened, and the callers
// that act on doubt are exactly the ones that must not be misled.
(!policy.permits(attempt)).then(|| {
StepError::Effect(crate::core::EffectError::Final {
detail: format!(
"effect {key} failed on attempt {attempt} of {}: {message}",
policy.max_attempts
),
disposition,
})
})
}
/// Suspend until an instant, durably.
///
/// The run's frame is persisted and the task is dropped: a sleeping run
/// costs a row, not a thread. A sweep wakes it when the instant arrives, so
/// a plane can hold as many sleeping runs as it has disk and a restart loses
/// none of them.
///
/// The instant is recorded under an effect key, so replay reads it back
/// rather than sleeping again — and a run that slept until Tuesday still
/// says Tuesday when it is audited next year.
pub async fn sleep_until(&mut self, until: Timestamp) -> Result<(), StepError> {
let timers = self.timers.clone().ok_or_else(|| {
StepError::Effect(crate::core::EffectError::Other(
"durable timers need a timer store — build the runtime with `.timers(store)`"
.into(),
))
})?;
// Whole seconds, matching the store's precision. Two records of one
// wake-up that disagree by a fraction of a second give "when does this
// fire?" two answers.
let until = until.replace_nanosecond(0).map_err(|e| {
StepError::Effect(crate::core::EffectError::Other(format!(
"unrepresentable wake instant: {e}"
)))
})?;
// The sleep is an effect: its output is the instant it woke at. Replay
// reads that back like any other recorded result, so none of the
// suspension machinery exists twice.
let descriptor = EffectDescriptor::new(
"timer.sleep",
serde_json::json!({ "until": until.unix_timestamp() }),
);
let key = self.next_effect_key(&descriptor);
// ── Replay: the timer already fired ────────────────────────────────
if self.mode.is_replaying() {
match self.cursor.next(key)? {
Some(EffectReplay::Done { spend, .. }) => {
self.bill(spend);
return Ok(());
}
Some(EffectReplay::Refused { limit, used }) => {
return Err(StepError::Budget(crate::core::BudgetExceeded::Recorded {
limit,
used,
}));
}
Some(EffectReplay::Denied {
reason,
action,
resource,
}) => {
return Err(StepError::Denied {
action,
resource,
reason,
});
}
Some(EffectReplay::Failed { error, .. }) => {
return Err(StepError::Effect(crate::core::EffectError::Rejected(error)));
}
// Announced, and *possibly* armed: whether the arm landed is
// unknowable from the journal, because a crash — or a
// transient store error — between the announcement and the
// registration leaves exactly this record. Suspending without
// repairing would strand the run forever: no timer, no
// subscription, a released lease — nothing in the system ever
// names it again, and it looks precisely like work in
// progress. Re-arming is safe because `until` derives from
// journaled reads (the same instant on every pass) and `arm`
// keeps the first registration (a timer somebody may have
// claimed is never moved). A strict pass dispatches nothing,
// so only a resume repairs — strict still suspends here, which
// is the honest reading of a journal that ends mid-wait.
Some(EffectReplay::Orphan { .. }) => {
if self.mode == Mode::Resume {
timers
.arm(&crate::core::Timer {
run: self.run,
case: self.case.as_ref().map(CaseContext::id),
effect: key,
step: self.step,
phase: self.phase,
fire_at: until,
})
.await?;
}
return Err(StepError::Suspended(
crate::core::SuspendReason::AwaitingTime { until },
));
}
None if self.mode == Mode::Strict => {
return Err(StepError::ReplayOverrun { actual: key });
}
None => {}
}
}
// Announce before arming, so a crash between the two leaves an orphan
// the resumed run recognises rather than a timer nobody is waiting on.
self.append_effect(
key,
RecordKind::EffectStarted {
descriptor,
recovery: crate::core::Recovery::Retry,
mutates: false,
attempt: 1,
backoff_ms: 0,
// A durable wait binds no outbound value.
outbound_label: None,
},
)
.await?;
timers
.arm(&crate::core::Timer {
run: self.run,
case: self.case.as_ref().map(CaseContext::id),
effect: key,
step: self.step,
phase: self.phase,
fire_at: until,
})
.await?;
Err(StepError::Suspended(
crate::core::SuspendReason::AwaitingTime { until },
))
}
/// Suspend for a duration.
///
/// The duration is resolved to an instant through the journaled clock, so
/// the wake time is a recorded fact rather than a formula re-evaluated on
/// every replay.
pub async fn sleep(&mut self, how_long: std::time::Duration) -> Result<(), StepError> {
let now = self.now().await?;
let until = now
.checked_add(time::Duration::try_from(how_long).map_err(|e| {
StepError::Effect(crate::core::EffectError::Other(format!(
"unrepresentable sleep duration: {e}"
)))
})?)
.ok_or_else(|| {
StepError::Effect(crate::core::EffectError::Other(
"sleep duration overflows the representable range".into(),
))
})?;
self.sleep_until(until).await
}
/// Record a sink-gate refusal under the key the refused dispatch would
/// have carried, then hand it back as the error to raise.
///
/// The refusal occupies the dispatch's position: the ordinal is consumed
/// and the record keyed exactly as the effect would have been (attempt 1 —
/// nothing was attempted), for the same reason a budget refusal and a
/// policy denial are keyed. Without a record the refusal is invisible one
/// mode later: a strict pass over the refused run finds nothing to consume
/// and reports history left over.
///
/// Reached only where the dispatch would be **live**, because that is the
/// only place a sink gate runs at all. A replayed prefix does not re-decide
/// these verdicts; it reads the record this wrote, through the same cursor
/// arm that replays a policy denial.
///
/// # It stays a [`StepError::Policy`], and the record says so
///
/// A sink gate refusing one call is something a tool-calling loop can act
/// on: the model is told `REFUSED` and may try another route. An
/// authorization denial is not — it ends the run. Both are journaled as
/// `PolicyDenied`, so the record carries
/// [`ACTION_EGRESS`](crate::core::ACTION_EGRESS) to keep the two
/// distinguishable, and `recorded_refusal` rebuilds this shape from it. A
/// replay that turned a sink refusal into a denial would end a run the
/// original completed.
async fn refuse_sink(
&mut self,
descriptor: &EffectDescriptor,
denial: PolicyError,
) -> StepError {
let key = self.next_effect_key(descriptor);
if let Err(e) = self
.append_effect(
key,
RecordKind::PolicyDenied {
reason: denial.to_string(),
action: crate::core::ACTION_EGRESS.to_owned(),
resource: descriptor.kind.clone(),
},
)
.await
{
// A runtime that cannot record what it refused must not report
// the tidier error instead.
return e;
}
denial.into()
}
/// Send a labeled value into a sink, handing the value to the effect and
/// the gate in one motion.
///
/// The closure receives the inner value and builds the effect from it, so
/// the bytes the gates check and the bytes the effect sends are one
/// argument rather than two the caller must keep in agreement:
///
/// ```ignore
/// let completion = cx
/// .sink_with(&prompt, |value| ModelCall::new(provider, model, value))
/// .await?;
/// ```
///
/// This replaces the two-pass spelling — `ModelCall::new(..,
/// prompt.peek().clone())` beside `cx.sink(call, &prompt)` — where the
/// same data was written twice and a runtime check caught the versions
/// drifting apart. Passing it once removes the drift at the API instead of
/// detecting it afterwards; the byte-for-byte binding check still runs
/// underneath, because a custom effect could bind something other than
/// what its constructor was handed, and that is a driver bug worth a loud
/// refusal.
///
/// Fallible construction composes: the closure may return
/// `Result<E, impl Into<StepError>>` — see [`BuildsEffect`] — which is
/// what `ToolCall::prepare` needs.
///
/// # Errors
///
/// Whatever the closure refuses with, and everything [`sink`](Self::sink)
/// refuses: the egress ceiling, the journal ceiling, the whole-value taint
/// gate, and the per-field provenance rules.
pub async fn sink_with<E, B, F>(
&mut self,
args: &Tainted<Value>,
build: F,
) -> Result<Tainted<E::Output>, StepError>
where
E: Effect,
B: BuildsEffect<E>,
F: FnOnce(Value) -> B,
{
let effect = build(args.peek().clone()).into_effect()?;
self.sink(effect, args).await
}
/// Send a labeled value into a sink, enforcing the information-flow gates.
///
/// Prefer [`sink_with`](Self::sink_with), which hands the value to the
/// effect and the gate in one motion. This form remains for effects that
/// bind their outbound value internally — a governed media fetch derives
/// its bound arguments from the URL it was constructed over — and for
/// callers holding an effect built elsewhere.
///
/// Two checks, both of which are the reason labels exist at all:
///
/// * **Egress ceiling** — a value's sensitivity may not exceed what the sink
/// is allowed to receive. This is the exfiltration path that actually
/// matters: not the network, but a legitimate-looking call carrying a
/// secret that was read three steps ago.
/// * **Authority-bearing fields** — a mutating sink either refuses all
/// untrusted arguments or declares protected JSON fields with explicit
/// trust, source, and sensitivity constraints.
///
/// Both are judged over the *effective label at this sink*: the base label
/// improved by exactly the release marks whose destination names this
/// sink's identity. A release for `tool://ledger/transfer` moves nothing
/// at `tool://mail/send`.
pub async fn sink<E: Effect>(
&mut self,
effect: E,
args: &Tainted<Value>,
) -> Result<Tainted<E::Output>, StepError> {
let sink_name = effect.descriptor().kind;
// The identity a destination-scoped release must name: the sink's
// provenance identity — `tool://server/name`, `model:provider/model` —
// the same exact name a `ProtectedField::from_sources` rule grants.
// One chokepoint, so a release cannot be "for the ledger" at one gate
// and "for tools generally" at another.
let sink_id = effect.source().to_string();
let Some(bound) = effect.sink_arguments() else {
return Err(PolicyError::UnboundSinkArguments { sink: sink_name }.into());
};
if canon::value_bytes(bound) != canon::value_bytes(args.peek()) {
return Err(PolicyError::SinkArgumentsMismatch { sink: sink_name }.into());
}
// The label these gates judge is the **effective label at this sink**:
// the base label improved by exactly the release marks granted for
// this destination. Everywhere outside a sink gate the base label
// speaks — a release is for a destination, not for storage — and this
// effective label is also what policy is asked over and what the
// dispatch journals as its outbound label, because it is the label the
// verdict was reached over.
let label = args.effective_label(&sink_id);
let label = &label;
// **Every sink gate applies to live dispatch only**, and "live
// dispatch" is a property of the *cursor*, not of the mode.
//
// A replayed effect reads its result back from the journal, and the
// verdict these gates reached the first time is already in that
// journal — a pass as the `EffectDone` beside it, a refusal as its own
// record the cursor hands back. So there is nothing here for a replay
// to decide, and deciding anyway is how a replay stops reproducing the
// run and starts re-judging it: a tightened ceiling refuses an effect
// that already happened, a loosened one blesses an effect that was
// refused.
//
// This covers the effect's own declarations as well as the manifest's,
// because for every effect that reaches a sink the "code" reading is
// wrong. A tool's ceiling and protected fields come from the operator's
// `ToolSafety`, an MCP prompt's from a reviewed grant, a peer's from
// its `PeerGrant` — configuration, all of it, editable without
// recompiling and absent from the effect key. Judging a replayed
// effect against today's copy makes an operator's catalogue edit
// retroactively change what a finished run was allowed to do.
//
// But `Resume` is only *replaying* until its history runs out, and
// then it dispatches **live** — new calls, against the real world,
// for the rest of the run. Keying these gates on the mode instead of
// on cursor exhaustion switches them off for that entire live tail:
// a run refused by the egress ceiling, resumed, sails the same value
// past the same ceiling — an enforcement whose second attempt is a
// bypass is not an enforcement. `writes_enabled` is precisely "will
// this effect dispatch live": always in `Live`, past the frontier in
// `Resume`, never in `Strict` (which cannot dispatch at all — an
// exhausted cursor there is `ReplayOverrun`, not permission).
let live_dispatch = self.writes_enabled();
#[cfg(feature = "manifest")]
let manifest_gates = live_dispatch;
let ceiling = {
let effect_ceiling = effect.max_sensitivity();
#[cfg(feature = "manifest")]
{
// Three ceilings, and the strictest wins: the sink's own, the
// agent-wide egress ceiling, and the ceiling on *this tool's*
// reviewed grant. The last is the finest-grained of the three —
// "this tool may see internal data, that one may not" — and
// omitting it made a per-tool declaration decorative.
let effect_ceiling = self
.tool_grant_for(&effect.descriptor())
.and_then(|g| g.max_sensitivity)
.filter(|_| manifest_gates)
.map_or(effect_ceiling, |grant| effect_ceiling.min(grant));
self.manifest
.as_ref()
.filter(|_| manifest_gates)
.and_then(|m| m.spec.security.max_sensitivity_egress)
.map_or(effect_ceiling, |manifest_ceiling| {
effect_ceiling.min(manifest_ceiling)
})
}
#[cfg(not(feature = "manifest"))]
effect_ceiling
};
if live_dispatch && label.sensitivity > ceiling {
let denial = PolicyError::EgressCeiling {
sink: sink_name,
actual: label.sensitivity,
ceiling,
};
return Err(self.refuse_sink(&effect.descriptor(), denial).await);
}
// What may be *written down* is a different question from what may
// leave, and it is the one that decides whether a run's personal data
// can ever be erased: this effect's canonical arguments are about to
// enter an append-only chain, where no record is ever removed. This is
// the *refuse it* half; `RuntimeBuilder::keyring` is the *seal it* half,
// and they compose — a sealed record is still a record, and a key ring
// is still an operational dependency, so a deployment may want both.
// Checked here, before the announcement, so the refusal costs nothing —
// and absent by default, because every deployment before this field had
// no ceiling and silence must not start refusing their traffic.
//
// Judged over the **base** label, not the effective one: what may be
// written down is a storage question, and a release is for a
// destination, not for storage. A sensitivity release toward this sink
// does not make the bytes en route to the append-only chain any more
// erasable.
#[cfg(feature = "manifest")]
let stored = args.label().sensitivity;
#[cfg(feature = "manifest")]
if let Some(journal_ceiling) = self
.manifest
.as_ref()
.filter(|_| manifest_gates)
.and_then(|m| m.spec.security.max_sensitivity_journaled)
&& stored > journal_ceiling
{
let denial = PolicyError::JournalCeiling {
sink: sink_name,
actual: stored,
ceiling: journal_ceiling,
};
return Err(self.refuse_sink(&effect.descriptor(), denial).await);
}
// The reviewed grant may only tighten — here as at the authorization
// gate, which has ORed the manifest's `mutates` in since it existed.
//
// `Effect::mutates` on a tool call reports what the **catalogue** says.
// A manifest declaring the same tool mutating is the deployment's own
// statement about it, and the whole-value taint gate below is precisely
// the control that statement buys. Without this line an operator
// catalogue calling a reviewed-mutating tool read-only exempts it from
// that gate, so model-chosen arguments reach something that changes the
// world — the one direction `ToolBox::check_against` says nobody can be
// right about, reached by the path that check cannot see.
//
// Live dispatch only, for the same reason the ceiling above is: a
// tightened manifest must not re-judge an effect that already happened.
#[cfg(feature = "manifest")]
let mutates = effect.mutates()
|| (manifest_gates
&& self
.tool_grant_for(&effect.descriptor())
.is_some_and(|g| g.mutates));
#[cfg(not(feature = "manifest"))]
let mutates = effect.mutates();
if live_dispatch
&& let Err(refusal) =
Self::enforce_protected_fields(&effect, args, sink_name, &sink_id, mutates)
{
// The whole-value taint gate and the per-field rules are sink
// gates like the ceilings above, and their refusals are recorded
// for the same reason.
return Err(match refusal {
StepError::Policy(denial) => self.refuse_sink(&effect.descriptor(), denial).await,
other => other,
});
}
// The same label the gates above enforced, handed to the deployment's
// own rules. See `authorize` for why it belongs there too.
self.effect_after_sink_gate(effect, Some(label)).await
}
/// The whole-object taint gate and the per-field rules, judged over the
/// **effective label at this sink**: the base label improved by exactly
/// the release marks whose destination is `sink_id`, field-scoped marks
/// applying only to their fields. A mark granted toward a different sink
/// changes nothing here except the refusal's wording — the operator is
/// told the release exists and where it points, never its basis or
/// evidence.
fn enforce_protected_fields<E: Effect>(
effect: &E,
args: &Tainted<Value>,
sink_name: String,
sink_id: &str,
mutates: bool,
) -> Result<(), StepError> {
let protected = effect.protected_fields();
if protected.is_empty() {
if mutates && args.effective_label(sink_id).is_untrusted() {
if let Some(mark) = misdirected_release(args, sink_id, "") {
return Err(PolicyError::ReleaseDestination {
sink: sink_name,
granted: mark.destination().to_owned(),
actual: sink_id.to_owned(),
}
.into());
}
return Err(PolicyError::TaintGate { sink: sink_name }.into());
}
return Ok(());
}
for field in protected {
let path = field.path();
let Some(field_label) = args.effective_label_at(sink_id, path) else {
return Err(PolicyError::ProtectedFieldMissing {
sink: sink_name,
path: path.to_owned(),
}
.into());
};
if field.requires_trusted() && field_label.is_untrusted() {
if let Some(mark) = misdirected_release(args, sink_id, path) {
return Err(PolicyError::ProtectedFieldReleaseDestination {
sink: sink_name,
path: path.to_owned(),
granted: mark.destination().to_owned(),
actual: sink_id.to_owned(),
}
.into());
}
return Err(PolicyError::ProtectedFieldTaint {
sink: sink_name,
path: path.to_owned(),
}
.into());
}
if !field.allowed_sources().is_empty() {
let source = field_label
.provenance
.iter()
.find(|source| !field.allowed_sources().contains(*source));
if let Some(source) = source {
return Err(PolicyError::ProtectedFieldSource {
sink: sink_name,
path: path.to_owned(),
actual_source: source.to_string(),
}
.into());
}
if field_label.provenance.is_empty() {
return Err(PolicyError::ProtectedFieldSource {
sink: sink_name,
path: path.to_owned(),
actual_source: "<no provenance>".to_owned(),
}
.into());
}
}
if let Some(field_ceiling) = field.sensitivity_ceiling()
&& field_label.sensitivity > field_ceiling
{
return Err(PolicyError::ProtectedFieldSensitivity {
sink: sink_name,
path: path.to_owned(),
actual: field_label.sensitivity,
ceiling: field_ceiling,
}
.into());
}
}
Ok(())
}
/// Grant a destination-scoped release over a whole value or selected
/// structured fields.
///
/// The release is policy-authorized and permanently records the releaser,
/// basis, field scope, destination, evidence, and prior label. It does
/// **not** relabel the value: it attaches release marks, and only the
/// sink whose identity equals the release's `destination` — the
/// provenance-style name, `tool://server/name`, `model:provider/model` —
/// computes an improved effective label from them. Everywhere else the
/// value keeps its base label: joined into other values, written to
/// memory, read as `label().trust`, it is still what it was. A selected
/// field release is accepted only when the value was assembled with
/// [`Tainted::object`](crate::core::Tainted::object) or
/// [`Tainted::array`](crate::core::Tainted::array), so precision can never
/// be invented after provenance was flattened.
pub async fn release(
&mut self,
value: Tainted<Value>,
release: crate::core::Release,
) -> Result<Tainted<Value>, StepError> {
release
.validate()
.map_err(|detail| PolicyError::InvalidRelease {
detail: detail.to_owned(),
})?;
let label = value.label().clone();
let field_labels = value
.field_labels()
.map(|(path, label)| (path.to_owned(), label.clone()))
.collect::<BTreeMap<_, _>>();
let value_bytes = canon::value_bytes(value.peek());
let value_digest = crate::core::Digest::of(&value_bytes);
let released = value
.apply_release(&release)
.ok_or(PolicyError::UntrackedReleaseField)?;
let result_label = released.label().clone();
let result_field_labels = released
.field_labels()
.map(|(path, label)| (path.to_owned(), label.clone()))
.collect::<BTreeMap<_, _>>();
let descriptor = EffectDescriptor::new(
crate::core::ACTION_RELEASE,
serde_json::json!({
"release": &release,
"label": &label,
"field_labels": &field_labels,
"result_label": &result_label,
"result_field_labels": &result_field_labels,
"value": value_digest,
}),
);
let key = self.next_effect_key(&descriptor);
if self.mode.is_replaying() {
match self.cursor.next(key)? {
Some(EffectReplay::Done { .. }) => return Ok(released),
Some(EffectReplay::Denied {
reason,
action,
resource,
}) => {
return Err(StepError::Denied {
action,
resource,
reason,
});
}
Some(_) => {
return Err(StepError::ReplayOverrun { actual: key });
}
None if self.mode == Mode::Strict => {
return Err(StepError::ReplayOverrun { actual: key });
}
None => {}
}
}
self.authorize_release(key, &release, &label).await?;
self.append_effect(
key,
RecordKind::Released {
releaser: self.agent.clone(),
release,
label,
field_labels,
result_label,
result_field_labels,
value: value_digest,
},
)
.await?;
Ok(released)
}
/// Authorize a live release from the information-flow lattice.
///
/// Historical releases are facts and are never re-judged during replay,
/// matching the effect authorization rule. A denial is still journaled:
/// otherwise a run would stop at a policy decision with no durable account
/// of why it stopped.
async fn authorize_release(
&mut self,
key: EffectKey,
release: &crate::core::Release,
label: &crate::core::Label,
) -> Result<(), StepError> {
let Some(engine) = self.policy.clone() else {
return Ok(());
};
let mut context = serde_json::json!({
"run": self.run.to_string(),
"step": self.step.0,
"release": release,
"label": label,
});
merge_identity(&mut context, self.identity.as_ref());
let request = crate::core::PolicyRequest {
principal: &self.agent,
action: crate::core::ACTION_RELEASE,
resource: "information_flow.label",
context: &context,
};
self.ledger
.lock()
.expect("budget mutex")
.admit_policy_check()
.map_err(StepError::Budget)?;
// Both refusals, one path. `let … else` over `Deny` alone would send
// every other variant to the permit branch, so a decision this gate
// does not know about becomes an allow — a gate that fails open the
// moment the vocabulary grows. `Malformed` is refused like a denial
// and journaled like one; what differs is the operator's telemetry,
// because the fix is the policy set rather than the request.
let decision = engine.authorize(&request);
let malformed = decision.is_malformed();
let Some(reason) = decision.reason().map(ToOwned::to_owned) else {
return Ok(());
};
tracing::error!(
target: telemetry::POLICY_DENIED,
run = %self.run,
step = %self.step,
action = crate::core::ACTION_RELEASE,
resource = "information_flow.label",
policy_error = malformed,
%reason,
);
self.meter
.count(metrics::POLICY_DENIALS, crate::core::ACTION_RELEASE);
self.append_effect(
key,
RecordKind::PolicyDenied {
reason: reason.clone(),
action: crate::core::ACTION_RELEASE.to_owned(),
resource: "information_flow.label".to_owned(),
},
)
.await?;
Err(StepError::Denied {
action: crate::core::ACTION_RELEASE.to_owned(),
resource: "information_flow.label".to_owned(),
reason,
})
}
/// Whether non-effect records should be written right now.
///
/// Effects carry keys and are matched against history individually, so they
/// look after themselves. Bookkeeping records — notes, releases —
/// have no key, so they need this rule instead:
///
/// * `Live` — always write.
/// * `Resume` — write only once history is exhausted. Inside the replayed
/// prefix these records already exist; re-appending them would duplicate
/// history rather than reconstruct it.
/// * `Strict` — never write. Verification is a pure read, and a
/// verification pass that mutates the journal would corrupt the very
/// history it is checking, moving the chain head every time someone ran a
/// regression test.
fn writes_enabled(&self) -> bool {
match self.mode {
Mode::Live => true,
Mode::Resume => self.cursor.exhausted(),
Mode::Strict => false,
}
}
/// Consume a recorded failure and decide what the run did next.
///
/// Billed on the way past, exactly as the live path bills it: a replayed run
/// must reach the same budget verdict at the same point, and a metered
/// failure is part of what the original run spent.
#[allow(clippy::too_many_arguments)]
fn replay_recorded_failure(
&mut self,
descriptor: &EffectDescriptor,
ordinal: u32,
attempt: u32,
key: EffectKey,
recovery: &crate::core::Recovery,
policy: &crate::core::RetryPolicy,
error: &str,
disposition: crate::core::Disposition,
spend: crate::core::Spend,
permanent: bool,
mutates: bool,
) -> Result<u32, StepError> {
self.bill(spend);
self.recorded_failure(
descriptor,
ordinal,
attempt,
key,
recovery,
policy,
error,
disposition,
permanent,
mutates,
)
}
/// The delegation-depth gate, with its refusal journaled.
async fn refuse_excess_delegation<E: Effect>(
&mut self,
effect: &E,
descriptor: &EffectDescriptor,
) -> Result<(), StepError> {
if let Err(refusal) = self.check_delegation_depth(effect) {
return Err(match refusal {
StepError::Policy(denial) => self.refuse_sink(descriptor, denial).await,
other => other,
});
}
Ok(())
}
/// Refuse an effect that would delegate deeper than the declaration allows.
///
/// Live dispatch only, like every other manifest gate — where "live" is
/// cursor exhaustion, not mode: a replayed effect reads its result back,
/// so a tightened ceiling must not retroactively refuse it, but a resumed
/// run past its frontier is dispatching *new* delegations against the
/// real world, and the loop a `specialist` role exists to prevent does
/// not pause because the run once crashed.
// `self` and `effect` are both unused without `manifest`, and the ceiling
// lives on the manifest — so a build with no manifest support has nothing to
// check rather than a different rule.
#[allow(
unused_variables,
clippy::unnecessary_wraps,
clippy::unused_self,
clippy::needless_pass_by_ref_mut
)]
fn check_delegation_depth<E: Effect>(&self, effect: &E) -> Result<(), StepError> {
#[cfg(feature = "manifest")]
let ceiling = self
.manifest
.as_ref()
.filter(|_| self.writes_enabled())
.and_then(|manifest| {
// Role is authority, not prose. A specialist means zero
// delegation even when the duplicate numeric ceiling is
// omitted; otherwise omission restores exactly the handoff
// power the role claims not to have.
manifest
.spec
.topology
.as_ref()
.is_some_and(|topology| topology.role == crate::manifest::Role::Specialist)
.then_some(0)
.or(manifest.spec.security.max_delegation_depth)
});
#[cfg(feature = "manifest")]
if let (Some(actual), Some(ceiling)) = (effect.delegation_depth(), ceiling)
&& actual > usize::from(ceiling)
{
return Err(PolicyError::DelegationDepth {
sink: effect.descriptor().kind,
actual,
ceiling: usize::from(ceiling),
}
.into());
}
Ok(())
}
/// One attempt: announce, act, record.
///
/// The nested result separates two failures that must not be confused. The
/// outer `StepError` is the runtime itself failing — the journal would not
/// accept a write, the output would not encode — and is never retryable,
/// because a runtime that cannot record what it did must not go on doing
/// things. The inner `EffectError` is the *effect* failing, which is
/// ordinary, journaled, and what the retry decision is made from.
async fn perform_once<E: Effect>(
&mut self,
effect: &E,
key: EffectKey,
attempt: u32,
backoff_ms: u64,
write_start: bool,
outbound: Option<&crate::core::Label>,
) -> Result<Result<E::Output, crate::core::EffectError>, StepError> {
// `EffectStarted` goes down *before* the call. If the process dies
// between here and the terminal record, replay sees an orphan and the
// declared recovery mode decides — which is only possible because the
// start was durable first.
if write_start {
self.append_effect(
key,
RecordKind::EffectStarted {
descriptor: effect.descriptor(),
recovery: effect.recovery(),
mutates: effect.mutates(),
attempt,
backoff_ms,
outbound_label: outbound.cloned(),
},
)
.await?;
}
// Past this point the call has returned, so a failure to *record* what
// it did is not a store error like any other: the announcement is
// durable, the terminal record is not, and this process — unlike the
// resume that will find the orphan — knows what actually happened.
// That knowledge travels as `StepError::Unrecorded` rather than being
// flattened into `Store`, because a consumer deciding what the failure
// permits (an effect group's cheap abort claims *taken back whole*)
// branches on whether the call reached the world.
match effect.perform().await {
Ok(output) => {
let unrecorded = |key, detail: String| StepError::Unrecorded {
key,
disposition: crate::core::Disposition::Landed,
detail,
};
let json = match serde_json::to_value(&output) {
Ok(json) => json,
Err(e) => return Err(unrecorded(key, e.to_string())),
};
let spend = effect.spend(&output);
self.bill_live(spend);
if let Err(e) = self
.append_effect(
key,
RecordKind::EffectDone {
output: json,
// Not an inbound event: only an awaited delivery has
// a sender to record.
source: None,
spend,
declared: crate::core::DeclaredOutput::of(effect),
},
)
.await
{
return Err(unrecorded(key, e.to_string()));
}
Ok(Ok(output))
}
Err(e) => {
// A failed call still occupied a call, which is what lets
// `max_effects` bound an effect that never succeeds — and it may
// also have spent real money before dying. A stream cut off
// after five hundred tokens is billed for five hundred tokens.
let spend = e.spend();
self.bill_live(spend);
// The disposition is recorded alongside the message because it
// is what every later decision reads — the retry taken now, and
// an operator's judgement afterwards. Messages get reworded;
// this is a fact about the run.
if let Err(append_failed) = self
.append_effect(
key,
RecordKind::EffectFailed {
error: e.to_string(),
spend,
disposition: e.disposition(),
// An answer, not a fault — recorded so the replayed
// retry decision stops where the live one did.
permanent: matches!(e, crate::core::EffectError::Refused(_)),
},
)
.await
{
return Err(StepError::Unrecorded {
key,
disposition: e.disposition(),
detail: format!("{e}; and recording that failure failed: {append_failed}"),
});
}
Ok(Err(e))
}
}
}
async fn append_effect(&mut self, key: EffectKey, kind: RecordKind) -> Result<(), StepError> {
self.store
.append(self.epoch, vec![self.stamp(kind).effect(key)])
.await?;
self.wrote = true;
Ok(())
}
pub(crate) async fn append(&mut self, kind: RecordKind) -> Result<(), StepError> {
if !self.writes_enabled() {
return Ok(());
}
self.store
.append(self.epoch, vec![self.stamp(kind)])
.await?;
self.wrote = true;
Ok(())
}
/// Tag a record with this step's run, step, and case.
///
/// Every record of a case-bound run carries its case, which is what
/// `JournalStore::case_history` scans. Without it, "show me everything
/// about this matter" is a join over the case's runs — and one that misses
/// every record written by a run the case does not own, which is exactly
/// what a sweep is.
fn stamp(&self, kind: RecordKind) -> Append {
let mut a = Append::new(self.run, kind)
.step(self.step)
.phase(self.phase);
if let Some(c) = &self.case {
a = a.case(c.case_id);
}
a
}
}
/// The escalation declaration must describe something the store can do.
///
/// One implementation serving [`StepCtx::task`] and [`StepCtx::open_task`],
/// mirroring the manifest parser's rules for `spec.oversight` — the coded tier
/// and the declared tier must refuse the same shapes, or which tier an agent
/// was written in decides whether its oversight declaration is checked.
///
/// Three shapes are refused:
///
/// * `Escalate` naming nobody — "widen the audience" with no audience to add
/// is a state flag wearing a control's name;
/// * `Escalate` over an empty `candidate_roles` — empty already means
/// *anyone*, and `Task::escalate` deliberately will not narrow it, so the
/// declared widening would do nothing;
/// * `escalate_to` beside a policy that never escalates — a declaration
/// nothing reads, which reads in review exactly like one something does.
fn escalation_names_its_audience(spec: &TaskSpec) -> Result<(), StepError> {
let refuse = |detail: &str| {
Err(StepError::Effect(crate::core::EffectError::Other(
detail.into(),
)))
};
if spec.on_expiry == OnExpiry::Escalate {
if spec.escalate_to.is_empty() {
return refuse(
"OnExpiry::Escalate requires `escalate_to(role)`: widening the audience \
is escalation's one enforceable meaning, so the declaration must say \
who is added",
);
}
if spec.candidate_roles.is_empty() {
return refuse(
"OnExpiry::Escalate needs a bounded audience: an empty `candidate_roles` \
already means anyone, and there is no wider audience than that — \
name the initial reviewers with `role(..)`, or use `Deny`",
);
}
} else if !spec.escalate_to.is_empty() {
return refuse(
"`escalate_to` names an escalation audience, but this task never escalates — \
set `on_expiry(OnExpiry::Escalate)` or drop the roles, so the declaration \
and the policy say the same thing",
);
}
Ok(())
}
/// The first release mark that covers `path`, would confer trust, and names a
/// destination other than the sink at hand — the evidence for a refusal that
/// can say "released, but not for here".
///
/// Only the two destinations reach the message; the release's basis and
/// evidence stay in the journal, where an operator reads them and a probing
/// model cannot.
fn misdirected_release<'a>(
args: &'a Tainted<Value>,
sink_id: &str,
path: &str,
) -> Option<&'a crate::core::ReleaseMark> {
args.label().releases.iter().find(|mark| {
mark.destination() != sink_id && mark.covers(path) && mark.scope().improves_trust()
})
}
/// A refusal the recorded run met, as the error this one meets.
///
/// The verdict is history: a run refused by a ceiling or a rule was refused
/// then, whatever the ceiling or the rule says now. Re-deriving either would
/// re-judge last year's run under this year's configuration, which is the one
/// thing replay must never do.
fn recorded_refusal(replay: EffectReplay) -> StepError {
match replay {
EffectReplay::Refused { limit, used } => {
StepError::Budget(crate::core::BudgetExceeded::Recorded { limit, used })
}
// Which gate refused is recorded in `action`, and rebuilding the right
// shape from it is what keeps a replay from ending a run the original
// finished: a sink refusal is one call the model may route around, an
// authorization denial is the run.
EffectReplay::Denied { reason, action, .. } if action == crate::core::ACTION_EGRESS => {
StepError::Policy(PolicyError::Recorded { reason })
}
EffectReplay::Denied {
reason,
action,
resource,
} => StepError::Denied {
action,
resource,
reason,
},
// The caller matches only these two.
other => StepError::Effect(crate::core::EffectError::Other(format!(
"not a recorded refusal: {other:?}"
))),
}
}
/// Wall-clock read for subscription bookkeeping.
///
/// Infrastructure metadata, not run-visible state: it never enters the journal
/// and therefore cannot affect replay. Run-visible time goes through
/// `StepCtx::now`, which journals the instant.
#[allow(clippy::disallowed_methods)]
fn subscription_clock() -> Timestamp {
Timestamp::now_utc()
}
/// Derive a reproducible RNG stream for one step.
fn seeded_rng(run: RunId, step: StepId) -> ChaCha8Rng {
let mut seed = [0u8; 32];
seed[..16].copy_from_slice(&run.0.to_bytes());
seed[16..20].copy_from_slice(&step.0.to_be_bytes());
ChaCha8Rng::from_seed(seed)
}
/// Case-scoped operations.
///
/// Available only when the runtime was built with a case store and the run was
/// admitted with correlation keys. A run without a case is a perfectly ordinary
/// run — it simply has no long-lived state to reach.
impl StepCtx<'_> {
/// The case this run belongs to, if any.
#[must_use]
pub fn case_id(&self) -> Option<CaseId> {
self.case.as_ref().map(|c| c.case_id)
}
/// The business keys this run's case is identified by.
///
/// Empty when the run has no case. These are the keys **as recorded when the
/// run bound to the case**, not as the case stands now: a case accumulates
/// keys over months, and reading the store here would make a resumed run see
/// a set the live run never did.
///
/// The intended use is scoping durable state to the party a run is about —
/// `Recall::about(cx.correlation_value("meter")?)` reads back exactly what a
/// declarative agent's `subject: "$correlation/meter"` wrote.
#[must_use]
pub fn correlation(&self) -> &[CorrelationKey] {
self.case.as_ref().map_or(&[], |c| c.correlation.as_slice())
}
/// One correlation value by namespace.
///
/// `None` for a run with no case, and for a namespace the case is not keyed
/// by. Two keys sharing a namespace is a correlation the deployment set up,
/// not something to arbitrate here, so the first in canonical order wins and
/// the choice is stable across runs rather than dependent on store order.
#[must_use]
pub fn correlation_value(&self, namespace: &str) -> Option<&str> {
self.correlation()
.iter()
.find(|key| key.namespace == namespace)
.map(|key| key.value.as_str())
}
fn case_ctx(&self) -> Result<&CaseContext, StepError> {
self.case.as_ref().ok_or_else(|| {
StepError::Effect(crate::core::EffectError::Other(
"this run has no case: build the runtime with a case store and admit the run \
with correlation keys"
.into(),
))
})
}
/// Read the case's opaque state, and the revision it was read at.
///
/// **A journaled effect**, so a replay reads back what the live run saw
/// rather than whatever the case holds now. Case state is mutable storage
/// shared by every run on the case; reading it is as non-deterministic as
/// reading a clock, and treating it as free was a hole in exactly the
/// property this crate exists to provide.
///
/// The version comes back with the value because [`put_case_state`] needs
/// it. Returning the value alone is what makes a lost update easy to write.
///
/// [`put_case_state`]: Self::put_case_state
///
/// # Errors
///
/// [`StepError`] if this run has no case, or the read fails.
pub async fn case_state(&mut self) -> Result<(Tainted<Value>, CaseVersion), StepError> {
let cx = self.case_ctx()?.clone();
let snapshot = self
.effect(crate::runtime::effects::ReadCaseState {
cases: Arc::clone(&cx.cases),
case: cx.case_id,
})
.await?;
let snapshot = snapshot.into_unlabelled();
// **Untrusted, always.** Case state is shared mutable state: several
// runs write it over a process that may last months, and the engine
// never interprets a byte of it. So a read is only as trustworthy as
// the least trustworthy thing anybody ever wrote — and nothing here
// knows what that was.
//
// Returning `trusted()` made this an exit from the lattice. A skill
// holding a model completion could `peek` it into case state and read
// it back clean in a later step, or a later *run*, having passed none of
// `cx.release`'s policy check and leaving no record that a
// declassification happened. Every taint gate downstream then had
// nothing to act on, which is the failure the labels exist to prevent.
//
// Storing the writer's label instead would be no better: it would
// describe one write of many and read as authoritative. The join of
// every writer is the only honest label, it decays to untrusted the
// moment anything untrusted lands, and it never recovers on its own —
// so this *is* that answer, without the machinery to arrive at it.
//
// A caller who genuinely needs it trusted asks for a release, which is
// journaled, policy-checked, and names who decided.
let label = crate::core::Label::untrusted(crate::core::SourceId::new(format!(
"case:{}",
cx.case_id
)));
Ok((Tainted::with_label(snapshot.state, label), snapshot.version))
}
/// Draw on a standing authority, or be refused.
///
/// The ceiling that outlives a run: a customer's approved spend, a purchase
/// order, a subscription mandate. A [`Budget`](crate::core::Budget) bounds
/// this run and a [`TenantQuota`](crate::quota::TenantQuota) bounds a billing
/// period; neither can express an authorization somebody granted once and may
/// take back.
///
/// Journaled, so a replay reads the receipt rather than consuming again, and
/// idempotent across retries of the same call — see
/// [`DrawOnAuthority`](crate::runtime::effects::DrawOnAuthority) for why the
/// deduplication key is the dispatch rather than the effect.
///
/// Expiry is evaluated against this run's journaled clock, so a replay
/// reaches the verdict the live run did rather than today's.
///
/// # Errors
///
/// [`StepError::Store`] when no authority store is wired, and the effect's
/// own error carrying whichever of the five refusals applies — unknown,
/// exhausted, out of draws, revoked, or expired.
pub async fn draw(
&mut self,
id: &crate::authority::AuthorityId,
amount: crate::core::Spend,
) -> Result<crate::authority::Drawn, StepError> {
let authorities = self.authorities.clone().ok_or_else(|| {
StepError::Store(crate::core::StoreError::Backend(
"no standing-authority store is configured; \
`Runtime::builder(..).authorities(..)` is what gives an agent a \
ceiling that outlives one run"
.to_owned(),
))
})?;
let at = self.now().await?;
Ok(self
.effect(crate::runtime::effects::DrawOnAuthority {
authorities,
id: id.clone(),
amount,
at,
key: None,
})
.await?
.into_unlabelled())
}
/// Recall what this agent remembers about a subject.
///
/// # Every item comes back labelled from its **provenance**
///
/// Never from its content. Text asserting its own reliability is the
/// cheapest thing an attacker can write, so a memory derived from a model,
/// a peer or an inbound message stays untrusted however many times it is
/// re-read — and reaching a mutating sink with it takes the same journaled
/// release as any other untrusted value.
///
/// That is the defence against the attack this whole module is shaped by: a
/// poisoned write becomes a standing instruction only if something later
/// treats it as one.
///
/// # Journaled, and replayed by version
///
/// The **selection** is recorded — ids, versions, content digests — and a
/// replay re-materialises exactly those versions rather than re-running the
/// search. So a run replayed after the corpus changed reads what it read,
/// not what a fresh ranking would return now.
///
/// # Errors
///
/// [`StepError`] if this plane has no memory store, if the recall fails, or
/// if a version this run read can no longer be reproduced — which is a
/// deliberate loud failure, not an empty result: a memory that was forgotten
/// makes the history that used it unreplayable, and saying so beats
/// replaying a different memory.
pub async fn recall(
&mut self,
mut query: crate::memory::Recall,
) -> Result<Vec<Tainted<crate::memory::MemoryItem>>, StepError> {
let memories = self.memories.clone().ok_or_else(|| {
StepError::Store(crate::core::StoreError::Backend(
"no memory store is configured; `Runtime::builder(..).memory(..)` is what \
gives an agent something to remember"
.to_owned(),
))
})?;
if query.as_of.is_none() {
query.as_of = Some(self.now().await?);
}
let recall_at = query.as_of.expect("recall cutoff set above");
let refresh_access = query.refresh_access;
let selected = self
.effect(crate::runtime::effects::RecallMemory {
memories: Arc::clone(&memories),
query,
})
.await?
.into_unlabelled();
if refresh_access && !selected.is_empty() {
self.effect(crate::runtime::effects::TouchMemory {
memories: Arc::clone(&memories),
ids: selected.iter().map(|pick| pick.id.clone()).collect(),
at: recall_at,
})
.await?;
}
let mut out = Vec::with_capacity(selected.len());
for pick in selected {
let item = memories
.version(&pick.id, pick.version)
.await
.map_err(StepError::Store)?
.ok_or_else(|| {
StepError::Store(crate::core::StoreError::Backend(
crate::memory::MemoryError::Forgotten {
id: pick.id.clone(),
version: pick.version,
}
.to_string(),
))
})?;
// A version is supposed to be immutable. If content or label inputs
// moved under one, the store cannot reproduce its own history — and
// a replay that quietly used the new value would be a different run
// wearing the old one's journal.
if item.selection_digest() != pick.digest {
return Err(StepError::Unreproducible {
what: format!("memory '{}' version {}", pick.id, pick.version),
detail: crate::memory::MemoryError::Rewritten {
id: pick.id,
version: pick.version,
}
.to_string(),
});
}
let label = item.label();
out.push(Tainted::with_label(item, label));
}
Ok(out)
}
/// Turn text into a vector, on the record, through the plane's embedder.
///
/// Going through here rather than calling an embedding client directly is
/// what makes semantic retrieval replayable at all: the query vector is in
/// the retrieval effect's key, and an embedding service is under no
/// obligation to return the same floats twice. Journaled, so a strict replay
/// reads the vector back instead of asking again — and so the call is
/// metered and the revision that produced it is on the record beside the
/// numbers.
///
/// The embedder is the one [`RuntimeBuilder::semantic_memory`] wired, which
/// is what makes [`Embedding::revision`] a fact rather than a claim.
///
/// The text carries its own label, and the returned vector carries it too: a
/// vector derived from an untrusted document is untrusted, and sending
/// confidential text to an embedding service is an egress like any other.
///
/// `max_sensitivity` is that egress decision, and it is a parameter because
/// there is no answer this crate could pick for every deployment. Note what
/// it has to admit for the call to be useful at all: a query worth embedding
/// has almost always crossed a trust boundary — a user's question, a model's
/// paraphrase, a recalled memory — and anything that has is already
/// [`Internal`].
///
/// [`Internal`]: crate::core::Sensitivity::Internal
/// [`Embedding::revision`]: crate::memory::Embedding::revision
/// [`RuntimeBuilder::semantic_memory`]: crate::runtime::RuntimeBuilder::semantic_memory
///
/// # Errors
///
/// [`StepError`] if this plane wired no semantic memory, or whatever the
/// effect protocol reports — a refused sink, an exhausted budget, or the
/// embedder's own failure.
pub async fn embed(
&mut self,
text: Tainted<String>,
max_sensitivity: crate::core::Sensitivity,
) -> Result<Tainted<crate::memory::Embedding>, StepError> {
let embedder = Arc::clone(&self.semantic_index()?.embedder);
let plain = text.peek().clone();
let arguments = text.map(serde_json::Value::String);
self.sink_with(&arguments, |value| crate::runtime::effects::Embed {
embedder,
text: plain,
arguments: value,
max_sensitivity,
})
.await
}
fn semantic_index(&self) -> Result<&Arc<crate::runtime::SemanticMemory>, StepError> {
self.semantic.as_ref().ok_or_else(|| {
StepError::Store(crate::core::StoreError::Backend(
"this plane wired no semantic memory; \
`Runtime::builder(..).semantic_memory(embedder, retriever)` is what \
gives an agent an index to search"
.to_owned(),
))
})
}
/// Rank governed memories by meaning, through the plane's semantic index.
///
/// Two journaled effects: the text is embedded, then the vector is ranked.
/// The retriever returns only immutable `(id, version, digest)` commitments
/// and scores, and the selection is recorded already screened — a hit
/// naming a superseded, expired, or erased version leaves it, for the
/// reasons on [`SemanticRecall`](crate::runtime::effects::SemanticRecall).
/// Live execution and replay then both materialise the surviving versions
/// and re-check scope and digest before any content is exposed, so an
/// index that *contradicts* durable truth — rather than merely trailing
/// it — is a refusal, never a plausible answer.
///
/// The [`SemanticSearch`] states the question; the space it is asked in
/// comes from the wired embedder and index, which `build` already held to
/// each other ([`IndexIdentity`]).
///
/// # The selected set is untrusted-influenced, whatever the items say
///
/// Similarity is computed over item content, so anything able to write a
/// memory is a ranking signal: an attacker who cannot taint a value can
/// still choose *which* clean values a model is shown, and no label shows
/// it. Every item still arrives labelled from its own provenance — but a
/// caller needing a selection nobody can steer wants
/// [`recall`](Self::recall), whose order is a fixed rule no stored item can
/// move.
///
/// [`MemoryStore`]: crate::memory::MemoryStore
/// [`SemanticSearch`]: crate::memory::SemanticSearch
/// [`IndexIdentity`]: crate::memory::IndexIdentity
///
/// # Errors
///
/// [`StepError`] if this plane wired no semantic memory or no memory store,
/// if either effect fails, or if the index returned a commitment the
/// authoritative store cannot honour.
pub async fn semantic_recall(
&mut self,
search: crate::memory::SemanticSearch,
text: Tainted<String>,
) -> Result<Vec<(Tainted<crate::memory::MemoryItem>, f32)>, StepError> {
let memories = self.memories.clone().ok_or_else(|| {
StepError::Store(crate::core::StoreError::Backend(
"no memory store is configured; semantic retrieval needs authoritative memory"
.to_owned(),
))
})?;
let retriever = Arc::clone(&self.semantic_index()?.retriever);
let as_of = self.now().await?;
let written = text.peek().clone();
let label = text.label().clone();
let embedding = self.embed(text, search.max_sensitivity).await?;
let label = label.join(embedding.label());
let query = crate::memory::SemanticQuery {
subject: search.subject.clone(),
purpose: search.purpose.clone(),
text: written,
index: crate::memory::IndexIdentity {
snapshot: retriever.index().snapshot,
query_revision: embedding.peek().revision.clone(),
},
embedding: embedding.into_unlabelled().vector,
limit: search.limit,
max_sensitivity: search.max_sensitivity,
as_of,
};
let searched = query.clone();
let screen = Arc::clone(&memories);
let arguments = Tainted::with_label(
serde_json::to_value(&query).expect("SemanticQuery serialization is infallible"),
label,
);
let hits = self
.sink_with(&arguments, |value| {
crate::runtime::effects::SemanticRecall {
retriever,
memories: screen,
query: searched,
arguments: value,
}
})
.await?
.into_unlabelled();
// The retriever's misconduct refusals — an answer past the declared
// limit, a non-finite score — live in the effect's `perform`, before
// the selection is journaled: a record is written once, and one that
// held either could not honestly be read back. What runs here is what
// must hold on **replay too**: the journaled selection materialises
// against durable truth, digest and scope re-checked.
let mut out = Vec::with_capacity(hits.len());
for hit in hits {
let item = memories
.version(&hit.selected.id, hit.selected.version)
.await
.map_err(StepError::Store)?
.ok_or_else(|| {
StepError::Store(crate::core::StoreError::Backend(
crate::memory::MemoryError::Forgotten {
id: hit.selected.id.clone(),
version: hit.selected.version,
}
.to_string(),
))
})?;
// Two failures, two systems to go look in. A digest that moved is
// the authoritative store contradicting itself; a hit outside the
// query's scope is the retriever misbehaving while durable truth is
// intact.
if item.selection_digest() != hit.selected.digest {
return Err(StepError::Unreproducible {
what: format!(
"memory '{}' version {}",
hit.selected.id, hit.selected.version
),
detail: crate::memory::MemoryError::Rewritten {
id: hit.selected.id,
version: hit.selected.version,
}
.to_string(),
});
}
if item.subject != query.subject
|| query
.purpose
.as_ref()
.is_some_and(|purpose| purpose != &item.purpose)
{
return Err(StepError::Store(crate::core::StoreError::Backend(format!(
"semantic retriever returned memory '{}', which is outside the \
scope the query asked for",
hit.selected.id
))));
}
let label = item.label();
out.push((Tainted::with_label(item, label), hit.score));
}
Ok(out)
}
/// Remember something, as a new version.
///
/// Journaled: a replay that wrote again would append a second version of a
/// memory this run wrote once, and the version number the run went on to use
/// would be wrong.
///
/// Trust, provenance and sensitivity are derived from `content`. They are
/// not fields the caller can declare: allowing a skill to store untrusted
/// model output with `trust: Trusted` would be an unjournaled release and a
/// cross-session laundering primitive.
///
/// # Errors
///
/// [`StepError`] if this plane has no memory store, or the write fails.
pub async fn remember(
&mut self,
write: crate::memory::MemoryWrite,
content: Tainted<Value>,
) -> Result<u64, StepError> {
let at = self.now().await?;
self.remember_at(write, content, at, Vec::new()).await
}
async fn remember_at(
&mut self,
write: crate::memory::MemoryWrite,
content: Tainted<Value>,
at: crate::core::Timestamp,
derived_from: Vec<crate::memory::Selected>,
) -> Result<u64, StepError> {
let memories = self.memories.clone().ok_or_else(|| {
StepError::Store(crate::core::StoreError::Backend(
"no memory store is configured; `Runtime::builder(..).memory(..)` is what \
gives an agent something to remember"
.to_owned(),
))
})?;
let label = content.label().clone();
let mut provenance: Vec<_> = label.provenance.iter().cloned().collect();
provenance.sort();
provenance.dedup();
let item = crate::memory::MemoryItem {
id: write.id,
subject: write.subject,
purpose: write.purpose,
content: content.into_unlabelled(),
provenance,
sensitivity: label.sensitivity,
trust: label.trust,
written_by: self.run.to_string(),
version: 0,
created_at: at,
expires_at: write.expires_at,
access_retention_seconds: write.access_retention_seconds,
superseded_at: None,
derived_from,
};
Ok(self
.effect(crate::runtime::effects::RememberMemory { memories, item })
.await?
.into_unlabelled())
}
/// Atomically erase memories expired at the run's journaled clock.
///
/// Legal holds remain authoritative in the backend. The cutoff and removed
/// count are journaled, so strict replay reports the historical decision
/// without mutating memory a second time.
pub async fn sweep_expired_memories(&mut self) -> Result<usize, StepError> {
let memories = self.memories.clone().ok_or_else(|| {
StepError::Store(crate::core::StoreError::Backend(
"no memory store is configured; there is nothing to sweep".to_owned(),
))
})?;
let at = self.now().await?;
Ok(self
.effect(crate::runtime::effects::SweepExpiredMemory { memories, at })
.await?
.into_unlabelled())
}
/// Summarise memories into a new, derived memory.
///
/// # The label is derived, never declared
///
/// This is the difference between `compact` and
/// [`remember`](Self::remember). A writer declares where ordinary content
/// came from; a summary's provenance is not a matter of opinion — it is the
/// **join of what was summarised**, plus the model that wrote it. Letting a
/// caller declare it would make compaction the laundering step: read three
/// untrusted memories, summarise, call the result trusted, and every gate
/// downstream has nothing to act on.
///
/// So the summary is untrusted whenever any input is, carries every input's
/// sources, and takes the highest sensitivity of any of them.
///
/// # It records what it was made from
///
/// Sources are recorded with the exact versions read. That is what makes a
/// summary **repairable**: a poisoned memory does not stop being a problem
/// when it is forgotten, because its content keeps arriving in every summary
/// that absorbed it. `MemoryStore::derivatives` walks that edge, and
/// `forget_cascading` is the form an erasure request needs.
///
/// # Compaction is an egress decision
///
/// It sends the memories to a model. So [`Compaction::max_sensitivity`](crate::memory::Compaction::max_sensitivity)
/// bounds what that model may be shown, and it defaults to `Public` —
/// summarising is otherwise the way to move confidential content past a
/// ceiling that stops every other path, while looking like housekeeping.
///
/// # The originals stay
///
/// Compaction adds; it does not delete. What a summary is *for* — fitting a
/// context window — is a reason to stop reading the originals, not a reason
/// to destroy the only record of what the summary claims to represent.
///
/// # Errors
///
/// [`StepError`] if this plane has no memory store, if the model call fails,
/// or if the write fails.
pub async fn compact(
&mut self,
into: crate::memory::Compaction,
sources: &[Tainted<crate::memory::MemoryItem>],
provider: Arc<dyn crate::model::ModelProvider>,
model: crate::model::ModelId,
) -> Result<u64, StepError> {
// The prompt is **built here**, from the sources, rather than accepted
// from the caller. The sink binds an effect's outbound arguments to the
// labelled value it checks, and a caller passing a pre-built call would
// have to reproduce this assembly exactly to satisfy that binding — an
// obligation nobody would meet twice.
//
// Labelled by the join of the sources, so the model call is checked like
// any other outbound value rather than around it.
let prompt = Tainted::object([
(
"instruction".to_owned(),
Tainted::trusted(serde_json::Value::String(into.instruction.clone())),
),
(
"memories".to_owned(),
Tainted::array(sources.iter().map(|s| {
let label = s.label().clone();
Tainted::with_label(s.peek().content.clone(), label)
})),
),
]);
let max_sensitivity = into.max_sensitivity;
let completion = self
.sink_with(&prompt, |value| {
crate::model::ModelCall::new(provider, model, value)
.with_max_sensitivity(max_sensitivity)
})
.await?;
let label = completion.label().clone();
let summary = completion.map(|c| c.structured.unwrap_or(serde_json::Value::String(c.text)));
let mut provenance: Vec<crate::core::SourceId> = label.provenance.iter().cloned().collect();
let mut sensitivity = label.sensitivity;
let mut trust = label.trust;
let mut derived_from = Vec::with_capacity(sources.len());
for source in sources {
let item = source.peek();
derived_from.push(crate::memory::Selected {
id: item.id.clone(),
version: item.version,
digest: item.selection_digest(),
});
let l = source.label();
provenance.extend(l.provenance.iter().cloned());
sensitivity = sensitivity.max(l.sensitivity);
// Doubled on purpose, and no test can distinguish the two halves.
// A summary is already untrusted because a model wrote it —
// `ModelCall` declares `Trust::Untrusted` unconditionally — so this
// line changes no outcome today. It is here for the day a
// deterministic local summariser is declared trusted, at which point
// the model half stops carrying it and this half is the only thing
// between an untrusted memory and a trusted summary.
//
// Sensitivity is doubled the same way, and the claim that it was
// not is what let its mutation look verified: the prompt is built
// from these very sources, so the completion's own label already
// carries their joined sensitivity, and deleting this line changed
// no outcome any test could see. It stays for the same future the
// trust half is kept for — a summariser whose output label does
// not inherit its input's sensitivity — and the mutation that
// proves the guarantee now targets the assignment below, which is
// the one place the written summary's sensitivity is decided.
//
// Provenance is the exception that is genuinely undoubled: nothing
// else unions the sources' provenance into the summary.
if l.trust == crate::core::Trust::Untrusted {
trust = crate::core::Trust::Untrusted;
}
}
provenance.sort();
provenance.dedup();
// The explicit joins above protect a future trusted local summariser.
// Bind them back onto the value before the common write path derives
// storage metadata; no parallel metadata channel remains.
let mut summary_label = label;
summary_label.provenance = provenance.into_iter().collect();
summary_label.sensitivity = sensitivity;
summary_label.trust = trust;
self.remember_at(
crate::memory::MemoryWrite::new(into.id, into.subject, into.purpose),
Tainted::with_label(summary.into_unlabelled(), summary_label),
into.at,
derived_from,
)
.await
}
/// Extract a bounded set of durable facts from labelled source material.
///
/// Formation is not an ambient hook. The reviewed declaration supplies the
/// destination and instruction; the model proposes only stable keys and
/// content. Every proposal remains labelled from the model and source and
/// is written through [`remember`](Self::remember).
///
/// # It takes the whole role, not a model id
///
/// Formation is untrusted contact — the source material derives from
/// whatever the run handled — so a manifest that declares a quarantined
/// role declares `max_tokens` and `reasoning_effort` beside the model for
/// exactly this call. Taking the id alone was how those two ceilings got
/// parsed into the digest and then dropped at this seam: a declared
/// control the runtime silently did not apply. The role's ceilings now
/// ride the formation call itself.
pub async fn form_memories(
&mut self,
formation: crate::memory::Formation,
source: Tainted<Value>,
provider: Arc<dyn crate::model::ModelProvider>,
role: crate::model::ModelRole,
) -> Result<Vec<(String, u64)>, StepError> {
let source_label = source.label().clone();
let prompt = Tainted::object([
(
"system".to_owned(),
Tainted::trusted(serde_json::Value::String(formation.instruction.clone())),
),
("source".to_owned(), source),
]);
let schema = serde_json::json!({
"type": "object",
"properties": {
"memories": {
"type": "array",
"maxItems": formation.max_items,
"items": {
"type": "object",
"properties": {
"key": {"type": "string", "minLength": 1},
"content": {}
},
"required": ["key", "content"],
"additionalProperties": false
}
}
},
"required": ["memories"],
"additionalProperties": false
});
let completion = self
.sink_with(&prompt, |value| {
role.applied_to(
crate::model::ModelCall::new(provider, role.model.clone(), value)
.with_max_sensitivity(formation.max_sensitivity)
.with_output_sensitivity(source_label.sensitivity)
.expecting(schema),
)
})
.await?;
let label = completion.label().join(&source_label);
// The schema above is enforced at the effect boundary, so a well-formed
// answer is the only one that reaches here. It is still read defensively
// rather than unwrapped: the boundary's *shape* check runs in every
// build but its full JSON Schema validation needs `jsonschema`, which a
// bare `testkit` build does not have. A model's answer is untrusted
// data, and untrusted data must never be able to abort the process —
// a panic here would unwind a run that has already announced effects,
// leaving exactly the terminal-record-less outcome I2 exists to prevent.
let unusable = |detail: &str| {
StepError::Effect(crate::core::EffectError::Rejected(format!(
"memory formation for subject `{}` could not read the model's answer: {detail}",
formation.subject
)))
};
let value = completion
.peek()
.structured
.as_ref()
.ok_or_else(|| unusable("it carried no structured value"))?;
let proposals = value["memories"]
.as_array()
.ok_or_else(|| unusable("`memories` is not an array"))?
.clone();
// The declared bound, enforced by the runtime rather than by the
// schema alone: `maxItems` above holds only where the `jsonschema`
// validator is in the build, and a declared ceiling that depends on a
// feature flag is a control that yields where nobody is looking. The
// truncation is silent toward the model on purpose — an over-long
// answer is not worth failing a run that has already paid for it, and
// which proposals survive is the declaration's order, first wins.
let mut written = Vec::with_capacity(proposals.len().min(formation.max_items));
let mut seen = std::collections::BTreeSet::new();
for proposal in proposals {
if written.len() == formation.max_items {
break;
}
let key = proposal["key"]
.as_str()
.ok_or_else(|| unusable("a proposal carries no string `key`"))?;
// The same first-wins rule the ceiling applies. A key proposed
// twice in one answer would otherwise write two versions back to
// back, with the *later* proposal silently superseding the one the
// declaration's order preferred — and a duplicate is not a
// distinct fact, so it does not spend a `max_items` slot either.
if !seen.insert(key.to_owned()) {
continue;
}
let id = format!(
"formed-{}",
crate::core::Digest::of(&crate::core::canon::value_bytes(&serde_json::json!({
"subject": formation.subject,
"purpose": formation.purpose,
"key": key,
})))
.to_hex()
);
let mut destination = crate::memory::MemoryWrite::new(
id.clone(),
formation.subject.clone(),
formation.purpose.clone(),
);
destination.expires_at = formation.expires_at;
destination.access_retention_seconds = formation.access_retention_seconds;
let version = self
.remember(
destination,
Tainted::with_label(proposal["content"].clone(), label.clone()),
)
.await?;
written.push((id, version));
}
Ok(written)
}
/// The blob store for this run, sealed to its case.
///
/// **Use this rather than a store held from the builder.** With a key ring
/// configured, bytes written here are encrypted under the case's data key,
/// and a store obtained any other way writes them in the clear — the two
/// would disagree about what erasing the case actually erased. It is also
/// what a skill passes to
/// [`ModelCall::with_media`](crate::model::ModelCall::with_media), so
/// materialization reads through the same envelope that sealed the bytes.
///
/// # Errors
///
/// If no blob store is configured, or the run belongs to no case while a
/// key ring is — there would be no erasure unit to scope the key to, and
/// falling back to storing in the clear would silently drop the guarantee.
pub fn blobs(&self) -> Result<Arc<dyn crate::blob::BlobStore>, StepError> {
self.blobs_scoped(None)
}
/// The blob store, sealed to whichever unit owns erasure for these bytes.
///
/// `scope` overrides the case, for bytes whose lifecycle another controller
/// owns — named external media retention is the only such caller. Sealing
/// those under a case they do not belong to would put them in an erasure
/// unit that does not own them; not sealing them would leave a hole in a
/// deployment that asked for none.
fn blobs_scoped(
&self,
scope: Option<&str>,
) -> Result<Arc<dyn crate::blob::BlobStore>, StepError> {
let blobs = self.blobs.clone().ok_or_else(|| {
StepError::Store(crate::core::StoreError::Backend(
"no blob store is configured; `Runtime::builder(..).blobs(..)` is what lets \
bytes live outside the journal"
.to_owned(),
))
})?;
// The tenant prefixes every scope. Without it two tenants sharing a
// key ring or a bucket collide the moment they use the same case or
// retention name — and the collision is invisible until one tenant's
// erasure destroys the other's key. `TenantId` refuses `/` for exactly
// this reason, so the prefix cannot be forged by naming a tenant
// `acme/prod`.
let unit = match scope {
Some(s) => Some(s.to_owned()),
None => self.case.as_ref().map(|c| c.case_id.to_string()),
};
// The erasure unit leads the storage address, sealed or not — the
// same bytes in two units are two objects, so one unit's erasure
// reaches only its own copies. `blob::ScopedBlobs` carries the
// argument.
let scoped = |u: &str| -> Arc<dyn crate::blob::BlobStore> {
Arc::new(crate::blob::ScopedBlobs::new(
blobs.clone(),
crate::core::erasure_scope(&self.tenant, u),
))
};
#[cfg(feature = "keyring")]
if let Some(keys) = self.keyring.clone() {
let unit = unit.ok_or_else(|| {
StepError::Store(crate::core::StoreError::Backend(
"a key ring is configured but this run belongs to no case and no \
other erasure unit was named, so there is nothing to scope its data \
key to. Bind the run to a case, name an external retention policy, \
or drop the key ring — storing these bytes in the clear would leave \
an erasure that silently does not reach them"
.to_owned(),
))
})?;
let scope = crate::core::erasure_scope(&self.tenant, &unit);
return Ok(Arc::new(crate::keyring::EncryptedBlobs::new(
scoped(&unit),
keys,
scope,
)));
}
// Unsealed: address by unit when the run has one. A caseless run with
// no named scope keeps the bare handle — it links no blobs through the
// case layer, so there is no erasure unit for an address to belong to.
Ok(match unit {
Some(u) => scoped(&u),
None => blobs,
})
}
/// Store bytes in the blob store and record that this case produced them.
///
/// The reason this lives on the context rather than on the blob store: the
/// runtime knows which case is running and the blob store deliberately does
/// not — it is content-addressed, and a digest cannot be reversed to find
/// the matter it belonged to. Writing through here means the association is
/// made at the only moment it is knowable, so an erasure request can later
/// be answered by case, which is the only unit anybody actually asks about.
/// The association is made before the blob write: a crash can leave a
/// harmless dangling link, repaired by retry, but never durable bytes that
/// case erasure cannot discover.
///
/// Deliberately **not** a journaled effect. The digest is a pure function of
/// the bytes, so a replay that re-derives it gets the same answer without
/// re-performing anything, and writing content-addressed bytes twice is the
/// same write. What *is* journaled is whatever the skill does with the
/// digest next — a tool call carrying it, a case-state write recording it.
///
/// # Errors
///
/// If no blob store is configured, if the write fails, or if this step is
/// not running inside a case.
pub async fn store_blob(&mut self, bytes: &[u8]) -> Result<crate::core::Digest, StepError> {
let cx = self.case_ctx()?.clone();
let digest = crate::core::Digest::of(bytes);
// Through `blobs()`, so a sealed deployment seals these too rather than
// having one write path that encrypts and another that does not.
let blobs = if self.mode == Mode::Strict {
None
} else {
Some(self.blobs()?)
};
let at = self.now().await?;
let Some(blobs) = blobs else {
return Ok(digest);
};
// Link before put: a crash may leave a dangling, erasable reference,
// but can never leave durable bytes unreachable from case erasure.
cx.cases
.link_blob(cx.case_id, digest, at)
.await
.map_err(StepError::Store)?;
let stored = blobs
.put(bytes)
.await
.map_err(|e| StepError::Store(crate::core::StoreError::Backend(e.to_string())))?;
debug_assert_eq!(stored, digest, "blob stores compute the content digest");
Ok(digest)
}
/// Fetch remote media through the governed, replayable ingestion boundary.
///
/// The URL stays labelled and is bound byte-for-byte to the fetch effect.
/// The fetcher checks and pins DNS, validates every redirect, caps time and
/// bytes, refuses content coding and ungranted media types, runs configured
/// validators, and writes the bytes to content-addressed blob storage. The
/// journal receives only [`FetchedMedia`](crate::media::FetchedMedia).
///
/// When the run belongs to a case, the digest is linked before blob storage
/// so [`erase_case`](crate::blob::erase_case) can enforce retention even
/// across crashes. Strict replay consumes the same clock record but never
/// rewrites that link.
///
/// # Errors
///
/// If no blob store is configured, any fetch control refuses the URL or
/// response, validation fails, or blob/case storage fails.
#[cfg(feature = "media")]
pub async fn fetch_media(
&mut self,
fetcher: &crate::media::GovernedMedia,
url: Tainted<String>,
) -> Result<Tainted<crate::media::FetchedMedia>, StepError> {
if fetcher.requires_case() && self.case.is_none() {
return Err(StepError::Store(crate::core::StoreError::Backend(
"governed media requires a case for retention; configure a named external retention policy only when another lifecycle controller owns erasure"
.to_owned(),
)));
}
// Through the sealed accessor: media bytes are payload bytes, and a
// fetch path that wrote them in the clear would leave exactly the hole
// this deployment configured a key ring to close.
// Propagated rather than replaced. Mapping every failure onto "no blob
// store is configured" would report a missing *erasure unit* as a
// missing store, and send whoever reads it to fix the wrong thing.
let blobs = self.blobs_scoped(fetcher.external_scope())?;
let raw = url.peek().clone();
let arguments = Tainted::object([("url".to_owned(), url.map(Value::String))]);
let case_link = if let Some(cx) = self.case.clone() {
let at = self.now().await?;
(self.mode != Mode::Strict).then_some(crate::media::MediaCaseLink {
cases: cx.cases,
case: cx.case_id,
at,
})
} else {
None
};
self.sink(fetcher.effect(blobs, &raw, case_link), &arguments)
.await
}
/// Replace the case's opaque state, if it is still at `at`.
///
/// **A journaled effect**, so a replay does not write again.
///
/// # Why you have to pass the version
///
/// A case is shared by every run correlated to it, and the window between
/// reading its state and writing it back contains a model call — which is
/// unbounded. Two runs on one case overlap as a matter of course, and a
/// blind write in that window silently discards whichever one lost, with
/// nothing in the record to show it happened.
///
/// Passing the version you read makes that unexpressible: the store rejects
/// a write against a revision the case has moved past. The remedy is to
/// re-read and decide again — **not** to retry the same write, which is the
/// lost update this exists to prevent.
///
/// # Errors
///
/// [`StepError`] if this run has no case, or if the case has moved on since
/// `at` — see [`StoreError::CaseConflict`](crate::core::StoreError::CaseConflict).
pub async fn put_case_state(
&mut self,
at: CaseVersion,
state: Value,
) -> Result<CaseVersion, StepError> {
let cx = self.case_ctx()?.clone();
let version = self
.effect(crate::runtime::effects::WriteCaseState {
cases: Arc::clone(&cx.cases),
case: cx.case_id,
expected: at,
state,
})
.await?;
Ok(version.into_unlabelled())
}
/// Move the case to a new status.
pub async fn set_case_status(&mut self, status: CaseStatus) -> Result<(), StepError> {
let cx = self.case_ctx()?.clone();
self.effect(crate::runtime::effects::SetCaseStatus {
cases: Arc::clone(&cx.cases),
case: cx.case_id,
status,
})
.await?;
Ok(())
}
/// Register a durable obligation on the case.
///
/// Resolution goes through the configured [`Calendar`] as a journaled
/// effect, so replay reads back the instant the original run registered
/// rather than recomputing it against whatever the calendar says today.
/// That is what keeps a corrected holiday table from retroactively moving a
/// deadline that has already been relied upon.
///
/// # Why `warn_before` is a `std::time::Duration`
///
/// Two reasons, and the first is the one that bites. `time::Duration` is
/// **signed**, so a negative warning offset would parse, compile, and put
/// `warn_at` *after* the instant it warns about: a warning that can only
/// fire once the obligation is already breached. A quantity that only makes
/// sense non-negative is an unsigned type here, as it is for
/// [`Spend`](crate::core::Spend).
///
/// And it is the `Duration` a caller already has.
/// [`sleep`](Self::sleep) takes the standard one, so the alternative is a
/// public surface with two types spelled `Duration`, only one of which
/// comes from a crate this
/// one re-exports — a reader with the obvious `use std::time::Duration`
/// met a type error naming a dependency the guides never mentioned.
pub async fn deadline(
&mut self,
name: impl Into<String>,
spec: &DeadlineSpec,
warn_before: Option<std::time::Duration>,
) -> Result<Deadline, StepError> {
let name = name.into();
let cx = self.case_ctx()?.clone();
let from = self.now().await?;
let resolved = self
.effect(ResolveDeadline {
calendar: Arc::clone(&cx.calendar),
name: name.clone(),
from,
spec: spec.clone(),
})
.await?
.into_unlabelled();
let deadline = Deadline {
case: cx.case_id,
name: name.clone(),
resolved_at: resolved.at,
calendar_digest: resolved.calendar_digest,
warn_at: warn_before
.and_then(|d| time::Duration::try_from(d).ok())
.and_then(|d| resolved.at.checked_sub(d)),
state: DeadlineState::Pending,
};
// Idempotent by primary key, so a resumed run re-registering the same
// obligation is a no-op rather than a duplicate — and on Resume that
// re-registration is deliberate even for a replayed effect, because it
// is what heals a crash between the resolution record and the case
// store's row. Strict never writes it, matching `store_blob`: a
// verification pass is a pure read, and one that re-registered
// obligations would mutate the case layer every time someone ran a
// regression check — including re-arming a deadline an operator had
// since cancelled.
if self.mode != Mode::Strict {
cx.cases.register_deadline(&deadline).await?;
}
self.append(RecordKind::DeadlineRegistered {
name,
resolved_at: resolved.at,
calendar_digest: resolved.calendar_digest,
})
.await?;
Ok(deadline)
}
/// Mark an obligation satisfied.
///
/// A case cannot be closed while any obligation is still open, so this is
/// what turns "we did the thing" into "the case may now be concluded".
pub async fn meet_deadline(&mut self, name: &str) -> Result<(), StepError> {
self.transition_deadline(name, DeadlineState::Met).await
}
/// Withdraw an obligation that no longer applies.
pub async fn cancel_deadline(&mut self, name: &str) -> Result<(), StepError> {
self.transition_deadline(name, DeadlineState::Cancelled)
.await
}
async fn transition_deadline(
&mut self,
name: &str,
to: DeadlineState,
) -> Result<(), StepError> {
let cx = self.case_ctx()?.clone();
// The read of `from` happens *inside* the effect, so it is journaled
// with the write it describes rather than beside it. Reading here would
// put a store lookup in the deterministic zone, and a replay would
// report whatever the deadline says now as the state it moved from.
let before = self
.effect(crate::runtime::effects::TransitionDeadline {
cases: Arc::clone(&cx.cases),
case: cx.case_id,
name: name.to_owned(),
to,
})
.await?
.into_unlabelled();
// A readable summary beside the effect record, for the same reason
// `StepCompensated` exists: "met" and "cancelled" mean very different
// things to whoever reads this in six months, and reconstructing them
// from an effect descriptor is work nobody does.
self.append(RecordKind::DeadlineTransition {
name: name.to_owned(),
from: before,
to,
})
.await?;
Ok(())
}
}
/// Durable waits.
impl StepCtx<'_> {
/// Wait for an inbound event correlated by business key.
///
/// On replay this returns the event that was recorded; on first execution it
/// either finds one already buffered, or suspends the run.
///
/// # The ordering that makes this safe
///
/// An event can arrive *before* the run reaches this call — a fast
/// counterparty, a slow earlier step, a retry that overtakes. So this looks
/// in the durable buffer **first**, and only registers a subscription and
/// suspends if nothing is there. Delivery and waiting meet in the store
/// rather than in time, which is the only way to close the race.
///
/// # Errors
///
/// Returns [`StepError::Suspended`] when the event has not arrived. That is
/// **not a failure** — propagate it with `?`. Catching it turns a durable
/// wait into a silent hang: the subscription stays live, the event arrives
/// later, and it resumes a run that already decided it was finished.
pub async fn await_event(&mut self, spec: &AwaitSpec) -> Result<Tainted<Value>, StepError> {
// A wait may carry no correlation key: **targeted** delivery
// (`Runtime::deliver_to`, which is how A2A task input arrives) finds
// the subscription by run id and needs none. What such a wait cannot
// be woken by is *broadcast* delivery — `POST /events` matches by
// key — so a run waiting on an event from a bus must `.correlate(...)`
// with the business key the event will carry, or, for a CloudEvent,
// with `("subject", <id>)`.
let correlation = spec.correlation.clone();
self.wait_on(
&spec.kind,
move |_| correlation,
&spec.deadline,
|_| async { Ok(()) },
)
.await
}
/// Ask a human, and wait for the answer.
///
/// The task is created, the run suspends, and a decision resumes it. Because
/// the task id is derived from the awaiting effect rather than minted, a
/// resumed run addresses the same task instead of opening a second one for
/// the same decision.
///
/// # Errors
///
/// Returns [`StepError::Suspended`] until somebody decides. Propagate it —
/// see [`Self::await_event`].
pub async fn task(&mut self, spec: &TaskSpec) -> Result<Decision, StepError> {
let cx = self.case_ctx()?.clone();
let tasks = cx.tasks.clone().ok_or_else(|| {
StepError::Effect(crate::core::EffectError::Other(
"human tasks need a task store — build the runtime with `.tasks(store)`".into(),
))
})?;
// Acting unattended must be chosen deliberately, not picked off a list.
if spec.on_expiry == OnExpiry::Proceed && !spec.allow_unattended {
return Err(StepError::Effect(crate::core::EffectError::Other(
"OnExpiry::Proceed requires `allow_unattended()`: acting without a human \
when the window closes must be an explicit decision, not a default"
.into(),
)));
}
escalation_names_its_audience(spec)?;
let due_at = self.deadline_instant(&cx, &spec.deadline).await?;
// The run's journaled clock, not the obligation's instant.
//
// `created_at` was the deadline. Both fields then said *when this is
// due*, so a worklist reported every row as created in the future and
// "oldest first" silently meant "soonest due" — a reasonable ordering
// under a field name that denies it, which is the worst combination for
// an operator trying to explain a backlog.
let created_at = self.now().await?;
let run = self.run;
let case_id = cx.case_id;
let spec = spec.clone();
let answer = self
.wait_on(
TASK_DECIDED,
|key| {
vec![CorrelationKey::new(
"task",
TaskId::derive(run, key).to_hex(),
)]
},
&spec.deadline.clone(),
move |key| {
let tasks = Arc::clone(&tasks);
let spec = spec.clone();
async move {
let id = TaskId::derive(run, key);
tasks
.open(&Task {
id,
run,
case: Some(case_id),
kind: spec.kind.clone(),
justification: spec.justification.clone(),
candidate_roles: spec.candidate_roles.clone(),
escalate_to: spec.escalate_to.clone(),
excluded_actors: spec.excluded_actors.clone(),
assignee: None,
priority: spec.priority,
state: TaskState::Open,
on_expiry: spec.on_expiry,
created_at,
due_at: Some(due_at),
})
.await?;
Ok(())
}
},
)
.await?;
// A decision is a human's assertion, not a fact the engine verified.
let decision: Decision = serde_json::from_value(answer.peek().clone())?;
Ok(decision)
}
/// Put something in front of a person **without waiting for them**.
///
/// # The control an advisory agent needs
///
/// [`task`](Self::task) asks and blocks. That is the right shape when the
/// answer decides what happens next, and the wrong one when nothing does: an
/// agent that has finished, whose finding a compliance desk must see, does
/// not need its run suspended — it needs a row in a worklist. Gating the
/// *answer* to achieve that is a worklist that blocks, and it costs one
/// suspended run per finding at whatever rate the world produces them.
///
/// So this opens the row and returns its id. The run continues, and nothing
/// resumes on the decision because nothing is waiting on it.
///
/// # Journaled, and the id is derived
///
/// It is an ordinary mutating effect: replay reads the id back rather than
/// opening a second row, and the id is derived from the effect key so a
/// *resume* addresses the row it already opened. `TaskStore::open` is
/// idempotent on that id, which is what makes an interrupted attempt safe to
/// repeat.
///
/// # The justification is untrusted, deliberately
///
/// What a reviewer is shown usually came from a model, and this does **not**
/// route it through the sink gate — the same arrangement [`task`](Self::task)
/// has always had. Refusing untrusted content at a worklist would mean a
/// task could only ever carry content nobody needs to review. See
/// [`OpenTask`](crate::runtime::effects::OpenTask) for the whole argument.
///
/// # Errors
///
/// [`StepError`] if this run has no case, if no task store is wired, or if
/// the named obligation is not registered on the case.
pub async fn open_task(&mut self, spec: &TaskSpec) -> Result<TaskId, StepError> {
let cx = self.case_ctx()?.clone();
let tasks = cx.tasks.clone().ok_or_else(|| {
StepError::Effect(crate::core::EffectError::Other(
"human tasks need a task store — build the runtime with `.tasks(store)`".into(),
))
})?;
// A notification is not a decision, so `OnExpiry::Proceed` has nothing
// to proceed *past* and the unattended consent it demands would be
// consent to nothing. Refused rather than accepted-and-ignored.
if spec.on_expiry == OnExpiry::Proceed {
return Err(StepError::Effect(crate::core::EffectError::Other(
"a task opened beside an answer has no decision to wait for, so \
`OnExpiry::Proceed` describes nothing — the run has already proceeded. \
Use `Deny` to let the window close, or `Escalate` to widen the audience"
.into(),
)));
}
escalation_names_its_audience(spec)?;
let due_at = self.deadline_instant(&cx, &spec.deadline).await?;
let at = self.now().await?;
let run = self.run;
Ok(self
.effect(crate::runtime::effects::OpenTask {
tasks,
run,
case: cx.case_id,
spec: spec.clone(),
at,
due_at,
key: None,
})
.await?
.into_unlabelled())
}
/// The shared machinery behind [`Self::await_event`] and [`Self::task`].
///
/// `before_suspend` runs once, after the effect key is known and the
/// subscription is registered, but before the buffer is consulted — the
/// window in which a task row must exist so that a decision arriving
/// immediately has something to attach to.
async fn wait_on<C, F, Fut>(
&mut self,
kind: &str,
correlate: C,
deadline: &str,
before_suspend: F,
) -> Result<Tainted<Value>, StepError>
where
C: FnOnce(EffectKey) -> Vec<CorrelationKey> + Send,
F: FnOnce(EffectKey) -> Fut + Send,
Fut: std::future::Future<Output = Result<(), StepError>> + Send,
{
// Correlation is computed from the key rather than passed in, because a
// human task's correlation key *is* its id, and that id is derived from
// the key. Taking a closure resolves the circularity without a second
// identifier that could drift from the first.
let key_preview = self.preview_key(kind, &[]);
let spec = &AwaitSpec {
kind: kind.to_owned(),
correlation: correlate(key_preview),
deadline: deadline.to_owned(),
};
let cx = self.case_ctx()?.clone();
let events = cx.events.clone().ok_or_else(|| {
StepError::Effect(crate::core::EffectError::Other(
"durable waits need an event store — build the runtime with `.events(store)`"
.into(),
))
})?;
// The wait is an effect: its output is the event. That means replay
// reads the event back like any other recorded result, and none of the
// suspension machinery has to exist twice.
let descriptor =
EffectDescriptor::new("event.await", serde_json::json!({ "kind": spec.kind }));
let key = self.preview_key(kind, &[]);
debug_assert_eq!(
key,
EffectKey::derive(
self.step,
self.phase,
self.ordinal,
1,
&descriptor.kind,
&canon::value_bytes(&descriptor.args),
),
"the previewed key must match the one the effect is recorded under"
);
self.ordinal += 1;
// ── Replay: the event is already in history ────────────────────────
// `repair` re-enters the registration below with the announcement
// skipped: the wait was announced and its registration may not have
// survived the crash that followed.
let mut repair = false;
if self.mode.is_replaying() {
match self.replayed_wait(key, spec, &cx).await? {
Some(ReplayedWait::Recorded(recorded)) => return Ok(recorded),
Some(ReplayedWait::Repair) => repair = true,
None => {}
}
}
let subscription = Subscription {
run: self.run,
case: Some(cx.case_id),
effect: key,
step: self.step,
phase: self.phase,
kind: spec.kind.clone(),
correlation: spec.correlation.clone(),
};
// NOTE: deliberately not `self.now()`. That is itself an effect, and
// taking it here would give the clock a later ordinal but an earlier
// journal position — replay verifies journal order, so the two must
// agree. The subscription's timestamp is store metadata anyway, like a
// lease: it never enters the journal and cannot affect replay.
let now = subscription_clock();
// Announce the wait before releasing the frame, so an event arriving in
// the same instant finds a durable subscription rather than a gap. On
// a repair pass the announcement is the one record that provably
// survived — writing it again would report one wait as two.
if !repair {
self.append_effect(
key,
RecordKind::EffectStarted {
descriptor,
recovery: crate::core::Recovery::Retry,
mutates: false,
attempt: 1,
backoff_ms: 0,
// An awaited inbound event binds no outbound value.
outbound_label: None,
},
)
.await?;
}
events.subscribe(&subscription, now).await?;
// Whatever must exist for a decision to attach to — a task row, say —
// is created here: after the subscription is durable, before the buffer
// is consulted. An answer arriving in this window finds both.
before_suspend(key).await?;
// Look in the buffer: the event may already be here. The journal
// write comes **before** the unsubscribe, because unsubscribing sheds
// the claimed row's payload — the journal holds the delivered copy
// from then on — and the old order left a crash window in which the
// payload existed nowhere: claimed and stripped in the buffer,
// never journaled. The delivery worker orders these two the same way.
if let Some(buffered) = events.claim_for(&subscription, now).await? {
self.append_effect(
key,
RecordKind::EffectDone {
output: buffered.event.payload.clone(),
source: Some(buffered.event.source.clone()),
spend: crate::core::Spend::default(),
// What `label_inbound` builds, stated rather than derived:
// an inbound payload is another party's data, and the
// provenance half of its label comes from `source` beside
// this and the wait's own kind.
declared: crate::core::DeclaredOutput::untrusted(),
},
)
.await?;
events.unsubscribe(self.run, key).await?;
return Ok(Self::label_inbound(
buffered.event.payload,
&spec.kind,
Some(&buffered.event.source),
));
}
Err(StepError::Suspended(self.suspend_reason(spec, &cx).await?))
}
/// The key this wait will be recorded under, computed without advancing the
/// ordinal.
///
/// Needed because a human task's correlation key is derived from its own
/// effect key, so the key must be known before the subscription is built.
fn preview_key(&self, kind: &str, _unused: &[CorrelationKey]) -> EffectKey {
// Attempt 1, always: a wait that times out suspends or dead-letters,
// it never repeats, so there is no second attempt to distinguish.
EffectKey::derive(
self.step,
self.phase,
self.ordinal,
1,
"event.await",
&canon::value_bytes(&serde_json::json!({ "kind": kind })),
)
}
/// An inbound message is external data by definition, and is labeled as
/// such — including when it comes from a first-party system.
///
/// The label names the *kind*, not the sender, and that is a limitation
/// rather than a choice. A replayed run rebuilds this from the recorded
/// await, which carries the payload and not the source — so deriving the
/// label from `InboundEvent::source` would give a live run and its replay
/// two different labels, which is divergence. Naming the sender in
/// provenance needs the source journaled with the await first.
fn label_inbound(payload: Value, kind: &str, source: Option<&str>) -> Tainted<Value> {
let mut label =
crate::core::Label::untrusted(crate::core::SourceId::new(format!("event:{kind}")));
// Provenance accumulates, so the kind and the sender are both there: a
// sink may allow an authority-bearing field from `event:ack` generally,
// or from one counterparty in particular.
if let Some(source) = source {
label
.provenance
.insert(crate::core::SourceId::new(format!("sender:{source}")));
}
Tainted::with_label(payload, label)
}
/// The instant an obligation falls due.
///
/// A wait's horizon is the obligation that bounds it, and the reviewer's
/// deadline is the same fact — so both read it from one place rather than
/// each computing their own.
async fn deadline_instant(&self, cx: &CaseContext, name: &str) -> Result<Timestamp, StepError> {
cx.cases
.deadlines(cx.case_id)
.await?
.into_iter()
.find(|d| d.name == name)
.map(|d| d.resolved_at)
.ok_or_else(|| {
StepError::Effect(crate::core::EffectError::Other(format!(
"wait references deadline '{name}', which is not registered on this case \
— register it before waiting, or the run has no horizon"
)))
})
}
async fn suspend_reason(
&self,
spec: &AwaitSpec,
cx: &CaseContext,
) -> Result<crate::core::SuspendReason, StepError> {
let until = self.deadline_instant(cx, &spec.deadline).await?;
Ok(crate::core::SuspendReason::AwaitingEvent {
kind: spec.kind.clone(),
correlation: spec.correlation.clone(),
until,
})
}
}
/// What a [`StepCtx::sink_with`] closure may hand back: the effect itself, or
/// a refusal to build one.
///
/// Two implementations and no third: an effect whose construction cannot fail
/// is returned bare, and one whose construction can — `ToolCall::prepare`,
/// which refuses a tool the catalogue does not hold — returns the `Result` it
/// already produces. Without this the infallible majority would write `Ok(..)`
/// at every call site to satisfy the fallible minority.
pub trait BuildsEffect<E: Effect> {
/// The effect, or the error that stops the step instead.
///
/// # Errors
///
/// Whatever the construction refused with, converted to a [`StepError`].
fn into_effect(self) -> Result<E, StepError>;
}
impl<E: Effect> BuildsEffect<E> for E {
fn into_effect(self) -> Result<E, StepError> {
Ok(self)
}
}
impl<T: Effect, Er: Into<StepError>> BuildsEffect<T> for Result<T, Er> {
fn into_effect(self) -> Result<T, StepError> {
self.map_err(Into::into)
}
}
/// Fold a delegation chain into a policy context object.
///
/// Merged rather than nested under a key so a rule reads `context.owner` and
/// `context.delegation_depth` directly — which is the shape the Cedar
/// examples assume, and a rule that has to reach through an extra level is a
/// rule somebody writes wrong once.
pub(crate) fn merge_identity(
context: &mut serde_json::Value,
identity: Option<&crate::core::Delegation>,
) {
let (Some(chain), Some(obj)) = (identity, context.as_object_mut()) else {
return;
};
if let Some(extra) = chain.as_context().as_object() {
for (k, v) in extra {
obj.insert(k.clone(), v.clone());
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use rand::Rng as _;
#[test]
fn rng_is_reproducible_for_the_same_run_and_step() {
let run = RunId::generate();
let mut a = seeded_rng(run, StepId(0));
let mut b = seeded_rng(run, StepId(0));
let xs: Vec<u64> = (0..8).map(|_| a.random()).collect();
let ys: Vec<u64> = (0..8).map(|_| b.random()).collect();
assert_eq!(xs, ys, "replay must reproduce the entropy stream exactly");
}
#[test]
fn rng_differs_across_steps_and_runs() {
let run = RunId::generate();
let other = RunId::generate();
let a: u64 = seeded_rng(run, StepId(0)).random();
let b: u64 = seeded_rng(run, StepId(1)).random();
let c: u64 = seeded_rng(other, StepId(0)).random();
assert_ne!(a, b, "steps must not share a stream");
assert_ne!(a, c, "runs must not share a stream");
}
}
/// One agent commissioning another on the same plane.
///
/// An effect rather than a direct call, so the sub-run's answer is journaled
/// under a key and a replay reads it back. Its arguments carry the label, so
/// commissioning the same work with a *differently trusted* brief is a different
/// effect rather than a cache hit on this one.
#[derive(Debug)]
struct Commission {
capability: String,
input: Value,
label: crate::core::Label,
plane: std::sync::Weak<super::Runtime>,
/// How deep the commissioning run already is.
depth: usize,
}
/// What a commission produced, and what it cost.
///
/// The cost travels with the answer because [`Effect::spend`] is handed the
/// output and nothing else — a commission whose output were the bare answer
/// could not report what the sub-run spent.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct Commissioned {
answer: Value,
tokens: u64,
minor_units: u64,
/// How sensitive the sub-run said its answer was.
///
/// Journaled with the answer rather than re-read afterwards, because the
/// label a replay applies has to come from history — asking the specialist
/// again would make the same run label the same value differently.
///
/// It exists because [`Effect::output_sensitivity`] is a *static*
/// declaration, evaluated before the effect performs, so a commission
/// cannot declare what it does not yet know. Without it every commissioned
/// answer arrived at the default `Internal` floor, which silently
/// downgrades a specialist that handled anything above it — delegation as
/// a laundering primitive, reached without anyone writing a release.
/// Absent in history written before this field existed, which reads back
/// as the floor an untrusted effect output already carries — the old
/// behaviour exactly, rather than a guess that could raise a ceiling.
#[serde(default = "internal_floor")]
sensitivity: crate::core::Sensitivity,
}
const fn internal_floor() -> crate::core::Sensitivity {
crate::core::Sensitivity::Internal
}
#[async_trait::async_trait]
impl Effect for Commission {
type Output = Commissioned;
fn descriptor(&self) -> EffectDescriptor {
EffectDescriptor::new(
"agent.commission",
serde_json::json!({
"capability": self.capability,
"input": self.input,
"label": self.label,
}),
)
}
/// Commissioning is not itself a mutation of the world: whatever the
/// sub-run does is journaled in the sub-run, where it belongs.
fn mutates(&self) -> bool {
false
}
/// Another agent's answer is somebody else's data.
fn trust(&self) -> crate::core::Trust {
crate::core::Trust::Untrusted
}
/// Which agent answered, so a source rule can name the specialist rather
/// than the act of delegating.
fn source(&self) -> crate::core::SourceId {
crate::core::SourceId::new(format!("agent/{}", self.capability))
}
/// Handing work to another agent **is** delegation, and the depth ceiling
/// has to see it.
///
/// This is the in-plane hand-off, and it is the one that matters for the
/// loop a `specialist` role exists to prevent: A commissions B commissions C
/// commissions A, inside one process, with no peer boundary to cross and no
/// egress allowlist to notice. Declaring nothing here meant the ceiling
/// governed only the A2A path — so the rule held across the network and not
/// across a function call, which is the wrong way round.
///
/// One deeper than the chain this run already carries, or the first link
/// when there is none.
fn delegation_depth(&self) -> Option<usize> {
Some(self.depth + 1)
}
/// Bill the commissioning run for what the sub-run spent, so a delegating
/// agent's ceiling bounds the work it ordered.
fn spend(&self, output: &Self::Output) -> crate::core::Spend {
crate::core::Spend {
tokens: output.tokens,
minor_units: output.minor_units,
}
}
async fn perform(&self) -> Result<Self::Output, crate::core::EffectError> {
let plane = self
.plane
.upgrade()
.ok_or_else(|| crate::core::EffectError::Other("the plane is gone".into()))?;
// `Interrupted`, not `Rejected`: this caller cannot know whether the
// commissioned agent performed effects before it failed, and asserting
// that nothing was applied would be a claim it has no basis for.
let out = plane
.run(
&self.capability,
Tainted::with_label(self.input.clone(), self.label.clone()),
)
.await
.map_err(|e| crate::core::EffectError::Interrupted {
driver: self.capability.clone(),
detail: e.to_string(),
})?;
let answer = out
.output
.ok_or_else(|| crate::core::EffectError::Interrupted {
driver: self.capability.clone(),
detail: format!("'{}' finished without producing output", self.capability),
})?;
Ok(Commissioned {
sensitivity: answer.label().sensitivity,
answer: answer.into_unlabelled(),
tokens: out.spend.tokens,
minor_units: out.spend.minor_units,
})
}
}